text
stringlengths
10
2.61M
class CompanySettingsController < ApplicationController skip_before_action :set_company before_action :set_company_settings_object, only: [:update, :destroy] before_filter :authenticate_user! layout "user_dashboard" load_and_authorize_resource # def create # @company_setting = CompanySetting.create(company_setting_params) # @company_setting.company = current_user.company # respond_to do |format| # if @company_setting.save # current_user.company.company_setting = @company_setting # format.json { render json: @company_setting } # else # format.json { render json: @company_setting.errors.full_messages, status: :unprocessable_entity } # end # end # end def update respond_to do |format| if @company_setting.update(company_setting_params) format.js format.json { render json: @company_setting } else format.js format.json { render json: @company_setting.errors, status: :unprocessable_entity } end end end def destroy end private def set_company_settings_object @company_setting = CompanySetting.find(params[:id]) end def company_setting_params params.require(:company_setting).permit(:company_id, :currency, :delivery, :delivery_types => []) end end
class CreateBuildings < ActiveRecord::Migration def change create_table :buildings do |t| t.string :address t.string :borough t.string :owner t.integer :stories t.integer :units t.timestamps end end end
class SubscriptionsMailer < ApplicationMailer include Roadie::Rails::Automatic def activate(user) @user = user mail to: @user.email, subject: "¡#{genderize("Bienvenido", "Bienvenida", @user)} a Make it Real! Activa tu cuenta" end def welcome_slack(user) @user = user mail to: @user.email, subject: "¡Bienvenido a Make it Real!" end def charge_validation(charge) @charge = charge mail to: charge.email, subject: "Pago en proceso de validación" end def charge_rejected(charge) @charge = charge mail to: charge.email, subject: "Pago rechazado por la entidad financiera" end def charge_approved(charge) @charge = charge mail to: charge.email, subject: "[#{charge.description}] Pago procesado con éxito!" end end
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/../fixtures/classes' describe "Implementing IEnumerable from IronRuby" do it "uses the enumerator method defined" do list = TestList.new list << "a" Tester.new.test(list).should include "a" end it "uses the enumerator method defined in Array (via clr_member)" do list_a = TestListFromArray.new list_a << "b" Tester.new.test(list_a).should include "b" end it "doesn't use Array's get_enumerator" do list = TestListMissing.new list << "c" lambda {Tester.new.test(list)}.should raise_error NoMethodError end end
FactoryBot.define do factory(:park) do area {Faker::Number.number(digits: 10)} description {Faker::Movie.quote} name {Faker::Mountain.name} state {Faker::Address.state} end factory(:bird) do family_name {Faker::Creature::Bird.common_family_name} common_name {Faker::Creature::Bird.common_name} color {Faker::Creature::Bird.color} geography {Faker::Creature::Bird.geo} end end
class MessagesController < ApplicationController before_action :authenticate_user!, only: :create def index @group = Group.find(params[:group_id]) @groups = current_user.groups @message = Message.new @users = @group.users end def create @message = current_user.messages.new(create_params) if @message.save redirect_to group_messages_url(params[:group_id]), notice: 'メッセージを入力しました' else flash.now[:alert] = 'メッセ―ジを入力してください' render :new end end private def create_params params.require(:message).permit(:text, :image).merge(group_id: params[:group_id]) end end
class CreateAccounts < ActiveRecord::Migration[6.0] def change create_table :accounts do |t| t.string :nome t.string :telefone t.string :cpf t.decimal :saldo, precision: 8, scale: 2 t.string :status t.timestamps end end end
# Read about factories at http://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :user_group_membership do |f| f.association :user_group f.association :user # Make sure that the User is a member of the Tenant. f.after_build do |instance| FactoryGirl.create(:tenant_membership, :tenant_id => instance.user_group.tenant.id, :user_id => instance.user.id ) end end end
# Jenkins Pullover Daemon # Author:: Sam de Freyssinet (sam@def.reyssi.net) # Copyright:: Copyright (c) 2012 Sittercity, Inc. All Rights Reserved. # License:: MIT License # # Copyright (c) 2012 Sittercity, Inc # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. module JenkinsPullover class Daemon PID = 'jenkins-pullover.pid' INPROC = "inproc://workers" attr_accessor :options, :github, :jenkins # stops the daemon def self.stop File.open(PID, 'r') do |fhandle| pid = fhandle.read() puts pid unless pid.empty? puts "Stopping server proc (#{pid})..." Process.kill("TERM", pid.to_i) end end end # Class constructor def initialize(options) @options = options # Create github client github_client = JenkinsPullover::Github::Client.new({ :github_user => @options.github_user, :github_repo => @options.github_repo, :user => @options.user, :password => @options.password }) # Create github model @github = JenkinsPullover::Github::Model.new({ :github_client => github_client, :debug => @options.debug, :base_branch => @options.branch }) jenkins_client = JenkinsPullover::Jenkins::Client.new({ :jenkins_url => @options.jenkins_url, :jenkins_build_key => @options.jenkins_token }) @jenkins = JenkinsPullover::Jenkins::Model.new({ :jenkins_client => jenkins_client }) end # Executes the daemon def exec case @options.daemon when :start start when :stop JenkinsPullover::Daemon.stop else github_proc(@options) end end # starts the daemon def start puts "starting server..." daemonize end # Daemonise the process def daemonize # fork first child process and exit parent raise RuntimeError, "Failed to fork first child" if (pid = fork) == -1 exit unless pid.nil? # Restablish the session Process.setsid # fork second child process and exit parent raise RuntimeError, "Failed to fork second child" if (pid = fork) == -1 exit unless pid.nil? sid = Process.pid # Write out pid File.open(PID, 'w') do |fhandle| fhandle.write("#{sid}") end file_handle = File.open(@options.logfile, 'w') # Make safe Dir.chdir('/') File.umask 0000 # Reconnect STD/IO STDIN.reopen('/dev/null') STDOUT.reopen(file_handle, 'a') STDERR.reopen(file_handle, 'a') STDOUT.sync = true STDERR.sync = true trap('TERM') { $stderr.puts "Shutting down server..." exit } while true raise RuntimeError, "Failed to fork worker process" if (pid = fork) == -1 if pid.nil? begin github_proc(@options) rescue => msg $stderr.puts "Encountered error:\n#{msg}" end exit else sleep @options.frequency end end end # Github server process def github_proc(options) $stderr.puts(options.inspect) @github.process_pull_requests.each do |pull| jenkins_proc(options, pull) @github.create_comment_for_pull( pull[:number], JenkinsPullover::Github::Model::JENKINS_PREFIX ) end end # Jenkins server process def jenkins_proc(options, pull) @jenkins.trigger_build_for_job(options.jenkins_job, { :GITHUB_ACCOUNT => options.github_user, :GITHUB_PULL_NUMBER => pull[:number], :GITHUB_USERNAME => options.user }) end end end
class ApplicationController < ActionController::Base protect_from_forgery # include ActionController::MimeResponds # include SessionsHelper # ログイン済ユーザーのみにアクセスを許可する # before_action :authenticate_user! # deviseコントローラーにストロングパラメータを追加する before_action :configure_permitted_parameters, if: :devise_controller? $days_of_the_week = %w{日 月 火 水 木 金 土} def current_user if (user_id = session[:user_id]) @current_user ||= User.find_by(id: user_id) elsif (user_id = cookies.signed[:user_id]) user = User.find_by(id: user_id) if user && user.authenticated?(cookies[:remember_token]) log_in user @current_user = user end end end def set_user @user = User.find(params[:id]) end def logged_in_user unless logged_in? store_location flash[:danger] = "ログインしてください。" redirect_to login_url end end def correct_user unless current_user?(@user) flash[:danger] = "アクセス権限がありません。" redirect_to root_url end end def editor_user unless current_user.editor? flash[:danger] = "アクセス権限がありません。" redirect_to root_url end end def admin_user unless current_user.admin? flash[:danger] = "アクセス権限がありません。" redirect_to root_url end end def access_denied(exception) redirect_to root_path, notice: "アクセス権限がありません。" end private def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up,keys:[:name]) end # def access_denied(exception) # redirect_to admin_organizations_path, alert: exception.message # end end
require File.expand_path("#{File.dirname(__FILE__)}/../helper") describe GChart::Map do before(:each) { @chart = GChart::Map.new } it "initializes to a default area of 'world'" do @chart.area.should == 'world' end it "defaults to maximum size of 440x220" do @chart.size.should == '440x220' end it "renders the correct chart type" do @chart.render_chart_type.should == "t" end end describe GChart::Map, "#query_params" do before(:each) { @chart = GChart::Map.new } it "contains the chart's type" do @chart.query_params["cht"].should == "t" end it "contains the map's area" do @chart.area = "usa" @chart.query_params.keys.include?("chtm").should be_true @chart.query_params["chtm"].should == "usa" end it "defaults to a blank map" do @chart.query_params["chd"].should =~ /^[es]:__?/ end it "checks for a valid area" do lambda { @chart.area = 'usa' }.should_not raise_error(ArgumentError) lambda { @chart.area = 'mars' }.should raise_error(ArgumentError) end it "makes sure the areas have one value" do @chart.data = [['NY',1],['VA',2],['WY',3]] @chart.area_codes.length.should == @chart.data.size * 2 end end describe GChart::Map, "#data" do it "accepts data as a hash or pair of arrays" do lambda { GChart::Map.new(:data => {"VA"=>5}) }.should_not raise_error(ArgumentError) lambda { GChart::Map.new(:data => {"VA"=>5, "NY"=>1}) }.should_not raise_error(ArgumentError) lambda { GChart::Map.new(:data => [["VA",5],["NY",1]]) }.should_not raise_error(ArgumentError) lambda { GChart::Map.new(:data => [["VA","NY"],[5,1]]) }.should raise_error(ArgumentError) lambda { GChart::Map.new(:data => [1, 2, 3]) }.should raise_error(ArgumentError) lambda { GChart::Map.new(:data => [[1, 2, 3]]) }.should raise_error(ArgumentError) end end
class Disk < Product def update(options) @album = options[:album_name] @artist_name = options[:artist_name] @genre = options[:genre] end def info return "Диск \"#{@album_name}\", исполнитель #{@artist_name} (#{@genre})" end end
class PigLatinizer attr_reader :text def initialize # @text = text end def piglatinize(text) @text = text #split text into an array of words words = @text.split(" ") #collect pig latin versions of words pig_words = words.map do |word| #find first vowel as an index of the array ([word] per iteration) vowel_index = word.index("#{word.scan(/[AEIOUaeiou]/).first}") #first scanned vowel's index #slice! deletes and returns deleted content removed_portion = word.slice!(0,vowel_index) #remove form start until vowel (can => c) #take remaining portion and add removed_portion to end + ay(way depending on if first letter == vowel) #ex1:egg=> eggway --ex2:dck => uck + d + ay => uckday puts "#{vowel_index}" word << "#{removed_portion}#{"w" if vowel_index == 0}ay" #0 indicates first letter == vowel end #put pig words together as spaced text pig_words.join(" ") end end
class ApplicationController < ActionController::API include ::ActionController::Serialization before_action :set_current_user before_action :ensure_authentication private def set_current_user @current_user = User.where(api_key: request.headers['HTTP_API_KEY']).first end def ensure_authentication head 401 if @current_user.nil? end end
require 'rails_helper' require "mathdojo" describe MathDojo do it "adds" do expect(MathDojo.new.add(3,8).result).to eq(11) end it "adds arrays" do expect(MathDojo.new.add([1,3,5,9]).result).to eq(18) end it "subtracts" do expect(MathDojo.new.subtract(3,4).result).to eq(-7) end it "subtracts arrays" do expect(MathDojo.new.subtract([2,5]).result).to eq(-7) end it "multiplies" do expect(MathDojo.new.add(3).multiply([5,7]).result).to eq(36) end it "resets" do expect(MathDojo.new.add([1,3,5]).reset().add(5).result).to eq(6) end end
require 'spec_helper' describe CrossSellProduct do it "is invalid without a option" do FactoryGirl.build(:cross_sell_product, option: nil).should_not be_valid end it "is invalid with a option 'a' and if product will be not present " do FactoryGirl.build(:cross_sell_product, option: "a", product: nil).should_not be_valid end it "is valid with a product if option will be a" do FactoryGirl.build(:cross_sell_product, option: "a", product: "1").should be_valid end #======================fail case================================ it "is invalid without a option" do FactoryGirl.build(:cross_sell_product, option: nil).should be_valid end it "is invalid with a option 'a' and if product will be not present " do FactoryGirl.build(:cross_sell_product, option: "a", product: nil).should be_valid end it "is valid with a product if option will be a" do FactoryGirl.build(:cross_sell_product, option: "a", product: "1").should_not be_valid end end
class BackupJobsController < ApplicationController load_and_authorize_resource :backup_job before_filter :spread_breadcrumbs def index end def show end def new # Do the same as create. # @backup_job = BackupJob.new(:started_at => Time.now) if @backup_job.save redirect_to backup_jobs_path, :notice => t('backup_jobs.controller.successfuly_created') else render :new end end def create @backup_job = BackupJob.new(:started_at => Time.now) if @backup_job.save redirect_to backup_jobs_path, :notice => t('backup_jobs.controller.successfuly_created') else render :new end end def destroy @backup_job.destroy redirect_to backup_jobs_url, :notice => t('backup_jobs.controller.successfuly_destroyed') end private def spread_breadcrumbs add_breadcrumb t("backup_jobs.index.page_title"), backup_jobs_path if @backup_job && !@backup_job.new_record? add_breadcrumb @backup_job, @backup_job end end end
class DatasetImplementationIssuesController < ApplicationController # GET /dataset_implementation_issues # GET /dataset_implementation_issues.xml def index @page_title = "Issues with VDW Dataset Implementations" @dataset_implementation_issues = DatasetImplementationIssue.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @dataset_implementation_issues } end end # GET /dataset_implementation_issues/1 # GET /dataset_implementation_issues/1.xml def show @dataset_implementation_issue = DatasetImplementationIssue.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @dataset_implementation_issue } end end # GET /dataset_implementation_issues/new # GET /dataset_implementation_issues/new.xml def new @dataset_implementation_issue = DatasetImplementationIssue.new @dataset_implementation_issue.submitting_user_id = current_user.id @dataset_implementation_issue.dataset_implementation_id = params[:diid] respond_to do |format| format.html # new.html.erb format.xml { render :xml => @dataset_implementation_issue } end end # GET /dataset_implementation_issues/1/edit def edit @dataset_implementation_issue = DatasetImplementationIssue.find(params[:id]) end # POST /dataset_implementation_issues # POST /dataset_implementation_issues.xml def create @dataset_implementation_issue = DatasetImplementationIssue.new(params[:dataset_implementation_issue]) respond_to do |format| if @dataset_implementation_issue.save flash[:notice] = 'DatasetImplementationIssue was successfully created.' format.html { redirect_to(@dataset_implementation_issue) } format.xml { render :xml => @dataset_implementation_issue, :status => :created, :location => @dataset_implementation_issue } else format.html { render :action => "new" } format.xml { render :xml => @dataset_implementation_issue.errors, :status => :unprocessable_entity } end end end # PUT /dataset_implementation_issues/1 # PUT /dataset_implementation_issues/1.xml def update @dataset_implementation_issue = DatasetImplementationIssue.find(params[:id]) respond_to do |format| if @dataset_implementation_issue.update_attributes(params[:dataset_implementation_issue]) flash[:notice] = 'DatasetImplementationIssue was successfully updated.' format.html { redirect_to(@dataset_implementation_issue) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @dataset_implementation_issue.errors, :status => :unprocessable_entity } end end end # DELETE /dataset_implementation_issues/1 # DELETE /dataset_implementation_issues/1.xml def destroy @dataset_implementation_issue = DatasetImplementationIssue.find(params[:id]) @dataset_implementation_issue.destroy respond_to do |format| format.html { redirect_to(dataset_implementation_issues_url) } format.xml { head :ok } end end end
## # Copyright 2017-2018 Bryan T. Meyers # # 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 'test/unit' require_relative('../../../../lib/wiki-that') class LinkParseTest < Test::Unit::TestCase def test_empty parser = WikiThat::Parser.new('', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(0, parser.result.children.length) end def test_external_unbalanced parser = WikiThat::Parser.new('[', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:text, parser.result.children[0].children[0].type) assert_equal('[', parser.result.children[0].children[0].value) end def test_external_empty parser = WikiThat::Parser.new('[]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('', parser.result.children[0].children[0].attributes[:href]) end def test_external_incomplete start = '[http://example.com Hello' parser = WikiThat::Parser.new(start, 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:text, parser.result.children[0].children[0].type) assert_equal(start, parser.result.children[0].children[0].value) end def test_external parser = WikiThat::Parser.new('[http://example.com]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('http://example.com', parser.result.children[0].children[0].attributes[:href]) end def test_external_space parser = WikiThat::Parser.new('[ http://example.com ]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('http://example.com', parser.result.children[0].children[0].attributes[:href]) end def test_external_inline parser = WikiThat::Parser.new('Go Here: [http://example.com]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(2, parser.result.children[0].children.length) assert_equal(:text, parser.result.children[0].children[0].type) assert_equal('Go Here: ', parser.result.children[0].children[0].value) assert_equal(:a, parser.result.children[0].children[1].type) assert_equal(1, parser.result.children[0].children[1].attributes.length) assert_equal('http://example.com', parser.result.children[0].children[1].attributes[:href]) end def test_external_inline2 parser = WikiThat::Parser.new('[http://example.com] -- Follow', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(4, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('http://example.com', parser.result.children[0].children[0].attributes[:href]) assert_equal(:text, parser.result.children[0].children[1].type) assert_equal(' ', parser.result.children[0].children[1].value) assert_equal(:text, parser.result.children[0].children[2].type) assert_equal('&mdash;', parser.result.children[0].children[2].value) assert_equal(:text, parser.result.children[0].children[3].type) assert_equal(' Follow', parser.result.children[0].children[3].value) end def test_external_alt parser = WikiThat::Parser.new('[http://example.com Example]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('http://example.com', parser.result.children[0].children[0].attributes[:href]) assert_equal(1, parser.result.children[0].children[0].children.length) assert_equal(:text, parser.result.children[0].children[0].children[0].type) assert_equal('Example', parser.result.children[0].children[0].children[0].value) end def test_internal_incomplete parser = WikiThat::Parser.new('[[', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:text, parser.result.children[0].children[0].type) assert_equal('[[', parser.result.children[0].children[0].value) end def test_internal_incomplete2 parser = WikiThat::Parser.new('[[]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:text, parser.result.children[0].children[0].type) assert_equal('[[]', parser.result.children[0].children[0].value) end def test_internal_empty parser = WikiThat::Parser.new('[[]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/BOB/sub/folder/', parser.result.children[0].children[0].attributes[:href]) end def test_internal_home parser = WikiThat::Parser.new('[[public/Home]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/BOB/sub/folder/public/Home', parser.result.children[0].children[0].attributes[:href]) end def test_internal_page parser = WikiThat::Parser.new('[[Home]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/BOB/sub/folder/Home', parser.result.children[0].children[0].attributes[:href]) assert_equal(1, parser.result.children[0].children[0].children.length) assert_equal(:text, parser.result.children[0].children[0].children[0].type) assert_equal('Home', parser.result.children[0].children[0].children[0].value) end def test_internal_no_base_url parser = WikiThat::Parser.new('[[public/Home]]', nil, 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/BOB/sub/folder/public/Home', parser.result.children[0].children[0].attributes[:href]) end def test_internal_no_sub_url parser = WikiThat::Parser.new('[[public/Home]]', 'wiki', 'BOB', '', '') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/BOB/public/Home', parser.result.children[0].children[0].attributes[:href]) end def test_internal_no_namespace parser = WikiThat::Parser.new('[[public/Home]]', 'wiki', '', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/sub/folder/public/Home', parser.result.children[0].children[0].attributes[:href]) end def test_internal_space parser = WikiThat::Parser.new('[[ public/Home ]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/BOB/sub/folder/public/Home', parser.result.children[0].children[0].attributes[:href]) end def test_internal_relative parser = WikiThat::Parser.new('[[/public/Home]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/BOB/public/Home', parser.result.children[0].children[0].attributes[:href]) end def test_interwiki parser = WikiThat::Parser.new('[[Test123:public/Home]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/Test123/sub/folder/public/Home', parser.result.children[0].children[0].attributes[:href]) end def test_interwiki_space parser = WikiThat::Parser.new('[[ Test123 : public/Home ]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/Test123/sub/folder/public/Home', parser.result.children[0].children[0].attributes[:href]) end def test_interwiki_relative parser = WikiThat::Parser.new('[[Test123:/public/Home]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/Test123/public/Home', parser.result.children[0].children[0].attributes[:href]) end def test_interwiki_named parser = WikiThat::Parser.new('[[Test123:/public/Home|Home]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/Test123/public/Home', parser.result.children[0].children[0].attributes[:href]) assert_equal(1, parser.result.children[0].children[0].children.length) assert_equal(:text, parser.result.children[0].children[0].children[0].type) assert_equal('Home', parser.result.children[0].children[0].children[0].value) end def test_interwiki_named_space parser = WikiThat::Parser.new('[[ Test123 : /public/Home | Home ]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/Test123/public/Home', parser.result.children[0].children[0].attributes[:href]) assert_equal(1, parser.result.children[0].children[0].children.length) assert_equal(:text, parser.result.children[0].children[0].children[0].type) assert_equal('Home', parser.result.children[0].children[0].children[0].value) end def test_internal_audio parser = WikiThat::Parser.new('[[Audio:/public/test.wav]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:audio, parser.result.children[0].children[0].type) assert_equal(2, parser.result.children[0].children[0].attributes.length) assert_equal(true, parser.result.children[0].children[0].attributes[:controls]) assert_equal('/media/folder/BOB/public/test.wav', parser.result.children[0].children[0].attributes[:src]) end def test_internal_video parser = WikiThat::Parser.new('[[Video:/public/test.mp4]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:video, parser.result.children[0].children[0].type) assert_equal(2, parser.result.children[0].children[0].attributes.length) assert_equal(true, parser.result.children[0].children[0].attributes[:controls]) assert_equal('/media/folder/BOB/public/test.mp4', parser.result.children[0].children[0].attributes[:src]) end def test_internal_image parser = WikiThat::Parser.new('[[Image:/public/test.png]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:img, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/media/folder/BOB/public/test.png', parser.result.children[0].children[0].attributes[:src]) end def test_internal_image_caption parser = WikiThat::Parser.new('[[Image:/public/test.png|Test PNG]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:img, parser.result.children[0].children[0].type) assert_equal('/media/folder/BOB/public/test.png', parser.result.children[0].children[0].attributes[:src]) assert_equal('Test PNG', parser.result.children[0].children[0].attributes[:alt]) end def test_internal_image_caption_incomplete1 start = '[[Image:/public/test.png|Test PNG' parser = WikiThat::Parser.new(start, 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:text, parser.result.children[0].children[0].type) assert_equal('[[Image:/public/test.png|Test PNG', parser.result.children[0].children[0].value) end def test_internal_image_caption_incomplete2 start = "[[Image:/public/test.png|Test PNG\n" parser = WikiThat::Parser.new(start, 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(2, parser.result.children[0].children.length) assert_equal(:text, parser.result.children[0].children[0].type) assert_equal('[[Image:/public/test.png|Test PNG', parser.result.children[0].children[0].value) assert_equal(:text, parser.result.children[0].children[1].type) assert_equal('&nbsp;', parser.result.children[0].children[1].value) end def test_internal_image_caption_incomplete3 start = '[[Image:/public/test.png|Test PNG] ' parser = WikiThat::Parser.new(start, 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(2, parser.result.children[0].children.length) assert_equal(:text, parser.result.children[0].children[0].type) assert_equal('[[Image:/public/test.png|Test PNG]', parser.result.children[0].children[0].value) assert_equal(:text, parser.result.children[0].children[1].type) assert_equal(' ', parser.result.children[0].children[1].value) end def test_internal_image_frame parser = WikiThat::Parser.new('[[Image:/public/test.png|frame|Test PNG]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:figure, parser.result.children[0].children[0].type) assert_equal('frame', parser.result.children[0].children[0].attributes[:class]) assert_equal(2, parser.result.children[0].children[0].children.length) assert_equal(:img, parser.result.children[0].children[0].children[0].type) assert_equal('/media/folder/BOB/public/test.png', parser.result.children[0].children[0].children[0].attributes[:src]) assert_equal('Test PNG', parser.result.children[0].children[0].children[0].attributes[:alt]) assert_equal(:figcaption, parser.result.children[0].children[0].children[1].type) assert_equal(1, parser.result.children[0].children[0].children[1].children.length) assert_equal(:text, parser.result.children[0].children[0].children[1].children[0].type) assert_equal('Test PNG', parser.result.children[0].children[0].children[1].children[0].value) end def test_internal_image_thumb parser = WikiThat::Parser.new('[[Image:/public/test.png|thumb|Test PNG]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:figure, parser.result.children[0].children[0].type) assert_equal('thumb', parser.result.children[0].children[0].attributes[:class]) assert_equal(2, parser.result.children[0].children[0].children.length) assert_equal(:img, parser.result.children[0].children[0].children[0].type) assert_equal('/media/folder/BOB/public/test.png', parser.result.children[0].children[0].children[0].attributes[:src]) assert_equal('Test PNG', parser.result.children[0].children[0].children[0].attributes[:alt]) assert_equal(:figcaption, parser.result.children[0].children[0].children[1].type) assert_equal(1, parser.result.children[0].children[0].children[1].children.length) assert_equal(:text, parser.result.children[0].children[0].children[1].children[0].type) assert_equal('Test PNG', parser.result.children[0].children[0].children[1].children[0].value) end def test_internal_image_width parser = WikiThat::Parser.new('[[Image:/public/test.png|100px|Test PNG]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:img, parser.result.children[0].children[0].type) assert_equal('/media/folder/BOB/public/test.png', parser.result.children[0].children[0].attributes[:src]) assert_equal('100', parser.result.children[0].children[0].attributes[:width]) assert_equal('Test PNG', parser.result.children[0].children[0].attributes[:alt]) end def test_internal_image_left parser = WikiThat::Parser.new('[[Image:/public/test.png|left|Test PNG]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:figure, parser.result.children[0].children[0].type) assert_equal('left', parser.result.children[0].children[0].attributes[:class]) assert_equal(1, parser.result.children[0].children[0].children.length) assert_equal(:img, parser.result.children[0].children[0].children[0].type) assert_equal('/media/folder/BOB/public/test.png', parser.result.children[0].children[0].children[0].attributes[:src]) assert_equal('Test PNG', parser.result.children[0].children[0].children[0].attributes[:alt]) end def test_internal_header parser = WikiThat::Parser.new('[[#Bob 1234]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('#Bob_1234', parser.result.children[0].children[0].attributes[:href]) end def test_hyphenated parser = WikiThat::Parser.new('[[Bob-1234]]', 'wiki', 'BOB', 'sub/folder', 'media/folder') parser.parse assert_true(parser.success?, 'Parsing should have succeeded') assert_equal(1, parser.result.children.length) assert_equal(:p, parser.result.children[0].type) assert_equal(1, parser.result.children[0].children.length) assert_equal(:a, parser.result.children[0].children[0].type) assert_equal(1, parser.result.children[0].children[0].attributes.length) assert_equal('/wiki/BOB/sub/folder/Bob-1234', parser.result.children[0].children[0].attributes[:href]) assert_equal('Bob-1234', parser.result.children[0].children[0].children[0].value) end end
module MaxemailApiSubscriptions extend self include MaxemailApiShared def subscribe(email_address:, list_id:) return MaxemailApiShared.send_request(params: { method: 'insertRecipient', data: { email_address: email_address, subscribed: 1 }.to_json, listID: list_id }, method: 'list') unless inserted?(email_address: email_address, list_id: list_id) MaxemailApiShared.send_request(params: { method: 'updateRecipient', data: { email_address: email_address, subscribed: 1 }.to_json, listID: list_id, recipientId: find_recipient_id(email_address: email_address) }, method: 'list') end def subscribed?(email_address:, list_id:) response = MaxemailApiShared.send_request(params: { method: 'fetchRecipient', listID: list_id, recipientId: find_recipient_id(email_address: email_address) }, method: 'list') return false if response.body.to_s == 'false' response = JSON.parse(response.body) return false if response['success'].to_s == 'false' return false if response['subscribed'].to_s == '0' return true if response['subscribed'].to_s == '1' rescue StandardError false end def inserted?(email_address:, list_id:) response = MaxemailApiShared.send_request(params: { method: 'fetchRecipient', listID: list_id, recipientId: find_recipient_id(email_address: email_address) }, method: 'list') return false if response.body.to_s == 'false' response = JSON.parse(response.body) return false if response['success'].to_s == 'false' return true if response['subscribed'].to_s == '0' return true if response['subscribed'].to_s == '1' rescue StandardError false end def unsubscribe(email_address: nil, recipient_id: nil, list_id:) recipient_id = find_recipient_id(email_address: email_address) if recipient_id.nil? return false if recipient_id.nil? MaxemailApiShared.send_request(params: { method: 'updateRecipient', data: { email_address: email_address, subscribed: 0 }.to_json, listID: list_id, recipientId: recipient_id }, method: 'list') end def subscriptions(email_address: nil, recipient_id: nil, list_id:) recipient_id = find_recipient_id(email_address: email_address) if recipient_id.nil? return false if recipient_id.nil? MaxemailApiShared.send_request(params: { method: 'fetchLists', listID: list_id, recipientId: recipient_id }, method: 'recipient') end def update_subscription_email(old_email_address: nil, recipient_id: nil, new_email_address:) recipient_id = find_recipient_id(email_address: old_email_address) if recipient_id.nil? return false if recipient_id.nil? MaxemailApiShared.send_request(params: { method: 'update', data: { email_address: new_email_address }.to_json, recipientId: recipient_id }, method: 'recipient') end def update_recipient(email_address:, data:) MaxemailApiShared.send_request(params: { method: 'updateByEmailAddress', emailAddress: email_address, data: data }, method: 'recipient') end def fetch_profile_data(email_address:, profile_descriptions:) MaxemailApiShared.send_request(params: { method: 'fetchProfileDataByEmailAddress', emailAddress: email_address, profileDescriptions: profile_descriptions }, method: 'recipient') end def find_recipient_id(email_address: nil) response = MaxemailApiShared.send_request(params: { method: 'findByEmailAddress', emailAddress: email_address }, method: 'recipient').to_s return nil if response == 'null' response end def available_subscriptions lists = JSON.parse(fetch_list) lists.delete_if { |list| list['type'] != 'include' } end def fetch_list MaxemailApiShared.send_request(params: { method: 'fetchAll' }, method: 'list') end end
class ApplicationController < ActionController::Base before_action :set_locale def set_locale if verify_locale(params[:locale]) cookies[:locale] = params[:locale] end if cookies[:locale] && I18n.locale != cookies[:locale] I18n.locale = cookies[:locale] end end def verify_locale(locale = nil) ['pt-BR', 'en'].include?(locale) && locale ? true : false end end
class SitemapsController < ApplicationController def show @stores = Store.active @products = Product.published @brands = Brand.active @posts = Post.published @tags = ActsAsTaggableOn::Tag end end
# = placemark.rb - Yahoo! Geo Placemaker Placemark object # # Copyright &copy; 2010 Joseph Bauser # require 'rubygems' require 'hpricot' module YahooGeo module Placemaker # == Overview # # A placemark is a parsed Placemaker response including the # place's WOEID, type, name, and place bounding rectangle # # == Example # # query = YahooGeo::Placemaker::Query.new # placemark = query.get( 43.0538, -77.5772 ) # # placemark.woeid => "12589339" # placemark.type => "Zip" # placemark.name => "14467, Henrietta, NY, US" # placemark.center => [ "43.0538", "-77.5772" ] # placemark.south_west => [ "43.0179", "-77.658" ] # placemark.north_east => [ "43.0687", "-77.5706" ] class Placemark attr_accessor :response, :woeid, :type, :name attr_accessor :center, :south_west, :north_east # Placemark.new( xmlResponse ) # # Create a new placemark given a successful response from a Placemaker query def initialize( xml ) doc = Hpricot.XML( xml ) @woeid = doc.at('geographicScope/woeId').inner_text @type = doc.at('geographicScope/type').inner_text @name = doc.at('geographicScope/name').inner_text @center = [doc.at('extents/center/latitude').inner_text, doc.at('extents/center/longitude').inner_text] @south_west = [doc.at('extents/southWest/latitude').inner_text, doc.at('extents/southWest/longitude').inner_text] @north_east = [doc.at('extents/northEast/latitude').inner_text, doc.at('extents/northEast/longitude').inner_text] end end end end
class SampleNameChangeColumnType2 < ActiveRecord::Migration[5.0] def change rename_column :community_areas, :Description, :description end end
#Transformar la clase Herviboro en un módulo. #Implementar el módulo en la clase Conejo mediante Mixin para poder acceder al método dieta desde la instancia. #Finalmente imprimir la definición de Hervíboro. class Herviboro Definir = 'Sólo me alimento de vegetales!' def definir Definir end def dieta "Soy un Herviboro!" end end class Animal def saludar "Soy un animal!" end end class Conejo < Herviboro # include Herviboro def initialize(name) @name = name end end conejo = Conejo.new('Bugs Bunny') # conejo.saludar puts conejo.dieta puts conejo.definir # puts Conejo.ancestors
class Thinginstance < ActiveRecord::Base attr_accessible :number, :thing_id, :user_id belongs_to :user belongs_to :thing def pronounce if self.number > 1 or self.number == 0 then name = self.thing.pluralname else name = self.thing.singularname end self.number.to_s + ' ' + name end def value self.thing.value * self.number end def random(value) offset = rand(Thing.count) self.thing = Thing.first(:offset => offset) self.number = value / self.thing.value; self end end
class SignupNotify < ActionMailer::Base default from: "zibs.shirsh@gmail.com" def successful_signup(user) @user=user @url='http://localhost/' mail to: @user.email, subject: 'Welcome Aboard' end end
require 'test_helper' class SearchEngiensControllerTest < ActionController::TestCase setup do @search_engien = search_engiens(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:search_engiens) end test "should get new" do get :new assert_response :success end test "should create search_engien" do assert_difference('SearchEngien.count') do post :create, search_engien: { footer: @search_engien.footer, head: @search_engien.head, title: @search_engien.title } end assert_redirected_to search_engien_path(assigns(:search_engien)) end test "should show search_engien" do get :show, id: @search_engien assert_response :success end test "should get edit" do get :edit, id: @search_engien assert_response :success end test "should update search_engien" do patch :update, id: @search_engien, search_engien: { footer: @search_engien.footer, head: @search_engien.head, title: @search_engien.title } assert_redirected_to search_engien_path(assigns(:search_engien)) end test "should destroy search_engien" do assert_difference('SearchEngien.count', -1) do delete :destroy, id: @search_engien end assert_redirected_to search_engiens_path end end
require_relative "board" require "byebug" class Game attr_accessor :board, :previous_guess def initialize @board = Board.new @previous_guess = [] self.play end def play print "Welcome to Memory Puzzle!" until board.won? board.render print "Please input a guess in the form of 'x,y' " guess = gets.chomp.split(",") self.make_guess(guess) sleep(0.5) end puts puts "Game Over. You won!" return end def make_guess(pos) pos = pos.map {|entry| entry.to_i } pg = previous_guess board.reveal(pos) board.render if pg.empty? self.previous_guess = pos elsif board[pg].value != board[pos].value sleep(0.5) board[pg].hide board[pos].hide self.previous_guess = [] else self.previous_guess = [] end end end
class ChangeSalutationToSalutationTemplateForContacts < ActiveRecord::Migration def self.up rename_column :contacts, :salutation, :salutation_template end def self.down rename_column :contacts, :salutation_template, :salutation end end
class AddEmailFullNameToComments < ActiveRecord::Migration def change add_column :comments, :email, :string add_column :comments, :full_name, :string end end
json.array!(@coordinator_semesters) do |coordinator_semester| json.extract! coordinator_semester, :id, :coordinator_id, :semester_id, :notes json.url coordinator_semester_url(coordinator_semester, format: :json) end
Gem::Specification.new do |s| s.name = %q{cast} s.version = "0.1.0" s.date = %q{2006-04-25} s.summary = %q{C parser and AST constructor.} s.email = %q{george.ogata@gmail.com} s.homepage = %q{http://cast.rubyforge.org} s.rubyforge_project = %q{cast} s.autorequire = %q{cast} s.authors = ["George Ogata"] s.files = ["README", "lib/cast", "lib/cast.rb", "lib/cast/node.rb", "lib/cast/c.y", "lib/cast/c_nodes.rb", "lib/cast/inspect.rb", "lib/cast/node_list.rb", "lib/cast/parse.rb", "lib/cast/to_s.rb", "ext/cast_ext.c", "ext/cast.h", "ext/extconf.rb", "ext/parser.c", "ext/yylex.re", "doc/index.html", "test/test_node.rb", "test/run.rb", "test/test_c_nodes.rb", "test/test_node_list.rb", "test/test_parse.rb", "test/test_parser.rb", "ext/yylex.c", "lib/cast/c.tab.rb"] s.test_files = ["test/run.rb"] s.extensions = ["ext/extconf.rb"] end
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2021-2023, by Samuel Williams. require_relative 'output/default' require_relative 'output/json' require_relative 'output/text' require_relative 'output/xterm' require_relative 'output/null' module Console module Output def self.new(output = nil, env = ENV, **options) if names = env['CONSOLE_OUTPUT'] names = names.split(',').reverse names.inject(output) do |output, name| Output.const_get(name).new(output, **options) end else return Output::Default.new(output, **options) end end end end
# Encoding: utf-8 # # Cookbook Name:: vim-go # Recipe:: default # # Copyright 2015, Mist Systems, Inc. # # 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. # include_recipe 'apt' include_recipe "git" include_recipe "vim" if node[:vim_go][:install_vim] node.set['go']['version'] = "1.6.2" node.set['go']['filename'] = "go#{node['go']['version']}.#{node['os']}-#{node['go']['platform']}.tar.gz" node.set['go']['url'] = "http://golang.org/dl/#{node['go']['filename']}" include_recipe 'golang' vim_users = search(:users, "vim:true") vim_users.each do |user_item| user = user_item[:id] next unless node[:etc][:passwd][user] Chef::Log.info "vim-go::default: Processing user #{user.inspect}" home_dir = File.join(File.expand_path("~#{user}")) next unless (user_item[:vim] && File.exist?(home_dir)) Chef::Log.info "vim-go::default: #{user}'s dir ${home_dir.inspect} exists and user_item[:vim] is true" directory File.join(home_dir, ".vim") do recursive true owner user group user mode '0755' end %w(autoload bundle).each do |dir| directory File.join(home_dir, ".vim", dir) do recursive true owner user group user mode '0755' end end pathogen_file = File.join(home_dir, ".vim", "autoload", "pathogen.vim") remote_file pathogen_file do source "https://tpo.pe/pathogen.vim" user user mode "0744" not_if { File.exist?(pathogen_file) } end vim_go_file = File.join(home_dir, ".vim", "bundle", "vim-go") git vim_go_file do repository "https://github.com/fatih/vim-go.git" user user not_if { File.exist?(vim_go_file) } end config_info = node[:vim_go][:vimrc] if config_info && (not config_info.empty?) vimrc_file = File.join(home_dir, ".vimrc") file vimrc_file do owner user mode '0755' content config_info not_if { File.exist?(vimrc_file) } end end if node[:vim_go][:install_go_binaries] Chef::Log.info "About to vim +GoInstallBinaries +qall" bash "finalize_vim_go" do code "vim +GoInstallBinaries +qall" cwd home_dir user user end end end
#tag: skill action module TSBS Staff_Icons = { # Raise the staff "Staff-RAISE" => [4, 0, 0, true, -30,-30,1,-1], "Xbow-RAISE" => [0,-4,-12, true, -30,45,1,-1], # Small rotation "Staff-Rotate1" => [4, 0, 0, true, -30,0,10,-1], # Heavy Rotation... I mean, Big rotation "Staff-Rotate2" => [4, 0, -5, false, -30,30,10,-1], } Moves = { #---------------------------------------------------------------------------- "Summon_Grenade" => [ [], [:change_skill, 41], [:pose, 2, 2, 30], [:pose, 3, 1, 5], [:pose, 3, 2, 5], [:sound, "Evasion1", 100, 100], [:proj_afimage], [:projectile, 0, 30, 15, 211, 15], [:pose, 3, 8, 30], [:wait, 30], ], #---------------------------------------------------------------------------- "Move" => [ [:slide, -45, 0, 10, 7], # Slide forward [:wait, 15], # Wait for 15 frames ], #---------------------------------------------------------------------------- "E_Move" => [ [:slide, 45, 0, 10, 7], # Slide forward [:wait, 15], # Wait for 15 frames ], #---------------------------------------------------------------------------- "Jump" => [ [:slide,0, 0, 10, 7], [:wait, 5], ], #---------------------------------------------------------------------------- "ATK" => [ [], [:action, "Move"], # Move forward #[:wait,10], #[:pose, 3,0,4,"Staff-RAISE"], # Swing the staff [:pose, 3,6,5], [:pose, 3,7,5], [:projectile, 150, 8, 0], [:wait, 20], ], # --------------------------------------------------------------------------- # Basic move for magic skill casting. To be called somewhere # --------------------------------------------------------------------------- "MagicCast" => [ [:action, "Move"], # [:icon,"Staff-RAISE"], # Raise staff! [:cast, 139], # Play casting animation [:loop, 3, "K-Cast"], # Loop three times [:wait, 10], # Wait for 15 frame ], #---------------------------------------------------------------------------- "Vcs_Fireball" => [ [], [:camera, 1, [-75,-25], 65, 1.2], [:focus, 60], [:action, "MagicCast"], [:proj_setup, { :start_pos => [0,0], :end_pos => [-50,0], :end => :feet, :anim_start => 2, :anim_end => :default, :flash => [false,true], }], [:camera, 0, [100,-50], 55, 1.0], [:projectile,57,14,0], # Show fireball [:wait, 4], [:proj_setup, { :change => true, :end_pos => [-10, 10], }], [:projectile,57,14,0], # Show fireball [:wait, 4], [:proj_setup, { :change => true, :end_pos => [-10, 10], }], [:projectile,57,14,0], # Show fireball [:wait, 75], # Wait for 30 frames [:unfocus, 30], # Unfocus for 30 frames duration [:wait,30], # Wait for 30 frames ], #---------------------------------------------------------------------------- "Thunder" => [ [], [:camera, 1, [-75,-25], 65, 1.3], [:icon,"Staff-RAISE"], # Raise staff! [:cast, 14], # Play casting animation [:loop, 3, "K-Cast"], # Loop three times [:wait, 15], # Wait for 15 frame [:camera, 1, [-220,-25], 65, 1.0], [:pose, 3, 3, 4,"Staff-Rotate1"], # Rotate staff + change pose [:pose, 3, 4, 4], # Change pose, wait for 4 frames [:pose, 3, 5, 5], # Change pose, wait for 4 frames [:summon, 1, :self, [-75, 0], -1, "Summon_Grenade", 61, 38], [:wait, 5], [:summon, 2, :self, [-25, 25], -1, "Summon_Grenade", 61, 38], [:wait, 120], [:camera, 0, [100,-50], 55, 1.0], [:summon, 3, :target, [-105, 0], -1, "Summon_Grenade", 42, 53, true], [:wait, 5], [:summon, 4, :target, [105, 0], -1, "Summon_Grenade", 42, 53], [:wait, 120], ], #---------------------------------------------------------------------------- "MMRain-Pre" => [ [], [:camera, 1, [-75,-25], 65, 1.3], [:action, "Move"], [:icon,"Staff-RAISE"], # Raise staff! [:cast, 14], # Play casting animation [:loop, 3, "K-Cast"], # Loop three times [:wait, 15], # Wait for 15 frame [:camera, 2, [100,-50], 55, 1.0], [:pose, 3,0,4,"Staff-Rotate2"], # Swing the staff [:pose, 3,1,4], [:pose, 3,2,4], ], #---------------------------------------------------------------------------- "MMRain" => [ [], [:proj_setup, { :pierce => true, :wait => 15, :start_pos => [-25, 0], :aftimg => true, :aft_rate => 1, }], [:projectile, 56, 10, 0], # Show magic projectile [:sound, "Ice7", 80, 100], [:wait, 15], [:sound, "Laser", 80, 150], [:sound, "Shot1", 80, 150], [:wait, 20], ], #---------------------------------------------------------------------------- "MMRain-Post" => [ [], [:wait, 50], [:action, "RESET"], ], #---------------------------------------------------------------------------- "Magic" => [ [], [:action, "MagicCast"], [:action, "Target Damage"], [:wait, 60], ], #---------------------------------------------------------------------------- "MagicRain" => [ [], [:camera, 1, [-75,-25], 65, 1.3], [:pose, 2, 2, 30], [:pose, 3, 1, 5], [:pose, 3, 2, 5], [:sound, "Evasion1", 100, 100], [:proj_setup, { :end => :self, :end_pos => [-115, -150, 1], :anim_end => 55, :aftimg => true, :damage => 0, }], [:one_anim], [:projectile, 0, 25, 7, 3224, 90], [:camera, 2, [100,-50], 55, 1.0], [:wait, 25 + 6], [:proj_setup, { :start_pos => [-115, -150], }], [:projectile, 56, 14, 7], [:wait, 20], [:check_collapse], [:wait, 40], ], #---------------------------------------------------------------------------- "Magic_missile" => [ [], [:wait,10], # Wait for 10 frames [:action,"MagicCast"], [:projectile, 220,8,0], [:wait, 4], [:projectile, 220,8, 0], [:wait, 4], [:projectile, 220, 8, 0], [:wait, 4], ], #---------------------------------------------------------------------------- "Grease" => [ [], [:wait,10], # Wait for 10 frames [:action,"MagicCast"], [:projectile, 140, 8, 0], # Show magic projectile ], #---------------------------------------------------------------------------- "Chromatic_Orb" => [ [], [:wait,10], # Wait for 10 frames [:action,"MagicCast"], [:projectile, 140, 8, 0], # Show magic projectile ], #---------------------------------------------------------------------------- "Blindness" => [ [], [:wait,10], # Wait for 10 frames [:action,"MagicCast"], [:projectile, 140, 8, 0], ], #---------------------------------------------------------------------------- "Scorcher" => [ [], [:wait,10], # Wait for 10 frames [:action,"MagicCast"], # 3 * 6 + 2 = 20 times [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], [:projectile, 155, 8, 0],[:wait,2], ], #---------------------------------------------------------------------------- "Acid_Arrow" => [ [], [:wait,10], # Wait for 10 frames [:action,"MagicCast"], [:projectile, 156, 8, 0], ], #---------------------------------------------------------------------------- "Mirror_Image" => [ [], [:wait,10], # Wait for 10 frames [:action,"MagicCast"], [:projectile, 140,3, 0], [:summon, 13, :self, [45, 10], -1, "Summon_Grenade", 61, 38], [:summon, 13, :self, [20, 0], -1, "Summon_Grenade", 61, 38], [:summon, 13, :self, [45, -10], -1, "Summon_Grenade", 61, 38], [:summon, 13, :self, [70, 0], -1, "Summon_Grenade", 61, 38], ], #---------------------------------------------------------------------------- "Ray"=>[ [], [:action,"MagicCast"], [:projectile, 174,15, 0], ], #---------------------------------------------------------------------------- "Comet"=>[ [], [:focus, 100], [:action,"MagicCast"], [:projectile,205,200,0], [:wait,200] ], #---------------------------------------------------------------------------- "Comet_E"=>[ [], [:focus, 100], [:action,"MagicCast"], [:projectile,208,200,0], [:wait,200], ], } Icons.merge!(Staff_Icons) AnimLoop.merge!(Moves) end
WhoRunIt::Application.routes.draw do # Sessions get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' delete '/logout', to: 'sessions#destroy' # Root root to: 'events#new' # Events resources :events # Routes resources :routes get "/routes/:id/remove", to: "routes#remove", as: "remove_route" # Users resources :users get "/profile/:id", to: 'users#show', as: "profile" # Notifications post "/commit", to: "notifications#commit" # LocationSettings resources :location_settings end
# @param {Integer} left # @param {Integer} right # @return {Array<Integer>} def self_dividing_numbers(left, right) self_divisors = [] for i in left..right do if is_self_dividing(i) self_divisors.push(i) end end self_divisors end # @param {Integer} num # @return Boolean def is_self_dividing(num) current = num while current > 0 toMod = current % 10 return false if toMod == 0 || num % toMod != 0 current/=10 end true end puts self_dividing_numbers(3,22)
# Copyright (C) 2011-2012 Tanaka Akira <akr@fsij.org> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Tb::Cmd.subcommands << 'gsub' Tb::Cmd.default_option[:opt_gsub_e] = nil Tb::Cmd.default_option[:opt_gsub_f] = nil def (Tb::Cmd).op_gsub op = OptionParser.new op.banner = "Usage: tb gsub [OPTS] REGEXP STRING [TABLE ...]\n" + "Substitute cells." define_common_option(op, "hNo", "--no-pager") op.def_option('-f FIELD', 'target field') {|field| Tb::Cmd.opt_gsub_f = field } op.def_option('-e REGEXP', 'specify regexp, possibly begins with a hyphen') {|pattern| Tb::Cmd.opt_gsub_e = pattern } op end Tb::Cmd.def_vhelp('gsub', <<'End') Example: % cat tst.csv foo,bar baz,qux hoge,moga % tb gsub o X tst.csv foo,bar baz,qux hXge,mXga % tb gsub -f foo o X tst.csv foo,bar baz,qux hXge,moga % tb gsub '[aeiou]' '{\&}' tst.csv foo,bar b{a}z,q{u}x h{o}g{e},m{o}g{a} End def (Tb::Cmd).main_gsub(argv) op_gsub.parse!(argv) exit_if_help('gsub') if Tb::Cmd.opt_gsub_e re = Regexp.new(Tb::Cmd.opt_gsub_e) else err('no regexp given.') if argv.empty? re = Regexp.new(argv.shift) end err('no substitution given.') if argv.empty? repl = argv.shift argv = ['-'] if argv.empty? creader = Tb::CatReader.open(argv, Tb::Cmd.opt_N) er = Tb::Enumerator.new {|y| creader.with_cumulative_header {|header0| if header0 y.set_header header0 end }.each {|pairs, header| fs = header.dup fs.pop while !fs.empty? && !pairs.has_key?(fs.last) if Tb::Cmd.opt_gsub_f pairs2 = pairs.map {|f, v| if f == Tb::Cmd.opt_gsub_f v ||= '' [f, v.gsub(re, repl)] else [f, v] end } else pairs2 = pairs.map {|f, v| v ||= '' [f, v.gsub(re, repl)] } end y.yield Hash[pairs2] } } output_tbenum(er) end
class Friend < ActiveRecord::Base belongs_to :user attr_accessible :facebook_id, :memo, :user_id, :name, :link def self.create_new_by_facebook_api(token) user = User.find_by_token(token) graph = Koala::Facebook::API.new(token) friends = graph.get_connections("me", "friends") friends.each do |friend| Friend.find_or_create_by_user_id_and_facebook_id_and_name(user_id: user.id, facebook_id: friend["id"], name: friend["name"], link: friend["link"]) end end end
############# # Iteration # ############# def countdown(n) while n >= 1 do puts "iterative countdown " + n.to_s n -= 1 end end ############# # Recursion # ############# def countdown(n) if n <= 1 # base case puts "recursive countdown " + n.to_s else puts "recursive countdown " + n.to_s countdown(n-1) # will take us closer to solution end end ############# # Factorial # ############# def r_factorial(n) if n <= 1 # base case 1 else n * r_factorial(n-1) end end ########################### # Iteration vs. Recursion # ########################### def i_factorial(n) factorial = 1 while n > 1 do factorial = factorial * n n -= 1 end factorial end # puts r_factorial(6)
# SyntaxError: (irb):2: syntax error, unexpected ')', expecting '}' # from /usr/local/rvm/rubies/ruby-2.0.0-rc2/bin/irb:16:in `<main>' # # The error above tells me that a hash was opened with '{' but never closed. # It was likely accidentally closed with a ')' instead of the expected '}'.
class Room attr_accessor :number, :guests def initialize(number, guests) @number = number @guests = guests end def add_guests(input_guests) @guests = [] for guest in input_guests @guests.push(guest) end end def checkout_guests(leaving_guests) @guests.delete_if{|guest| leaving_guests.include?(guest)} end end
require "integration/factories/collection_factory" class InstanceGroupsFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].instance_groups, example) end def get(identity) @subject.get(identity, TEST_ZONE) end def all @subject.all(zone: TEST_ZONE) end def params { :name => resource_name, :zone => TEST_ZONE } end end
class Public::MusicsController < ApplicationController def index @musics = Music.page(params[:page]).reverse_order end def search @musics = Music.search(params[:search]) end def show @music = Music.find(params[:id]) @band = Band.find(@music.band_id) end def new @music = Music.new end def create music = Music.new(music_params) music.band = current_user.band if music.save redirect_to public_music_path(music.id) else flash.now[:alert] = "入力漏れがありました。再度入力お願いいたします。" render :new end end def edit @music = Music.find(params[:id]) unless music.band == current_user.band redirect_to public_music_path(@music.id) end end def update music = Music.find(params[:id]) music.update(music_params) redirect_to public_music_path(params[:id]) end def destroy music = current_user.band.musics.find(params[:id]) music.destroy redirect_to public_musics_path end private def music_params params.require(:music).permit(:img_id, :name, :file, :introduction) end end
Gem::Specification.new do |s| s.name = "xen" s.version = "0.0.3" s.date = "2010-04-17" s.authors = ["nico"] s.email = "nico@rottenbytes.info" s.rubyforge_project = "xen" s.has_rdoc = false s.summary = "Library for accessing Xen informations" s.homepage = "http://www.github.com/rottenbytes/ruby-xen" s.description = "" s.files = ["README", "lib/xen.rb"] end
class AddBasePriceToUsers < ActiveRecord::Migration def change add_column :users, :base_price, :decimal, :precision => 8, :scale => 2, :default => 70.00 end end
# encoding: binary # frozen_string_literal: true RSpec.describe RbNaCl::OneTimeAuth do let(:key) { vector "auth_key_#{described_class.key_bytes}".to_sym } let(:message) { vector :auth_message } let(:tag) { vector :auth_onetime } context ".new" do it "raises ArgumentError on a key which is too long" do expect { described_class.new("\0" * described_class.key_bytes.succ) }.to raise_error(ArgumentError) end end context ".auth" do it "raises ArgumentError on a key which is too long" do expect { described_class.auth("\0" * described_class.key_bytes.succ, message) }.to raise_error(ArgumentError) end end context ".verify" do it "raises ArgumentError on a key which is too long" do expect { described_class.verify("\0" * described_class.key_bytes.succ, tag, message) }.to raise_error(ArgumentError) end end include_examples "authenticator" end
require 'rails_helper' RSpec.describe Item, type: :model do describe '#create' do context 'can save' do it 'is valid with title,explanation,image,video' do expect(create(:item)).to be_valid end it "it Even if you don't have an image, a video will work" do expect(create(:item, image: nil)).to be_valid end it "it Even if you don't have an video, a image will work" do expect(create(:item, video: nil)).to be_valid end end context 'can not save' do it 'is invalid without title and explanation and image and video' do item = build(:item, title: nil, explanation: nil, image: nil, video: nil) item.valid? expect(item.errors[:title]).to include(I18n.t('errors.messages.blank')) end it 'is invalid without user_id' do item = build(:item, user_id: nil) item.valid? expect(item.errors[:user]).to include(I18n.t('errors.messages.blank')) end it 'is invalid without collection_id' do item = build(:item, collection: nil) item.valid? expect(item.errors[:collection]).to include(I18n.t('errors.messages.blank')) end end end end
require 'rails_helper' describe Meta::MapsController do before(:all) do @game = create(:game) @admin = create(:user) @admin.grant(:edit, :games) @user = create(:user) end describe 'GET #index' do it 'succeeds for authorized user' do sign_in @admin get :index expect(response).to have_http_status(:success) end end describe 'GET #new' do it 'succeeds for authorized user' do sign_in @admin get :new expect(response).to have_http_status(:success) end end describe 'POST #create' do it 'succeeds for authorized user' do sign_in @admin post :create, params: { map: { game_id: @game.id, name: 'Foo', description: 'Bar' } } map = Map.first expect(map.game).to eq(@game) expect(map.name).to eq('Foo') expect(map.description).to eq('Bar') expect(response).to redirect_to(meta_map_path(map)) end it 'fails for invalid data' do sign_in @admin post :create, params: { map: { game_id: @game.id, name: '' } } expect(Map.all).to be_empty expect(response).to have_http_status(:success) end it 'redirects for unauthorized user' do sign_in @user post :create, params: { map: { game_id: @game.id, name: 'Foo', description: 'Bar' } } expect(Map.all).to be_empty expect(response).to redirect_to(root_path) end end context 'existing map' do before(:all) do @game2 = create(:game) end let!(:map) { create(:map, game: @game) } describe 'GET #show' do it 'succeeds' do get :show, params: { id: map.id } expect(response).to have_http_status(:success) end end describe 'GET #edit' do it 'succeeds for authorized user' do sign_in @admin get :edit, params: { id: map.id } expect(response).to have_http_status(:success) end end describe 'PATCH #update' do it 'succeeds for authorized user' do sign_in @admin patch :update, params: { id: map.id, map: { game_id: @game2.id, name: 'A', description: 'B' } } map.reload expect(map.game).to eq(@game2) expect(map.name).to eq('A') expect(map.description).to eq('B') expect(response).to redirect_to(meta_map_path(map)) end it 'fails for invalid data' do sign_in @admin patch :update, params: { id: map.id, map: { game_id: @game2.id, name: '' } } map.reload expect(map.game).to eq(@game) expect(map.name).to_not eq('') expect(response).to have_http_status(:success) end it 'redirects for unauthorized user' do sign_in @user post :create, params: { map: { game_id: @game.id, name: 'Foo' } } map.reload expect(map.game).to eq(@game) expect(map.name).to_not eq('Foo') expect(response).to redirect_to(root_path) end end describe 'DELETE #destroy' do it 'succeeds for authorized user' do sign_in @admin delete :destroy, params: { id: map.id } expect(Map.all).to be_empty end it 'fails for unauthorized user' do sign_in @user delete :destroy, params: { id: map.id } expect(Map.all).to_not be_empty end it 'fails for unauthenticated user' do delete :destroy, params: { id: map.id } expect(Map.all).to_not be_empty end end end end
require 'pry' class MembersController < ApplicationController def index @group = Group.find(member_params.group_id) @member.where(group_id: @group.id) end def new @group = Group.find(params[:group_id]) @member = Member.new(group: @group) end def create @member = Member.new(member_params) # binding.pry @group = Group.find(@member.group_id) if @member.save redirect_to group_path(@group) else render :new end end private def member_params params.require(:member).permit(:nick_name, :group_id) end end
class AddItemToDocuments < ActiveRecord::Migration[5.0] def change add_reference :documents, :item, foreign_key: true end end
require 'bundler/setup' require 'sinatra' require 'json' require 'tempfile' require 'sinatra/cross_origin' require_relative 'form_filler.rb' require 'pry' configure do enable :cross_origin end options '/sf2809' do halt 200 end post '/sf2809' do begin json_params = JSON.parse(request.body.read) form = SF2809.new(fill_values: json_params) file = form.save('tmp') bytes = File.read(file) File.delete(file) tmpfile = Tempfile.new('response.pdf') tmpfile.write(bytes) send_file(tmpfile) rescue => e content_type :json return { error: e.to_s } end end
class CreateNotes < ActiveRecord::Migration def change create_table :notes do |t| t.integer :user_id, null: false t.string :header, null: false t.string :text, null: false t.datetime :date, null: false t.timestamps end add_index(:notes, [:header, :date], :unique => true) end end
require "rails_helper" require "rack/mock" describe OauthStateMiddleware do context "using site id from site" do before do @site = FactoryBot.create(:site) @user = FactoryBot.create(:user) @site = FactoryBot.create(:site) @app_callback_url = "http://atomic.example.com" @payload = { user_id: @user.id, site_id: @site.id, application_instance_id: nil, app_callback_url: @app_callback_url, oauth_complete_url: nil, canvas_url: "https://mysite.canvas.com", request_env: { "oauth_restored_env": "env_abc", }, request_params: { "oauth_restored_param": "param_abc", }, }.deep_stringify_keys @oauth_state = FactoryBot.create(:oauth_state, payload: @payload.to_json) @state = @oauth_state.state @code = "1234" @nonce = SecureRandom.hex(64) app = lambda { |env| } @middleware = OauthStateMiddleware.new(app) end context "Initial request after OAuth response" do before do @env = Rack::MockRequest.env_for("http://example.com?state=#{@state}&code=#{@code}") end it "doesn't delete the oauth state" do @middleware.call(@env) oauth_state = OauthState.find(@oauth_state.id) expect(oauth_state).to eq(@oauth_state) end it "signs the redirect" do response = @middleware.call(@env) location = response[1]["Location"] query = Rack::Utils.parse_nested_query(location) expect(query["oauth_redirect_signature"].present?).to be true end it "redirects back to the original app url" do response = @middleware.call(@env) expect(response[0]).to be(302) expect(response[1]["Location"].starts_with?(@app_callback_url)).to be true end end context "Redirect to original url" do before do query = { code: @code, state: @state, nonce: @nonce, }.to_query return_url = @app_callback_url return_url << "?" return_url << @middleware.signed_query_string(query, @site.secret) @env = Rack::MockRequest.env_for(return_url) end it "Restores env based on existing oauth_state" do @middleware.call(@env) expect(@env["canvas.url"]).to eq("https://mysite.canvas.com") expect(@env["oauth_state"]).to include(@payload.except("app_callback_url")) end it "Restores request env based on oauth_state" do @middleware.call(@env) expect(@env["oauth_restored_env"]).to eq("env_abc") end it "Restores request params based on oauth_state" do @middleware.call(@env) request = Rack::Request.new(@env) expect(request.params["oauth_restored_param"]).to eq("param_abc") end it "Sets the oauth_code in the request env" do @middleware.call(@env) expect(@env["oauth_code"]).to eq(@code) end it "Deletes the Oauth State" do expect { @middleware.call(@env) }.to change { OauthState.count }.by(-1) end it "Deletes the Oauth State" do expect { @middleware.call(@env) }.to change { OauthState.count }.by(-1) end it "Rejects an expired state" do oauth_state = OauthState.find(@oauth_state.id) oauth_state.update(created_at: 24.hours.ago) expect { @middleware.call(@env) }.to raise_exception(OauthStateMiddlewareException, /expired/) end it "Rejects a bad signature" do request = Rack::Request.new(@env) request.update_param("oauth_redirect_signature", "invalidsig") expect { @middleware.call(@env) }.to raise_exception(OauthStateMiddlewareException, /signatures do not match/) end it "Rejects a missing oauth state" do oauth_state = OauthState.find(@oauth_state.id) oauth_state.destroy expect { @middleware.call(@env) }.to raise_exception(OauthStateMiddlewareException, /Invalid state/) end it "Doesn't allow a repeat launch" do @middleware.call(@env) expect { @middleware.call(@env) }.to raise_exception(OauthStateMiddlewareException, /Invalid state/) end end end end
# RSence 'Welcome' plugin. # An instance of a class extended from GUIPlugin includes basic functionality # to initialize their user interface from YAML files without extra code. class WelcomePlugin < GUIPlugin def gui_params( msg ) params = super params[:text] = { :welcome => file_read('text/welcome.html') } return params end # Responder for the value defined as `:close` in values.yaml # A responder is called whenever its value is changed on the client. def close_button( msg, value ) # Gets the value of the checkbox dont_show_again = get_ses(msg)[:dont_show_again] # If both the checkbox is checked (true) and the button clicked, # calls the disable_self method defined below. if (value.data == 1) and (dont_show_again.data == true) disable_self end # For most uses of HClickButton combined with a value, resetting the data # to 0 (to make the button clickable again) is done like this: # value.set( msg, 0 ) # Responders should always return true, until more specific return # values are defined in a future version of RSence. # Returning false causes the responder to be called on every request # the client makes until the responder returns true. return true end # Called by close_button, when the checkbox is checked (true) and the Close-button is clicked (1). def disable_self file_write( 'disabled', 'This plugin is disabled. Remove this file to re-enable.' ) @plugins.unload_bundle( @name ) end end
class Jarvis::ScheduleParser < Jarvis::Action def attempt return unless valid_words? ::Jarvis::Schedule.schedule( scheduled_time: @scheduled_time, user_id: @user.id, words: @remaining_words, type: :command, ) @response = "I'll #{Jarvis::Text.rephrase(@remaining_words)} #{natural_time}" return @response.presence || "Sent to Schedule" end def natural_time relative_time.gsub(/12:00 ?pm/i, "noon").gsub(/12:00 ?am/i, "midnight").gsub(":00", "") end def relative_time if @scheduled_time.today? "today at #{@scheduled_time.strftime("%-l:%M%P")}" elsif @scheduled_time.tomorrow? "tomorrow at #{@scheduled_time.strftime("%-l:%M%P")}" else # Maybe even say things like "next Wednesday at ..." if Time.current.year == @scheduled_time.year "on #{@scheduled_time.strftime("%a, %b %-d at %-l:%M%P")}" else "on #{@scheduled_time.strftime("%a, %b %-d, %Y at %-l:%M%P")}" end end end def valid_words? time_str, @scheduled_time = Jarvis::Times.extract_time(@msg.downcase.squish, context: :future) return false unless @scheduled_time @remaining_words = @msg.sub(Regexp.new("(?:\b(?:at)\b )?#{time_str}", :i), "").squish @scheduled_time.present? end end
class LazyLockStrategy def self.display_code(lock_code) # decide whether to go up or down direction = [1, -1].sample digits = (0..9).to_a # rotate each dial by <= 4 spots in direction lazy_code = lock_code.map do |n| digits.rotate(direction * (1 + rand(4)))[n] end lazy_code end end
require 'spec_helper' require 'spaces/interactors/updates_spaces' require 'spaces/entities/space' module Spaces describe UpdatesSpaces do let(:repo) { Repository.for(:space) } after :each do repo.clear end it "receives no params and does nothing" do saved_space = repo.save Space.new(name: "Factory") updater = UpdatesSpaces.new(params: {}) expect { updater.update(saved_space) }.not_to change{repo.all.size} end it "receives a space and updates it according to the params" do saved_space = repo.save Space.new(name: "Factory") new_name = 'Cowork X' updater = UpdatesSpaces.new(params: {name: new_name}) updater.update(saved_space) expect(repo.find_by_id(saved_space.id).name).to eq new_name end end end
class Admin::SettingController < Admin::BaseController load_and_authorize_resource def current_issue @setting = Setting.find_or_create_by_meta_key("current_issue") end def block_placements @settings = Setting.where(meta_key: "block_placement") end def create @setting = Setting.new(params[:setting]) if @setting.save redirect_to(:back, :notice => "Setting was successfully updated.", :setting => @setting) else redirect_to(:back, :notice => "Something going wrong", :setting => @setting) end rescue ActionController::RedirectBackError redirect_to "/admin/setting/current_issue" end def update begin @setting = Setting.find(params[:id]) if @setting.update_attributes(params[:setting]) redirect_to(:back, :notice => "Setting was successfully updated.", :setting => @setting) else redirect_to(:back, :notice => "Something going wrong", :setting => @setting) end rescue ActionController::RedirectBackError redirect_to "/admin/setting/current_issue" end end def destroy @setting = Setting.find(params[:id]) @setting.destroy redirect_to(:back, :notice => "Setting was successfully deleted") end end
require 'test_helper' class CurrencyTest < ActiveSupport::TestCase test '#converted_value returns a valid conversion with exchange rate 1' do assert_includes 97..98, Currency.converted_value(100, 'CAD') end end
require 'test_helper' class Admin::LogsControllerTest < ActionController::TestCase include Devise::TestHelpers def setup john_smith = User.find_by_email("john.smith@mmu.ac.uk") sign_in john_smith end test "should get index" do get :index assert_response :success, "Could not render show all logs page" end end
module Mirror module Helpers include Mirror::Inflections # Gera uma sentença com uma array def sentence(array) array.to_sentence :last_word_connector => " and " end # Flexiona a palara para plurar ou singular def inflect(word,count) if count>1 word.pluralize else word end end end end
class SessionsController < ApplicationController def create @user = User.find_by_github_uid(omniauth["uid"]) || User.create_from_omniauth(omniauth) self.current_user = @user redirect_to user_omniauth_callback_path(:github) end protected def omniauth request.env['omniauth.auth'] end end
FactoryGirl.define do factory :career, :class => Refinery::Careers::Career do sequence(:career_title) { |n| "refinery#{n}" } end end
class AddStatusToReview < ActiveRecord::Migration def change add_column :reviews, :status, :integer add_column :reviews, :moderation_status, :integer end end
class Oystercard MAXIMUM_BALANCE = 90 attr_reader :balance, :MAXIMUM_BALANCE, :in_journey def initialize @balance = 0 @in_journey = false end def top_up(amount) fail 'Maximum balance exceeded' if amount + balance > MAXIMUM_BALANCE @balance += amount end def deduct(amount) @balance -= amount end def in_journey? @in_journey end def touch_in fail "Insufficient balance to touch in" if balance < 1 @in_journey = true end def touch_out @in_journey = false end end
module Istisnalar class Tip < TypeError end class Yukleme < LoadError end class Dizilim < SyntaxError def message "Yazım Hatası" end end end raise Istisnalar::Dizilim
module Refinery module Bookings class Setting < Refinery::Core::BaseModel class << self def confirmation_body Refinery::Setting.find_or_set(:booking_confirmation_body, "Thank you for your booking %name%,\n\nThis email is a receipt to confirm we have received your booking and we'll be in touch shortly.\n\nThanks." ) end def confirmation_subject Refinery::Setting.find_or_set(:booking_confirmation_subject, "Thank you for your booking") end def confirmation_subject=(value) Refinery::Setting.set(:booking_confirmation_subject, value) end def notification_recipients Refinery::Setting.find_or_set(:booking_notification_recipients, (Role[:refinery].users.first.try(:email) if defined?(Role)).to_s) end def notification_subject Refinery::Setting.find_or_set(:booking_notification_subject, "New booking from your website") end end end end end
class User < ApplicationRecord include Memery include Flipperable include PgSearch::Model AUTHENTICATION_TYPES = { email_authentication: "EmailAuthentication", phone_number_authentication: "PhoneNumberAuthentication" } APP_USER_CAPABILITIES = [:can_teleconsult].freeze CAPABILITY_VALUES = { true => "yes", false => "no" }.freeze enum sync_approval_status: { requested: "requested", allowed: "allowed", denied: "denied" }, _prefix: true enum access_level: UserAccess::LEVELS.map { |level, info| [level, info[:id].to_s] }.to_h, _suffix: :access def can_teleconsult? teleconsultation_facilities.any? end def app_capabilities {can_teleconsult: CAPABILITY_VALUES[can_teleconsult?]} end belongs_to :organization, optional: true has_many :user_authentications has_many :blood_pressures has_many :blood_sugars has_many :patients, -> { distinct }, through: :blood_pressures has_many :diabetes_patients, -> { distinct }, through: :blood_sugars has_many :registered_patients, inverse_of: :registration_user, class_name: "Patient", foreign_key: :registration_user_id has_many :phone_number_authentications, through: :user_authentications, source: :authenticatable, source_type: "PhoneNumberAuthentication" has_many :email_authentications, through: :user_authentications, source: :authenticatable, source_type: "EmailAuthentication" has_many :appointments has_many :medical_histories has_many :prescription_drugs has_many :requested_teleconsultations, class_name: "Teleconsultation", foreign_key: :requester_id has_many :recorded_teleconsultations, class_name: "Teleconsultation", foreign_key: :medical_officer_id has_many :deleted_patients, inverse_of: :deleted_by_user, class_name: "Patient", foreign_key: :deleted_by_user_id has_and_belongs_to_many :teleconsultation_facilities, class_name: "Facility", join_table: "facilities_teleconsultation_medical_officers" has_many :accesses, dependent: :destroy has_many :drug_stocks has_many :questionnaire_responses, foreign_key: "last_updated_by_user_id" pg_search_scope :search_by_name, against: [:full_name], using: {tsearch: {prefix: true, any_word: true}} pg_search_scope :search_by_teleconsultation_phone_number, against: [:teleconsultation_phone_number], using: {tsearch: {any_word: true}} scope :search_by_email, ->(term) { joins(:email_authentications).merge(EmailAuthentication.search_by_email(term)) } scope :search_by_phone, ->(term) { joins(:phone_number_authentications).merge(PhoneNumberAuthentication.search_by_phone(term)) } scope :search_by_name_or_email, ->(term) { search_by_name(term).union(search_by_email(term)) } scope :search_by_name_or_phone, ->(term) { search_by_name(term).union(search_by_phone(term)) } scope :teleconsult_search, ->(term) do search_by_teleconsultation_phone_number(term).union(search_by_name_or_phone(term)) end scope :non_admins, -> { joins(:phone_number_authentications).where.not(phone_number_authentications: {id: nil}) } scope :admins, -> { joins(:email_authentications).where.not(email_authentications: {id: nil}) } def self.find_by_email(email) joins(:email_authentications).find_by(email_authentications: {email: email}) end validates :full_name, presence: true validates :role, presence: true, if: -> { email_authentication.present? } validates :teleconsultation_phone_number, allow_blank: true, format: {with: /\A[0-9]+\z/, message: "only allows numbers"} validates_presence_of :teleconsultation_isd_code, if: -> { teleconsultation_phone_number.present? } validates :access_level, presence: true, if: -> { email_authentication.present? } validates :receive_approval_notifications, inclusion: {in: [true, false]} validates :device_created_at, presence: true validates :device_updated_at, presence: true delegate :registration_facility, :access_token, :logged_in_at, :has_never_logged_in?, :mark_as_logged_in, :phone_number, :localized_phone_number, :otp, :otp_valid?, :facility_group, :password_digest, to: :phone_number_authentication, allow_nil: true delegate :email, :password, :authenticatable_salt, :invited_to_sign_up?, to: :email_authentication, allow_nil: true delegate :accessible_organizations, :accessible_facilities, :accessible_facility_groups, :accessible_district_regions, :accessible_block_regions, :accessible_facility_regions, :accessible_users, :accessible_admins, :accessible_protocols, :accessible_protocol_drugs, :access_across_organizations?, :access_across_facility_groups?, :can_access?, :manage_organization?, :grant_access, :permitted_access_levels, to: :user_access, allow_nil: false after_destroy :destroy_email_authentications after_discard :destroy_email_authentications def phone_number_authentication phone_number_authentications.first end def email_authentication email_authentications.first end def user_access UserAccess.new(self) end def region_access(memoized: false) @region_access ||= RegionAccess.new(self, memoized: memoized) end def registration_facility_id registration_facility.id end alias_method :facility, :registration_facility def full_teleconsultation_phone_number number = teleconsultation_phone_number.presence || phone_number isd_code = teleconsultation_isd_code || Rails.application.config.country["sms_country_code"] Phonelib.parse(isd_code + number).full_e164 end def authorized_facility?(facility_id) registration_facility && registration_facility.facility_group.facilities.where(id: facility_id).present? end def access_token_valid? sync_approval_status_allowed? end def self.build_with_phone_number_authentication(params) phone_number_authentication = PhoneNumberAuthentication.new( phone_number: params[:phone_number], password_digest: params[:password_digest], registration_facility_id: params[:registration_facility_id] ) phone_number_authentication.set_otp phone_number_authentication.set_access_token user = new( id: params[:id], full_name: params[:full_name], organization_id: params[:organization_id], device_created_at: params[:device_created_at], device_updated_at: params[:device_updated_at] ) user.sync_approval_requested(I18n.t("registration")) user.phone_number_authentications = [phone_number_authentication] user end def update_with_phone_number_authentication(params) user_params = params.slice( :full_name, :teleconsultation_phone_number, :teleconsultation_isd_code, :sync_approval_status, :sync_approval_status_reason ) phone_number_authentication_params = params.slice( :phone_number, :password, :password_digest, :registration_facility_id ) transaction do update(user_params) && phone_number_authentication.update!(phone_number_authentication_params) end end def sync_approval_denied(reason = "") self.sync_approval_status = :denied self.sync_approval_status_reason = reason end def sync_approval_allowed(reason = "") self.sync_approval_status = :allowed self.sync_approval_status_reason = reason end def sync_approval_requested(reason) self.sync_approval_status = :requested self.sync_approval_status_reason = reason end def reset_phone_number_authentication_password!(password_digest) transaction do authentication = phone_number_authentication authentication.password_digest = password_digest authentication.set_access_token sync_approval_requested(I18n.t("reset_password")) unless feature_enabled?(:auto_approve_users) authentication.save! save! end end def self.requested_sync_approval where(sync_approval_status: :requested) end def destroy_email_authentications destroyable_email_auths = email_authentications.load user_authentications.each(&:destroy) destroyable_email_auths.each(&:destroy) true end # Datadog only accepts flat key/value pairs, not nested hashes. The "usr.xxx" format is converted # in the DD UI into a hash for representation, but apparently it only deals with a flattened list of key/values. def to_datadog_hash { "usr.id" => id, "usr.access_level" => access_level, "usr.sync_approval_status" => sync_approval_status } end def regions_access_cache_key power_user? ? "users/power_user_region_access" : cache_key end def power_user? power_user_access? && email_authentication.present? end def district_level_sync? can_teleconsult? end memoize def drug_stocks_enabled? facility_group_ids = accessible_facilities(:view_reports).select(:facility_group_id).distinct Region.where(source_id: facility_group_ids).any? { |district| district.feature_enabled?(:drug_stocks) } end end
# input: Integer (total number of switches) # output: array (which lights are on after n repetitions) # Switches numbered from 1 to n # Each switch connected to 1 light that is initially off # Go through row of switches and toggle all of them # Go back to beginning for second iteration, toggle switches 2,4,6 ... # For third iteration, toggle switches 3,6,9 ... # Repeat for n repetitions # All switches initially off # First iteration is every switch turned on # Second iteration is multiples of 2 are toggled # Third iteration is multiples of 3 are toggled # Fourth iteration is multiples of 4 are toggled and so on # Method argument is total number of switches # n is equal to method argument # Data Structure: Hash # Algorithm: # initialize variable for starting switch # create initial hash of integers from starting switch to n (method argument) for first pass with states of off # for each pass, use a range from starting switch to n and check if all proceeding numbers are multiples of starting switch # check if the current switch is on or not # if they are a multiple, change their state # for each consecutive pass, increment starting switch by 1 # repeat process until n # return initial array def initial_pass(starting_switch, total_switches) initial_lights_on = {} starting_switch.upto(total_switches) do |num, state| initial_lights_on[num] = 'off' end initial_lights_on end def turning_switch(switches, nth) switches.each do |position, state| if position % nth == 0 switches[position] = (state == 'off') ? 'on' : 'off' end end end def lights_left_on(switches) switches.select { |_position,state| state == 'on' }.keys end def toggling_switches(total_switches) initial_switch = 1 inital_on_lights = initial_pass(initial_switch, total_switches) initial_switch.upto(total_switches) do |num| turning_switch(inital_on_lights, num) end lights_left_on(inital_on_lights) end
class ContentPagesController < ApplicationController before_action :set_main_page, only: [:show, :edit, :update, :destroy] # GET / def index @pictures = Picture.front_page_set @cache_buster = "?cb=#{Time.now.to_i}" render :layout => 'main_page' end def faq @title = 'FAQ' end def history @title = 'History' end def legal_information @title = 'Legal Information' end def vendors @title = 'Vendors' end def method_missing(method_sym, *arguments, &block) if Rails.configuration.rendezvous[:info_pages].include? method_sym.to_s render method_sym.to_s else super end end def respond_to? (method_sym, include_private = false) if Rails.configuration.rendezvous[:info_pages].include? method_sym.to_s true else super end end def contact_us @name = params[:name] @email = params[:email] @message = params[:message] Mailer.send_to_us(@name, @email, @message).deliver_later Mailer.autoresponse(@name, @email, @message).deliver_later flash_notice 'Thank you for sending us a message: you should receive a confirmation email shortly.' redirect_to :root end private # Use callbacks to share common setup or constraints between actions. def set_main_page @main_page = MainPage.find(params[:id]) end # Only allow a trusted parameter "white list" through. def main_page_params params[:main_page] end end
Rails.application.routes.draw do namespace :api, defaults: {format: 'json'} do namespace :v1 do resources :profiles, only: [:index, :show] end end root 'ember#bootstrap' get '/*path' => 'ember#bootstrap' end
# frozen_string_literal: true class CustomStylesController < ApplicationController before_action :set_custom_style, only: %i[show edit update destroy] # GET /custom_styles def index @custom_styles = CustomStyle.all end # GET /custom_styles/1 def show; end # GET /custom_styles/new def new @custom_style = CustomStyle.new end # GET /custom_styles/1/edit def edit; end # POST /custom_styles def create @custom_style = CustomStyle.new(custom_style_params) if @custom_style.save redirect_to @custom_style, notice: 'Custom style was successfully created.' else render :new end end # PATCH/PUT /custom_styles/1 def update if @custom_style.update(custom_style_params) redirect_to @custom_style, notice: 'Custom style was successfully updated.' else render :edit end end # DELETE /custom_styles/1 def destroy @custom_style.destroy redirect_to custom_styles_url, notice: 'Custom style was successfully destroyed.' end private # Use callbacks to share common setup or constraints between actions. def set_custom_style @custom_style = CustomStyle.find(params[:id]) end # Only allow a trusted parameter "white list" through. def custom_style_params params.require(:custom_style).permit(:text) end end
class Member < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :trackable # Setup accessible (or protected) attributes for your model # attr_accessible :remember_me # attr_accessible :title, :body def self.create_or_get(facebook) member = Member.first(:conditions => { :facebook_id => facebook.facebook_id }) if !member member = Member.new member.facebook_id = facebook.facebook_id member.name = facebook.name member.access_token = facebook.access_token member.save else member.name = facebook.name member.access_token = facebook.access_token member.save end return member end def is_member? true end end
# == Schema Information # # Table name: categories # # id :bigint not null, primary key # depth :integer # lft :integer # name :string # rgt :integer # slug :string # created_at :datetime not null # updated_at :datetime not null # parent_id :integer # # Indexes # # index_categories_on_slug (slug) # class Category < ActiveRecord::Base # Associations has_many :categorizations has_many :posts, through: :categorizations belongs_to :parent, class_name: "Category", optional: true has_many :children, foreign_key: :parent_id, class_name: "Category" # awesome_nested_sets gem acts_as_nested_set # Friendly ID include FriendlyId friendly_id :name, :use => :slugged # Methods def post_count posts.count end end
get "/send/:survey_id/tweet" do if authorized?(params[:survey_id]) @survey = current_survey(params[:survey_id]) erb :"/send/send_tweet" else get_failure erb :index end end post "/send/:survey_id/tweet" do @survey = current_survey(params[:survey_id]) if authorized?(params[:survey_id]) handles = valid_handles(params[:handles]) body = valid_body(params[:body]) if valid_tweet?(handles,body) send_tweet(tweet_construct(handles,body,@survey)) Survey.update(@survey.id, sent: 1) flash[:error] = "Tweet Sent!" redirect to("/surveys/#{@survey.id}/send") else tweet_error(handles, body) redirect to("/send/#{@survey.id}/tweet") end else post_failure erb :index end end get '/send/:survey_id/email' do if authorized?(params[:survey_id]) @survey = Survey.find(params[:survey_id]) @url = @survey.url @full_url = "http://localhost:9393/url/#{@url}" erb :'send/send_email' end end post '/send/:survey_id/email' do if authorized?(params[:survey_id]) @survey = Survey.find(params[:survey_id]) @url = @survey.url emails = params[:emails] subject = params[:subject] body = params[:body] mail = Mail.new do from "test@surveydonkey.com" to emails subject subject body body end mail.delivery_method :sendmail mail.deliver flash[:error] = "Email sent!" redirect to("/surveys/#{@survey.id}/send" ) end end get "/send/:survey_id/link" do if authorized?(params[:survey_id]) @survey = current_survey(params[:survey_id]) erb :'/send/send_link' else get_failure erb :index end end post "/send/:survey_id/link" do if authorized?(params[:survey_id]) @survey = current_survey(params[:survey_id]) flash[:error] = "Survey Sent!" erb :'/send/send_portal' else post_failure erb :index end end
# encoding: utf-8 control "V-53997" do title "Connections by mid-tier web and application systems to the Oracle DBMS from a DMZ or external network must be encrypted." desc "Multi-tier systems may be configured with the database and connecting middle-tier system located on an internal network, with the database located on an internal network behind a firewall and the middle-tier system located in a DMZ. In cases where either or both systems are located in the DMZ (or on networks external to DoD), network communications between the systems must be encrypted.false" impact 0.5 tag "check": "Review the System Security Plan for remote applications that access and use the database. For each remote application or application server, determine whether communications between it and the DBMS are encrypted. If any are not encrypted, this is a finding." tag "fix": "Configure communications between the DBMS and remote applications/application servers to use DoD-approved encryption." # Write Check Logic Here end
module HiveMindHive class Plugin < ActiveRecord::Base has_one :device, as: :plugin has_many :runner_version_history def self.create(*args) if args[0].keys.include? 'version' version = args[0]['version'] args[0].delete('version') end hive = super(*args) hive.update_version(version) if version hive end def update(*args) if args[0].keys.include? :version version = args[0][:version] args[0].delete(:version) end self.update_version(version) if version super(*args) end def name self.hostname end def version history = self.runner_version_history.where(end_timestamp: nil).order(start_timestamp: :desc) history.length > 0 ? history.first.runner_version.version : nil end def update_version version if self.runner_version_history.length > 0 self.runner_version_history.last.end_timestamp = Time.now end self.runner_version_history << RunnerVersionHistory.create( runner_version: RunnerVersion.find_or_create_by(version: version), start_timestamp: Time.now ) end def details { 'version' => self.version } end def self.plugin_params params params.permit(:hostname, :version) end end end
class CreateElectionsParticipatedUsers < ActiveRecord::Migration def change create_table :elections_participated_users do |t| t.integer :user_id t.integer :election_id t.timestamps null: false end end end
class AddMesaToList < ActiveRecord::Migration def change add_column :lists, :mesa_n, :string end end
# More on Iteration and arrays ## Basic While Loop array_one = ["Fish", "Cat", "Dog", "Bird"] x = 0 while x < array_one.length puts array_one[x] x += 1 end ## Basic Until Loop array_two = ["Baboon", "Cheetah", "Elephant", "Zebra"] y = 0 until y >= array_two.length puts y puts array_two[y] y += 1 end ## Example of using the Break keyword array_three = ["Amber", "Amber", "Amber", "Amber", "Ruby", "Amber","Amber","Amber"] z = 0 while z < array_three.length current = array_three[z] if current == "Ruby" puts "Yay! Found an Ruby!" break else puts "#{current} is not Ruby" end z += 1 end ## Using break in a Block array_four = [1, 2, "Hello!", 3, 4, 5] array_four. each do |num| if num.is_a?(Fixnum) puts "The square of #{num} is #{num ** 2}" else puts "That's not a number, I'm done.. ." break end end ## Using the next keyword array_five = [11, 12, 13, "Hi again!", 14, 15, []] array_five.each do |num| unless num.is_a?(Fixnum) next else puts "The square of #{num} is #{num ** 2}" end end ## Using the .reverse() array_six = [10, 20, 30, 40, 50] p array_six.reverse p array_six ## Using the .sort() array_seven = [5, 13, 1, -2, 8] p array_seven.sort ## Using the concat array_eight = [41, 42, 43] array_nine = [51, 52, 53] p array_eight p array_nine p array_eight.concat(array_nine) ## Using concat in a method array_ten = [1, 2, 3] array_eleven = [4, 5, 6] def coustom_concat(arr1, arr2) arr2.each {|elem| arr1 << elem} arr1 end p coustom_concat(array_ten, array_eleven)
module APICoder module Commands class Mock < Thor::Group argument :config_file class_option :port, type: :numeric, default: 8080 class_option :host, type: :string, default: '0.0.0.0' def mock require 'rack' require 'rack/api_coder' load config_file Rack::Server.start(app: app, Port: options[:port], Host: options[:host]) end private def app Rack::Builder.new do use Rack::APICoder::RequestValidator use Rack::APICoder::Mock run ->(_env) { [404, {}, [{ id: 'not_found', message: 'link not found' }.to_json]] } end end end end end
module Types::Inclusions module AnnotationBehaviors extend ActiveSupport::Concern included do implements GraphQL::Types::Relay::Node global_id_field :id field :id, GraphQL::Types::ID, null: false field :annotation_type, GraphQL::Types::String, null: true, camelize: false field :annotated_id, GraphQL::Types::String, null: true, camelize: false field :annotated_type, GraphQL::Types::String, null: true, camelize: false field :content, GraphQL::Types::String, null: true field :dbid, GraphQL::Types::String, null: true field :permissions, GraphQL::Types::String, null: true def permissions object.permissions(context[:ability], object.annotation_type_class) end field :created_at, GraphQL::Types::String, null: true, camelize: false def created_at object.created_at.to_i.to_s end field :updated_at, GraphQL::Types::String, null: true, camelize: false def updated_at object.updated_at.to_i.to_s end field :medias, ::ProjectMediaType.connection_type, null: true def medias object.entity_objects end field :annotator, ::AnnotatorType, null: true field :version, ::VersionType, null: true field :assignments, ::UserType.connection_type, null: true def assignments object.assigned_users end field :annotations, ::AnnotationUnion.connection_type, null: true do argument :annotation_type, GraphQL::Types::String, required: true, camelize: false end def annotations(annotation_type:) ::Annotation.where( annotation_type: annotation_type, annotated_type: ["Annotation", object.annotation_type.camelize], annotated_id: object.id ) end field :locked, GraphQL::Types::Boolean, null: true field :project, ::ProjectType, null: true field :team, ::TeamType, null: true field :file_data, ::JsonStringType, null: true, camelize: false field :data, ::JsonStringType, null: true field :parsed_fragment, ::JsonStringType, null: true, camelize: false end end end
Capistrano::Configuration.instance.load do namespace :db do desc "Load seed data into Mongoid database" task :seed_fu do run %{cd #{release_path} && bundle exec rake RAILS_ENV=#{rails_env} db:seed_fu} end end after 'deploy:update_code', 'db:seed_fu' end
class Product < ApplicationRecord has_one_attached :primary_image has_many_attached :supporting_images has_many :orders belongs_to :category validate :no_negative_stock def no_negative_stock if stock.negative? errors.add(:title, 'stock must be positive integer') end end end
class NovoCadastroMailer < ApplicationMailer default from: "LabAberto <contato@beeprinted.com.br>" def novo_cadastro_email(user, admin) @site = "http://52.67.230.136/solicitacoes" @user = user @admin = admin mail(to: @admin.email, subject: "Novo Cadastro | Laboratório Aberto de Brasília") end end
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.string :surname t.string :email t.string :password_digest t.string :facebook_username t.string :twitter_username t.string :linkedin_username t.string :website_url t.integer :sector_cd t.text :description t.references :city t.timestamps end add_index :users, :city_id end end
require 'minitest' require 'minitest/autorun' require 'mocha/setup' require 'delve/scheduler/simple_scheduler' class SimpleSchedulerTest < Minitest::Test def setup @queue = mock('object') @scheduler = SimpleScheduler.new @queue @item = 'item' end def test_add @queue.expects(:add).with(@item, 0) @scheduler.add(@item, false) end def test_next_without_repeating @queue.expects(:get).returns(@item) assert_equal @item, @scheduler.next end def test_next_with_repeating @queue.expects(:get).twice.returns(@item) @queue.expects(:add).with(@item, 0) @scheduler.add(@item, true) @queue.expects(:add).with(@item, 0) @scheduler.next assert_equal @item, @scheduler.next end end
require 'securerandom' class RemoteTask::Tasks::Adduser < RemoteTask::Tasks::Base def initialize(execution, password_tier_id:) super(execution) @password_tier = PasswordTier.includes(:contest, passwords: :person).find(password_tier_id) end def script [ @password_tier.passwords.map do |password| "sudo getent passwd '#{password.person.login}' || sudo useradd -g contestant -s /bin/bash '#{password.person.login}'" end, "cat \"${IOI_SCRATCH_PATH}\" | sudo chpasswd -e", ].flatten.join(?\n) end def scratch StringIO.new( @password_tier.passwords.map do |password| [password.person.login, password.plaintext_password.crypt("$6$#{SecureRandom.base64(12).tr(?+, ?.)}")].join(?:) end.join("\n") + "\n", 'r') end end
class RemoveCreatedatFromAccounts < ActiveRecord::Migration[6.0] def change remove_column :Accounts, :created_at end end
#!/usr/bin/env ruby require 'rubygems' require 'commander/import' require 'ruby-progressbar' require_relative '../lib/experiment' require 'rugged' require 'thwait' require "colorize" require 'tmpdir' require 'bigdecimal' require 'csv' def to_numeric(anything) num = BigDecimal.new(anything.to_s) if num.frac == 0 num.to_i else num.to_f end end program :name, 'experiment' program :version, Experiment::VERSION program :description, 'A tool for running concurrent multi-configuration experiments' def values(spec) if spec =~ /^set\((.*)\)$/m return CSV.parse_line($1).map { |v| v.strip } elsif spec =~ /^range\((.*)\)$/m args = $1.split(/\s*,\s*/).map { |v| to_numeric(v.strip) } values = [] i = args[0] while i < args[1] values.push i i += (args.length > 2 ? args[2] : 1) end return values elsif spec =~ /^cmd(_[l])?\((.*)\)$/m cmd = $1 out = `#{$2}` if cmd == nil return out.split(/\x00+/).reject { |c| c.empty? } elsif cmd == "_l" return out.split(/\n+/m).reject { |c| c.empty? } end end raise ArgumentError.new sprintf("unknown template spec: %s", spec) end def replace(vname, template, parameters) r = Proc.new { |x| x = x.gsub(/(?<!\\)\$(\w+)/) {|m| parameters.include?($1) ? parameters[$1] : $&} x = x.gsub(/(?<!\\)\${(.*?)}/) {|m| parameters.include?($1) ? parameters[$1] : $&} x } version = {} template.each do |k, v| if k == "vary" next end if v.is_a? String version[k] = r.call(v) elsif v.is_a? Array version[k] = v.map { |x| r.call(x) } else version[k] = v end end return [r.call(vname), version] end command :run do |c| c.syntax = 'experiment run' c.summary = 'Run the experiments outlined in experiment.json' c.option '-s', '--single VERSION', String, 'run only a single iteration of a single version' c.option '-r', '--repository FILE', String, 'override location of source code' c.option '-o', '--output DIR', String, 'override location of experiment output' c.option '-l', '--list', 'list all versions and exit' c.action do |args, options| begin config = Experiment::read_config Dir.pwd rescue Exception => er raise ArgumentError.new er.message end # Inherit global options config["versions"].each do |vname, version| config["versions"][vname]["arguments"] = (version["arguments"] || config["arguments"]).dup config["versions"][vname]["build"] = (version["build"] || config["build"]) config["versions"][vname]["checkout"] = (version["checkout"] || config["checkout"]) config["versions"][vname]["into"] = (version["into"] || config["into"]) config["versions"][vname]["diffs"] = (version["diffs"] || config["diffs"]) end # Expand version templates all_versions = {} config["versions"].each do |vname, template| versions = [] if not template.include? "vary" versions.push [vname, template] else fields = [] vals = [] template["vary"].each do |field, spec| fields.push field vals.push values(spec) end vals = [nil].product *vals vals.each do |parameters| parameters = Hash[fields.zip parameters[1..-1]] versions.push replace(vname, template, parameters) end end versions.each do |version| if all_versions.include? version[0] raise ArgumentError.new "Found multiple definitions for version #{version[0]}" end all_versions[version[0]] = version[1] end end if options.list puts all_versions.keys next end if options.single if not all_versions.include? options.single raise ArgumentError.new "Told to run unknown version #{options.single}" end v = all_versions[options.single] all_versions.clear all_versions[options.single] = v config["iterations"] = 1 end if options.output if File.exist? options.output raise ArgumentError.new "Output directory #{options.output} already exists; exiting." end FileUtils.mkdir_p options.output Dir.chdir options.output end repository = (options.repository || config["repository"].gsub("~", Dir.home)) repo = Rugged::Repository.new(repository) # Create list of versions, organized by build build_versions = Hash.new { |hash,key| hash[key] = {} } all_versions.each do |vname, version| app = Experiment::Application.new(:wd => Dir.pwd + "/" + vname, :config => config, :version => version, :repo => repo) build_versions[app.build][vname] = app end # Build each distinct build, then use it to initialize the relevant # versions. bad = [] build_versions.each do |build, versions| begin Dir.mktmpdir do |build_dir| begin build.build(build_dir) rescue RuntimeError => e FileUtils.cp_r build_dir, "failed-build-#{bad.length+1}" raise end versions.each do |vname, a| a.copy_build(vname, build_dir) end end rescue RuntimeError => e STDERR.puts sprintf(" -> %s failed!", build).red bad.push build end end if bad.length == build_versions.length STDERR.puts sprintf("==> ERROR: no buildable version found!").red.bold exit 1 end ops = [] for n in 1..config["iterations"] do iops = [] build_versions.each do |build, versions| if bad.include? build if n == 1 versions.each do |vname, a| STDERR.puts sprintf("==> WARNING: ignoring version with failed build: %s", vname).yellow.bold end end next end versions.each do |vname, a| iops << [vname, a, n] end end # to improve time estimation, run versions in random # order while ensuring all versions within an iteration # are run before the next iteration is started. iops.shuffle! ops << iops end ops.flatten! 1 running = 0 threads = [] twait = nil puts "==> Versions ready, starting experiment".bold p = ProgressBar.create :total => ops.count, :format => "Progress: [%B] %p%% %E " Signal.trap("TERM") do Experiment.stop end Signal.trap("INT") do Experiment.stop end for op in ops do break if Experiment.stopped vname, a, n = *op if running >= config["parallelism"] begin t = twait.next_wait rescue # woken up by a signal break end p.increment threads.delete t end break if Experiment.stopped threads << Thread.new(vname, a, n) do |vname, a, n| begin a.run(n) rescue Exception => er STDERR.puts sprintf("\n -> Failed to run version %s: %s", vname, er).red.bold end end twait = ThreadsWait.new *threads running += 1 end twait.all_waits { p.increment } puts "==> Stopped experimenting after user interrupt".bold if Experiment.stopped end end command :init do |c| c.syntax = 'experiment init' c.summary = 'Create a fresh experiment.json' #c.description = '' #c.example 'description', 'command example' #c.option '--some-switch', 'Some switch that does something' c.action do |args, options| file = "experiment.json" description = ask 'Describe your experiment: ' repo = ask 'Where is the source repository located: ' checkout = ask 'What commit do you want to base the experiment on? ' iterations = ask 'Number of iterations for each version: ' parallelism = ask 'Number of parallel executions: ' versions = ask_for_array 'List the versions you wish to create: ' begin File.open(file, 'w') do |f| f.write <<-"..." { "experiment": "#{description}", "repository": "#{repo}", "checkout": "#{checkout}", "iterations": #{iterations}, "parallelism": #{parallelism}, "build": "make", "arguments": [ ], "versions": { ... versions.each do |version| f.write <<-"..." "#{version}": { } ... end f.write <<-"..." } } ... end end say "experiment.json created, now configure your versions and the execution command" end end default_command :run
class TipoTesserasController < ApplicationController before_filter :signed_in_user def show @tipo_tessera = TipoTessera.find_by_id(params[:id]) end def edit @tipo_tessera = TipoTessera.find_by_id(params[:id]) end def update tipo_tessera = TipoTessera.find(params[:id]) if(tipo_tessera.update_attributes(params[:tipo_tessera])) flash[:success] = "Aggiornamento completato" redirect_to tipo_tessera_path(tipo_tessera.id) # OK else render 'edit' end end def new @tipo_tessera = TipoTessera.new end def create @tipo_tessera = TipoTessera.new(params[:tipo_tessera]) if @tipo_tessera.save redirect_to @tipo_tessera else render 'new' end end def delete end def index @tipo_tesseras = TipoTessera.paginate(page: params[:page], :per_page=>20).order('id DESC') end private def signed_in_user redirect_to signin_url, notice: "Occorre autenticarsi" unless signed_in? end end
class RemoveContactsReferencesFromMonths < ActiveRecord::Migration[5.0] def change remove_reference(:months, :contacts, index: true) end end
class AddAmazonBackupToWorkflowAccrualJob < ActiveRecord::Migration def change add_reference :workflow_accrual_jobs, :amazon_backup, index: true add_foreign_key :workflow_accrual_jobs, :amazon_backups end end
FactoryGirl.define do factory :account, class: IGMarkets::Account do account_alias 'alias' account_id 'A1234' account_name 'CFD' account_type 'CFD' balance { build :account_balance } can_transfer_from true can_transfer_to true currency 'USD' preferred true status 'ENABLED' end end
require_relative 'spec_helper' describe 'static loading' do def app Sinatra::Application end before do @browser = Rack::Test::Session.new(Rack::MockSession.new(app)) end it 'loads the boostrap css file' do @browser.get '/css/bootstrap.min.css' assert @browser.last_response.ok?, 'Last response is not ok' refute @browser.last_response.body.empty?, 'Body is empty - file not loaded' end it 'loads the jquery js file' do @browser.get '/js/jquery-2.1.3.min.js' assert @browser.last_response.ok?, 'Last response is not ok' refute @browser.last_response.body.empty?, 'Body is empty - file not loaded' end it 'loads the bootstrap js file' do @browser.get '/js/bootstrap.min.js' assert @browser.last_response.ok?, 'Last response is not ok' refute @browser.last_response.body.empty?, 'Body is empty - file not loaded' end it 'loads the background image' do @browser.get 'img/crossword.png' assert @browser.last_response.ok?, 'Last response is not ok' refute @browser.last_response.body.empty?, 'Body is empty - file not loaded' end end
# frozen_string_literal: true # Create a function that takes three values (hours, minutes, seconds) # and returns the longest duration def longest_time(h, m, s) normalized_time = [h * 60 * 60, m * 60, s] [h, m, s][normalized_time.index(normalized_time.max)] end
class ChangingNames < ActiveRecord::Migration[5.0] def change rename_column :users, :f_name, :first_name rename_column :users, :l_name, :last_name end end
#!/usr/bin/env ruby # encoding: UTF-8 # # Copyright © 2012-2015 Cask Data, Inc. # # 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 'tempfile' require_relative 'utils' require_relative '../lib/provisioner/logging' module Coopr class Worker include Logging attr_accessor :name def initialize(tenant) pid = Process.pid @name = "worker.#{tenant}.#{pid}" # Logging.configure("#{File.dirname(__FILE__)}/#{@name}.log") Logging.level = 0 log.info "* worker #{name} starting" @sigterm = Coopr::SignalHandler.new('TERM') end def work log.info("worker #{@name} starting up") loop { sleeptime = Random.rand(20) # puts "worker #{@name} sleeping #{sleeptime}" log.info "worker #{@name} sleeping #{sleeptime}" # While provisioning, don't allow the provisioner to terminate by disabling signal @sigterm.dont_interrupt { sleep sleeptime } } end end end if __FILE__ == $PROGRAM_NAME tenant = ARGV[0] || 'superadmin' worker = Coopr::Worker.new(tenant) worker.work end