text
stringlengths
10
2.61M
# encoding: utf-8 # frozen_string_literal: true RSpec.describe TTY::Tree::PathWalker do it "walks path tree and collects nodes" do walker = TTY::Tree::PathWalker.new within_dir(fixtures_path) do walker.traverse('dir1') end expect(walker.nodes).to eq([ TTY::Tree::Node.new('dir1', '', '', 0), TTY::Tree::Node.new('dir1/config.dat', 'dir1', '', 1), TTY::Tree::Node.new('dir2', 'dir1', '', 1), TTY::Tree::Node.new('dir3', 'dir1/dir2', ':pipe', 2), TTY::Tree::LeafNode.new('dir1/dir2/dir3/file3-1.txt', 'dir1/dir2/dir3', ':pipe:pipe', 3), TTY::Tree::LeafNode.new('dir1/dir2/file2-1.txt', 'dir1/dir2', ':pipe', 2), TTY::Tree::Node.new('dir1/file1-1.txt', 'dir1', '', 1), TTY::Tree::LeafNode.new('dir1/file1-2.txt', 'dir1', '', 1), ]) expect(walker.nodes.map(&:full_path).map(&:to_s)).to eq([ "dir1", "dir1/config.dat", "dir1/dir2", "dir1/dir2/dir3", "dir1/dir2/dir3/file3-1.txt", "dir1/dir2/file2-1.txt", "dir1/file1-1.txt", "dir1/file1-2.txt", ]) end it "walks orphaned path tree and collects nodes" do walker = TTY::Tree::PathWalker.new within_dir(fixtures_path) do walker.traverse('orphan_dir') end expect(walker.nodes).to eq([ TTY::Tree::Node.new("orphan_dir", '', '', 0), TTY::Tree::Node.new("orphan_dir/a.txt", 'orphan_dir', '', 1), TTY::Tree::Node.new("orphan_dir/b.txt", 'orphan_dir', '', 1), TTY::Tree::LeafNode.new("data", 'orphan_dir', '', 1), TTY::Tree::Node.new("orphan_dir/data/data1.bin", 'orphan_dir/data', ':space', 2), TTY::Tree::Node.new("orphan_dir/data/data2.sql", 'orphan_dir/data', ':space', 2), TTY::Tree::LeafNode.new("orphan_dir/data/data3.inf", 'orphan_dir/data', ':space', 2) ]) expect(walker.nodes.map(&:full_path).map(&:to_s)).to eq([ "orphan_dir", "orphan_dir/a.txt", "orphan_dir/b.txt", "orphan_dir/data", "orphan_dir/data/data1.bin", "orphan_dir/data/data2.sql", "orphan_dir/data/data3.inf" ]) end it "walks path tree and collects nodes limited by the level" do walker = TTY::Tree::PathWalker.new(level: 2) within_dir(fixtures_path) do walker.traverse('dir1') end expect(walker.nodes.map(&:full_path).map(&:to_s)).to eq([ "dir1", "dir1/config.dat", "dir1/dir2", "dir1/dir2/file2-1.txt", "dir1/file1-1.txt", "dir1/file1-2.txt", ]) end it "doesn't walk paths exceeding file limit" do walker = TTY::Tree::PathWalker.new(file_limit: 4) within_dir(fixtures_path) do walker.traverse('large_dir') end expect(walker.nodes.map(&:full_path).map(&:to_s)).to eq([ "large_dir", "large_dir/huge_dir", "large_dir/large1", "large_dir/large2", "large_dir/large3" ]) end it "counts files & dirs" do walker = TTY::Tree::PathWalker.new within_dir(fixtures_path) do walker.traverse('dir1') end expect(walker.files_count).to eq(5) expect(walker.dirs_count).to eq(2) end it "counts files & dirs including max level limit" do walker = TTY::Tree::PathWalker.new(level: 2) within_dir(fixtures_path) do walker.traverse('dir1') end expect(walker.files_count).to eq(4) expect(walker.dirs_count).to eq(1) end it "raises when walking non-directory" do walker = TTY::Tree::PathWalker.new expect { walker.traverse('unknown-dir') }.to raise_error(ArgumentError, /unknown-dir is not a directory path/) end end
require_relative 'recipe' require 'csv' class Cookbook def initialize(filepath) @recipe_file = filepath @recipes = [] load_csv end def all @recipes = [] load_csv @recipes end def add_recipe(attributes = {}) write_csv(attributes) end def remove_recipe(number) @recipes.delete_at(number) write_csv end private def load_csv CSV.foreach(@recipe_file) do |row| @recipes << Recipe.new(row[0], row[1]) end end def write_csv(attributes = nil) csv_options = { col_sep: ',' } CSV.open(@recipe_file, 'wb', csv_options) do |csv| add_previous_recipes(csv) if attributes.class == Hash csv << [attributes[:name], attributes[:description]] else csv << [attributes.name, attributes.description] unless attributes.nil? end end end def add_previous_recipes(csv) @recipes.each do |recipe| csv << [recipe.name, recipe.description] end end end
class ChargesController < ApplicationController def index @charges_failed = Charge.failed @charges_successful = Charge.successful @charges_disputed = Charge.disputed end end
class Lineup < ActiveRecord::Base has_many :players, :autosave => true, :dependent => :destroy belongs_to :team end
include_recipe "partial_search" # This code iterates through node['admin']['cloud_network']['recipes'] to find # network information about the location of each recipe. Then, populates the public and private # IP info for further use throughout the cookbook. Chef environments are used # to isolate different installations from each other. # ========================================================================= puts "Current environment is: \"#{node.chef_environment}\"" if node.chef_environment.index("default") raise "Not in a working environment" end node['admin']['cloud_network']['recipes'].each_pair do |var, recipe| nodes = partial_search(:node, "run_list:recipe\\[chef-openstack\\:\\:#{recipe}\\] AND chef_environment:#{node.chef_environment}", :keys => { 'network_info' => ['network'] }) current_node = nil current_node = nodes[rand(nodes.length)] if current_node == nil raise "Cannot find recipe: #{recipe} " + "in environment #{node.chef_environment}\n\n" + "You may need to wait up to 60 seconds after bootstrapping" + "or check that all recipes have been assigned." end is_bonded = "False" current_node['br-ex_ip'] = nil current_node['network_info']['interfaces'].each do |iface, addrs| is_bonded = "True" if iface.start_with?('bond') addrs['addresses'].each do |ip, params| current_node["#{iface}_ip"] = ip if params['family'].eql?('inet') end end if current_node['br-priv_ip'].nil? node.default[var][:private_ip] = current_node["#{node['network']['private_interface']}_ip"] else node.default[var][:private_ip] = current_node['br-priv_ip'] end if current_node['br-ex_ip'].nil? node.default[var][:public_ip] = current_node["#{node['network']['public_interface']}_ip"] else node.default[var][:public_ip] = current_node['br-ex_ip'] end end
require 'spec_helper' describe AuthenticationsController do let(:user) { create(:user) } let(:omniauth_callback) { {'provider' => 'twitter', 'uid' => '1234', 'credentials' => {'token' => 'token', 'secret' => 'secret'} } } before(:each) { controller.stub!(:auth_hash).and_return(omniauth_callback) } context "when an authentication exists and we found it" do it "should find the authentication and redirect if it exists" do create(:authentication, user: user) post :create, provider: "twiiter" response.should redirect_to root_url flash[:notice].should eql("Signed in!") end end context "when an authentication does not exist" do context "and the user is signed in" do before(:each) { controller.stub!(:current_user).and_return(user) } it "should create a new authentication" do expect do post :create end.should change(Authentication, :count).by(1) end it "should not create a new user" do expect do post :create end.should_not change(User, :count) end end context "and the user is not signed in" do it "should create a new user" do expect do post :create end.should change(User, :count).by(1) end it "should create the new authentication" do expect do post :create end.should change(Authentication, :count).by(1) end end it "should not change position count if auth isn't linkedin" do expect do post :create end.should_not change(Position, :count) end end end
require 'rails_helper' describe 'merchant items show (/merchant/:merchant_id/items/:id)' do let!(:merchant) { create(:merchant) } let!(:item1) { create(:item, unit_price: 10, merchant: merchant) } let!(:item2) { create(:item, unit_price: 8, merchant: merchant) } let!(:item3) { create(:item, unit_price: 5, merchant: merchant) } let!(:item4) { create(:item, unit_price: 1, merchant: merchant) } describe 'as a merchant' do context 'when I visit the merchant item show page' do before { visit merchant_item_path(merchant, item1) } it { expect(page).to have_no_content('Success!') } it { expect(page).to have_no_content('Error!') } it 'displays the items attributes' do expect(page).to have_content(item1.name) expect(page).to have_content(item1.description) expect(page).to have_content(item1.unit_price / 100.00) expect(page).to have_no_content(item2.name) end it 'displays a link to update item info' do expect(page).to have_link('Update Item') click_link 'Update Item' expect(page).to have_current_path(edit_merchant_item_path(merchant, item1)) end end end end
class Meeting < ApplicationRecord validates :date, :speaker, presence: true scope :date, -> { order("date ASC") } end
# Copyright 2007-2014 Greg Hurrell. All rights reserved. # Licensed under the terms of the BSD 2-clause license. require 'spec_helper' describe 'using shorthand operators to combine String, Symbol and Regexp parsers' do it 'should be able to chain a String and a Regexp together' do # try in one order sequence = 'foo' & /\d+/ expect(sequence.parse('foo1000')).to eq(['foo', '1000']) expect { sequence.parse('foo') }.to raise_error(Walrat::ParseError) # first part alone is not enough expect { sequence.parse('1000') }.to raise_error(Walrat::ParseError) # neither is second part alone expect { sequence.parse('1000foo') }.to raise_error(Walrat::ParseError) # order matters # same test but in reverse order sequence = /\d+/ & 'foo' expect(sequence.parse('1000foo')).to eq(['1000', 'foo']) expect { sequence.parse('foo') }.to raise_error(Walrat::ParseError) # first part alone is not enough expect { sequence.parse('1000') }.to raise_error(Walrat::ParseError) # neither is second part alone expect { sequence.parse('foo1000') }.to raise_error(Walrat::ParseError) # order matters end it 'should be able to choose between a String and a Regexp' do # try in one order sequence = 'foo' | /\d+/ expect(sequence.parse('foo')).to eq('foo') expect(sequence.parse('100')).to eq('100') expect { sequence.parse('bar') }.to raise_error(Walrat::ParseError) # same test but in reverse order sequence = /\d+/ | 'foo' expect(sequence.parse('foo')).to eq('foo') expect(sequence.parse('100')).to eq('100') expect { sequence.parse('bar') }.to raise_error(Walrat::ParseError) end it 'should be able to freely intermix String and Regexp objects when chaining and choosing' do sequence = 'foo' & /\d+/ | 'bar' & /[XYZ]{3}/ expect(sequence.parse('foo123')).to eq(['foo', '123']) expect(sequence.parse('barZYX')).to eq(['bar', 'ZYX']) expect { sequence.parse('foo') }.to raise_error(Walrat::ParseError) expect { sequence.parse('123') }.to raise_error(Walrat::ParseError) expect { sequence.parse('bar') }.to raise_error(Walrat::ParseError) expect { sequence.parse('XYZ') }.to raise_error(Walrat::ParseError) expect { sequence.parse('barXY') }.to raise_error(Walrat::ParseError) end it 'should be able to specify minimum and maximum repetition using shorthand methods' do # optional (same as "?" in regular expressions) sequence = 'foo'.optional expect(sequence.parse('foo')).to eq('foo') expect { sequence.parse('bar') }.to throw_symbol(:ZeroWidthParseSuccess) # zero_or_one (same as optional; "?" in regular expressions) sequence = 'foo'.zero_or_one expect(sequence.parse('foo')).to eq('foo') expect { sequence.parse('bar') }.to throw_symbol(:ZeroWidthParseSuccess) # zero_or_more (same as "*" in regular expressions) sequence = 'foo'.zero_or_more expect(sequence.parse('foo')).to eq('foo') expect(sequence.parse('foofoofoobar')).to eq(['foo', 'foo', 'foo']) expect { sequence.parse('bar') }.to throw_symbol(:ZeroWidthParseSuccess) # one_or_more (same as "+" in regular expressions) sequence = 'foo'.one_or_more expect(sequence.parse('foo')).to eq('foo') expect(sequence.parse('foofoofoobar')).to eq(['foo', 'foo', 'foo']) expect { sequence.parse('bar') }.to raise_error(Walrat::ParseError) # repeat (arbitary limits for min, max; same as {min, max} in regular expressions) sequence = 'foo'.repeat(3, 5) expect(sequence.parse('foofoofoobar')).to eq(['foo', 'foo', 'foo']) expect(sequence.parse('foofoofoofoobar')).to eq(['foo', 'foo', 'foo', 'foo']) expect(sequence.parse('foofoofoofoofoobar')).to eq(['foo', 'foo', 'foo', 'foo', 'foo']) expect(sequence.parse('foofoofoofoofoofoobar')).to eq(['foo', 'foo', 'foo', 'foo', 'foo']) expect { sequence.parse('bar') }.to raise_error(Walrat::ParseError) expect { sequence.parse('foo') }.to raise_error(Walrat::ParseError) expect { sequence.parse('foofoo') }.to raise_error(Walrat::ParseError) end it 'should be able to apply repetitions to other combinations wrapped in parentheses' do sequence = ('foo' & 'bar').one_or_more expect(sequence.parse('foobar')).to eq(['foo', 'bar']) expect(sequence.parse('foobarfoobar')).to eq([['foo', 'bar'], ['foo', 'bar']]) # fails: just returns ['foo', 'bar'] end it 'should be able to combine use of repetition shorthand methods with other shorthand methods' do # first we test with chaining sequence = 'foo'.optional & 'bar' & 'abc'.one_or_more expect(sequence.parse('foobarabc')).to eq(['foo', 'bar', 'abc']) expect(sequence.parse('foobarabcabc')).to eq(['foo', 'bar', ['abc', 'abc']]) expect(sequence.parse('barabc')).to eq(['bar', 'abc']) expect { sequence.parse('abc') }.to raise_error(Walrat::ParseError) # similar test but with alternation sequence = 'foo' | 'bar' | 'abc'.one_or_more expect(sequence.parse('foobarabc')).to eq('foo') expect(sequence.parse('barabc')).to eq('bar') expect(sequence.parse('abc')).to eq('abc') expect(sequence.parse('abcabc')).to eq(['abc', 'abc']) expect { sequence.parse('nothing') }.to raise_error(Walrat::ParseError) # test with defective sequence (makes no sense to use "optional" with alternation, will always succeed) sequence = 'foo'.optional | 'bar' | 'abc'.one_or_more expect(sequence.parse('foobarabc')).to eq('foo') expect { sequence.parse('nothing') }.to throw_symbol(:ZeroWidthParseSuccess) end it 'should be able to chain a "not predicate"' do sequence = 'foo' & 'bar'.not! expect(sequence.parse('foo')).to eq('foo') # fails with ['foo'] because that's the way ParserState works... expect(sequence.parse('foo...')).to eq('foo') # same expect { sequence.parse('foobar') }.to raise_error(Walrat::ParseError) end it 'an isolated "not predicate" should return a zero-width match' do sequence = 'foo'.not! expect { sequence.parse('foo') }.to raise_error(Walrat::ParseError) expect { sequence.parse('bar') }.to throw_symbol(:NotPredicateSuccess) end it 'two "not predicates" chained together should act like a union' do # this means "not followed by 'foo' and not followed by 'bar'" sequence = 'foo'.not! & 'bar'.not! expect { sequence.parse('foo') }.to raise_error(Walrat::ParseError) expect { sequence.parse('bar') }.to raise_error(Walrat::ParseError) expect { sequence.parse('abc') }.to throw_symbol(:NotPredicateSuccess) end it 'should be able to chain an "and predicate"' do sequence = 'foo' & 'bar'.and? expect(sequence.parse('foobar')).to eq('foo') # same problem, returns ['foo'] expect { sequence.parse('foo...') }.to raise_error(Walrat::ParseError) expect { sequence.parse('foo') }.to raise_error(Walrat::ParseError) end it 'an isolated "and predicate" should return a zero-width match' do sequence = 'foo'.and? expect { sequence.parse('bar') }.to raise_error(Walrat::ParseError) expect { sequence.parse('foo') }.to throw_symbol(:AndPredicateSuccess) end it 'should be able to follow an "and predicate" with other parslets or combinations' do # this is equivalent to "foo" if followed by "bar", or any three characters sequence = 'foo' & 'bar'.and? | /.../ expect(sequence.parse('foobar')).to eq('foo') # returns ['foo'] expect(sequence.parse('abc')).to eq('abc') expect { sequence.parse('') }.to raise_error(Walrat::ParseError) # it makes little sense for the predicate to follows a choice operator so we don't test that end it 'should be able to follow a "not predicate" with other parslets or combinations' do # this is equivalent to "foo" followed by any three characters other than "bar" sequence = 'foo' & 'bar'.not! & /.../ expect(sequence.parse('fooabc')).to eq(['foo', 'abc']) expect { sequence.parse('foobar') }.to raise_error(Walrat::ParseError) expect { sequence.parse('foo') }.to raise_error(Walrat::ParseError) expect { sequence.parse('') }.to raise_error(Walrat::ParseError) end it 'should be able to include a "not predicate" when using a repetition operator' do # basic example sequence = ('foo' & 'bar'.not!).one_or_more expect(sequence.parse('foo')).to eq('foo') expect(sequence.parse('foofoobar')).to eq('foo') expect(sequence.parse('foofoo')).to eq(['foo', 'foo']) expect { sequence.parse('bar') }.to raise_error(Walrat::ParseError) expect { sequence.parse('foobar') }.to raise_error(Walrat::ParseError) # variation: note that greedy matching alters the behaviour sequence = ('foo' & 'bar').one_or_more & 'abc'.not! expect(sequence.parse('foobar')).to eq(['foo', 'bar']) expect(sequence.parse('foobarfoobar')).to eq([['foo', 'bar'], ['foo', 'bar']]) expect { sequence.parse('foobarabc') }.to raise_error(Walrat::ParseError) end it 'should be able to use regular expression shortcuts in conjunction with predicates' do # match "foo" as long as it's not followed by a digit sequence = 'foo' & /\d/.not! expect(sequence.parse('foo')).to eq('foo') expect(sequence.parse('foobar')).to eq('foo') expect { sequence.parse('foo1') }.to raise_error(Walrat::ParseError) # match "word" characters as long as they're not followed by whitespace sequence = /\w+/ & /\s/.not! expect(sequence.parse('foo')).to eq('foo') expect { sequence.parse('foo ') }.to raise_error(Walrat::ParseError) end end describe 'omitting tokens from the output using the "skip" method' do it 'should be able to skip quotation marks delimiting a string' do sequence = '"'.skip & /[^"]+/ & '"'.skip expect(sequence.parse('"hello world"')).to eq('hello world') # note this is returning a ParserState object end it 'should be able to skip within a repetition expression' do sequence = ('foo'.skip & /\d+/).one_or_more expect(sequence.parse('foo1...')).to eq('1') expect(sequence.parse('foo1foo2...')).to eq(['1', '2']) # only returns 1 expect(sequence.parse('foo1foo2foo3...')).to eq(['1', '2', '3']) # only returns 1 end it 'should be able to skip commas separating a list' do # closer to real-world use: a comma-separated list sequence = /\w+/ & (/\s*,\s*/.skip & /\w+/).zero_or_more expect(sequence.parse('a')).to eq('a') expect(sequence.parse('a, b')).to eq(['a', 'b']) expect(sequence.parse('a, b, c')).to eq(['a', ['b', 'c']]) expect(sequence.parse('a, b, c, d')).to eq(['a', ['b', 'c', 'd']]) # again, using the ">>" operator sequence = /\w+/ >> (/\s*,\s*/.skip & /\w+/).zero_or_more expect(sequence.parse('a')).to eq('a') expect(sequence.parse('a, b')).to eq(['a', 'b']) expect(sequence.parse('a, b, c')).to eq(['a', 'b', 'c']) expect(sequence.parse('a, b, c, d')).to eq(['a', 'b', 'c', 'd']) end end describe 'using the shorthand ">>" pseudo-operator' do it 'should be able to chain the operator multiple times' do # comma-separated words followed by comma-separated digits sequence = /[a-zA-Z]+/ >> (/\s*,\s*/.skip & /[a-zA-Z]+/).zero_or_more >> (/\s*,\s*/.skip & /\d+/).one_or_more expect(sequence.parse('a, 1')).to eq(['a', '1']) expect(sequence.parse('a, b, 1')).to eq(['a', 'b', '1']) expect(sequence.parse('a, 1, 2')).to eq(['a', '1', '2']) expect(sequence.parse('a, b, 1, 2')).to eq(['a', 'b', '1', '2']) # same, but enclosed in quotes sequence = '"'.skip & /[a-zA-Z]+/ >> (/\s*,\s*/.skip & /[a-zA-Z]+/).zero_or_more >> (/\s*,\s*/.skip & /\d+/).one_or_more & '"'.skip expect(sequence.parse('"a, 1"')).to eq(['a', '1']) expect(sequence.parse('"a, b, 1"')).to eq(['a', 'b', '1']) expect(sequence.parse('"a, 1, 2"')).to eq(['a', '1', '2']) expect(sequence.parse('"a, b, 1, 2"')).to eq(['a', 'b', '1', '2']) # alternative construction of same sequence = /[a-zA-Z]+/ >> (/\s*,\s*/.skip & /[a-zA-Z]+/).zero_or_more & /\s*,\s*/.skip & /\d+/ >> (/\s*,\s*/.skip & /\d+/).zero_or_more expect(sequence.parse('a, 1')).to eq(['a', '1']) expect(sequence.parse('a, b, 1')).to eq(['a', 'b', '1']) expect(sequence.parse('a, 1, 2')).to eq(['a', '1', '2']) expect(sequence.parse('a, b, 1, 2')).to eq(['a', 'b', '1', '2']) end end
require 'rails_helper' feature 'application header' do let(:client) { create :user, role: :client } let(:admin) { create :user, role: :admin } # describe 'when no user is logged in' do # before do # visit root_path # end # it 'shows the brand' do # expect(page).to have_css '.brand' # end # it 'does not show links' do # expect(page).not_to have_css '.links' # end # end # describe 'when user is logged in as an administrator' do # before do # sign_in_as admin # visit root_path # end # it 'shows the brand' do # expect(page).to have_css '.brand' # end # it 'shows a signout link' do # expect(page).to have_link 'Sign out' # end # it 'shows an administration link' do # expect(page).to have_link 'Admin' # end # end # describe 'when user is logged in as an client' do # before do # sign_in_as client # visit root_path # end # it 'shows the brand' do # expect(page).to have_css '.brand' # end # it 'shows a signout link' do # expect(page).to have_link 'Sign out' # end # it 'does not show an administration link' do # expect(page).not_to have_link 'Admin' # end # end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe UpdateGLYCMembers, type: :service do let(:pdf) { file_fixture('update_glyc_members/GLYC_Roster.pdf') } let(:service) { described_class.new(pdf) } it 'updates the stored members' do create(:glyc_member) service.update expect(GLYCMember.all).to contain_exactly( having_attributes(email: 'member1@example.com'), having_attributes(email: 'member2@example.com') ) end end
#!/bin/env ruby # frozen_string_literal: true require 'rubygems' COIN_SIDES = %w[heads tails].freeze #### # Name: fifty_fifty # Description: returns true or false # Arguments: none # Response: boolean #### def fifty_fifty [true, false].sample end #### # Name: one_third # Description: returns true approximately one third of the time. # Arguments: none # Response: boolean #### def one_third [false, true, false].sample end #### # Name: coin_flip # Description: returns heads or tails string. # Arguments: none # Response: string #### def coin_flip COIN_SIDES.sample end
class PiecesController < ApplicationController before_action :load_batiment def index @pieces = @batiment.pieces.all end def new @batiment = Batiment.find(params[:batiment_id]) @piece = @batiment.pieces.new end def create @piece = @batiment.pieces.new(piece_params) if @piece.save flash[:notice] = "Pièce créée!" redirect_to batiment_path(@batiment) else flash[:alert] = "Pièce non créée!" redirect_to batiment_path(@batiment) end end def show @piece = Piece.find(params[:id]) @batiment = @piece.batiment end def edit @piece = Piece.find(params[:id]) end def update @piece = Piece.find(params[:id]) if @piece.update_attributes(piece_params) flash[:notice] = "Pièce modifiée!" end redirect_to batiment_piece_path(@batiment,@piece) end def delete @piece = Piece.find(params[:id]) end def destroy piece = Piece.find(params[:id]).destroy flash[:notice] = "Pièce supprimée!" redirect_to batiment_pieces_path(@batiment) end private #pour charger le bâtiment parent après chaque méthode def load_batiment @batiment = Batiment.find(params[:batiment_id]) end #pour create - sécurité def piece_params params.require(:piece).permit(:nom, :numero) end end
class RemoveRegionFromBirds < ActiveRecord::Migration[5.1] def change remove_column :birds, :region end end
class Practice < ApplicationRecord has_one_attached :eyecatch attr_accessor :image def eyecatch=(image) return unless image.present? prefix = image[%r{(image|application)(/.*)(?=\;)}] type = prefix.sub(%r{(image|application)(/)}, '') data = Base64.decode64(image.sub(/data:#{prefix};base64,/, '')) filename = "#{Time.zone.now.strftime('%Y%m%d%H%M%S%L')}.#{type}" File.open("#{Rails.root}/app/assets/images/#{filename}", 'wb') do |f| f.write(data) end eyecatch.detach if eyecatch.attached? eyecatch.attach(io: File.open("#{Rails.root}/app/assets/images/#{filename}"), filename: filename) end end
module MessagesController extend Sinatra::Extension configure do set :webhook_token, ENV['PLIVO_WEBHOOK_TOKEN'] end helpers do def send_message to = params['to'] text = params['text'] @contact = Contact.find(phone_number: to, user_id: @current_user.id) text = substituted_values(text, @contact) if @contact @message = Message.create(type: 'sms', direction: 'out', external_id: nil, from: @current_user.phone_number, to: to, text: text, state: 'pending', seen_at: Time.now) MessageSender.perform_async(@message.id) @message.to_json end def substituted_values(text, contact) text.gsub(/\$\w+/) do |prop| method = prop[1..-1] if contact.methods.map(&:to_s).include? method contact.send(method) else prop end end end def receive_message # Callback for both sent and received messages @message = Message.create(type: params['Type'], direction: 'in', external_id: params['MessageUUID'], from: params['From'], to: params['To'], text: params['Text'], state: 'unknown') # Message from and to are normalized after save @user = User.find(phone_number: @message.to) @contact = Contact.find_or_create(phone_number: @message.from, user_id: @user.id) included = %i[messages unseen_messages_count unresponsive] contact_json = @contact.to_json(include: included) notify(@user.id, 'new_message', contact_json) @message.to_json end end post '/messages' do if @current_user send_message elsif params['token'] == settings.webhook_token receive_message else 403 end end patch '/messages/:id' do return 403 unless @current_user @message = Message.find(id: params['id']) # return 403 unless @current_user.received_messages.include? @message @message.update(seen_at: Time.now) if params['seen_at'] @message.to_json end end
FactoryGirl.define do sequence :den_number do |n| "#{n}" end sequence :rank do |r| ["Tiger", "Wolf", "Bear", "Webelo 1", "Webelo 2"][rand(5)] end factory :den do den_number { FactoryGirl.generate(:den_number) } rank { FactoryGirl.generate(:rank) } leader_name "Karl Smith" leader_email "threadhead@gmail.com" assistant_leader_name "John Bartholomew" assistant_leader_email "threadhead@gmail.com" # pack_id {|pack| pack.association(:pack)} association :pack, :factory => :pack end end
class RenameAccessTokenTable < ActiveRecord::Migration[5.2] def change rename_column :instagram_access_tokens, :encrypted_message, :encrypted_access_token rename_column :instagram_access_tokens, :encrypted_message_iv, :encrypted_access_token_iv end end
module VipUser::VipClient require "#{Rails.root}/lib/Vip_User/VIPUserServicesDriver.rb" class VipClient def initialize(uri_path) @driver = AuthenticationServicePort.new("https://vipuserservices-auth.verisign.com/" + uri_path) @driver.loadproperty("#{Rails.root}/config/vip_auth.properties") end def evaluate_risk(username, ip_address, user_agent, ia_auth_data) request_id = "abcd1234" # requestId on_behalf_of_account_id = nil key_value_pairs = [] req = EvaluateRiskRequestType.new(request_id, on_behalf_of_account_id, username, ip_address, user_agent, ia_auth_data, key_value_pairs) evaluate_risk_result_to_hash(@driver.evaluateRisk(req)) end def deny_risk(username, event_id, ia_auth_data) request_id = "abcd1234" # requestId on_behalf_of_account_id = nil verify_method = nil # verifyMethod remember_device = true # rememberDevice key_value_pairs = [] req = DenyRiskRequestType.new(request_id, on_behalf_of_account_id, username, event_id, verify_method, ia_auth_data, remember_device, key_value_pairs) feedback_risk_result_to_hash(@driver.denyRisk(req)) end def confirm_risk(username, event_id) request_id = "abcd1234" # requestId on_behalf_of_account_id = nil # onBehalfOfAccountId verify_method = nil # verifyMethod key_value_pairs = [] # keyValuePairs req = ConfirmRiskRequestType.new(request_id, on_behalf_of_account_id, username, event_id, verify_method, key_value_pairs) feedback_risk_result_to_hash(@driver.confirmRisk(req)) end def create_user(username) request_id = "abcd1234" # requestId req = CreateUserRequestType.new(request_id, nil, username, nil) convert_endian(@driver.createUser(req)) end def add_credential(username, credential_id, otp) request_id = "abcd1234" # requestId credential_type = CredentialTypeEnum.new() credential_type = "STANDARD_OTP" credential_detail = CredentialDetailType.new(credential_id, credential_type, nil) otp_auth_data = OtpAuthDataType.new(otp, nil) req = AddCredentialRequestType.new(request_id, nil, username, credential_detail, otp_auth_data) convert_endian(@driver.addCredential(req)) end def authenticate_user(username, otp) request_id = "abcd1234" # requestId otp_auth_data = OtpAuthDataType.new(otp, nil) req = AuthenticateUserRequestType.new(request_id, nil, username, nil, otp_auth_data) convert_endian(@driver.authenticateUser(req)) end def evaluate_tr_risk(username, ip_address, user_agent, ia_auth_data, bank_code, dst_account, amount) request_id = "abcd1234" # requestId on_behalf_of_account_id = nil key_value_pairs = [] event_id = nil account_type = AccountType.new() account_type = "BUSINESS" # BUSINESS, CHECKING, OTHER, SAVINGS src_account = Account.new(username, "Bizy", account_type, nil, nil) dst_account = Account.new(dst_account, bank_code, account_type, nil, nil) transaction_type = TransactionType.new() transaction_type = "WIRETRANSFER" # BILLPAYMENT, CHECKREQUEST, ELECTRONICREALTIMEBANKTRANSFER, JOURNALING, OTHER, WIRETRANSFER channel_type = MonetaryTransactionChannelType.new() channel_type = "WEB" # ATM, MOBILE, OTHER, PHONE, TELLER, WEB mt_obj = MonetaryTransactionType.new(src_account, dst_account, event_id, amount, nil, transaction_type, channel_type) req = EvaluateMonetaryTransactionRiskRequestType.new(request_id, on_behalf_of_account_id, username, ip_address, user_agent, ia_auth_data, key_value_pairs, mt_obj) evaluate_tr_risk_result_to_hash(@driver.evaluateMonetaryTransactionRisk(req)) end def deny_tr_risk(username, transaction_id) request_id = "abcd1234" # requestId on_behalf_of_account_id = nil verify_method = nil # verifyMethod is_monetary_transaction = true # isMonetaryTransaction key_value_pairs = [] req = DenyTransactionRiskRequestType.new(request_id, on_behalf_of_account_id, username, transaction_id, is_monetary_transaction, verify_method, key_value_pairs) feedback_risk_result_to_hash(@driver.denyTransactionRisk(req)) end def confirm_tr_risk(username, transaction_id) request_id = "abcd1234" # requestId on_behalf_of_account_id = nil # onBehalfOfAccountId verify_method = nil # verifyMethod is_monetary_transaction = true # isMonetaryTransaction key_value_pairs = [] # keyValuePairs req = ConfirmTransactionRiskRequestType.new(request_id, on_behalf_of_account_id, username, transaction_id, is_monetary_transaction, verify_method, key_value_pairs) feedback_risk_result_to_hash(@driver.confirmTransactionRisk(req)) end private def evaluate_risk_result_to_hash(ret) ret_hash = { 'StatusCode' => convert_endian(ret), 'Message' => ret::statusMessage, 'Risky' => ret::risky, 'RiskScore' => ret::riskScore, 'RiskThreshold' => ret::riskThreshold, 'RiskReason' => ret::riskReason, 'PolicyVersion' => ret::policyVersion, 'EventID' => ret::eventId } if ret::keyValuePairs result_to_hash(ret::keyValuePairs).keys.sort.each do |e| ret_hash.store(e, result_to_hash(ret::keyValuePairs)[e]) end end if (ret::detailMessage) ret_hash.store('ErrorDitail', ret::detailMessage) end return ret_hash end def evaluate_tr_risk_result_to_hash(ret) ret_hash = { 'StatusCode' => convert_endian(ret), 'Message' => ret::statusMessage, 'Risky' => ret::risky, 'RiskScore' => ret::riskScore, 'RiskThreshold' => ret::riskThreshold, 'RiskReason' => ret::riskReason, 'PolicyVersion' => ret::policyVersion, 'TransactionID' => ret::transactionId } if ret::keyValuePairs result_to_hash(ret::keyValuePairs).keys.sort.each do |e| ret_hash.store(e, result_to_hash(ret::keyValuePairs)[e]) end end if (ret::detailMessage) ret_hash.store('ErrorDitail', ret::detailMessage) end return ret_hash end def feedback_risk_result_to_hash(ret) ret_hash = { 'StatusCode' => convert_endian(ret), 'Message' => ret::statusMessage, } if ret::keyValuePairs result_to_hash(ret::keyValuePairs).keys.sort.each do |e| ret_hash.store(e, result_to_hash(ret::keyValuePairs)[e]) end end if (ret::detailMessage) ret_hash.store('ErrorDitail', ret::detailMessage) end return ret_hash end # エンディアン変換 def convert_endian(ret) rcbyte = [ret::status].pack("H*") rcbyte = rcbyte.unpack("N*") rc = rcbyte.pack("N*") return rc end def result_to_hash(result) ret_hash = {} result.each do |e| ret_hash[e.key] = e.value end ret_hash end end end
class ChangeRefereeMatchToRefereeMatchIdForRedCards < ActiveRecord::Migration[5.1] def change remove_column :red_cards, :referee_match, :integer add_column :red_cards, :referee_match_id, :integer end end
FactoryBot.define do factory :transfer_marker do reporting_relationship { create :reporting_relationship } body { "i am a transfer marker #{SecureRandom.hex(17)}" } end end
class Activity < ActiveRecord::Base belongs_to :user has_many :events validates :user_id, presence: true validates :activity_name, presence: true end
require 'rubygems' require 'gtk3' load 'Sauvegarde.rb' load 'Highscore.rb' # Cette classe gère tout l'aspect graphique du début de l'application, elle utilise le DP singleton # @param nom_joueur [String] le nom du joueur # @param window [GTK::Window] la fenetre actuelle # @param @builder [GTK::Builder] le constructeur contenant toutes les fenetres .glade # @param @menu [Menu] l'instance de la classe Menu class Menu @nom_joueur @window @@builder ||= Gtk::Builder.new @@menu ||= Menu.new # retourne l'instance du Menu (singleton) # @return [Menu] le singleton menu def Menu.getInstance() return @@menu end #Gère la première page de l'application # @return [void] def afficheDemarrage() if(@window != nil) then @window.hide() end @@builder.add_from_file("../Glade/Menu.glade") #récupère Menu.glade #déclaration de toute la page et des boutons @window = @@builder.get_object("fn_debut") bt_ok = @@builder.get_object("bt_ok") bt_ok.signal_connect('clicked') { |_widget| onClickDemarrage() } @window.signal_connect("key-press-event") do |w, e| onClickDemarrage() if Gdk::Keyval.to_name(e.keyval) == "Return" end @window.signal_connect('destroy') { |_widget| exit!() } @window.show_all() Gtk.main() #exécution du GTK end # Traitement à effectuer apès avoir entré son pseudo et valider # @note on traite puis affecte la variable globale du pseudo et enfin on change de fenêtre # @return [void] def onClickDemarrage() ch_pseudo= @@builder.get_object("ch_pseudo") @nom_joueur=ch_pseudo.text().gsub('/',"") @nom_joueur = 'sans_nom' if @nom_joueur == '' afficheChoixMode(nil) end # Affichage du menu du jeu # @param nom_j [String] le nom du joueur si cette page est appelée autrement que par cette classe # @return [void] def afficheChoixMode(nom_j) if(nom_j != nil) @nom_joueur = nom_j end if(@window != nil) @window.hide() end @@builder = Gtk::Builder.new @@builder.add_from_file("../Glade/Menu-titre.glade") #déclaration de toute la page et des boutons @window = @@builder.get_object("fn_menu") @window.signal_connect('destroy') { |_widget| exit!() } bt_quit = @@builder.get_object("bt_quit") bt_quit.signal_connect('clicked') { |_widget| exit!() } bt_nv = @@builder.get_object("bt_nv") bt_nv.signal_connect('clicked') { |_widget| afficheChoixPlateau() } bt_cs = @@builder.get_object("bt_cs") bt_cs.signal_connect('clicked') { |_widget| afficheChoixSauvegarde() } stack_box_fac = @@builder.get_object("stack_box_fac") stack_box_int = @@builder.get_object("stack_box_int") stack_box_dif = @@builder.get_object("stack_box_dif") #récupèration des highscores grâce à la classe Highscore getHighscore = Highscore.recuperer_ds_fichier Sauvegarde.sauvegarde_highscore(getHighscore) getHighscore = Highscore.recuperer_ds_fichier classement_fac = getHighscore.classement_facile classement_int = getHighscore.classement_moyen classement_dif = getHighscore.classement_difficile #génération dynamique des classement if(classement_fac) i = 1 for score in classement_fac do label_fac = Gtk::Label.new(i.to_s + '. ' + score) stack_box_fac.add(label_fac) i+=1 end end if(classement_int) i = 1 for score in classement_int do label_int = Gtk::Label.new(i.to_s + '. ' + score) stack_box_int.add(label_int) i+=1 end end if(classement_dif) i = 1 for score in classement_dif do label_dif = Gtk::Label.new(i.to_s + '. ' + score) stack_box_dif.add(label_dif) i+=1 end end @window.show_all Gtk.main() end # Affichage des différents mode de jeu # @return [void] def afficheChoixPlateau() if(@window != nil) @window.hide() end @@builder.add_from_file("../Glade/Selection_niveau.glade") #déclaration de toute la page et des boutons @window = @@builder.get_object("fn_selec") bouton_retour = @@builder.get_object("btn_retour") bouton_retour.signal_connect('clicked'){ |_widget| afficheChoixMode(nil)} @window.signal_connect('destroy') { |_widget| exit!() } lab_pseu = @@builder.get_object("lab_pseu") lab_pseu.set_text("Pseudo : " + @nom_joueur) box_fac_haut = @@builder.get_object("box_fac_haut") box_fac_bas = @@builder.get_object("box_fac_bas") i = 0 files_fac = Dir["../data/template/Facile/*.png"] #génération des images cliquables de chaques maps faciles disponibles if files_fac.length() <= 8 then toggles_fac = [] for n in files_fac do toggles_fac[i] = Gtk::Button.new() image = Gtk::Image.new(:file => n) toggles_fac[i].signal_connect('clicked') { |_widget| btn_to_img(toggles_fac, files_fac,_widget) } toggles_fac[i].add(image) if(i <= 3) then box_fac_haut.add(toggles_fac[i]) else box_fac_bas.add(toggles_fac[i]) end i += 1 end end box_int_haut = @@builder.get_object("box_int_haut") box_int_bas = @@builder.get_object("box_int_bas") i = 0 files_int = Dir["../data/template/Intermediaire/*.png"] #génération des images cliquables de chaques maps intermédiaires disponibles if files_int.length() <= 8 then toggles_int = [] for n in files_int do toggles_int[i] = Gtk::Button.new() image = Gtk::Image.new(:file => n) toggles_int[i].signal_connect('clicked') { |_widget| btn_to_img(toggles_int, files_int,_widget) } toggles_int[i].add(image) if(i <= 3) then box_int_haut.add(toggles_int[i]) else box_int_bas.add(toggles_int[i]) end i += 1 end end box_dif_haut = @@builder.get_object("box_dif_haut") box_dif_bas = @@builder.get_object("box_dif_bas") i = 0 files_dif = Dir["../data/template/Difficile/*.png"] #génération des images cliquables de chaques maps difficiles disponibles if files_dif.length() <= 8 then toggles_dif = [] for n in files_dif do toggles_dif[i] = Gtk::Button.new() image = Gtk::Image.new(:file => n) toggles_dif[i].signal_connect('clicked') { |_widget| btn_to_img(toggles_dif, files_dif, _widget)} toggles_dif[i].add(image) if(i <= 3) then box_dif_haut.add(toggles_dif[i]) else box_dif_bas.add(toggles_dif[i]) end i += 1 end end @window.show_all Gtk.main() end # Affiche toutes les sauvegardes du joueur *nom_joueur* # @note on lui permet de charger ou de supprimer chaque sauvegarde def afficheChoixSauvegarde() if(@window != nil) @window.hide() end @@builder.add_from_file("../Glade/Charger_sauvegarde.glade") #déclaration de toute la page et des boutons @window = @@builder.get_object("fn_save") bouton_retour = @@builder.get_object("btn_retour") bouton_retour.signal_connect('clicked'){ |_widget| afficheChoixMode(nil)} @window.signal_connect('destroy') { |_widget| exit!() } scrl = @@builder.get_object("scrl_save") file = Dir["../data/save/"+@nom_joueur+"/*.snurikabe"] box_save = @@builder.get_object("box_liste_save") box_save.margin = 20 bouton_charger = [] bouton_supprimer = [] i = 0 #affichage si le joueur n'a aucune sauvegarde if(file.length == 0) label = Gtk::Label.new("Vous n'avez aucune sauvegarde.") box_save.add(label) else #créer une box contenant deux boutons, charger et supprimer, pour chaque sauvegarde for n in file do hbox = Gtk::Box.new(:horizontal, 0) hbox.margin = 20 nom_save = n.split("/") label = Gtk::Label.new("Sauvegarde du " + nom_save[4].split(".")[0]) bouton_charger[i] = Gtk::Button.new(:label => "Charger") bouton_supprimer[i] = Gtk::Button.new(:label => "Supprimer") bouton_charger[i].signal_connect('clicked'){|_widget| charger_save(bouton_charger, file, _widget)} bouton_supprimer[i].signal_connect('clicked'){|_widget| supprimer_save(bouton_supprimer, file, _widget)} hbox.pack_start(label,:expand => true, :fill => false, :padding => 0) hbox.add(bouton_charger[i]) hbox.add(bouton_supprimer[i]) box_save.add(hbox) i+=1 end end @window.show_all Gtk.main() end # Permet de charger une sauvegarde # @param boutons [Array[GTK::Button]], la liste des boutons et donc des sauvegarde # @param files [Array[String]], la liste des fichiers # @param btn [GTK::Button], le bouton qui a été pressé # @return [void] def charger_save(boutons, files, btn) j = 0 for b in boutons do if(b == btn) @window.hide() jeu = Sauvegarde.charger_sauvegarde(files[j]) jeu.affiche_toi() end end end # Permet de supprimer une sauvegarde # @param boutons [Array[GTK::Button]], la liste des boutons et donc des sauvegarde # @param files [Array[String]], la liste des fichiers # @param btn [GTK::Button], le bouton qui a été pressé # @return [void] def supprimer_save(boutons, files, btn) j = 0 for b in boutons do if(b == btn) File.delete(files[j]) if File.exist?(files[j]) end end afficheChoixSauvegarde() end # Permet de récupérer la map correspondante au bouton sélectionner # @param toggles [Array[GTK::Button]], la liste des boutons et donc des sauvegarde # @param files [Array[String]], la liste des fichiers # @param btn [GTK::Button], le bouton qui a été pressé # @return [void] def btn_to_img(toggles, files, btn) j = 0 for b in toggles do if(btn == b) executer_map(files[j]) end j+=1 end end # Executer la map correspondante # @param file_image [String], le lien vers l'image correspondante au niveau # @return [void] def executer_map(file_image) file_niveau = file_image[0..file_image.length-4] file_niveau +="nurikabe" @window.hide() jeu = Jeu.new(plateau: Sauvegarde.charger_template(file_niveau), nom_joueur: @nom_joueur, temps_de_jeu: 0) puts jeu.affiche_toi end end menu = Menu.new() menu.afficheDemarrage()
# frozen_string_literal: true # a video model containing youtube urls class Video < ApplicationRecord has_many :user_videos has_many :users, through: :user_videos belongs_to :tutorial def default_video? title == 'Tutorial Has No Videos' end validates_presence_of :position end
# frozen_string_literal: true require "spec_helper" module Decidim module Opinions describe VoteOpinion do describe "call" do let(:opinion) { create(:opinion) } let(:current_user) { create(:user, organization: opinion.component.organization) } let(:command) { described_class.new(opinion, current_user) } context "with normal conditions" do it "broadcasts ok" do expect { command.call }.to broadcast(:ok) end it "creates a new vote for the opinion" do expect do command.call end.to change(OpinionVote, :count).by(1) end end context "when the vote is not valid" do before do # rubocop:disable RSpec/AnyInstance allow_any_instance_of(OpinionVote).to receive(:valid?).and_return(false) # rubocop:enable RSpec/AnyInstance end it "broadcasts invalid" do expect { command.call }.to broadcast(:invalid) end it "doesn't create a new vote for the opinion" do expect do command.call end.to change(OpinionVote, :count).by(0) end end context "when the threshold have been reached" do before do expect(opinion).to receive(:maximum_votes_reached?).and_return(true) end it "broadcasts invalid" do expect { command.call }.to broadcast(:invalid) end end context "when the threshold have been reached but opinion can accumulate more votes" do before do expect(opinion).to receive(:maximum_votes_reached?).and_return(true) expect(opinion).to receive(:can_accumulate_supports_beyond_threshold).and_return(true) end it "creates a new vote for the opinion" do expect do command.call end.to change(OpinionVote, :count).by(1) end end end end end end
class Page < ActiveRecord::Base extend FriendlyId friendly_id :title, :use => :slugged validates :title, :presence => true, :uniqueness => true end # == Schema Information # # Table name: pages # # id :integer not null, primary key # title :string(255) # content :text # slug :string(255) # created_at :datetime # updated_at :datetime #
require_relative "../../db/chores/populator" namespace :populate do namespace :ncr do desc "Populate the database with identical NCR data" task uniform: :environment do Populator.new.uniform_ncr_data end desc "Populate the database with random NCR data" task random: :environment do Populator.new.random_ncr_data end desc "Populate database for a user based on email passed in" task :for_user, [:email] => [:environment] do |_t, args| Populator.new.ncr_data_for_user(email: args[:email]) end end end
class Api::BookmarksController < Api::ApiController before_action :set_bookmark, only: [:show, :edit, :update, :destroy] # /bookmarks?user_id=6 def index bookmarks = Bookmark.where(user_id: params[:user_id]) if bookmarks.count == 0 bookmarks = Bookmark.all end # bookmarks = Bookmark.includes(:user, :record) render json: bookmarks.to_json(only: :id, include: { user: { only: [:id, :nickname, :email] }, record: { only: [:id, :audio_file_name, :audio_content_type] } }) end def show # bookmarks = Bookmark[:user_id].eq(params[:user_id]).and(Bookmark[:record_id].matches(params[:user_id])) bookmarks = Bookmark.find(user_id: params[:user_id]) # bookmarks = Bookmark.includes(:user, :record) render json: bookmarks.to_json(only: :id, include: { user: { only: [:id, :nickname, :email] }, record: { only: [:id, :audio_file_name, :audio_content_type] } }) end # GET /bookmarks/new def new @bookmark = Bookmark.new end # GET /bookmarks/1/edit def edit end # POST /bookmarks # POST /bookmarks.json def create @bookmark = Bookmark.new(bookmark_params) respond_to do |format| if @bookmark.save # format.html { redirect_to @bookmark, notice: 'Bookmark was successfully created.' } format.json { render :show, status: :created, location: @bookmark } else # format.html { render :new } format.json { render json: @bookmark.errors, status: :unprocessable_entity } end end end # PATCH/PUT /bookmarks/1 # PATCH/PUT /bookmarks/1.json def update respond_to do |format| if @bookmark.update(bookmark_params) # format.html { redirect_to @bookmark, notice: 'Bookmark was successfully updated.' } format.json { render :show, status: :ok, location: @bookmark } else # format.html { render :edit } format.json { render json: @bookmark.errors, status: :unprocessable_entity } end end end # DELETE /bookmarks/1 # DELETE /bookmarks/1.json def destroy @bookmark.destroy respond_to do |format| # format.html { redirect_to bookmarks_url, notice: 'Bookmark was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_bookmark @bookmark = Bookmark.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def bookmark_params params.require(:bookmark).permit(:user_id, :record_id) end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require_relative 'data_for_seed' # My db:seed puts "Cleaning database..." if Rails.env.development? Cocktail.destroy_all Dose.destroy_all Ingredient.destroy_all end puts "Now #{Cocktail.all.size} cocktails and #{Ingredient.all.size} ingredients and #{Dose.all.size} doses in database !" puts "Adding all ingredients from data_for_seed..." INGREDIENTS.each{ |ingredient| Ingredient.create(name: ingredient)} puts "Adding random cocktails..." 20.times do cocktail = Cocktail.new() until cocktail.save cocktail = Cocktail.new(name: COCKTAILS.sample) end 4.times do dose = Dose.new until dose.save dose = Dose.new(description: DESCRIPTION.sample, cocktail: cocktail, ingredient: Ingredient.all.sample ) end end end puts "Now #{Cocktail.all.size} cocktails and #{Ingredient.all.size} ingredients and #{Dose.all.size} doses in database !"
# frozen_string_literal: true require 'logging' require 'bolt/node/errors' module Bolt module Transport class Docker < Base class Connection def initialize(target) raise Bolt::ValidationError, "Target #{target.safe_name} does not have a host" unless target.host @target = target @logger = Logging.logger[target.safe_name] @docker_host = @target.options['service-url'] @logger.debug("Initializing docker connection to #{@target.safe_name}") end def connect # We don't actually have a connection, but we do need to # check that the container exists and is running. output = execute_local_docker_json_command('ps') index = output.find_index { |item| item["ID"] == @target.host || item["Names"] == @target.host } raise "Could not find a container with name or ID matching '#{@target.host}'" if index.nil? # Now find the indepth container information output = execute_local_docker_json_command('inspect', [output[index]["ID"]]) # Store the container information for later @container_info = output[0] @logger.debug { "Opened session" } true rescue StandardError => e raise Bolt::Node::ConnectError.new( "Failed to connect to #{@target.safe_name}: #{e.message}", 'CONNECT_ERROR' ) end # Executes a command inside the target container # # @param command [Array] The command to run, expressed as an array of strings # @param options [Hash] command specific options # @option opts [String] :interpreter statements that are prefixed to the command e.g `/bin/bash` or `cmd.exe /c` # @option opts [Hash] :environment A hash of environment variables that will be injected into the command # @option opts [IO] :stdin An IO object that will be used to redirect STDIN for the docker command def execute(*command, options) command.unshift(options[:interpreter]) if options[:interpreter] # Build the `--env` parameters envs = [] if options[:environment] options[:environment].each { |env, val| envs.concat(['--env', "#{env}=#{val}"]) } end command_options = [] # Need to be interactive if redirecting STDIN command_options << '--interactive' unless options[:stdin].nil? command_options << '--tty' if options[:tty] command_options.concat(envs) unless envs.empty? command_options << container_id command_options.concat(command) @logger.debug { "Executing: exec #{command_options}" } stdout_str, stderr_str, status = execute_local_docker_command('exec', command_options, options[:stdin]) # The actual result is the exitstatus not the process object status = status.nil? ? -32768 : status.exitstatus if status == 0 @logger.debug { "Command returned successfully" } else @logger.info { "Command failed with exit code #{status}" } end stdout_str.force_encoding(Encoding::UTF_8) stderr_str.force_encoding(Encoding::UTF_8) # Normalise line endings stdout_str.gsub!("\r\n", "\n") stderr_str.gsub!("\r\n", "\n") [stdout_str, stderr_str, status] rescue StandardError @logger.debug { "Command aborted" } raise end def write_remote_file(source, destination) @logger.debug { "Uploading #{source}, to #{destination}" } _, stdout_str, status = execute_local_docker_command('cp', [source, "#{container_id}:#{destination}"]) raise "Error writing file to container #{@container_id}: #{stdout_str}" unless status.exitstatus.zero? rescue StandardError => e raise Bolt::Node::FileError.new(e.message, 'WRITE_ERROR') end def write_remote_directory(source, destination) @logger.debug { "Uploading #{source}, to #{destination}" } _, stdout_str, status = execute_local_docker_command('cp', [source, "#{container_id}:#{destination}"]) raise "Error writing directory to container #{@container_id}: #{stdout_str}" unless status.exitstatus.zero? rescue StandardError => e raise Bolt::Node::FileError.new(e.message, 'WRITE_ERROR') end def mkdirs(dirs) _, stderr, exitcode = execute('mkdir', '-p', *dirs, {}) if exitcode != 0 message = "Could not create directories: #{stderr}" raise Bolt::Node::FileError.new(message, 'MKDIR_ERROR') end end def make_tempdir tmpdir = @target.options.fetch('tmpdir', container_tmpdir) tmppath = "#{tmpdir}/#{SecureRandom.uuid}" stdout, stderr, exitcode = execute('mkdir', '-m', '700', tmppath, {}) if exitcode != 0 raise Bolt::Node::FileError.new("Could not make tempdir: #{stderr}", 'TEMPDIR_ERROR') end tmppath || stdout.first end def with_remote_tempdir dir = make_tempdir yield dir ensure if dir _, stderr, exitcode = execute('rm', '-rf', dir, {}) if exitcode != 0 @logger.warn("Failed to clean up tempdir '#{dir}': #{stderr}") end end end def write_remote_executable(dir, file, filename = nil) filename ||= File.basename(file) remote_path = File.join(dir.to_s, filename) write_remote_file(file, remote_path) make_executable(remote_path) remote_path end def make_executable(path) _, stderr, exitcode = execute('chmod', 'u+x', path, {}) if exitcode != 0 message = "Could not make file '#{path}' executable: #{stderr}" raise Bolt::Node::FileError.new(message, 'CHMOD_ERROR') end end private # Converts the JSON encoded STDOUT string from the docker cli into ruby objects # # @param stdout_string [String] The string to convert # @return [Object] Ruby object representation of the JSON string def extract_json(stdout_string) # The output from the docker format command is a JSON string per line. # We can't do a direct convert but this helper method will convert it into # an array of Objects stdout_string.split("\n") .reject { |str| str.strip.empty? } .map { |str| JSON.parse(str) } end # rubocop:disable Layout/LineLength # Executes a Docker CLI command # # @param subcommand [String] The docker subcommand to run e.g. 'inspect' for `docker inspect` # @param command_options [Array] Additional command options e.g. ['--size'] for `docker inspect --size` # @param redir_stdin [IO] IO object which will be use to as STDIN in the docker command. Default is nil, which does not perform redirection # @return [String, String, Process::Status] The output of the command: STDOUT, STDERR, Process Status # rubocop:enable Layout/LineLength def execute_local_docker_command(subcommand, command_options = [], redir_stdin = nil) env_hash = {} # Set the DOCKER_HOST if we are using a non-default service-url env_hash['DOCKER_HOST'] = @docker_host unless @docker_host.nil? command_options = [] if command_options.nil? docker_command = [subcommand].concat(command_options) # Always use binary mode for any text data capture_options = { binmode: true } capture_options[:stdin_data] = redir_stdin unless redir_stdin.nil? stdout_str, stderr_str, status = Open3.capture3(env_hash, 'docker', *docker_command, capture_options) [stdout_str, stderr_str, status] end # Executes a Docker CLI command and parses the output in JSON format # # @param subcommand [String] The docker subcommand to run e.g. 'inspect' for `docker inspect` # @param command_options [Array] Additional command options e.g. ['--size'] for `docker inspect --size` # @return [Object] Ruby object representation of the JSON string def execute_local_docker_json_command(subcommand, command_options = []) command_options = [] if command_options.nil? command_options = ['--format', '{{json .}}'].concat(command_options) stdout_str, _stderr_str, _status = execute_local_docker_command(subcommand, command_options) extract_json(stdout_str) end # The full ID of the target container # # @return [String] The full ID of the target container def container_id @container_info["Id"] end # The temp path inside the target container # # @return [String] The absolute path to the temp directory def container_tmpdir '/tmp' end end end end end
# Processes have exit codes. # Every process that exits does so with a numeric exit code (0-255) # Kernel#exit exit # Custom exit code exit 133 # Invoke block at exit at_exit { puts 'Exit' } exit # Exists with status code 1 (default) and doesn't invoke at_exit exit! # Exit a process unsuccessfully abort "Something went wrong." # An unhandled exception will also end a process; exit code will be 1 raise 'hell'
require 'sumac' # make sure it exists describe Sumac::RemoteEntry do def build_remote_entry future = instance_double('QuackConcurrency::Future') allow(QuackConcurrency::Future).to receive(:new).and_return(future) remote_entry = Sumac::RemoteEntry.new end # ::new example do future = instance_double('QuackConcurrency::Future') allow(QuackConcurrency::Future).to receive(:new).with(no_args).and_return(future) remote_entry = Sumac::RemoteEntry.new expect(remote_entry.instance_variable_get(:@future)).to be(future) expect(remote_entry).to be_a(Sumac::RemoteEntry) end # #cancel example do remote_entry = build_remote_entry future = remote_entry.instance_variable_get(:@future) expect(future).to receive(:raise).with(Sumac::ClosedObjectRequestBrokerError) remote_entry.cancel end # #get example do remote_entry = build_remote_entry future = remote_entry.instance_variable_get(:@future) value = double expect(future).to receive(:get).with(no_args).and_return(value) expect(remote_entry.get).to be(value) end # #set example do remote_entry = build_remote_entry value = double future = remote_entry.instance_variable_get(:@future) expect(future).to receive(:set).with(value) remote_entry.set(value) end end
# frozen_string_literal: true require 'test_helper' class ViewTest < ActiveSupport::TestCase setup do @workspace = workspaces(:one) @view = views(:one) end test "to_s should return name" do view = View.new(name: "View Foo") assert_equal "View Foo", view.to_s end test "duplicate should return new view" do assert_difference('@workspace.views.count') do new_view = @view.duplicate assert_equal "View1-duplicate", new_view.to_s end end end
class Post < ActiveRecord::Base validates :title, presence: true, length: {minimum: 5} validates :body, presence: true has_many :comments, as: :commentable end
class AddReferencesToTaskcomments < ActiveRecord::Migration[6.0] def change add_reference :task_comments, :boss, foreign_key: true add_reference :task_comments, :child_task, foreign_key: true end end
require 'rails_helper' RSpec.describe "offers/edit", type: :view do before(:each) do @offer = assign(:offer, Offer.create!( :nombre => "MyText", :descripción => "MyText", :imagen => "MyString" )) end it "renders the edit offer form" do render assert_select "form[action=?][method=?]", offer_path(@offer), "post" do assert_select "textarea#offer_nombre[name=?]", "offer[nombre]" assert_select "textarea#offer_descripción[name=?]", "offer[descripción]" assert_select "input#offer_imagen[name=?]", "offer[imagen]" end end end
class CreateSmoothies < ActiveRecord::Migration[5.2] def change create_table :smoothies, :options => 'ENGINE=InnoDB ROW_FORMAT=DYNAMIC' do |t| t.string :smoothie_name t.string :smoothie_image t.text :comment t.datetime :created_at t.datetime :updated_at t.datetime :deleted_at t.integer :user_id t.timestamps end end end
module CDI module V1 class SimpleGameItemSerializer < ActiveModel::Serializer root false attributes :id, :game_related_item_id, :word, :related_word, :has_uploaded_image?, :image_url, :has_uploaded_related_image?, :related_image_url, :created_at, :updated_at def filter(keys) blacklist_keys = scope.try(:student?) ? [:related_word] : [] keys - blacklist_keys end end end end
class CreateItems < ActiveRecord::Migration[5.2] def change create_table :items do |t| t.string :name, null: false t.text :description, null:false t.integer :price, null:false t.integer :brand_id t.integer :condition_id, null:false t.integer :delivery_fee_id, null:false t.integer :shipping_method_id, null:false t.integer :ship_from_area_id, null:false t.integer :shipping_day_id, null:false t.references :category, null:false, foreign_key: true t.references :size, foreign_key: true t.references :user, null:false,foreign_key: true t.boolean :item_status, default: false, null: false t.timestamps end end end
# DashboardManifest tells Administrate which dashboards to display class DashboardManifest # `DASHBOARDS` # a list of dashboards to display in the side navigation menu # # These are all of the rails models that we found in your database # at the time you installed Administrate. # # To show or hide dashboards, add or remove the model name from this list. # Dashboards returned from this method must be Rails models for Administrate # to work correctly. DASHBOARDS = [ :users, :localities, :surveys ] ROOT_DASHBOARD = DASHBOARDS.first end
# frozen_string_literal: true require 'rails_helper' RSpec.describe UserChannel, type: :channel do let!(:current_user) { create(:user) } describe 'User' do it 'should subscribe' do stub_connection current_user: current_user expect do subscribe(id: current_user.id) end.to have_broadcasted_to('activity').exactly(:once).with(action: 'user_update_status', id: current_user.id, status: 'online') expect(subscription).to be_confirmed current_user.reload expect(current_user.status).to eq('online') unsubscribe expect do unsubscribe end.to have_broadcasted_to('activity').exactly(:once).with(action: 'user_update_status', id: current_user.id, status: 'offline') current_user.reload expect(current_user.status).to eq('offline') end end end
# terminal: rspec --tag @dropdown describe 'Dropdown list', :dropdown do it 'specific simple item' do visit 'https://training-wheels-protocol.herokuapp.com/dropdown' select('Loki', from: 'dropdown') sleep 3 end it 'specific item by find' do visit 'https://training-wheels-protocol.herokuapp.com/dropdown' drop = find('.avenger-list') drop.find('option', text: 'Bucky').select_option sleep 3 end it 'any item', :sample do visit 'https://training-wheels-protocol.herokuapp.com/dropdown' drop = find('.avenger-list') drop.all('option').sample.select_option # Sample -> Select a random element sleep 4 end end
require "application_responder" class ApplicationController < ActionController::Base self.responder = ApplicationResponder respond_to :html protect_from_forgery rescue_from CarrierWave::DropBox::Error do |exception| redirect_to new_dropbox_sessions_url(:return_url => request.referer) end def after_sign_in_path_for(resource) if resource.class == User documents_url else admin_url end end before_filter :check_user_payments def check_user_payments return unless current_user if !current_user.trial? and !current_user.paypal_recurring_profile_token redirect_to edit_user_registration_url unless params[:controller] == "devise/registrations" end end before_filter :check_uploader_storage def check_uploader_storage return unless current_user if current_user.use_dropbox? DocumentUploader.storage(:dropbox) if !current_user.dropbox_access_token && controller_path != 'dropbox_sessions' redirect_to new_dropbox_sessions_url end else DocumentUploader.storage(CarrierWave::Uploader::Base.storage) end DocumentUploader.dropbox_access_token = current_user.dropbox_access_token end rescue Xeroizer::OAuth::TokenInvalid redirect_to new_xero_session_url end
class EventsController < ApplicationController before_action :set_event, only: [:show, :edit, :update, :destroy] before_action :logged_in_user, only: [:new, :create, :edit, :update, :destroy] def search address = GeocodedAddress.new(params['user_geo']) # find events within the search radius, and filter on the chosen criteria @events = Event.within(params[:radius].to_i, :origin => [ address.latitude , address.longitude ]) .where('activity_id=?', params['activity_id']) .where('start_date >= ?', DateTime.now) .order('start_date') .paginate(page: params[:page]) end def get_event_types @event_types = EventType.where("activity_id = ?", params[:activity_id]) respond_to do |format| format.js end end def index @events = Event.paginate(page: params[:page]) end def show end def new @event = Event.new end def edit @event.start_date = @event.start_date.strftime("%m/%d/%Y") end def create @event = Event.new(event_params) @event.owner_id = current_user.id respond_to do |format| if @event.save if @event.is_urgent? client = Twilio::REST::Client.new( ENV["TWILIO_ACCOUNT_SID"], ENV["TWILIO_AUTH_TOKEN"] ) subscribers = User.within(50, :origin => [@event.latitude, @event.longitude]) .where('receive_urgent_notifications=true') .where('phone is not null') .where('id in (select user_id from activities_users where activity_id = ' + @event.activity_id.to_s + ')') subscribers.each do |sub| client.messages.create( to: sub.phone, from: ENV["TWILIO_PHONE_NUMBER"], body: APP_NAME + " urgent notification -- " + @event.title + ". " + "Contact " + current_user.name + " at " + current_user.phone + "." ) end end format.html { flash[:success] = "Event was successfully created." redirect_to root_path } format.json { render :show, status: :created, location: @event } else format.html { render :new } format.json { render json: @event.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @event.update(event_params) format.html { flash[:success] = "Event was successfully updated." redirect_to root_path } format.json { render :show, status: :ok, location: @event } else format.html { render :edit } format.json { render json: @event.errors, status: :unprocessable_entity } end end end def destroy @event.destroy respond_to do |format| format.html { flash[:success] = "Event was successfully deleted." redirect_to events_path } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_event @event = Event.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def event_params params.require(:event).permit(:activity_id, :event_type_id, :venue_id, :title, :subtitle, :description, :details, :price, :restrictions, :info_url, :registration_url, :start_date, :start_time, :recurrence, :latitude, :longitude, :is_urgent) end def fix_date_format(raw_date_string) date_buffer = raw_date_string.split('/') return date_buffer[2] + '-' + date_buffer[0] + '-' + date_buffer[1] end # Confirms a logged-in user. def logged_in_user unless logged_in? store_location flash[:danger] = "You have to be a registered user to do that. It's easy to <a href='/signup' style='color:black;'>join</a>!" redirect_to login_url end end end
# The input array should be sorted. This is when we use binary search. It is much faster than the linear search. module Kata module Algorithms module Searching class BinarySearch < Struct.new(:array, :value_to_search_for) def search return nil if array.nil? || array.empty? || value_to_search_for.nil? result = nil i = 0 j = array.size - 1 while i <= j m = (i + j) / 2 if array[m] == value_to_search_for return m elsif array[m] > value_to_search_for j = m - 1 elsif array[m] < value_to_search_for i = m + 1 end end result end end end end end
module Jsonapi class TurnResource < JSONAPI::Resource attributes :hole_number, :par, :strokes has_one :scorecard def self.updatable_fields(_) super - [:holes_count] end def self.creatable_fields(_) super - [:holes_count] end paginator :none end end
class Admins::PortfoliosController < ApplicationController before_filter :authenticate_admin! layout "admins" def index @portfolios = Portfolio.all respond_to do |format| format.html end end def new @portfolio = Portfolio.new @portfolio.photos.build respond_to do |format| format.html end end def create @portfolio = Portfolio.new(params[:portfolio]) @portfolio.placement = Portfolio.count if @portfolio.save respond_to do |format| format.html { redirect_to(admins_portfolio_path(@portfolio), :notice => 'Misc was successfully created.') } end else redirect_to new_admins_portfolio_path end end def show @portfolio = Portfolio.where(:id => params[:id]).last if @portfolio respond_to do |format| format.html end else redirect_to admins_portfolios_path end end def edit @portfolio = Portfolio.where(:id => params[:id]).last end def update @portfolio = Portfolio.where(:id => params[:id]).last respond_to do |format| if @portfolio.update_attributes(params[:portfolio]) format.html { redirect_to admins_portfolios_path, notice: 'Misc was successfully updated.' } else format.html { render action: "edit" } end end end def destroy portfolio = Portfolio.where(:id => params[:id]).last if portfolio portfolio.photos.each do |photo| photo.destroy end portfolio.destroy end respond_to do |format| format.html { redirect_to admins_portfolios_path } end end end
require 'space' describe Space do describe '.all' do it '.all method exists' do expect(Space).to respond_to(:all) end it 'returns a space' do add_row_to_places_test_database connection = PG.connect(dbname: 'makersbnb_test') expect(Space.all[0].name).to eq "Shed" expect(Space.all[0]).to be_a Space expect(Space.all[0].owner).to eq "Joe" expect(Space.all[0].availability).to eq "t" expect(Space.all[0].description).to eq "Lots of spiders" expect(Space.all[0].date).to eq "2020-11-10" expect(Space.all[0].price).to eq "2" end end describe '.create' do it '.create a new space' do space = Space.create(name: 'Shed', owner: 'Joe', availability: true, description: 'Lots of spiders', date: '2020-11-10', price: 2) persisted_data = PG.connect(dbname: 'makersbnb_test').query("SELECT * FROM spaces WHERE id = #{space.id};") expect(space).to be_a Space expect(space.id).to eq persisted_data.first['id'] expect(space.name).to eq 'Shed' expect(space.owner).to eq 'Joe' expect(space.availability).to eq "t" expect(space.description).to eq 'Lots of spiders' expect(space.date).to eq "2020-11-10" expect(space.price).to eq "2" end end end
class EventType < ActiveRecord::Base belongs_to :activity validates_presence_of :name end
class CreateOnlineExamGroupsQuestions < ActiveRecord::Migration def self.up create_table :online_exam_groups_questions do |t| t.references :online_exam_group t.references :online_exam_question t.decimal :mark, :precision=>15, :scale=>4 t.text :answer_ids t.integer :position t.timestamps end end def self.down drop_table :online_exam_groups_questions end end
# GET & HANDLES DATA FROM YELP API class YelpHandler def self.get_by_coordinates(lat, long) client = setup_client data = client.search_by_coordinates({latitude: lat, longitude: long}, limit: 10, radius_filter: 100, sort: 1) output = data.businesses.map do |business| { name: business.name,categories: business.categories,rating: business.rating, coordinates: {lat: business.location.coordinate.latitude, long: business.location.coordinate.longitude}, url: business.url } end return output end def self.get_by_business_name(name) client = setup_client data = client.business(name) output = data.businesses.map do |business| { name: business.name,categories: business.categories,rating: business.rating, location: {lat: business.location.coordinate.latitude, long: business.location.coordinate.longitude}, url: business.url } end return output end private def self.setup_client client = Yelp::Client.new( { consumer_key: ENV['YELP_CONSUMER_KEY'], consumer_secret: ENV['YELP_CONSUMER_SECRET'], token: ENV['YELP_TOKEN'], token_secret: ENV['YELP_TOKEN_SECRET'] } ) client end end
# # Cookbook Name:: redis # Recipe:: source # # Author:: Gerhard Lazu (<gerhard@lazu.co.uk>) # # Copyright 2011, Gerhard Lazu # # 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 "build-essential" user "redis" do comment "Redis Administrator" system true shell "/bin/false" end directory node[:redis][:datadir] do owner "redis" group "redis" mode 0755 recursive true end unless `redis-server -v 2> /dev/null`.include?(node[:redis][:version]) # ensuring we have this directory directory "#{node[:redis][:basedir]}/src" remote_file "#{node[:redis][:basedir]}/src/redis-#{node[:redis][:version]}.tar.gz" do source node[:redis][:source] checksum node[:redis][:checksum] action :create_if_missing end bash "Compiling Redis v#{node[:redis][:version]} from source" do cwd "#{node[:redis][:basedir]}/src" code %{ tar zxf redis-#{node[:redis][:version]}.tar.gz cd redis-#{node[:redis][:version]} && make && make install } end end file node[:redis][:logfile] do owner "redis" group "redis" mode 0644 action :create_if_missing backup false end template node[:redis][:config] do source "redis.conf.erb" owner "redis" group "redis" mode 0644 backup false end execute "echo 1 > /proc/sys/vm/overcommit_memory" do not_if "[ $(cat /proc/sys/vm/overcommit_memory) -eq 1 ]" end include_recipe "redis::init"
class User < ActiveRecord::Base belongs_to :tribe has_many :happenings has_many :rsvps def name "#{first_name} #{last_name}" end def profile_incomplete? home_zip.blank? || work_zip.blank? end def self.from_omniauth(auth) where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user| user.provider = auth.provider user.uid = auth.uid user.first_name = auth.info.first_name user.last_name = auth.info.last_name user.img = auth.info.image user.oauth_token = auth.credentials.token user.oauth_expires_at = Time.at(auth.credentials.expires_at) user.save! end end end
# Require any additional compass plugins here. # Set this to the root of your project when deployed: http_path = "/" css_dir = "Assets/css" sass_dir = "Assets/sass" images_dir = "Assets/images" javascripts_dir = "AsiCommon/Scripts" # You can select your preferred output style here (can be overridden via the command line): # output_style = :expanded or :nested or :compact or :compressed # To enable relative paths to assets via compass helper functions. Uncomment: # relative_assets = true # This line hides the comments that display the Sass file lines in comments. # Comment out if line comments are wanted. line_comments = false # Enabling sourcemaps allows for easier Sass debugging in Chrome # See https://developers.google.com/chrome-developer-tools/docs/css-preprocessors # If sourcemaps are needed, comment this line back in # sourcemap = true # increase the decimal precision to 10 decimal places Sass::Script::Number.precision = 10 # The following code moves the theme CSS files to their respective folders # See http://css-tricks.com/compass-compiling-and-wordpress-themes/ # Theme CSS files must be named 99-[ThemeName].css for this to work properly require 'fileutils' on_stylesheet_saved do |file| if File.exists?(file) && File.basename(file).start_with?("99-") puts "Moving: #{file}" FileUtils.mv(file, File.dirname(file) + "/../../App_Themes/" + File.basename(file)[3..-5] + "/" + File.basename(file)) end end
class Image < ActiveRecord::Base self.table_name = 'uploads' has_many :sections, through: :upload_sections attr_accessible :title, :size, :filetype, :file, :section_id mount_uploader :file, ImageUploader def self.is_image where("filetype LIKE 'image%'") end end
require 'spec_helper' describe HomeController do context 'subdomains' do before { set_subdomain } context 'GET :index' do it 'renders the :index template' do get :index expect(response).to render_template(:index) end end end context 'custom domains' do before { set_custom_domain } context 'GET :index' do it 'renders the :index template' do get :index expect(response).to render_template(:index) end end end end
require 'rails_helper' RSpec.describe 'supply_teachers/suppliers/master_vendors.html.erb' do let(:suppliers) { [] } before do assign(:suppliers, suppliers) end it 'displays the number of suppliers' do render expect(rendered).to have_text(/0 agencies/) end end
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module MobileCenterApi # # Microsoft Visual Studio Mobile Center API # class RepositoryConfigurations # # Creates and initializes a new instance of the RepositoryConfigurations class. # @param client service class for accessing basic functionality. # def initialize(client) @client = client end # @return [MobileCenterClient] reference to the MobileCenterClient attr_reader :client # # Returns the repository build configuration status of the app # # @param owner_name [String] The name of the owner # @param app_name [String] The name of the application # @param include_inactive [Boolean] Include inactive configurations if none are # active # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Object] operation results. # def list(owner_name, app_name, include_inactive = nil, custom_headers = nil) response = list_async(owner_name, app_name, include_inactive, custom_headers).value! response.body unless response.nil? end # # Returns the repository build configuration status of the app # # @param owner_name [String] The name of the owner # @param app_name [String] The name of the application # @param include_inactive [Boolean] Include inactive configurations if none are # active # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRest::HttpOperationResponse] HTTP response information. # def list_with_http_info(owner_name, app_name, include_inactive = nil, custom_headers = nil) list_async(owner_name, app_name, include_inactive, custom_headers).value! end # # Returns the repository build configuration status of the app # # @param owner_name [String] The name of the owner # @param app_name [String] The name of the application # @param include_inactive [Boolean] Include inactive configurations if none are # active # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_async(owner_name, app_name, include_inactive = nil, custom_headers = nil) fail ArgumentError, 'owner_name is nil' if owner_name.nil? fail ArgumentError, 'app_name is nil' if app_name.nil? request_headers = {} path_template = 'v0.1/apps/{owner_name}/{app_name}/repo_config' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'owner_name' => owner_name,'app_name' => app_name}, query_params: {'includeInactive' => include_inactive}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 || status_code == 400 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = { required: false, serialized_name: 'parsed_response', type: { name: 'Sequence', element: { required: false, serialized_name: 'RepoConfigElementType', type: { name: 'Composite', class_name: 'RepoConfig' } } } } result.body = @client.deserialize(result_mapper, parsed_response, 'result.body') rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end # Deserialize Response if status_code == 400 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = MobileCenterApi::Models::ValidationErrorResponse.mapper() result.body = @client.deserialize(result_mapper, parsed_response, 'result.body') rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Configures the repository for build # # @param owner_name [String] The name of the owner # @param app_name [String] The name of the application # @param repo_url [String] The repository url # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Object] operation results. # def update(owner_name, app_name, repo_url, custom_headers = nil) response = update_async(owner_name, app_name, repo_url, custom_headers).value! response.body unless response.nil? end # # Configures the repository for build # # @param owner_name [String] The name of the owner # @param app_name [String] The name of the application # @param repo_url [String] The repository url # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRest::HttpOperationResponse] HTTP response information. # def update_with_http_info(owner_name, app_name, repo_url, custom_headers = nil) update_async(owner_name, app_name, repo_url, custom_headers).value! end # # Configures the repository for build # # @param owner_name [String] The name of the owner # @param app_name [String] The name of the application # @param repo_url [String] The repository url # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def update_async(owner_name, app_name, repo_url, custom_headers = nil) fail ArgumentError, 'owner_name is nil' if owner_name.nil? fail ArgumentError, 'app_name is nil' if app_name.nil? fail ArgumentError, 'repo_url is nil' if repo_url.nil? repo = RepoInfo.new unless repo_url.nil? repo.repo_url = repo_url end request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Serialize Request request_mapper = MobileCenterApi::Models::RepoInfo.mapper() request_content = @client.serialize(request_mapper, repo, 'repo') request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'v0.1/apps/{owner_name}/{app_name}/repo_config' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'owner_name' => owner_name,'app_name' => app_name}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:post, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 || status_code == 400 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = MobileCenterApi::Models::SuccessResponse.mapper() result.body = @client.deserialize(result_mapper, parsed_response, 'result.body') rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end # Deserialize Response if status_code == 400 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = MobileCenterApi::Models::ValidationErrorResponse.mapper() result.body = @client.deserialize(result_mapper, parsed_response, 'result.body') rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Removes the configuration for the respository # # @param owner_name [String] The name of the owner # @param app_name [String] The name of the application # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Object] operation results. # def remove(owner_name, app_name, custom_headers = nil) response = remove_async(owner_name, app_name, custom_headers).value! response.body unless response.nil? end # # Removes the configuration for the respository # # @param owner_name [String] The name of the owner # @param app_name [String] The name of the application # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRest::HttpOperationResponse] HTTP response information. # def remove_with_http_info(owner_name, app_name, custom_headers = nil) remove_async(owner_name, app_name, custom_headers).value! end # # Removes the configuration for the respository # # @param owner_name [String] The name of the owner # @param app_name [String] The name of the application # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def remove_async(owner_name, app_name, custom_headers = nil) fail ArgumentError, 'owner_name is nil' if owner_name.nil? fail ArgumentError, 'app_name is nil' if app_name.nil? request_headers = {} path_template = 'v0.1/apps/{owner_name}/{app_name}/repo_config' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'owner_name' => owner_name,'app_name' => app_name}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:delete, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 || status_code == 400 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = MobileCenterApi::Models::SuccessResponse.mapper() result.body = @client.deserialize(result_mapper, parsed_response, 'result.body') rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end # Deserialize Response if status_code == 400 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = MobileCenterApi::Models::ValidationErrorResponse.mapper() result.body = @client.deserialize(result_mapper, parsed_response, 'result.body') rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end end end
class AddTypeToEvent < ActiveRecord::Migration def change add_column :events, :event_type, :integer, :default => 0 add_column :events, :to_do_id, :integer add_column :events, :request_map_id, :integer end end
require "base64" class RootMe < Botpop::Plugin include Cinch::Plugin FloatRegexp = "\d+(\.\d+)?" match(/!ep1 (\w+)/, use_prefix: false, method: :start_ep1) match(/!ep2 (\w+)/, use_prefix: false, method: :start_ep2) match(/^(#{FloatRegexp}) ?\/ ?(#{FloatRegexp})$/, use_prefix: false, method: :play_ep1) match(/^(\d+) ?\/ ?(\d+)$/, use_prefix: false, method: :play_ep1) match(/^(\w+)$/, use_prefix: false, method: :play_ep2) ENABLED = config['enable'].nil? ? false : config['enable'] CONFIG = config def start_ep1 m, botname bot = User(botname) bot.send "!ep1" end def start_ep2 m, botname bot = User(botname) bot.send "!ep2" end def play_ep1 m, n1, n2 r = n1.to_f**(0.5) * n2.to_f str = "!ep1 -rep #{r.round 2}" puts str m.reply str # response will be logged by the bot, check the log end def play_ep2 m, b64 r = Base64.decode64(b64) str = "!ep2 -rep #{r}" puts str m.reply str # response will be logged by the bot, check the log end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :students, only: [:new, :create, :edit, :update, :show] resources :school_classes, only: [:new, :create, :edit, :update, :show] end # could have done it like this: # Rails.application.routes.draw do # resources :students, except: [:destroy, :index] # resources :school_classes, except: [:destroy, :index] # end
class Preference < ActiveRecord::Base include Lolita::Configuration has_and_belongs_to_many :profiles end
class CreateLeaseItems < ActiveRecord::Migration def change create_table :leasingx_lease_items do |t| t.string :name t.string :description t.decimal :hourly_rate, :precision => 7, :scale => 2 t.boolean :active, :default => true t.integer :discount, :default => 0 t.integer :input_by_id t.timestamps end end end
class AddAdminUserIdAndVisibilityToPhoto < ActiveRecord::Migration[5.2] def change add_column :photos, :admin_user_id, :integer add_column :photos, :visibility, :integer Photo.update_all(admin_user_id: 1) Photo.find_each do |photo| if photo.id % 2 == 0 photo.update!(visibility: 0) else photo.update!(visibility: 1) end end end end
class Gag < ActiveRecord::Base attr_accessible :title, :image, :votes_up, :imagelink, :videolink #:ratio, :title, :user_id, :votes, :votes_up, :image has_attached_file :image, dependent: :destroy, :styles => { :medium => "300x300>", :thumb => "100x100>" } validates_attachment_content_type :image, :content_type => /^image\/(png|gif|jpeg)/ belongs_to :user validates :user_id, presence: true validates :title, presence: true, length: { maximum: 50 }, uniqueness: { case_sensitive: false } has_many :comments, foreign_key: "gag_id", dependent: :destroy validate :at_least_one validate :videolink_format validate :imagelink_format def at_least_one if [self.image, self.imagelink, self.videolink].compact.size == 0 errors[:base] << ("You must add a Gag") end end def videolink_format if self.videolink? if (self.videolink.include?("youtube") && self.videolink.include?("v="))==false errors[:base] << ("Invalid video link") else self.videolink="http://www.youtube.com/embed/"+self.videolink[self.videolink.index("v=")+2, self.videolink.length] end end end def imagelink_format if self.imagelink? if( self.imagelink.include?(".gif") || self.imagelink.include?(".png") || self.imagelink.include?(".jpg") || self.imagelink.include?(".jpeg") )==false errors[:base] << ("Invalid image link") end end end #gaglike has_many :gaglikes, foreign_key: "liked_id", dependent: :destroy has_many :gagreports, foreign_key: "reported_id", dependent: :destroy default_scope order: 'gags.created_at DESC' def self.from_users_followed_by(user) followed_user_ids = "SELECT followed_id FROM relationships WHERE follower_id = :user_id" where("user_id IN (#{followed_user_ids}) OR user_id = :user_id", user_id: user.id) end end
# -*- coding: utf-8 -*- MindpinSidebar::Base.config do # example # # rule :admin do # nav :students, :name => '学生', :url => '/admin/students' do # controller :'admin/students' # subnav :student_info, :name => '学生信息', :url => '/admin/students/info' do # controller :'admin/student_infos' # end # end # end # rule [:teacher,:student] do # nav :media_resources, :name => '我的文件夹', :url => '/file' do # controller :media_resources, :except => [:xxx] # controller :file_entities, :only => [:upload] # end # end rule :admin do group :default, :name => '教务功能…' do nav :home, :name => '首页', :url => '/admin' do controller :'admin/index' end nav :teaching_plans, :name => '教学计划', :url => '/admin/teaching_plans' do controller :'admin/teaching_plans' end nav :students, :name => '学籍管理', :url => '/admin/students' do controller :'admin/students' end nav :teams, :name => '班级管理', :url => '/admin/teams' do controller :'admin/teams' end nav :courses, :name => '课程管理', :url => '/admin/courses' do controller :'admin/courses' controller :'admin/course_teachers' end nav :course_score_records, :name => '成绩管理', :url => '/admin/course_score_records' do controller :'admin/course_score_records' end nav :teachers, :name => '教师管理', :url => '/admin/teachers' do controller :'admin/teachers' end nav :course_surveys, :name => '课堂教学评价', :url => '/admin/course_surveys' do controller :'admin/course_surveys' end nav :categories, :name => '资源分类管理', :url => '/admin/categories' do controller :'admin/categories' end nav :announcements, :name => '公告', :url => '/admin/announcements' do controller :'admin/announcements' end end end # ------------------------- # 教师 rule :teacher do group :resources, :name => '教师功能…' do nav :dashboard, :name => '教学工作台', :url => '/dashboard' do controller :index, :only => :dashboard subnav :dashboard, :name => '信息概览', :url => '/dashboard' do controller :index, :only => :dashboard end subnav :homeworks, :name => '布置的作业和实践', :url => '/homeworks' do controller :homeworks controller :homework_assigns end subnav :course_surveys, :name => '在线调查', :url => '/course_surveys' do controller :course_surveys end subnav :questions, :name => '在线问答', :url => '/questions' do controller :questions end end nav :'teaching-info', :name => '教学信息', :url => '/teachers' do subnav :teachers, :name => '教师浏览', :url => '/teachers' do controller :teachers, :only => :index end subnav :students, :name => '学生浏览', :url => '/students' do controller :students, :only => :index end subnav :courses, :name => '课程浏览', :url => '/courses' do controller :courses, :only => [:index,:show] end subnav :couse_subscriptions, :name => '订阅的课程', :url => '/courses/subscriptions' do controller :courses, :only => :subscriptions end end nav :'media-resources', :name => '媒体资源', :url => '/file' do controller :media_resources subnav :my_resources, :name => '我的文件夹', :url => '/file' do controller :media_resources end subnav :media_shares, :name => '收到的共享', :url => '/media_shares' do controller :media_shares end subnav :public_resources, :name => '公共资源库', :url => '/public_resources' do controller :public_resources end end nav :course, :name => '课程', :url => '/courses/curriculum' do subnav :curriculum, :name => '我的课程表', :url => '/courses/curriculum' do controller :courses, :only => :curriculum end end nav :notice, :name => '系统通知', :url => '/announcements' do controller :announcements subnav :announcements, :name => '通知', :url => '/announcements' do controller :announcements end subnav :comments, :name => '收到的评论', :url => '/comments/received' do controller :comments end end end end # ------------------ # 学生 rule :student do group :resources, :name => '学生功能…' do nav :media_resources, :name => '媒体资源', :url => '/file' do subnav :my_resources, :name => '我的文件夹', :url => '/file' do controller :media_resources end subnav :media_shares, :name => '收到的共享', :url => '/media_shares' do controller :media_shares end subnav :public_resources, :name => '公共资源库', :url => '/public_resources' do controller :public_resources end end nav :dashboard, :name => '我的工作台', :url => '/dashboard' do controller :index, :only => :dashboard subnav :dashboard, :name => '信息概览', :url => '/dashboard' do controller :index, :only => :dashboard end subnav :students, :name => '学生浏览', :url => '/students' do controller :students, :only => :index end subnav :teachers, :name => '老师浏览', :url => '/teachers' do controller :teachers, :only => :index end subnav :homeworks, :name => '我的作业和实践', :url => '/homeworks' do controller :homeworks end subnav :course_surveys, :name => '在线调查', :url => '/course_surveys' do controller :course_surveys end subnav :questions, :name => '在线问答', :url => '/questions' do controller :questions end subnav :mentor_students, :name => '导师双向选择', :url => '/mentor_students' do controller :mentor_students end end nav :course, :name => '课程', :url => '/courses/curriculum' do subnav :curriculum, :name => '我的课程表', :url => '/courses/curriculum' do controller :courses, :only => :curriculum end subnav :couses, :name => '课程浏览', :url => '/courses' do controller :courses, :only => [:index,:show] end subnav :couse_subscriptions, :name => '订阅的课程', :url => '/courses/subscriptions' do controller :courses, :only => :subscriptions end end nav :notice, :name => '系统通知', :url => '/announcements' do controller :announcements subnav :announcements, :name => '通知', :url => '/announcements' do controller :announcements end subnav :comments, :name => '收到的评论', :url => '/comments/received' do controller :comments end end end end end
namespace :oai do desc "Harvest records from OAI providers" task :harvest => :environment do if ENV['ID'] provider = Provider.find(ENV['ID']) if provider.first_consumption print "Consuming #{provider.endpoint_url} for first time: " count = provider.first_consume! print "#{count} records" print "\n" else print "Consuming #{provider.endpoint_url}: " count = provider.consume! print "#{count} records" print "\n" end else Provider.all.select { |x| Time.now > x.next_harvest_at }.each do |provider| if provider.first_consumption print "Consuming #{provider.endpoint_url} for first time: " count = provider.first_consume! print "#{count} records" print "\n" else print "Consuming #{provider.endpoint_url}: " print "all" count = provider.consume! print "#{count} records" print "\n" end end end end end
class ChangeColumnFilms < ActiveRecord::Migration[6.1] def change add_column :films, :author, :string add_column :films, :description, :string add_column :films, :status, :integer add_column :films, :time, :integer end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :reservation do reservation_from "2014-07-17 04:55:37" reservation_to "2014-07-17 04:55:37" notes "MyText" user nil no_of_people 1 end end
class LogEntriesController < ApplicationController before_filter :authenticate_user! before_filter :find_activity_log before_filter :find_log_entry, only: [:show, :edit, :update, :destroy] before_filter :build_favorites def new # log_entry = @activity_log.log_entries.where(date: params[:date]).first # log_entry.destroy if log_entry @log_entry = @activity_log.build_log_entry(params[:date], 8) @log_entry.build_activities end def create @log_entry = @activity_log.log_entries.build(params[:log_entry]) if @log_entry.save flash[:success] = "Log entry has been created." redirect_to [@activity_log, @log_entry] else render :new end end def show @activities = @log_entry.activities.order(:activity_category_id) end def edit @activities = @log_entry.activities.order(:activity_category_id) end def update if @log_entry.update_attributes(params[:log_entry]) flash[:success] = "Log entry has been updated." redirect_to [@activity_log, @log_entry] else render :edit end end def destroy @log_entry.destroy flash[:notice] = "Log entry has been deleted." redirect_to [@activity_log.survey, @activity_log] end private def find_activity_log @activity_log = ActivityLog.find(params[:activity_log_id]) rescue ActiveRecord::RecordNotFound flash[:alert] = "The record you were looking" + " for could not be found." redirect_to surveys_path end def find_log_entry @log_entry = LogEntry.find(params[:id]) rescue ActiveRecord::RecordNotFound flash[:alert] = "The record you were looking" + " for could not be found." redirect_to [@activity_log.survey, @activity_log] end def build_favorites @favorite_activities = current_user.favorite_activities @favorite_activities += @log_entry.activity_ids_with_hours if @log_entry end end
class ElasticSearch < DebianFormula url 'https://github.com/downloads/elasticsearch/elasticsearch/elasticsearch-0.17.1.tar.gz' homepage 'http://www.elasticsearch.org' md5 '439002f5f0e7d213d2e27b166fb87d87' source 'https://github.com/mobz/elasticsearch-head.git' name 'elasticsearch' version '0.17.1' section 'database' description 'You know, for Search' build_depends \ 'sun-java6-jdk' depends \ 'sun-java6-jre' def build rm_f Dir["bin/*.bat"] mv 'bin/plugin', 'bin/elasticsearch-plugin' inreplace %w[ bin/elasticsearch bin/elasticsearch-plugin ] do |s| s.gsub! %{ES_HOME=`dirname "$SCRIPT"`/..}, 'ES_HOME=/usr/share/elasticsearch/' end inreplace 'bin/elasticsearch.in.sh' do |s| s << "\n" s << "# System-wide settings\n" s << "pidfile=/var/run/elasticsearch.pid\n" #s << "ES_JAVA_OPTS=-Des.config=/etc/elasticsearch/elasticsearch.yml\n" end inreplace "config/elasticsearch.yml" do |s| s.gsub! "#cluster:\n# name: elasticsearch", <<-EOS.undent cluster: name: escluster path: logs: /var/log/elasticsearch data: /var/lib/elasticsearch EOS end end def install (prefix/'bin').install Dir['bin/elasticsearch{,-plugin}'] (share/'elasticsearch').install Dir['{bin/elasticsearch.in.sh,lib,*.*}'] (share/'elasticsearch/web').install Dir[builddir/'elasticsearch-head.git/*'] ln_s '../../../etc/elasticsearch', share/'elasticsearch/config' (etc/'elasticsearch').install Dir['config/*'] %w( run log/elasticsearch lib/elasticsearch ).each { |path| (var+path).mkpath } end end
# frozen_string_literal: true class EventsController < ApplicationController layout false $adminBOOLEAN = 0 def index @households = Household.all @events = Event.order('name ASC') if $adminBOOLEAN == 1 render('index') else redirect_to(controller: 'member_view', action: 'index') end end def show @event = Event.find(params[:id]) end def new @event = Event.new if $adminBOOLEAN == 1 render('new') else redirect_to(controller: 'member_view', action: 'index') end end def create @event = Event.new(event_params) @event.save flash[:added] = "you have added #{@event.name}" redirect_to(events_path) end def edit @event = Event.find(params[:id]) if $adminBOOLEAN == 1 render('edit') else redirect_to(controller: 'member_view', action: 'index') end end def update @event = Event.find(params[:id]) if @event.update(event_params) redirect_to(event_path(@event)) else render('edit') end end def delete @event = Event.find(params[:id]) if $adminBOOLEAN == 1 render('delete') else redirect_to(controller: 'member_view', action: 'index') end end def destroy @event = Event.find(params[:id]) @event.destroy redirect_to(events_path) end def login redirect_to(controller: 'login', action: 'index') end def logout $adminBOOLEAN = 0 redirect_to(controller: 'member_view', action: 'index') end private def event_params params.require(:event).permit(:name, :description, :location, :date, :time, :points, :link) end end
require "spec_helper" describe Reflect::Permalink do describe "when creating a permalink" do it "should return a permalink" do slug = Reflect::Permalink.new("my super slug") slug.should eq("my-super-slug") end end end
require 'rspec' require_relative '../lib/node' describe Attribute do let(:attr_class) { Attribute.new :class, 'some-class' } context 'attribute instance' do it 'return attribute name' do expect(attr_class.name).to eq :class end it 'return attribute value' do expect(attr_class.value).to eq 'some-class' end end end
class EditHashtags < ActiveRecord::Migration[5.2] def change remove_column :hashtags, :article_id end end
require 'rake/testtask' namespace :test do namespace :unit do Rake::TestTask.new :string_calculator do |t| t.test_files = FileList['test/string_calculator_test.rb'] end end namespace :spec do Rake::TestTask.new :string_calculator do |t| t.test_files = FileList['spec/string_calculator_spec.rb'] end Rake::TestTask.new :prime_factors do |t| t.test_files = FileList['spec/prime_factors_spec.rb'] end desc 'Run all specification tests' task :all => %w(test:spec:string_calculator test:spec:prime_factors) do # running all specs end end end
require 'yaml' module Env class << self attr_accessor :redis end module Redis CONFIG_FILE = "config/redis.yml" def self.start! configs = YAML.load_file(File.join(File.dirname(__FILE__), '..', '..', CONFIG_FILE)) redis_configs = configs['redis'] Env.redis = ::Redis.new redis_configs end end end
class LikesController < ApplicationController before_action :authenticate_user! before_action :set_user before_action :set_likeable def create if (liked = current_user.likeable_like(@likeable)).present? liked.destroy! end @like = Like.new() @like.is_upvote = params[:is_upvote] @like.user = @user @like.likeable = @likeable @like.save redirect_to :back end def update @like = Like.find(params[:id]) @like.update(like_params) @like.save redirect_to :back end def destroy @like = Like.find(params[:id]) @like.destroy! redirect_to :back end private def set_user @user = current_user end def likeable_type %w(article comment).detect{ |type| params["#{type}_id"].present? } end def likeable_id params["#{likeable_type}_id"] end def set_likeable @likeable = likeable_type.camelize.constantize.find(likeable_id) end end
require 'lita/handlers/enhance/node_index' module Lita module Handlers class Enhance class IpEnhancer < Enhancer IP_REGEX = /(?:[0-9]{1,3}\.){3}[0-9]{1,3}/ def initialize(redis) super @nodes_by_ip = NodeIndex.new(redis, 'nodes_by_ip') end def index(ip, node) @nodes_by_ip[ip] = node end def enhance!(string, level) substitutions = [] string.scan(IP_REGEX) do match = Regexp.last_match ip = match.to_s range = (match.begin(0)...match.end(0)) node = @nodes_by_ip[ip] if node new_text = render(node, level) substitutions << Substitution.new(range, new_text) end end substitutions end def to_s "#{self.class.name}: #{@nodes_by_ip.size} IPs indexed" end end end end end
module Veeqo class Order < Base include Veeqo::Actions::Base def create(channel_id:, customer_id:, delivery_method_id:, **attributes) required_attributes = { channel_id: channel_id, customer_id: customer_id, delivery_method_id: delivery_method_id, } create_resource(order: required_attributes.merge(attributes)) end def update(order_id, attributes = {}) update_resource(order_id, attributes) end private def end_point "orders" end end end
require 'rails_helper' RSpec.describe AddressForm, :address_form do subject { AddressForm.new(attributes_for(:type_address, :shipping)) } context 'validation' do %i(firstname lastname address zipcode phone city country_id).each do |attribute_name| it { should validate_presence_of(attribute_name) } end end %i(firstname lastname city).each do |attribute_name| it { should validate_length_of(attribute_name).is_at_most(50) } end it { should validate_length_of(:zipcode).is_at_most(10) } context 'phone' do it { should validate_length_of(:phone).is_at_least(9) } it { should validate_length_of(:phone).is_at_most(15) } it 'format' do subject.phone = '+380AAAAA42342' is_expected.not_to be_valid end end end
class AddColumnsToPublications2 < ActiveRecord::Migration def change add_column :publications, :publication_type_id, :integer add_column :publications, :alt_title, :text add_column :publications, :publanguage, :text add_column :publications, :extid, :text add_column :publications, :links, :text add_column :publications, :url, :text add_column :publications, :category_hsv_local, :text add_column :publications, :keywords, :text add_column :publications, :pub_notes, :text add_column :publications, :journal, :text add_column :publications, :sourcetitle, :text add_column :publications, :sourcevolume, :text add_column :publications, :sourceissue, :text add_column :publications, :sourcepages, :text add_column :publications, :project, :text add_column :publications, :eissn, :text add_column :publications, :extent, :text add_column :publications, :publisher, :text add_column :publications, :place, :text add_column :publications, :series, :text add_column :publications, :artwork_type, :text add_column :publications, :dissdate, :text add_column :publications, :disstime, :text add_column :publications, :disslocation, :text add_column :publications, :dissopponent, :text add_column :publications, :patent_applicant, :text add_column :publications, :patent_application_number, :text add_column :publications, :patent_application_date, :text add_column :publications, :patent_number, :text add_column :publications, :patent_date, :text end end
class MatchesController < ApplicationController before_action :login_user # respond_to :json # GET api/matches def index #return JSON of a user's matches profile information # render :text => "Match index" #THIS SHOULD PROBABLY BE MOVED TO MODEL # user = User.find(1) # match_ids = [] # user.first_user_matches.each do |match| # match_ids << match.second_user_id # end # user.second_user_matches.each do |match| # match_ids << match.first_user_id # end # @matches = [] # match_ids.each do |id| # @matches << User.find(id) # end # render 'index' if current_user @matches = current_user.matches render 'index' else end # user = User.find(2) #need to pull user_id from Devise # respond_with user.matches end # GET api/matches/:id def show # Here is a new comment render :text => "Match show page" # This should lead into chat mode #return information needed for chat interface # respond_with Match.find(params[:id]) end end
describe PlayerCharacter, type: :model do describe 'validations' do describe 'name' do it 'is not valid if no name' do expect(PlayerCharacter.new.valid?).to eq(false) end it 'is valid if name' do expect(PlayerCharacter.new(name: 'foobar').valid?).to eq(true) end end describe 'sheet url' do it 'is not valid if bad url' do expect(PlayerCharacter.new(name: 'foobar', sheet_url: 'alert(\'foobar\')').valid?).to eq(false) end it 'is valid if OK url' do expect(PlayerCharacter.new(name: 'foobar', sheet_url: 'http://www.example.com').valid?).to eq(true) end it 'is valid if blank' do expect(PlayerCharacter.new(name: 'foobar', sheet_url: '').valid?).to eq(true) end end describe 'image url' do it 'is not valid if bad url' do expect(PlayerCharacter.new(name: 'foobar', image_url: 'alert(\'foobar\')').valid?).to eq(false) end it 'is valid if OK url' do expect(PlayerCharacter.new(name: 'foobar', image_url: 'http://www.example.com').valid?).to eq(true) end it 'is valid if blank' do expect(PlayerCharacter.new(name: 'foobar', image_url: '').valid?).to eq(true) end end end end
ENV['SINATRA_ENV'] ||= "development" #we should use the "development" environment for both the shotgun and the testing suite #we want to make sure that our migrations run on the same environment require 'bundler/setup' Bundler.require(:default, ENV['SINATRA_ENV']) configure :development do set :database, 'sqlite3:db/database.db' end #sets up a connection to sqlite3 database named database.db #rake gives us the ability to quickly make files and set up automated tasks require './app'
module Ripley module Loggers class Stdout # logs to stdout def fatal(message) puts "FATAL #{message}" end def error(message) puts "ERROR #{message}" end def warn(message) puts "WARN #{message}" end def info(message) puts "INFO #{message}" end def debug(message) puts "DEBUG #{message}" end def trace(message) puts "TRACE #{message}" end Ripley.ignore_file __FILE__ end end end
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! # GET /users # GET /users.json def index @users = User.all end # GET /users/1 # GET /users/1.json def show end # GET /users/new def new @user = User.new end # GET /users/1/edit def edit end # POST /users # POST /users.json def create @user = User.new(user_params) respond_to do |format| if @user.save format.html { redirect_to @user, notice: 'User was successfully created.' } format.json { render :show, status: :created, location: @user } else format.html { render :new } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # PATCH/PUT /users/1 # PATCH/PUT /users/1.json def update respond_to do |format| if @user.update(user_params) format.html { redirect_to @user, notice: 'User was successfully updated.' } format.json { render :show, status: :ok, location: @user } else format.html { render :edit } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # DELETE /users/1 # DELETE /users/1.json def destroy @user.destroy respond_to do |format| format.html { redirect_to users_url, notice: 'User was successfully destroyed.' } format.json { head :no_content } end end # GET /oauth_redirect def oauth_redirect if params.key?('code') # code换取token response = Net::HTTP.post_form( URI('https://api.weibo.com/oauth2/access_token'), client_id: APP_ID, client_secret: APP_SECRET, grant_type: 'authorization_code', redirect_uri: "http://#{APP_HOST}/oauth_redirect", code: params['code']) json = JSON.parse(response.body) @token = json['access_token'] # token换uid uri = URI.parse("https://api.weibo.com/2/account/get_uid.json?access_token=#{@token}") response = Net::HTTP.get_response(uri) json = JSON.parse(response.body) @uid = json['uid'] if @uid && @token #user = User.find(params['user_id']) user = current_user user.weibo_uid = @uid user.token = @token user.save #sign_in user end redirect_to users_path end end def user_timeline uri ='https://api.weibo.com/2/statuses/user_timeline.json?'+ "source=#{APP_ID}&access_token=#{params['access_token']}" response = Net::HTTP.get_response(URI(uri)) json = JSON.parse(response.body) happy, unhappy, count = 0.0, 0.0, 0 if json.key?('statuses') statuses = json['statuses'] statuses.each do |s| text = s['text'] current_words = ((text.scan /\[[^\[\]]+\]/).map { |x| x[1...-1] }) h, u = get_em(current_words) happy += h * current_words.size unhappy += u * current_words.size s['count'] = current_words.size s['happy'] = h s['unhappy'] = u count += s['count'] end render json: { posts: statuses, happy: happy / count, unhappy: unhappy / count } else render json: { posts: [], happy: 0, unhappy: 0 } end end def posts uri ='https://api.weibo.com/2/statuses/user_timeline.json?'+ "source=#{APP_ID}&access_token=#{current_user.token}" response = Net::HTTP.get_response(URI(uri)) json = JSON.parse(response.body) if json.key?('statuses') statuses = json['statuses'] render json: { posts: statuses } else render json: { posts: [] } end end def emotion respond_to do |format| format.html do @user = current_user @token = current_user.token end format.json do uri ='https://api.weibo.com/2/statuses/user_timeline.json?'+ "source=#{APP_ID}&access_token=#{current_user.token}" response = Net::HTTP.get_response(URI(uri)) json = JSON.parse(response.body) happy, unhappy, count = 0.0, 0.0, 0 if json.key?('statuses') statuses = json['statuses'] statuses.each do |s| text = s['text'] current_words = ((text.scan /\[[^\[\]]+\]/).map { |x| x[1...-1] }) h, u = get_em(current_words) happy += h * current_words.size unhappy += u * current_words.size s['count'] = current_words.size s['happy'] = h s['unhappy'] = u count += s['count'] end render json: { posts: statuses, happy: happy / count, unhappy: unhappy / count } else render json: { posts: [], happy: 0, unhappy: 0 } end end end end private def get_em(words) return [0.5, 0.5] unless words && words.size > 0 uri = URI('http://api.bosondata.net/sentiment/analysis') res = Net::HTTP.start(uri.host, uri.port) do |http| req = Net::HTTP::Post.new(uri) req['Content-Type'] = 'application/json' req['X-Token'] = 'j7qM_fTv.5457.u0OqgFcklbUv' # The body needs to be a JSON string, use whatever you know to parse Hash to JSON req.body = words.to_json http.request(req) end result = JSON.parse(res.body) ret = result.reduce([0, 0]) do |sum, x| [sum.first + x.first, sum.last + x.last] end [ret.first / result.count, ret.last / result.count] end # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.fetch(:user, {}) end end
module DSLSet module DSLRestful require 'rest_client' require "base64" require "nori" require 'json' class << self def config cfgs puts "Calling config: #{cfgs.to_s}" unless cfgs.keys.include?(:web_host) puts "parameters you should input are :web_host" exit 1 end $web_host = cfgs[:web_host] end def visit(uri) cleanup $uri = uri $properties ||= {} end def set_auth(options) $headers[:Authorization] = "Basic #{Base64.encode64("#{options[:username]}:#{options[:password]}")}" end def fill_in(locator, options = {}) $properties ||= {} if locator.split('/').length > 0 hash = options[:with] #p hash locator.split('/').reverse.each do |node| if locator =~ /^#{node}/ $properties[node.downcase] = hash else hash = {node => hash} end end #p $properties else $properties[locator.downcase] = options[:with] end end def get(url) delegate(:get, url, $properties) end alias :retrieve :get def put(url) delegate(:put, url, self.send("build_req_data_#{get_content_type}", $properties)) end alias :update :put def post(url) delegate(:post, url, self.send("build_req_data_#{get_content_type}", $properties)) end alias :create :post def delete(url) delegate(:delete, url, $properties) end def page() self end def read_id(resp_body, xpath = nil) self.send("read_id_#{get_content_type}", resp_body, xpath) end def resp_body() if $response if $response.class == String return $response elsif $response.class == RestClient::Unauthorized return nil else return $response.body end end end def result_data if default_content_type == 'xml' nori.parse(resp_body) elsif default_content_type == 'json' begin s = JSON.parse(resp_body) return s rescue => e puts e end end end def resp_code if $response if $response.class == String return $response elsif $response.class == RestClient::Unauthorized return $response.http_code else return $response.code end end end def has_content?(text) return $response =~ /#{text}/ end def has_no_content?(text) return !has_content?(text) end private def cleanup $properties = {} $headers ||= {} auth = $headers[:Authorization] $headers = {} $headers[:Authorization] = auth $content_type = nil end def delegate(call, url, data) requrl = build_req_url(call, url, data) appurl = "#{$web_host}#{$uri+requrl}" build_headers($headers) begin puts "#{call} #{appurl}" if call =~ /get|retrieve|delete/ $response = RestClient.send(call, URI.encode(appurl), $headers) else $headers[:content_type] = "application/#{default_content_type}" $headers[:accept] = default_content_type if $exe_output == 'html' and data puts to_html(data) else puts data end $response = RestClient.send(call, appurl, data, $headers) end rescue => ex #p ex.class autinfo = '' if $headers[:Authorization] autinfo = Base64.decode64($headers[:Authorization].split(' ')[1]) end er = "Server failed to process the request, #{ex.message}\nheaders: #{$headers}, #{autinfo}\ndata: \n#{data}" puts er raise er if ex.message =~ /500/ $response = ex.message return end #Set session id if $response and $response.code >= 200 and $response.code < 300 if $response.headers[:content_type] $content_type = $response.headers[:content_type] end if $response.cookies['_applicatioN_session_id'] set_session($response.cookies['_applicatioN_session_id']) #p $headers else #puts "Seesion not found from cookie. #{$response.cookies} #{$response.headers}" end format_data = $response.body if $content_type =~ /xml/ and format_data #puts "Formatting output with xml format" doc = Nokogiri::XML($response.body){ |x| x.noblanks } format_data = doc.to_xml(:indent => 2, :encoding => 'UTF-8') if $exe_output == 'html' format_data = to_html(format_data) end end puts "Response code: #{$response.code}, Response body:\n#{format_data}" else puts "Response code: #{$response.code}, Response body: #{$response.body}" if $response end $response end def to_html(xml) return nil if xml.nil? s = xml.gsub('<','&lt;') s.gsub!('>','&gt;') '<pre>'+s+'</pre>' end def get_content_type if $content_type t = $content_type.scan(/\/([a-z]*)/) if t and t[0] and t[0].class ==Array #puts "#{$content_type} #{t}" return t[0][0] end return "Unable to parse content type from #{$content_type}" else puts "No content type, use default: #{default_content_type}" end default_content_type end def set_session(sessionid) $headers[:session] = {:session_id => sessionid} end def build_req_url call, method, data appurl = method && method.length > 0 ? "/#{method}" : '' if call =~ /get|retrieve/ query = '' data.each do |key, value| query += "#{key}=#{value}&" end #query.delete!(/\&$/) if query.length > 0 appurl += "?#{query}" end end return appurl end def nori return @nori if @nori nori_options = { :strip_namespaces => true, :convert_tags_to => lambda { |tag| tag.snakecase.to_sym}, :advanced_typecasting => true, :parser => :nokogiri } non_nil_nori_options = nori_options.reject { |_, value| value.nil? } @nori = Nori.new(non_nil_nori_options) end end end end
Dir[File.expand_path('face_detect/*.rb', __dir__)].each { |file| require file } class FaceDetect attr_reader :file, :adapter_instance # TODO accept a File or a URL def initialize(file:, adapter:) @file = file @adapter_instance = adapter.new(file) end def run adapter_instance.run end end
class UserCategory < ApplicationRecord # Associations belongs_to :user belongs_to :category # ------------ # Validations validates :user_id, presence: true validates :category_id, presence: true validates :total_weightage, presence: true # ---------------- end
require 'test_helper' require 'tins/find' require 'fileutils' require 'tempfile' module Tins class FindTest < Test::Unit::TestCase include Tins::Find include FileUtils def setup mkdir_p @work_dir = File.join(Dir.tmpdir, "test.#$$") end def teardown rm_rf @work_dir end def test_raising_errors assert_equal [], find(File.join(@work_dir, 'nix'), :raise_errors => false).to_a assert_equal [], find(File.join(@work_dir, 'nix')).to_a assert_raise(Errno::ENOENT) do find(File.join(@work_dir, 'nix'), :raise_errors => true).to_a end end def test_showing_hidden touch file = File.join(@work_dir, '.foo') assert_equal [ @work_dir ], find(@work_dir, :show_hidden => false).to_a assert_equal [ @work_dir, file ], find(@work_dir).to_a assert_equal [ @work_dir, file ], find(@work_dir, :show_hidden => true).to_a end def test_check_directory_without_access # do not run this test on JRuby omit_if(RUBY_PLATFORM =~ /java/, "Can't run the test on JRuby") # do not run this test if we're root, as it will fail. omit_if(Process::UID.eid == 0, "Can't run the test as root") begin mkdir_p directory1 = File.join(@work_dir, 'foo') mkdir_p directory2 = File.join(directory1, 'bar') touch file = File.join(directory2, 'file') chmod 0, directory2 assert_equal [ @work_dir, directory1, directory2 ], find(@work_dir, :raise_errors => false).to_a assert_equal [ @work_dir, directory1, directory2 ], find(@work_dir).to_a assert_raise(Errno::EACCES) do find(@work_dir, :raise_errors => true).to_a end ensure File.exist?(directory2) and chmod 0777, directory2 end end def test_follow_symlinks mkdir_p directory1 = File.join(@work_dir, 'foo1') mkdir_p directory2 = File.join(@work_dir, 'foo2') mkdir_p directory3 = File.join(directory1, 'bar') touch file = File.join(directory3, 'foo') ln_s directory3, link = File.join(directory2, 'baz') assert_equal [ directory2, link ], find(directory2, :follow_symlinks => false).to_a assert_equal [ directory2, link, linked = File.join(link, 'foo') ], find(directory2).to_a assert_equal [ directory2, link, linked ], find(directory2, :follow_symlinks => true).to_a end def test_path_file File.open(File.join(@work_dir, 'foo'), 'w') do |f| f.print "hello" f.fsync assert_equal "hello", find(@work_dir).select { |f| f.stat.file? }.first.file.read end end def test_path_extension finder = Tins::Find::Finder.new f = File.open(path = File.join(@work_dir, 'foo.bar'), 'w') ln_s path, path2 = File.join(@work_dir, 'foo2.bar') path2 = finder.prepare_path path2 path = finder.prepare_path path assert_true path.exist? assert_true path.file? assert_false path.directory? assert_true finder.prepare_path(Dir.pwd).directory? assert_equal Pathname.new(path), path.pathname assert_equal 'bar', path.suffix assert_true path2.lstat.symlink? ensure f and rm_f f.path end def test_suffix finder = Tins::Find::Finder.new(:suffix => 'bar') f = File.open(fpath = File.join(@work_dir, 'foo.bar'), 'w') g = File.open(gpath = File.join(@work_dir, 'foo.baz'), 'w') fpath = finder.prepare_path fpath gpath = finder.prepare_path gpath assert_true finder.visit_path?(fpath) assert_false finder.visit_path?(gpath) finder.suffix = nil assert_true finder.visit_path?(fpath) assert_true finder.visit_path?(gpath) ensure f and rm_f f.path g and rm_f g.path end def test_prune mkdir_p directory1 = File.join(@work_dir, 'foo1') mkdir_p directory2 = File.join(@work_dir, 'foo2') result = [] find(@work_dir) { |f| f =~ /foo2\z/ and prune; result << f } assert_equal [ @work_dir, directory1 ], result end end end
When("user click in entry button must appears screen of stock controll") do @m_Object.click "entrada" temp = @m_Object.get_element "lbl_titulo" expect(temp.text).to eql("Adicionar estoque") end Given("which product stock increase {int} units in amount") do |_Amount| @m_Object.add_text "txt_qtdentrada", _Amount @m_Type = 0 @m_Value = _Amount.to_i end Then("after save this information the product should have a update your amount") do @m_Object.click "btn_salvar" temp = @m_Object.get_element "txt_quantidade" temp = temp.text.to_i if @m_Type == 0 result = @m_Product[:Amount].to_i + @m_Value else result = @m_Product[:Amount].to_i - @m_Value end expect(temp).to eql(result) end When("user click in exit button must appears screen of stock controll") do @m_Object.click "saida" temp = @m_Object.get_element "lbl_titulo" expect(temp.text).to eql("Diminuir estoque") end Given("which product stock decrease {int} units in amount") do |_Amount| @m_Object.add_text "txt_qtdsaida", _Amount @m_Type = 1 @m_Value = _Amount.to_i end Given("which product stock increase {string} units in amount") do |_Amount| @m_Value = _Amount.to_i @m_Object.add_text "txt_qtdentrada", _Amount @m_Type = 0 end Then("in required field should appears feedback about problem and can't be updated this product") do #TODO: Get element of feedback popup error @m_Object.click "btn_salvar" temp = @m_Object.get_element "lbl_titulo" expect(temp.text).to eql("Adicionar estoque") end
# frozen_string_literal: true module Enums class LocaleEnum < BaseEnum from_enum Locale end end
class V1::TokensController < ApplicationController before_action :authenticate!, except: [:create] def create jwt_token = AuthToken.encode(id: valid_account.id) token = valid_account.tokens.create(token: jwt_token) render json: serialize_model(token), status: 201 end private def valid_account account = Account.find_by(email: account_params[:email]) fail Unauthorized unless account fail Unauthorized unless account.valid_password?(account_params[:password]) account end def account_params params.require(:account) .permit(:email, :password) end end
require_relative '../../../../spec_helper' describe 'collectd::plugin::process', :type => :define do let(:pre_condition) { 'Collectd::Plugin <||>' } describe 'when title is valid' do let(:title) { 'giraffe' } it { is_expected.to contain_collectd__plugin('process-giraffe').with_content(<<EOS <Plugin Processes> CollectFileDescriptor true Process "giraffe" </Plugin> EOS )} describe 'regex is provided' do let(:params) {{ :regex => '^gi.*fe$', }} it { is_expected.to contain_collectd__plugin('process-giraffe').with_content(<<EOS <Plugin Processes> CollectFileDescriptor true ProcessMatch "giraffe" "^gi.*fe$" </Plugin> EOS )} end describe "disables CollectFileDescriptor on precise" do let(:facts) {{ 'lsbdistcodename' => 'precise' }} let(:title) { 'giraffe' } it { is_expected.to contain_collectd__plugin('process-giraffe').with_content(<<EOS <Plugin Processes> Process "giraffe" </Plugin> EOS )} end describe 'regex containing single and double blackslash' do let(:params) {{ :regex => "^giraffe\\\.giraffe\\\\$", }} it { is_expected.to contain_collectd__plugin('process-giraffe').with_content(<<EOS <Plugin Processes> CollectFileDescriptor true ProcessMatch "giraffe" "^giraffe\\\\.giraffe\\\\\\\\$" </Plugin> EOS )} end end describe 'when title is invalid' do let(:title) { 'this makes for a bad filename' } it do expect { is_expected.to contain_collectd__plugin('process-giraffe') }.to raise_error(Puppet::Error, /validate_re/) end end end
require "zip" require "json" require "kartograph" require "resource_kit" require "qualtrics/version" require "active_model" require "active_support/all" module Qualtrics module API autoload :Client, "qualtrics/client" # Models autoload :BaseModel, "qualtrics/models/base_model" autoload :Organization, "qualtrics/models/organization" autoload :Division, "qualtrics/models/division" autoload :Group, "qualtrics/models/group" autoload :Survey, "qualtrics/models/survey" Survey.autoload :Expiration, "qualtrics/models/survey/expiration" autoload :User, "qualtrics/models/user" autoload :LibraryMessage, "qualtrics/models/library_message" autoload :Distribution, "qualtrics/models/distribution" Distribution.autoload :Headers, "qualtrics/models/distribution/headers" Distribution.autoload :Message, "qualtrics/models/distribution/message" Distribution.autoload :Recipients, "qualtrics/models/distribution/recipients" Distribution.autoload :SurveyLink, "qualtrics/models/distribution/survey_link" autoload :ResponseExport, "qualtrics/models/response_export" autoload :Response, "qualtrics/models/response" autoload :MailingList, "qualtrics/models/mailing_list" MailingList.autoload :Contact, "qualtrics/models/mailing_list/contact" # Resources autoload :OrganizationResource, "qualtrics/resources/organization_resource" autoload :DivisionResource, "qualtrics/resources/division_resource" autoload :GroupResource, "qualtrics/resources/group_resource" autoload :SurveyResource, "qualtrics/resources/survey_resource" autoload :UserResource, "qualtrics/resources/user_resource" autoload :LibraryMessageResource, "qualtrics/resources/library_message_resource" autoload :DistributionResource, "qualtrics/resources/distribution_resource" autoload :ResponseExportResource, "qualtrics/resources/response_export_resource" autoload :ResponseImportResource, "qualtrics/resources/response_import_resource" autoload :MailingListResource, "qualtrics/resources/mailing_list_resource" # JSON Maps autoload :OrganizationMapping, "qualtrics/mappings/organization_mapping" autoload :DivisionMapping, "qualtrics/mappings/division_mapping" autoload :GroupMapping, "qualtrics/mappings/group_mapping" autoload :SurveyMapping, "qualtrics/mappings/survey_mapping" autoload :ExpirationMapping, "qualtrics/mappings/expiration_mapping" autoload :UserMapping, "qualtrics/mappings/user_mapping" autoload :LibraryMessageMapping, "qualtrics/mappings/library_message_mapping" autoload :DistributionMapping, "qualtrics/mappings/distribution_mapping" autoload :ResponseExportMapping, "qualtrics/mappings/response_export_mapping" autoload :ResponsesMapping, "qualtrics/mappings/responses_mapping" autoload :MailingListMapping, "qualtrics/mappings/mailing_list_mapping" autoload :ContactMapping, "qualtrics/mappings/contact_mapping" # Utils autoload :ErrorHandlingResourceable, "qualtrics/error_handling_resourceable" autoload :Kartograph, "qualtrics/utils/kartograph_optional_properties" # Errors autoload :ErrorMapping, "qualtrics/mappings/error_mapping" Error = Class.new(StandardError) FailedCreate = Class.new(Qualtrics::API::Error) FailedUpdate = Class.new(Qualtrics::API::Error) class RateLimitReached < Qualtrics::API::Error attr_accessor :reset_at attr_writer :limit, :remaining def limit @limit.to_i if @limit end def remaining @remaning.to_i if @remaning end end end end
class Admin::VolunteersController < ApplicationController before_filter :authenticate_user! authorize_resource before_filter :load_model, only: [:edit, :show, :update, :destroy] def index scope = Volunteer.joins(:congregation) @part, @order, @congregation_id, @vacancy = nil, nil, nil, nil if params[:volunteer] @part = params[:volunteer][:part] @order = params[:volunteer][:order] @congregation_id = params[:volunteer][:congregation_id] @vacancy = params[:volunteer][:vacancy] scope = scope.where("email ilike :part or first_name ilike :part or last_name ilike :part or phone ilike :part", part: "%#{@part}%") if @part.present? scope = scope.where("congregation_id = ?", @congregation_id) if @congregation_id.present? scope = scope.where("vacancy_id is null") if @vacancy == "2" scope = scope.where("vacancy_id is not null") if @vacancy == "1" scope = scope.order("#{@order}") if @order.present? end @volunteers = scope end def show end def new @volunteer = Volunteer.new end def create @volunteer = Volunteer.new params_volunteer if @volunteer.save redirect_to admin_volunteers_path, notice: "Доброволец успешно создан!" else render :new end end def edit end def update if @volunteer.update params_volunteer redirect_to admin_volunteers_path, notice: "Информация о добровольце обновлена" else render :edit end end def destroy @volunteer.destroy redirect_to admin_volunteers_path end def print @volunteers = Volunteer.order(:congregation_id).order(:responsibility_id) render layout: false end def print_managing @vacancies = Vacancy.order(:number) render layout: false end def load_xls @congregation = Congregation.find params[:congregation_id] Uploads::Manager.async_process_file params[:file], @congregation # full_file_path = Uploads::Manager.save_file(params[:file]) # @upload = Upload.create!(:supplier_id => @client.id, storage_life_days: @client.store.storage_life_days) # Uploads::Manager.process_file(full_file_path, @client, @upload) redirect_to admin_volunteers_path, notice: "Файл принят в обработку!" end private def params_volunteer params.require(:volunteer).permit(:congregation_id, :last_name, :first_name, :age, :service_time_id, :convenient_start_time, :convenient_end_time, :will_be_since_8, :car, :will_be_until_17, :outdoor, :service_id, :phone,:email, :comment, :responsibility_id) end def load_model @volunteer = Volunteer.find params[:id] end end
require 'spec_helper' describe PermissionCollection do before(:each) do @law_case = build(:law_case) @permission_collection = PermissionCollection.new end describe "#add_case_permission" do it "should add a case permission" do @permission_collection.add_case_permission(@law_case, :read_only) @permission_collection.case_permissions.count.should == 1 end end describe "#add_lawyer_cases_permission" do it "should add a case permission" do @permission_collection.add_lawyer_cases_permission(@lawyer, :read_only) @permission_collection.lawyer_cases_permissions.count.should == 1 end end describe "#can_read?" do context "for another lawyer's case" do it "should return false with no permissions" do law_case = build(:law_case) @permission_collection.can_read?(law_case).should be_false end context "with a case permission on the given law case" do before(:each) do @law_case = build(:law_case) end it "should return true for full_access" do @permission_collection.add_case_permission(@law_case, :full_access) @permission_collection.can_read?(@law_case).should be_true end it "should return true for read_only" do @permission_collection.add_case_permission(@law_case, :read_only) @permission_collection.can_read?(@law_case).should be_true end it "should return false for no_access" do @permission_collection.add_case_permission(@law_case, :no_access) @permission_collection.can_read?(@law_case).should be_false end end context "with a lawyer cases permission" do before(:each) do @lawyer = build(:lawyer) @law_case = @lawyer.init_case(1234) end it "should return true for full_access" do @permission_collection.add_lawyer_cases_permission(@lawyer, :full_access) @permission_collection.can_read?(@law_case).should be_true end it "should return true for read_only" do @permission_collection.add_lawyer_cases_permission(@lawyer, :read_only) @permission_collection.can_read?(@law_case).should be_true end it "should return false for no_access" do @permission_collection.add_lawyer_cases_permission(@lawyer, :no_access) @permission_collection.can_read?(@law_case).should be_false end end context "with a lawyer cases permission but a not access case permission" do before(:each) do @lawyer = build(:lawyer) @law_case = @lawyer.init_case(1234) @permission_collection.add_case_permission(@law_case, :no_access) end it "should return false if the permission is full_access and the lawyer onws the case" do @permission_collection.add_lawyer_cases_permission(@lawyer, :full_access) @permission_collection.can_read?(@law_case).should be_false end it "should return false if the permission is read_only and the lawyer onws the case" do @permission_collection.add_lawyer_cases_permission(@lawyer, :read_only) @permission_collection.can_read?(@law_case).should be_false end it "should return false if the permission is no_access" do @permission_collection.add_lawyer_cases_permission(@lawyer, :no_access) @permission_collection.can_read?(@law_case).should be_false end end end end describe "#can_write?" do context "for another lawyer's case" do it "should return false with no permissions" do law_case = build(:law_case) @permission_collection.can_write?(law_case).should be_false end context "with a case permission on the given law case" do before(:each) do @law_case = build(:law_case) end it "should return true for full_access" do @permission_collection.add_case_permission(@law_case, :full_access) @permission_collection.can_write?(@law_case).should be_true end it "should return true for read_only" do @permission_collection.add_case_permission(@law_case, :read_only) @permission_collection.can_write?(@law_case).should be_false end it "should return false for no_access" do @permission_collection.add_case_permission(@law_case, :no_access) @permission_collection.can_write?(@law_case).should be_false end end context "with a lawyer cases permission" do before(:each) do @lawyer = build(:lawyer) @law_case = @lawyer.init_case(1234) end it "should return true for full_access" do @permission_collection.add_lawyer_cases_permission(@lawyer, :full_access) @permission_collection.can_write?(@law_case).should be_true end it "should return true for read_only" do @permission_collection.add_lawyer_cases_permission(@lawyer, :read_only) @permission_collection.can_write?(@law_case).should be_false end it "should return false for no_access" do @permission_collection.add_lawyer_cases_permission(@lawyer, :no_access) @permission_collection.can_write?(@law_case).should be_false end end context "with a lawyer cases permission but a not access case permission" do before(:each) do @lawyer = build(:lawyer) @law_case = @lawyer.init_case(1234) @permission_collection.add_case_permission(@law_case, :no_access) end it "should return false if the permission is full_access and the lawyer onws the case" do @permission_collection.add_lawyer_cases_permission(@lawyer, :full_access) @permission_collection.can_write?(@law_case).should be_false end it "should return false if the permission is read_only and the lawyer onws the case" do @permission_collection.add_lawyer_cases_permission(@lawyer, :read_only) @permission_collection.can_write?(@law_case).should be_false end it "should return false if the permission is no_access" do @permission_collection.add_lawyer_cases_permission(@lawyer, :no_access) @permission_collection.can_read?(@law_case).should be_false end end end end describe "#remove_case_permission" do before(:each) do @lawyer = build(:lawyer) @permission_collection.add_case_permission(@law_case, :read_only) end it "should add a case permission" do @permission_collection.remove_case_permission(@law_case) @permission_collection.case_permissions.count.should == 0 end end describe "#remove_lawyer_cases_permission" do before(:each) do @permission_collection.add_lawyer_cases_permission(@lawyer, :read_only) end it "should add a case permission" do @permission_collection.remove_lawyer_cases_permission(@lawyer) @permission_collection.lawyer_cases_permissions.count.should == 0 end end describe "#all_redeable_cases" do before(:each) do @lawyer = build(:lawyer) @law_case1 = build(:law_case, number: 1234) @law_case2 = build(:law_case, number: 2345) @law_case3 = build(:law_case, number: 3456) @law_case4 = @lawyer.init_case(4567) @law_case5 = @lawyer.init_case(5678) @permission_collection.add_case_permission(@law_case1, :read_only) @permission_collection.add_case_permission(@law_case2, :read_only) @permission_collection.add_case_permission(@law_case3, :read_only) @permission_collection.add_lawyer_cases_permission(@lawyer, :read_only) end it "should return all cases that can read" do @permission_collection.all_redeable_cases.should =~ [@law_case1, @law_case2, @law_case3, @law_case4, @law_case5] end end end
# Lesson 2 # Заполнение массива числами от 10 до 100 с шагом 5 numbers = [] number = 10 while number <= 100 numbers << number number += 5 end puts numbers
class FreeContentsController < ApplicationController before_action :set_variables, only: :show def show raise ActionController::RoutingError.new('Not Found') if !@document.present? end private def set_variables @courses = Course.joins(:topics => {:subtopics => :documents}).where(documents: {free_content: true}) @document = Document.includes(subtopic: [topic: :course]).find_by(id: params[:id], free_content: true) return if !@document.present? topic = @document.subtopic.topic @subtopics = Subtopic.joins(:documents).where(documents: {free_content: true}, subtopics: {topic_id: topic.id}) end end