text
stringlengths
10
2.61M
require "rails_helper" feature "Image details" do scenario "Show details of image", :vcr do visit "/" click_link "hello-world", match: :first expect(page).to have_content "Namespace" expect(page).to have_content "/" expect(page).to have_content "Image" expect(page).to have_content "hello-world" expect(page).to have_content "Tag v2\nTag v1\nTag latest" end scenario "Use custom sort for tags", :vcr do visit "/repo/hello-world?sort_tags_by=api&sort_tags_order=asc" expect(page).to have_content "Tag v2\nTag latest\nTag v1" end end
# typed: true # frozen_string_literal: true module Packwerk module Checker extend T::Sig extend T::Helpers interface! sig { returns(ViolationType).abstract } def violation_type; end sig { params(reference: Reference).returns(T::Boolean).abstract } def invalid_reference?(reference); end end end
DirectionAndAngle = Struct.new(:dir, :angle) E = DirectionAndAngle.new('E', 0) N = DirectionAndAngle.new('N', Math::PI/2) W = DirectionAndAngle.new('W', Math::PI) S = DirectionAndAngle.new('S', Math::PI*3/2) DirectionHash = {'N' => N, 'E' => E, 'S' => S, 'W' => W} class Rotator def initialize(initial_direction = 'N') @commands = {'l'=> 'left', 'r' => 'right'} @directions = [N, E, S, W] @direction = @directions.find_index(DirectionHash[initial_direction]) end def direction @directions[@direction].dir end def angle @directions[@direction].angle end def left @direction = @direction - 1 end def right @direction = (@direction + 1) % 4 end def process(direction) if @commands.has_key?(direction) send @commands[direction] end end end
#Include this in items to make them automatically be deleted after a specified time. module Expires def initialize *args super end def run super if info.expiration_time and Time.now.to_i > info.expiration_time expire end end def expire_in seconds info.expiration_time = (Time.now + seconds).to_i end private def expire raise "expire is not yet properly implemented" end end
class Special # database find_all def self.find_all tag = Tag.find_by_name(tag_name) return [] if tag.blank? Appointment.public.recurring.all(:joins => :tags, :conditions => ["tags.id = ?", tag.id]) end # database find_by_city def self.find_by_city(city, options={}) return [] if city.blank? tag = Tag.find_by_name(tag_name) return [] if tag.blank? # find public recurring appointments in the specified city Appointment.public.recurring.all(:joins => [:tags, :location], :conditions => ["locations.city_id = ? AND tags.id = ?", city.id, tag.id]) end # database find_by_day # find location specials for the specified day def self.find_by_day(location, day) # find tag 'day' tag = Tag.find_by_name(day) return [] if tag.blank? # find appointment tagged with tag Appointment.public.recurring.all(:joins => [:tags, :location], :conditions => ["locations.id = ? AND tags.id = ?", location.id, tag.id]) end # returns true if the specified string is a valid day def self.day?(s) return false if s.blank? Recurrence::DAYS_OF_WEEK.values.include?(s.titleize) end # days supported def self.days ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] end # find today in long format, e.g. 'Sunday' def self.today Time.now.to_s(:appt_week_day_long) end def self.create(name, location, recur_rule, options={}) company = options[:company] || location.company start_at = options[:start_at] end_at = options[:end_at] tags = Array(options[:tags] || []) preferences = options[:preferences] || Hash[] # create the special as a public, recurring appointment special = location.appointments.create(:name => name, :company => company, :recur_rule => recur_rule, :start_at => start_at, :end_at => end_at, :mark_as => Appointment::FREE, :public => true) # add 'special' tag tags.push(tag_name) if Recurrence.frequency(recur_rule) == 'weekly' # add day tags Recurrence.days(recur_rule, :format => :long).each do |day| tags.push(day.to_s.downcase) end end # add tags if !tags.empty? special.tag_list.add(tags) special.save end # add preferences unless preferences.empty? preferences.each_pair { |k, v| special.preferences[k] = v } special.save end special end def self.tag_name 'special' end # find or create the 'Specials' event category def self.find_event_category options = Hash[:name => event_category_name, :source_id => "0", :source_type => "Specials"] category = EventCategory.find_by_name(event_category_name) || EventCategory.create(options) end def self.event_category_name 'Specials' end # return collection of special preferences def self.preferences(hash) hash.keys.inject(Hash[]) do |prefs, key| if match = key.to_s.match(/^special_(\w+)/) prefs[key] = hash[key] end prefs end end # return the preference name, without the leading 'special_' def self.preference_name(s) match = s.to_s.match(/^special_(\w+)/) match ? match[1] : s end # normalize comma separated list into a collection def self.collectionize(s) s.split(/(\$[^\$]*,{0,1})/).reject(&:blank?).map{ |s| s.strip.gsub(/,/, '') } end # import specials from specified yaml file def self.import(file = "data/specials.yml") s = YAML::load_stream(File.open(file)) s.documents.each do |object| locations = match(object) if locations.blank? puts "[error] no match" next elsif locations.size > 1 puts "[error] too many matches" next end location = locations.first puts "*** matched location #{location.id}:#{location.company_name}" added = add(location, object) end end def self.add(location, object) # check rule rule = object["rule"] days = Recurrence.days(rule, :format => :long) if days.empty? puts "[error] recurrence rule has no days" raise Exception, "invalid recurrence" end added = 0 preferences = Special.preferences(object) # puts "*** preferences: #{preferences.inspect}" days.each do |day| # check any existing day specials specials = Special.find_by_day(location, day.downcase) next if !specials.empty? puts "[ok] adding #{day.downcase} special" title = object["title"] ? object['title'] : 'Special' start_at = DateRange.find_next_date(day.downcase) end_at = start_at.end_of_day special = Special.create(title, location, rule, :start_at => start_at, :end_at => end_at, :preferences => preferences) added += 1 end added end end
require 'test_helper' class Cms::StoresControllerTest < ActionDispatch::IntegrationTest setup do @cms_store = cms_stores(:one) end test "should get index" do get cms_stores_url assert_response :success end test "should get new" do get new_cms_store_url assert_response :success end test "should create cms_store" do assert_difference('Cms::Store.count') do post cms_stores_url, params: { cms_store: { description: @cms_store.description, name: @cms_store.name, order: @cms_store.order, references: @cms_store.references, status: @cms_store.status } } end assert_redirected_to cms_store_url(Cms::Store.last) end test "should show cms_store" do get cms_store_url(@cms_store) assert_response :success end test "should get edit" do get edit_cms_store_url(@cms_store) assert_response :success end test "should update cms_store" do patch cms_store_url(@cms_store), params: { cms_store: { description: @cms_store.description, name: @cms_store.name, order: @cms_store.order, references: @cms_store.references, status: @cms_store.status } } assert_redirected_to cms_store_url(@cms_store) end test "should destroy cms_store" do assert_difference('Cms::Store.count', -1) do delete cms_store_url(@cms_store) end assert_redirected_to cms_stores_url end end
require 'rails_helper' RSpec.describe 'Verticals' do let(:user) { create :user } let(:token) { token_for(user.username, 'password') } let!(:verticals_list) { create_list :vertical, 20 } let(:vertical) { verticals_list.first } it 'paginates the stored verticals' do api_get '/verticals', token: token first_page = JSON.parse(response.body) expect(first_page['verticals'].count).to eq(10) api_get '/verticals?page=2', token: token second_page = JSON.parse(response.body) expect(second_page['verticals'].count).to eq(10) expect(first_page['verticals'].first['id']).not_to eq(second_page['verticals'].first['id']) end it 'shows a single vertical' do api_get "/verticals/#{vertical.id}", token: token json_res = JSON.parse(response.body) expect(json_res['vertical']['id']).to eq(vertical.id) end context 'with valid params' do let(:params) { { name: 'Comedy Writing' } } it 'creates a new vertical' do api_post '/verticals', params: { vertical: params }, token: token json_res = JSON.parse(response.body) expect(json_res['vertical']['name']).to eq(params[:name]) end it 'updates an existing vertical' do api_put "/verticals/#{vertical.id}", params: { vertical: params }, token: token json_res = JSON.parse(response.body) expect(json_res['vertical']['name']).to eq(params[:name]) expect(vertical.reload.name).to eq(params[:name]) end it 'deletes a vertical' do expect { api_delete "/verticals/#{vertical.id}", token: token }.to change { Vertical.count }.by(-1) end end context 'without valid params' do let(:name) { 'TAKEN' } let!(:category) { create :category, name: name } let(:params) { { name: name } } it 'returns an error instead of creating' do api_post '/verticals', params: { vertical: params }, token: token json_res = JSON.parse(response.body) expect(response).to be_bad_request expect(json_res.keys).to include('errors') end it 'returns an error instead of updating' do api_put "/verticals/#{vertical.id}", params: { vertical: params }, token: token json_res = JSON.parse(response.body) expect(response).to be_bad_request expect(json_res.keys).to include('errors') end end end
require 'byebug' class Code POSSIBLE_PEGS = { "R" => :red, "G" => :green, "B" => :blue, "Y" => :yellow } def self.valid_pegs?(arr) arr.all? { |ele| POSSIBLE_PEGS.has_key?(ele.upcase) } end attr_reader :pegs def self.random(num) rgby = "RGBY".split('') Code.new(Array.new(num) {rgby.sample}) #rgby[rand(num - 1)] end def self.from_string(str) Code.new(str.chars) # returns the Code instance end def initialize(char_arr) if !Code.valid_pegs?(char_arr) raise "Error!" else @pegs = char_arr.map(&:upcase) end end def [](idx) @pegs[idx] end def length @pegs.length end # Part 2 def num_exact_matches(guess) count = 0 guess.pegs.each.with_index do |ele, i| count += 1 if ele == @pegs[i] end count end # expect(code.num_near_matches( # Code.new(["R", "R", "R", "R"]))).to eq(2) # copy: # #<Code:0x00007fb27c9e9a90 @pegs=["R", "G", "R", "B"]> # guess: # #<Code:0x00007fb27c9e8fc8 @pegs=["R", "R", "R", "R"]> #expect 2*exact 2*near # secret: RYYB guess: RGRB 2,1 #expect 2*exact 0*near # exact [0,2] # [0,3] def num_near_matches(guess) # secret: RGRB guess: RYYB expect 2*exact 0*near # puts 'self:' # p self # puts 'guess:' # p guess # # p @pegs # copy = @pegs.dup # be sure to not mutate! # copy.each.with_index do |ele, i| # if ele == guess.pegs[i] # copy[i] = '_' # end # end # # p copy # count = 0 # guess.pegs.each_with_index do |ele, i| # if copy.include?(ele) # count += 1 # end # end # count count = 0 guess.pegs.each_with_index do |ele, i| if ele != @pegs[i] && @pegs.include?(ele) count += 1 end end count end def ==(code) self.pegs == code.pegs end end
module Gossiper module Concerns module Models module Notification extend ActiveSupport::Concern STATUSES = %w(pending delivered) included do serialize :data, JSON validates :kind, presence: true belongs_to :user, polymorphic: true end def status read_attribute(:status).presence || STATUSES.first end def data read_attribute(:data).presence || {} end def deliver mail.deliver update_delivered_at! end def deliver! mail.deliver! update_delivered_at! end def kind=(value) value = value.present? ? value.parameterize.underscore : nil write_attribute(:kind, value) end def config begin klass = "Notifications::#{kind.classify}Notification" klass.constantize.new(self) rescue NameError klass = Gossiper.configuration.default_notification_config_class klass.constantize.new(self) end end def method_missing(method, *args, &block) STATUSES.each do |status| if method.to_s == "#{status}?" return self.status == status end end super(method, *args, &block) end protected def mail Gossiper::Mailer.mail_for(self) end def update_delivered_at! self.delivered_at = Time.now save! end end end end end
class Location < ActiveRecord::Base validates :name, :zip, presence: true validates :zip, length: { is: 5 } belongs_to :user end
module Decidim module Participations module Admin # This controller allows admins to answer participations in a participatory process. class CopyParticipationsController < Decidim::Admin::Features::CustomBaseController helper_method :participation def create Admin::CopyParticipation.call(@participation) do on(:ok) do flash[:notice] = I18n.t("participations.copy.success", scope: "decidim.participations.admin") redirect_to participations_path end on(:invalid) do flash.now[:alert] = I18n.t("participations.copy.invalid", scope: "decidim.participations.admin") redirect_to participations_path end end end private def participation @participation ||= Participation.current_feature_participations(current_feature).find(params[:participation_id]) end protected # Here we use show to copy the participations as all actions #apart from index and show require to manage the current_feature def manage_authorization authorize! :duplicate, participation end end end end end
Given(/^I am on the "([^"]*)" page$/) do |page| visit "#{page}.html" end When(/^I press the "([^"]*)" button$/) do |button| click_button button end When(/^I click the "([^"]*)" link$/) do |link| click_link link end When(/^I press the "([^"]*)" button (\d+) times?$/) do |button, n| n.to_i.times { click_button button } end When(/^I press the (\d+)(?:st|nd|rd|th) "([^"]*)" button$/) do |nth, className| click_nth_button(className, nth) end When(/^I press the (\d+)(?:st|nd|rd|th) "([^"]*)" button (\d+) times?$/) do |nth, className, times| times.to_i.times { click_nth_button(className, nth) } end When(/^I write "([^"]*)" into the input$/) do |value| first_input.set(value) end When(/^I hit enter$/) do first_input.native.send_keys(:return) end
require 'rest-client' require 'json' require 'pry' GOOGLE_BOOKS_API_BASE_URL = "https://www.googleapis.com/books/v1/volumes?q=" def welcome_user # welcome user puts "Welcome to our Book Searcher!" end def get_search_terms # ask user for input about search terms puts "What would you like to search for?" search_terms = gets.chomp puts "You searched for #{search_terms}" return search_terms end def build_url(search_terms) return GOOGLE_BOOKS_API_BASE_URL + search_terms end def get_response_from_google(url) # make a request to the Google Books API response = RestClient.get(url) return JSON.parse(response.body) end def parse_book_info(response) # get authors and titles for first 10 books on that subject first_ten = response["items"][0..10] first_ten.map do |book_info| {title: book_info["volumeInfo"]["title"], authors: parse_authors(book_info["volumeInfo"]["authors"])} end end def display_book_info(book) # prints authors and title of book puts "****************" puts "#{book[:title]} by #{book[:authors]}" end def parse_authors(author_array) author_array ||= ["Unknown"] return author_array.join(" & ") end def main welcome_user search_terms = get_search_terms url = build_url(search_terms) response = get_response_from_google(url) book_hashes = parse_book_info(response) book_hashes.each do |book| display_book_info(book) end end main # display author and title of those books
class CreateMedias < ActiveRecord::Migration[4.2] def change create_table :medias do |t| t.belongs_to :user t.belongs_to :account t.string :url t.string :file t.string :quote t.string :type t.timestamps null: false end add_index :medias, :url, unique: true end end
require_relative 'spec_helper' describe 'Solr' do include EventedSpec::SpecHelper include EventedSpec::EMSpec default_timeout 100 before :all do @start_delay = 0 end it 'checks java' do stdin, stdout,stderr = Open3.popen3("java -version") expect(stderr.readlines[0]).to match /java version \"?1.[6-9]/ done end it 'search server is running' do EM.add_timer(@start_delay + 1) do expect(@solr.server_running?).to be_true expect(@solr.get_total_docs).to be_a_kind_of Integer done end end it 'removes index' do EM.add_timer(@start_delay + 3) do expect(@solr.server_running?).to be_true expect(@solr.remove_index).to be_true expect(@solr.get_total_docs).to eq 0 done end end it 'fullimport' do EM.add_timer(@start_delay + 6) do expect(@solr.server_running?).to be_true expect(@solr.remove_index).to be_true expect(@solr.get_total_docs).to eq 0 @solr.index EM.add_periodic_timer(5){ status = @solr.check_index["status"] p status if status == "idle" p "Ola! I've finished Full Import" p "status: #{status}" expect(@solr.get_total_docs).to be >= 50#eq 69504 done else p "Full import in progress...I'm #{status}" end } end end it 'matches products and stores in db' do expect(@solr.server_running?).to be_true #expect(Product.count).to eq 9854 expect(Price.count).to eq 2 Comparison.delete_all expect(Comparison.count).to eq 0 Fiber.new{@mapper.match}.resume EM.add_timer(10){ expect(Comparison.count).to be >= 50#9000 done } end end
class TicketsController < ApplicationController # GET /tickets # GET /tickets.json def index @tickets = Ticket.all respond_to do |format| format.html # index.html.erb format.json { render json: @tickets } end end # GET /tickets/1 # GET /tickets/1.json def show @event = Event.find(params[:event_id]) @ticket = @event.tickets(params[:ticket]) respond_to do |format| format.html # show.html.erb format.json { render json: @ticket } end end # GET /tickets/new # GET /tickets/new.json def new @ticket = Ticket.new respond_to do |format| format.html # new.html.erb format.json { render json: @ticket } end end # GET /tickets/1/edit def edit @ticket = Ticket.find(params[:id]) end # POST /tickets # POST /tickets.json def create @event = Event.find(params[:event_id]) @ticket = @event.tickets.create(params[:ticket]) redirect_to event_path(@event) end # PUT /tickets/1 # PUT /tickets/1.json def update end # DELETE /tickets/1 # DELETE /tickets/1.json def destroy @ticket = Ticket.find(params[:id]) @ticket.destroy respond_to do |format| format.html { redirect_to tickets_url } format.json { head :no_content } end end end
class Book < ApplicationRecord belongs_to :author validates :title, presence: {message: 'Judul harus diisi'} validates :description, length: {minimum: 10, message: 'Minimal 10 huruf'} validates :page, numericality: {greater_than: 10, message: 'Halaman harus lebih dari 10'} def self.expensive where('price > 150000') end def self.cheap where('price < 150000') end def self.price_equal_more(price) where('price >= ?', price) end end
require "spec_helper" feature "User sessions" do scenario "Unauthenticated users are redirected to sign in page" do visit root_path expect(current_path).to eq(sign_in_path) end scenario "Sign in directs users to the root path" do create(:user, email: "test@example.com", password: "password") visit sign_in_path fill_in "session_email", with: "test@example.com" fill_in "session_password", with: "password" click_button 'Sign in' expect(current_path).to eq(root_path) end end
# encoding: UTF-8 # Copyright 2011-2013 innoQ Deutschland GmbH # # 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. module FormHelper ## Generates verbose bootstrap wrapper HTML for generic forms # ## Accepts a hash of arguments with the following keys: ## id: id attribute of the input element (necessary for accessible labels) ## label: label text def input_block(options = {}, &block) label_text = options.delete(:label) id = options.delete(:id) label = if label_text label_tag(id, label_text, class: 'col-form-label') else ActiveSupport::SafeBuffer.new # empty safe string end content_tag(:div, class: 'control-group') do label << content_tag(:div, class: 'controls') do capture(&block) end end end end
# # Cookbook Name:: ruby # Recipe:: default # # Copyright (C) 2012 Mathias Lafeldt <mathias.lafeldt@gmail.com> # # 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 'ruby_build' include_recipe 'rbenv::system' # The rbenv cookbook installs /etc/profile.d/rbenv.sh which sets up the Ruby # environment. But that file will only be sourced after the next login, # causing the first converge to fail. With this workaround, rbenv will be # available immediately. ruby_block "Add rbenv to PATH" do block do rbenv_root = node['rbenv']['root_path'] ENV['PATH'] = "#{rbenv_root}/shims:#{rbenv_root}/bin:#{ENV['PATH']}" end end
class User < ActiveRecord::Base acts_as_authentic validates_uniqueness_of :email validates_presence_of :email validates_presence_of :crypted_password end
# frozen_string_literal: true # MetaTag Model class MetaTag < ApplicationRecord include ActivityHistory include CloneRecord include Uploadable include Downloadable include Sortable acts_as_list before_save :split_url validates_uniqueness_of :url validates_presence_of :title, :meta_tags, :url def self.get_by_url(url) url = url.split('//').last.split('www.').last find_by_url(url) end def self.title(post_param, product_param, setting) post = post_param&.title product = product_param&.title || product_param&.name post || product || setting.name end def self.description(post_param, product_param, setting) unless post_param&.body.blank? body = post_param.body post = sanitize(body, tags: []).truncate(300) end product = product_param&.description || product_param&.body post || product || setting.description end def self.image(request, post_param, product_param, setting_param) post = post_param&.image product = product_param&.image || product_param&.photo setting = setting_param&.logo unless setting_param&.logo.blank? image = '/assets/admin/slice.png' url = request.protocol + request.host_with_port url + (post || product || setting || image).to_s end def self.search_field :title_or_description_or_url_cont_any end private def split_url self.url = url.split('//').last.split('www.').last end end
require 'model_test_helper' class RuleTest < ActiveSupport::TestCase # assert_attr_protected test "assert_attr_protected" do assert_attr_protected :name assert_fail_assertion "is_admin is not protected" do assert_attr_protected :is_admin end end test "assert_attr_protected deve aceitar as rules" do assert_attr_protected :name, :as => :default assert_fail_assertion "name is not protected for admin" do assert_attr_protected :name, :as => :admin end end test "assert_attr_protected deve aceitar custm messages" do assert_fail_assertion "no protection for is_admin" do assert_attr_protected :is_admin, "no protection for is_admin" end end # assert_belongs_to test "assert_belongs_to" do assert_belongs_to :user assert_fail_assertion "Rule has no belongs_to association with team" do assert_belongs_to :team end end test "assert_belongs_to deve apresentar a mensagem customizada" do assert_fail_assertion "no belongs_to for teams" do assert_belongs_to :team, "no belongs_to for teams" end end end
class PacientesController < ApplicationController before_action :set_paciente, only: [:show, :edit, :update, :destroy] # GET /pacientes def index @pacientes = Paciente.all end # GET /pacientes/1 def show end # GET /pacientes/new def new @paciente = Paciente.new end # GET /pacientes/1/edit def edit end # POST /pacientes def create @paciente = Paciente.new(paciente_params) if @paciente.save redirect_to pacientes_url, notice: 'Paciente criado com sucesso.' else render :new end end # PATCH/PUT /pacientes/1 def update if @paciente.update(paciente_params) redirect_to pacientes_url, notice: 'Paciente atualizado com sucesso.' else render :edit end end # DELETE /pacientes/1 def destroy @paciente.destroy redirect_to pacientes_url, notice: 'Paciente foi removido.' end private # Use callbacks to share common setup or constraints between actions. def set_paciente @paciente = Paciente.find(params[:id]) end # Only allow a trusted parameter "white list" through. def paciente_params params.require(:paciente).permit(:nome, :email, :telefone, :data_nascimento, :sexo, :estado_civil, :profissao, :trabalha, :sangue, :fumante, :etilista, :cirurgias, :doencas_paternas, :doencas_maternas, :historico_peso) end end
class ImdbClient include HTTParty base_uri 'imdb.com' def self.scrape_top_250! chart = Chart.create! chart.transaction do top_250 = fetch_top_250 existing_movies = Movie.select(:id, :imdb_id).where(:imdb_id => top_250.map{|m| m[:imdb_id]}).map{|m| [m.imdb_id, m.id]}.to_h top_250.each do |movie_hash| print '.' movie_id = existing_movies[movie_hash[:imdb_id]].present? ? existing_movies[movie_hash[:imdb_id]] : Movie.create!(movie_hash.except(:ranking)).id r = chart.rankings.create! :movie_id => movie_id, :rank => movie_hash[:ranking] end chart.save! end chart end private # returns an array of hashes corresponding to each of the 250 rows in # imdb's top 250 rankings page: http://www.imdb.com/chart/top def self.fetch_top_250 doc = Nokogiri::HTML( get('/chart/top').body ) table_rows = doc.css("div[data-collectionid='top-250'] table > tbody > tr") raise "Wrong number of table rows detected (#{table_rows.count} instead of 250)" if table_rows.length != 250 table_rows.map do |tr| title_col = tr.css('.titleColumn > a').first # TODO: this block is too sensitive to IMDB's html structure, it is prone to undefined method for Nilclass errors { :imdb_id => title_col['href'].split('/')[2], :ranking => title_col['href'].split('chttp_tt_').last.to_i, :title => title_col.text, :poster_thumb => tr.css('.posterColumn > a > img').first['src'], :rating => tr.css('.imdbRating > strong').first.text.to_f } end end end
class AppointmentNotification::ScheduleExperimentReminders < ApplicationJob queue_as :high class << self prepend SentryHandler end def self.call perform_now end def logger @logger ||= Notification.logger(class: self.class.name) end def perform return unless Flipper.enabled?(:experiment) notifications = Notification.due_today next_messaging_time = Communication.next_messaging_time logger.info "scheduling #{notifications.count} notifications that are due with next_messaging_time=#{next_messaging_time}" notifications.each do |notification| notification.status_scheduled! AppointmentNotification::Worker.perform_at(next_messaging_time, notification.id) rescue => e Sentry.capture_message("Scheduling notification for experiment failed", extra: { notification: notification.id, next_messaging_time: next_messaging_time, exception: e }, tags: {type: "notifications"}) end logger.info "scheduling experiment notifications complete" end end
class AjaxMessenger attr_accessor :result attr_accessor :message def initialize(message = '', success = true) @message = message @result = success ? 'success' : 'failure' end end
# frozen_string_literal: true require "bundler/gem_tasks" require "rspec/core/rake_task" task :run_specs do require "rspec/core" types_result = RSpec::Core::Runner.run(["spec/dry"]) RSpec.clear_examples Dry::Types.load_extensions(:maybe) ext_result = RSpec::Core::Runner.run(["spec"]) exit [types_result, ext_result].max end task default: :run_specs require "yard" require "yard/rake/yardoc_task" YARD::Rake::YardocTask.new(:doc)
class AddColumnsModeyIdAndChangeTipeToProvisions < ActiveRecord::Migration def change add_column :provisions, :money_id, :integer add_column :provisions, :exchange_of_rate, :float end end
require 'mspire/molecular_formula' module Mspire class Isotope module AA # These represent counts for the individual residues (i.e., no extra H # and OH on the ends) aa_to_el_hash = { 'A' => { C: 3, H: 5, O: 1, N: 1, S: 0, P: 0 }, 'C' => { C: 3, H: 5, O: 1, N: 1, S: 1, P: 0 }, 'D' => { C: 4, H: 5, O: 3, N: 1, S: 0, P: 0 }, 'E' => { C: 5, H: 7, O: 3, N: 1, S: 0, P: 0 }, 'F' => { C: 9, H: 9, O: 1, N: 1, S: 0, P: 0 }, 'G' => { C: 2, H: 3, O: 1, N: 1, S: 0, P: 0 }, 'I' => { C: 6, H: 11, O: 1, N: 1, S: 0, P: 0 }, 'H' => { C: 6, H: 7, O: 1, N: 3, S: 0, P: 0 }, 'K' => { C: 6, H: 12, O: 1, N: 2, S: 0, P: 0 }, 'L' => { C: 6, H: 11, O: 1, N: 1, S: 0, P: 0 }, 'M' => { C: 5, H: 9, O: 1, N: 1, S: 1, P: 0 }, 'N' => { C: 4, H: 6, O: 2, N: 2, S: 0, P: 0 }, 'O' => { C: 12, H: 19, O: 2, N: 3, S: 0, P: 0 }, 'P' => { C: 5, H: 7, O: 1, N: 1, S: 0, P: 0 }, 'Q' => { C: 5, H: 8, O: 2, N: 2, S: 0, P: 0 }, 'R' => { C: 6, H: 12, O: 1, N: 4, S: 0, P: 0 }, 'S' => { C: 3, H: 5, O: 2, N: 1, S: 0, P: 0 }, 'T' => { C: 4, H: 7, O: 2, N: 1, S: 0, P: 0 }, 'U' => { C: 3, H: 5, O: 1, N: 1, S: 0, P: 0, :Se =>1 }, 'V' => { C: 5, H: 9, O: 1, N: 1, S: 0, P: 0 }, 'W' => { C: 11, H: 10, O: 1, N: 2, S: 0, P: 0 }, 'Y' => { C: 9, H: 9, O: 2, N: 1, S: 0, P: 0 }, } # FORMULAS_STR = Hash[ aa_to_el_hash.map {|k,v| [k, Mspire::MolecularFormula.new(v)] } ] FORMULAS_SYM = Hash[FORMULAS_STR.map {|k,v| [k.to_sym, v] }] # string and symbol access of amino acid residues (amino acids are # accessed upper case and atoms are all lower case symbols) FORMULAS = FORMULAS_SYM.merge FORMULAS_STR # an alias for FORMULAS ATOM_COUNTS = FORMULAS end end end
class ApplicationController < ActionController::API rescue_from ActiveRecord::RecordNotDestroyed, with: :not_destroyed rescue_from ActiveRecord::RecordNotFound, with: :not_found private def not_destroyed(data) render json: { errors: data.record.errors }, status: :unprocessable_entity end def not_found render json: { errors: 'Unable to find IBAN' }, status: :not_found end end
# == Schema Information # # Table name: messages # # id :bigint(8) not null, primary key # user_id :integer # text :text # data :json # created_at :datetime not null # updated_at :datetime not null # resource_type :string # resource_id :bigint(8) # class Message < ApplicationRecord belongs_to :user belongs_to :resource, polymorphic: true include PgSearch pg_search_scope :search, against: :text, using: { tsearch: { prefix: true } } end
# frozen_string_literal: true require "aws-sdk-ssm" require "json" require "link-header-parser" require "logger" require "log_formatter" require "log_formatter/ruby_json_formatter" require "net/https" require "uri" require_relative "ssm_client" class Cleaner attr_reader :asa_token, :log, :instance_id def initialize(instance_id) @instance_id = instance_id @asa_token = get_asa_api_token @last_response = "" @log = Logger.new($stdout) @log.formatter = Ruby::JSONFormatter::Base.new do |config| config[:type] = false config[:app] = false end end def run log.info({ message: "ASA Cleaner lambda triggered for instance #{@instance_id}", instance_id: @instance_id, event_type: "lambda_start", method: "run", env: ENV["ENVIRONMENT"] }) clean_asa log.info({ message: "API requests left: #{@last_response.to_h["x-ratelimit-remaining"]}", ratelimit_remaining: @last_response.to_h["x-ratelimit-remaining"], event_type: "api_ratelimit_renamining", method: "run", env: ENV["ENVIRONMENT"] }) end def clean_asa asa_api_query("projects").each do |project| asa_api_query("projects/#{project["name"]}/servers?count=1000").each do |server| next if server["instance_details"].nil? next unless server["instance_details"]["instance_id"] == @instance_id asa_api_delete("projects/#{project["name"]}/servers/#{server["id"]}") log.info({ message: "Removed #{server["hostname"]} from #{project["name"]}", instance_id: @instance_id, asa_project: project["name"], asa_hostname: server["hostname"], event_type: "instance_removed", method: "clean_asa", env: ENV["ENVIRONMENT"] }) return true end end log.info({ message: "Instance #{@instance_id} does not exist in ASA", instance_id: @instance_id, event_type: "asa_node_not_found", method: "clean_asa", env: ENV["ENVIRONMENT"] }) false end def get_asa_api_token(ssm_path) asa_api_key = SSMClient.new.get_parameter(ENV["ASA_API_KEY_PATH"]) asa_api_secret = SSMClient.new.get_parameter(ENV["ASA_API_SECRET_PATH"]) uri = URI.parse("https://app.scaleft.com/v1/teams/#{ENV["ASA_TEAM"]}/service_token") data = { "key_id": asa_api_key.to_s, "key_secret": asa_api_secret.to_s } http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.request_uri, 'Content-Type': "application/json") request.body = data.to_json response = http.request(request) result = JSON.parse(response.body) @last_response = response.each_header result["bearer_token"] end def asa_api_query(path) result = [] query_path = "https://app.scaleft.com/v1/teams/#{ENV["ASA_TEAM"]}/#{path}" loop do uri = URI.parse(query_path) header = { 'Content-Type': "application/json", 'Authorization': "Bearer #{asa_token}" } http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri.request_uri, header) response = http.request(request) result += JSON.parse(response.body)["list"] @last_response = response.each_header break if response["link"].nil? link_header = LinkHeaderParser.parse(response["link"], base: "https://app.scaleft.com/v1/").first query_path = link_header.target_uri break if link_header.relations_string == "prev" end result end def asa_api_delete(path) uri = URI.parse("https://app.scaleft.com/v1/teams/#{ENV["ASA_TEAM"]}/#{path}") header = { 'Content-Type': "application/json", 'Authorization': "Bearer #{asa_token}" } http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Delete.new(uri.request_uri, header) response = http.request(request) @last_response = response.each_header response end end
class RobotsController < ApplicationController def show render file: Rails.application.root.join("public", "#{Rails.env}_robots.txt"), layout: false, content_type: "text/plain" end end
## Array Addition I # Using the Ruby language, have the function # ArrayAdditionI(arr) take the array of numbers stored in # arr and return the string true if any combination of numbers # in the array can be added up to equal the largest number in # the array, otherwise return the string false. For example: # if arr contains [4, 6, 23, 10, 1, 3] the output should return # true because 4 + 6 + 10 + 3 = 23. The array will not be # empty, will not contain all the same elements, and may # contain negative numbers. def ArrayAdditionI(array) max = array.max array.delete(max) array.length.times do array.rotate! (0...array.length).each do |y| return true if array[0..y].reduce(&:+) == max || array[0, y].reduce(&:+) == max end end false end
# frozen_string_literal: true require 'ffi' module Rollenspielsache # Wrapped up string class FFIString < FFI::AutoPointer def self.release Binding.free self end def to_s @to_s ||= read_string.force_encoding('UTF-8') end # Rust externs module Binding extend FFI::Library ffi_lib 'librollenspielsache' # Pass back to Rust's memory management attach_function :free, :ffi_string_free, [FFIString], :void end end end
# encoding: utf-8 class CrawlAlbumInfoWorker include Sidekiq::Worker sidekiq_options queue: "lyric" def perform(album_id) album = Album.find(album_id) begin c = LyricCrawler.new c.fetch album.link c.crawl_album_info album.id rescue end end end
class AddFirstTimeMessageToMatches < ActiveRecord::Migration def change add_column :matches, :first_message_time, :datetime end end
class AddDataToPhotos < ActiveRecord::Migration def change add_column :photos, :name, :string add_column :photos, :date_taken, :datetime end end
class Adventure < ActiveRecord::Base has_many :pages belongs_to :library accepts_nested_attributes_for :pages #validates :title, length { minimum: 4 } #validates :author, length { minimum: 3 } # validates :GUID, presence: true, length: { is: 10} end
class CreatePersonalInfos < ActiveRecord::Migration def change create_table :personal_infos do |t| t.string :first_name t.string :last_name t.text :about t.string :tagline_profession t.string :tagline_background t.string :address_1 t.string :address_2 t.string :suburb t.string :postcode t.string :country t.string :email t.string :phone t.string :linkedin t.string :twitter t.string :facebook t.string :github t.string :profile_pic t.timestamps end end end
class CreateTopFiftyGems < ActiveRecord::Migration def change create_table :top_fifty_gems do |t| t.string :name t.string :version t.string :summary t.string :url t.text :description t.timestamps end end end
require 'spec_helper' resource "Notifications" do let(:user) { users(:owner) } before do log_in user end get "/notifications" do pagination example_request "Get a list of notifications for the current user" do status.should == 200 end end put "/notifications/read" do parameter :'notification_ids[]', "IDs of events to be marked as read" let(:'notification_ids[]') { user.notifications[0..1].map(&:event_id) } required_parameters :'notification_ids[]' example_request "Mark notifications as read" do status.should == 200 end end end
class GFA::RecordSet::SegmentSet < GFA::RecordSet CODE = :S INDEX_FIELD = 2 # Name: Segment name ## # Computes the sum of all individual segment lengths def total_length set.map(&:length).reduce(0, :+) end end
# == Schema Information # # Table name: parkings # # id :integer not null, primary key # user_id :integer # name :string(255) # description :text(65535) # parking_type_id :integer # spaces :integer # address :text(65535) # district_id :integer # price_per_hour :decimal(10, ) # start_date :date # end_date :date # published :boolean # created_at :datetime not null # updated_at :datetime not null # photo_file_name :string(255) # photo_content_type :string(255) # photo_file_size :integer # photo_updated_at :datetime # # Indexes # # index_parkings_on_district_id (district_id) # index_parkings_on_parking_type_id (parking_type_id) # index_parkings_on_user_id (user_id) # # Foreign Keys # # fk_rails_89c657275d (user_id => users.id) # fk_rails_9d04a1c873 (parking_type_id => parking_types.id) # fk_rails_c523c1239a (district_id => districts.id) # class Parking < ApplicationRecord belongs_to :user belongs_to :parking_type belongs_to :district has_many :reviews has_many :ratings has_many :bookings has_many :users, through: :bookings has_many :parking_schedules has_and_belongs_to_many :parking_features has_attached_file :photo, styles: { medium: "365x260>" }, default_url: "/images/placeholder.png" validates_attachment_content_type :photo, content_type: /\Aimage\/.*\Z/ validates :name, presence: true end
# == Schema Information # # Table name: api_keys # # id :integer not null, primary key # access_token :string # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe ApiKey, type: :model do describe "#model token creation" do it "generates a unique token" do @key = FactoryGirl.build(:api_key) expect(@key.access_token).to eql "auniquetoken123" end it "generates another token when one already has been taken" do existing_key = FactoryGirl.create(:api_key, access_token: "auniquetoken123") @new_key = FactoryGirl.build(:api_key) expect(@new_key.access_token).not_to eql existing_key.access_token end end end
#!/bin/ruby require 'ocr' reader = OCR::AccountReader.new($stdin) begin reader.each do |account_number| puts account_number.show end rescue OCR::StandardError => ex puts "Error detected on account number starting at line #{ex.line_number}" if ex.line_number puts "Error Message: #{ex.message}" puts "OCR Aborted" exit 1 end
# ## Exo 1 - Le palindrone # Le script Ruby permettra de saisir un mot et de vérifier que ce mot est un palindrome. # Le retour de code se fera comme suit : # Le mot mot saisie est un palindrome # Le mot mot saisie n’est pas un palindrome # je prepare la methode palindrome qui attend une string def palindrome(string) # si la string est egal a la sring inverser if string == string.reverse # la string est bien un palindrome puts " #{string}est un palindrome" else # sinon la string n'est pas un palindrome puts "#{string} n’est pas un palindrome" end end palindrome(gets.chomp)
require 'rails_helper' describe 'navigate' do before do @admin_user = FactoryBot.create(:admin_user) login_as(@admin_user, :scope => :user) end describe 'edit' do before do @post = FactoryBot.create(:post) end it 'has a status field that can be edited in the form' do visit edit_admin_post_path(@post) expect(@post.status).to eq('submitted') select('Approved', from: 'post_status') click_on('Update Post') expect(@post.reload.status).to eq('approved') end end end
require 'rails_helper' RSpec.describe Api::V1::FindCustomersController, type: :controller do fixtures :customers describe "#index" do it "finds and serves all customers' json by ID" do get :index, format: :json, id: customers(:customer_1).id expect(response.status).to eq(200) expect(response.content_type).to eq "application/json" body = JSON.parse(response.body) first_customer = body.first expect(first_customer["first_name"]).to eq customers(:customer_1).first_name expect(first_customer["last_name"]).to eq customers(:customer_1).last_name expect(first_customer["created_at"]).to eq "2012-03-27T14:54:09.000Z" expect(first_customer["updated_at"]).to eq "2012-03-27T14:54:09.000Z" expect(first_customer["first_name"]).to_not eq customers(:customer_2).first_name expect(first_customer["last_name"]).to_not eq customers(:customer_2).last_name expect(first_customer["created_at"]).to_not eq "2012-03-26T14:54:09.000Z" expect(first_customer["updated_at"]).to_not eq "2012-03-26T14:54:09.000Z" end it "finds and serves all customers' json by first_name" do get :index, format: :json, first_name: customers(:customer_1).first_name expect(response.status).to eq(200) expect(response.content_type).to eq "application/json" body = JSON.parse(response.body) first_customer = body.first expect(first_customer["first_name"]).to eq customers(:customer_1).first_name expect(first_customer["last_name"]).to eq customers(:customer_1).last_name expect(first_customer["created_at"]).to eq "2012-03-27T14:54:09.000Z" expect(first_customer["updated_at"]).to eq "2012-03-27T14:54:09.000Z" expect(first_customer["first_name"]).to_not eq customers(:customer_2).first_name expect(first_customer["last_name"]).to_not eq customers(:customer_2).last_name expect(first_customer["created_at"]).to_not eq "2012-03-26T14:54:09.000Z" expect(first_customer["updated_at"]).to_not eq "2012-03-26T14:54:09.000Z" end it "finds and serves all customers' json by last_name" do get :index, format: :json, last_name: customers(:customer_1).last_name expect(response.status).to eq(200) expect(response.content_type).to eq "application/json" body = JSON.parse(response.body) first_customer = body.first expect(first_customer["first_name"]).to eq customers(:customer_1).first_name expect(first_customer["last_name"]).to eq customers(:customer_1).last_name expect(first_customer["created_at"]).to eq "2012-03-27T14:54:09.000Z" expect(first_customer["updated_at"]).to eq "2012-03-27T14:54:09.000Z" expect(first_customer["first_name"]).to_not eq customers(:customer_2).first_name expect(first_customer["last_name"]).to_not eq customers(:customer_2).last_name expect(first_customer["created_at"]).to_not eq "2012-03-26T14:54:09.000Z" expect(first_customer["updated_at"]).to_not eq "2012-03-26T14:54:09.000Z" end it "finds and serves all customers' json by created_at" do get :index, format: :json, created_at: customers(:customer_1).created_at expect(response.status).to eq(200) expect(response.content_type).to eq "application/json" body = JSON.parse(response.body) first_customer = body.first expect(first_customer["first_name"]).to eq customers(:customer_1).first_name expect(first_customer["last_name"]).to eq customers(:customer_1).last_name expect(first_customer["created_at"]).to eq "2012-03-27T14:54:09.000Z" expect(first_customer["updated_at"]).to eq "2012-03-27T14:54:09.000Z" expect(first_customer["first_name"]).to_not eq customers(:customer_2).first_name expect(first_customer["last_name"]).to_not eq customers(:customer_2).last_name expect(first_customer["created_at"]).to_not eq "2012-03-26T14:54:09.000Z" expect(first_customer["updated_at"]).to_not eq "2012-03-26T14:54:09.000Z" end it "finds and serves all customers' json by updated_at" do get :index, format: :json, updated_at: customers(:customer_1).updated_at expect(response.status).to eq(200) expect(response.content_type).to eq "application/json" body = JSON.parse(response.body) first_customer = body.first expect(first_customer["first_name"]).to eq customers(:customer_1).first_name expect(first_customer["last_name"]).to eq customers(:customer_1).last_name expect(first_customer["created_at"]).to eq "2012-03-27T14:54:09.000Z" expect(first_customer["updated_at"]).to eq "2012-03-27T14:54:09.000Z" expect(first_customer["first_name"]).to_not eq customers(:customer_2).first_name expect(first_customer["last_name"]).to_not eq customers(:customer_2).last_name expect(first_customer["created_at"]).to_not eq "2012-03-26T14:54:09.000Z" expect(first_customer["updated_at"]).to_not eq "2012-03-26T14:54:09.000Z" end end describe "#show" do it "finds and serves one customers' json by ID" do get :show, format: :json, id: customers(:customer_1).id expect(response.status).to eq(200) expect(response.content_type).to eq "application/json" body = JSON.parse(response.body) expect(body["first_name"]).to eq customers(:customer_1).first_name expect(body["last_name"]).to eq customers(:customer_1).last_name expect(body["created_at"]).to eq "2012-03-27T14:54:09.000Z" expect(body["updated_at"]).to eq "2012-03-27T14:54:09.000Z" end it "finds and serves one customers' json by first_name" do get :show, format: :json, first_name: customers(:customer_1).first_name expect(response.status).to eq(200) expect(response.content_type).to eq "application/json" body = JSON.parse(response.body) expect(body["first_name"]).to eq customers(:customer_1).first_name expect(body["last_name"]).to eq customers(:customer_1).last_name expect(body["created_at"]).to eq "2012-03-27T14:54:09.000Z" expect(body["updated_at"]).to eq "2012-03-27T14:54:09.000Z" end it "finds and serves one customers' json by last_name" do get :show, format: :json, last_name: customers(:customer_1).last_name expect(response.status).to eq(200) expect(response.content_type).to eq "application/json" body = JSON.parse(response.body) expect(body["first_name"]).to eq customers(:customer_1).first_name expect(body["last_name"]).to eq customers(:customer_1).last_name expect(body["created_at"]).to eq "2012-03-27T14:54:09.000Z" expect(body["updated_at"]).to eq "2012-03-27T14:54:09.000Z" end it "finds and serves one customers' json by created_at" do get :show, format: :json, created_at: customers(:customer_1).created_at expect(response.status).to eq(200) expect(response.content_type).to eq "application/json" body = JSON.parse(response.body) expect(body["first_name"]).to eq customers(:customer_1).first_name expect(body["last_name"]).to eq customers(:customer_1).last_name expect(body["created_at"]).to eq "2012-03-27T14:54:09.000Z" expect(body["updated_at"]).to eq "2012-03-27T14:54:09.000Z" end it "finds and serves one customers' json by updated_at" do get :show, format: :json, updated_at: customers(:customer_1).updated_at expect(response.status).to eq(200) expect(response.content_type).to eq "application/json" body = JSON.parse(response.body) expect(body["first_name"]).to eq customers(:customer_1).first_name expect(body["last_name"]).to eq customers(:customer_1).last_name expect(body["created_at"]).to eq "2012-03-27T14:54:09.000Z" expect(body["updated_at"]).to eq "2012-03-27T14:54:09.000Z" end end end
class Product < ApplicationRecord has_many :order_items validates_numericality_of :price validates_numericality_of :stock, :only_integer => true, :greater_than_or_equal_to => 0 def price=(input) input.delete!("$") super end end
require 'spotify_web/assertions' require 'spotify_web/event' require 'spotify_web/loggable' module SpotifyWeb # Represents a callback that's been bound to a particular event # @api private class Handler include Assertions include Loggable # The event this handler is bound to # @return [String] attr_reader :event # Whether to only call the handler once and then never again # @return [Boolean] +true+ if only called once, otherwise +false+ attr_reader :once # The data that must be matched in order for the handler to run # @return [Hash<String, Object>] attr_reader :conditions # Builds a new handler bound to the given event. # # @param [String] event The name of the event to bind to # @param [Hash] options The configuration options # @option options [Boolean] :once (false) Whether to only call the handler once # @option options [Hash] :if (nil) Data that must be matched to run # @raise [ArgumentError] if an invalid option is specified def initialize(event, options = {}, &block) assert_valid_values(event, *Event.commands.values) assert_valid_keys(options, :once, :if) options = {:once => false, :if => nil}.merge(options) @event = event @once = options[:once] @conditions = options[:if] @block = block end # Runs this handler for each result from the given event. # # @param [SpotifyWeb::Event] event The event being triggered # @return [Boolean] +true+ if conditions were matched to run the handler, otherwise +false+ def run(event) if conditions_match?(event.data) # Run the block for each individual result event.results.each do |args| begin @block.call(*args) rescue StandardError => ex logger.error(([ex.message] + ex.backtrace) * "\n") end end true else false end end private # Determines whether the conditions configured for this handler match the # event data def conditions_match?(data) if conditions conditions.all? {|(key, value)| data[key] == value} else true end end end end
class ServiceStat < ActiveRecord::Base belongs_to :custom belongs_to :station end
class AddIncludesRemixesToGenres < ActiveRecord::Migration def change add_column :genres, :includes_remixes, :boolean, :default => false end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :get_hostname_and_port before_filter :get_browser_details def get_hostname_and_port @host = request.host @port = request.port end def get_browser_details user_agent = UserAgent.parse(request.env['HTTP_USER_AGENT']) @browser = user_agent.browser @version = user_agent.version end end
class Debug def self.elapsed(name) puts "Performing #{name}" t = Time.now yield elapsed = (Time.now - t).to_f puts "took #{elapsed} seconds" end end
require 'spec_helper' require 'fog' require 'my_fog_helper' describe Fog do let(:username) { ENV['RAX_USERNAME'] } let(:api_key) { ENV['RAX_API_KEY'] } context "Mock with Fog", :mock => :fog do it "should create a server (Fog.mock!)", :mock => :fog do helper = MyFogHelper.new(username, api_key) server = helper.create_server() server.state.should eq('ACTIVE') end end context "Use VCR", :mock => :vcr do it "should create a server (vcr)", :vcr do helper = MyFogHelper.new(username, api_key) server = helper.create_server() server.state.should eq('ACTIVE') end end it "should create a server (live)", :live do helper = MyFogHelper.new(username, api_key) server = helper.create_server() server.state.should eq('ACTIVE') end end
class AddTuningIndices < ActiveRecord::Migration @@indices = { 'customers_labels' => :customer_id, 'vouchers' => :showdate_id, } def self.up @@indices.each_pair { |k,v| add_index k, v } end def self.down @@indices.each_pair { |k,v| remove_index k, v } end end
#Note that we are using Postgres and therefore ActiveRecord #we don't define attributes inside the classes but rather in the database tables class User < ActiveRecord::Base # validates_presence_of :email, :password validates_uniqueness_of :email validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i validates_length_of :email, maximum: 255 validates_length_of :password, minimum: 6, maximum: 20 has_many :lists end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :posts root 'posts#index' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed wit "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#/view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/ end
require 'spec_helper' describe Acfs::Collection do let(:model) { MyUser } describe 'Pagination' do let(:params) { Hash.new } let!(:collection) { model.all params } subject { Acfs.run; collection } context 'without explicit page parameter' do before do stub_request(:get, 'http://users.example.org/users') .to_return response([{id: 1, name: 'Anon', age: 12, born_at: 'Berlin'}], headers: { 'X-Total-Pages' => '2', 'X-Total-Count' => '10' }) end its(:total_pages) { should eq 2 } its(:current_page) { should eq 1 } its(:total_count) { should eq 10 } end context 'with page parameter' do let(:params) { {page: 2} } before do stub_request(:get, 'http://users.example.org/users?page=2') .to_return response([{id: 1, name: 'Anon', age: 12, born_at: 'Berlin'}], headers: { 'X-Total-Pages' => '2', 'X-Total-Count' => '10' }) end its(:total_pages) { should eq 2 } its(:current_page) { should eq 2 } its(:total_count) { should eq 10 } end context 'with non-numerical page parameter' do let(:params) { {page: 'e546f5'} } before do stub_request(:get, 'http://users.example.org/users?page=e546f5') .to_return response([{id: 1, name: 'Anon', age: 12, born_at: 'Berlin'}], headers: { 'X-Total-Pages' => '2', 'X-Total-Count' => '10' }) end its(:total_pages) { should eq 2 } its(:current_page) { should eq 'e546f5' } its(:total_count) { should eq 10 } end describe '#next_page' do before do stub_request(:get, 'http://users.example.org/users') .to_return response([{id: 1, name: 'Anon', age: 12, born_at: 'Berlin'}], headers: { 'X-Total-Pages' => '2', 'Link' => '<http://users.example.org/users?page=2>; rel="next"' }) end let!(:req) do stub_request(:get, 'http://users.example.org/users?page=2').to_return response([]) end let!(:collection) { model.all } subject { Acfs.run; collection.next_page } it { should be_a Acfs::Collection } it 'should have fetched page 2' do subject Acfs.run expect(req).to have_been_requested end end describe '#prev_page' do before do stub_request(:get, 'http://users.example.org/users?page=2') .to_return response([{id: 2, name: 'Anno', age: 1604, born_at: 'Santa Maria'}], headers: { 'X-Total-Pages' => '2', 'Link' => '<http://users.example.org/users>; rel="prev"' }) end let!(:req) do stub_request(:get, 'http://users.example.org/users').to_return response([]) end let!(:collection) { model.all page: 2 } subject { Acfs.run; collection.prev_page } it { should be_a Acfs::Collection } it 'should have fetched page 1' do subject Acfs.run expect(req).to have_been_requested end end describe '#first_page' do before do stub_request(:get, 'http://users.example.org/users?page=2') .to_return response([{id: 2, name: 'Anno', age: 1604, born_at: 'Santa Maria'}], headers: { 'X-Total-Pages' => '2', 'Link' => '<http://users.example.org/users>; rel="first"' }) end let!(:req) do stub_request(:get, 'http://users.example.org/users').to_return response([]) end let!(:collection) { model.all page: 2 } subject { Acfs.run; collection.first_page } it { should be_a Acfs::Collection } it 'should have fetched page 1' do subject Acfs.run expect(req).to have_been_requested end end describe '#last_page' do before do stub_request(:get, 'http://users.example.org/users?page=2') .to_return response([{id: 2, name: 'Anno', age: 1604, born_at: 'Santa Maria'}], headers: { 'X-Total-Pages' => '2', 'Link' => '<http://users.example.org/users?page=12>; rel="last"' }) end let!(:req) do stub_request(:get, 'http://users.example.org/users?page=12').to_return response([]) end let!(:collection) { model.all page: 2 } subject { Acfs.run; collection.last_page } it { should be_a Acfs::Collection } it 'should have fetched page 1' do subject Acfs.run expect(req).to have_been_requested end end end end
require 'spec_helper' require 'yt/models/claim' describe Yt::Claim do subject(:claim) { Yt::Claim.new data: data } describe '#id' do context 'given fetching a claim returns an id' do let(:data) { {"id"=>"aBcD1EfGHIk"} } it { expect(claim.id).to eq 'aBcD1EfGHIk' } end end describe '#asset_id' do context 'given fetching a claim returns an assetId' do let(:data) { {"assetId"=>"A123456789012601"} } it { expect(claim.asset_id).to eq 'A123456789012601' } end end describe '#video_id' do context 'given fetching a claim returns an videoId' do let(:data) { {"videoId"=>"9bZkp7q19f0"} } it { expect(claim.video_id).to eq '9bZkp7q19f0' } end end describe '#status' do context 'given fetching a claim returns a status' do let(:data) { {"status"=>"active"} } it { expect(claim.status).to eq 'active' } end end describe '#active?' do context 'given fetching a claim returns an active status' do let(:data) { {"status"=>"active"} } it { expect(claim).to be_active } end context 'given fetching a claim does not return an active status' do let(:data) { {"status"=>"unknown"} } it { expect(claim).not_to be_active } end end describe '#appealed?' do context 'given fetching a claim returns an appealed status' do let(:data) { {"status"=>"appealed"} } it { expect(claim).to be_appealed } end context 'given fetching a claim does not return an appealed status' do let(:data) { {"status"=>"unknown"} } it { expect(claim).not_to be_appealed } end end describe '#disputed?' do context 'given fetching a claim returns an disputed status' do let(:data) { {"status"=>"disputed"} } it { expect(claim).to be_disputed } end context 'given fetching a claim does not return an disputed status' do let(:data) { {"status"=>"unknown"} } it { expect(claim).not_to be_disputed } end end describe '#inactive?' do context 'given fetching a claim returns an inactive status' do let(:data) { {"status"=>"inactive"} } it { expect(claim).to be_inactive } end context 'given fetching a claim does not return an inactive status' do let(:data) { {"status"=>"unknown"} } it { expect(claim).not_to be_inactive } end end describe '#pending?' do context 'given fetching a claim returns an pending status' do let(:data) { {"status"=>"pending"} } it { expect(claim).to be_pending } end context 'given fetching a claim does not return an pending status' do let(:data) { {"status"=>"unknown"} } it { expect(claim).not_to be_pending } end end describe '#potential?' do context 'given fetching a claim returns an potential status' do let(:data) { {"status"=>"potential"} } it { expect(claim).to be_potential } end context 'given fetching a claim does not return an potential status' do let(:data) { {"status"=>"unknown"} } it { expect(claim).not_to be_potential } end end describe '#takedown?' do context 'given fetching a claim returns an takedown status' do let(:data) { {"status"=>"takedown"} } it { expect(claim).to be_takedown } end context 'given fetching a claim does not return an takedown status' do let(:data) { {"status"=>"unknown"} } it { expect(claim).not_to be_takedown } end end describe '#has_unknown_status?' do context 'given fetching a claim returns an unknown status' do let(:data) { {"status"=>"unknown"} } it { expect(claim).to have_unknown_status } end context 'given fetching a claim does not return an unknown status' do let(:data) { {"status"=>"active"} } it { expect(claim).not_to have_unknown_status } end end describe '#content_type' do context 'given fetching a claim returns a content type' do let(:data) { {"contentType"=>"audio"} } it { expect(claim.content_type).to eq 'audio' } end end describe '#audio?' do context 'given fetching a claim returns an audio content type' do let(:data) { {"contentType"=>"audio"} } it { expect(claim).to be_audio } end context 'given fetching a claim does not return an audio content type' do let(:data) { {"contentType"=>"audiovisual"} } it { expect(claim).not_to be_audio } end end describe '#video?' do context 'given fetching a claim returns an video content type' do let(:data) { {"contentType"=>"video"} } it { expect(claim).to be_video } end context 'given fetching a claim does not return an video content type' do let(:data) { {"contentType"=>"audiovisual"} } it { expect(claim).not_to be_video } end end describe '#audiovisual?' do context 'given fetching a claim returns an audiovisual content type' do let(:data) { {"contentType"=>"audiovisual"} } it { expect(claim).to be_audiovisual } end context 'given fetching a claim does not return an audiovisual content type' do let(:data) { {"contentType"=>"audio"} } it { expect(claim).not_to be_audiovisual } end end describe '#created_at' do context 'given fetching a claim returns a creation timestamp' do let(:data) { {"timeCreated"=>"2014-04-22T19:14:49.000Z"} } it { expect(claim.created_at.year).to be 2014 } end end describe '#block_outside_ownership?' do context 'given fetching a claim returns blockOutsideOwnership true' do let(:data) { {"blockOutsideOwnership"=>true} } it { expect(claim.block_outside_ownership?).to be true } end context 'given fetching a claim returns blockOutsideOwnership false' do let(:data) { {"blockOutsideOwnership"=>false} } it { expect(claim.block_outside_ownership?).to be false } end end describe '#match_reference_id' do context 'given fetching a claim returns matchInfo' do let(:data) { {"matchInfo"=>{"referenceId"=>"0r3JDtcRLuQ"}} } it { expect(claim.match_reference_id).to eq "0r3JDtcRLuQ" } end end describe '#third_party?' do context 'given fetching a claim returns thirdPartyClaim true' do let(:data) { {"thirdPartyClaim"=>true} } it { expect(claim.third_party?).to be true } end context 'given fetching a claim returns thirdPartyClaim true' do let(:data) { {"thirdPartyClaim"=>false} } it { expect(claim.third_party?).to be false } end end describe '#source' do context 'given fetching a claim returns a source' do let(:data) { {"origin"=>{"source"=>"webUpload"}} } it { expect(claim.source).to eq 'webUpload' } end context 'given fetching a claim does not return a source' do let(:data) { {"origin"=>{}} } it { expect(claim.source).to eq nil } end end end
require 'test_helper' class CriminalsControllerTest < ActionController::TestCase setup do @criminal = criminals(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:criminals) end test "should get new" do get :new assert_response :success end test "should create criminal" do assert_difference('Criminal.count') do post :create, criminal: @criminal.attributes end assert_redirected_to criminal_path(assigns(:criminal)) end test "should show criminal" do get :show, id: @criminal assert_response :success end test "should get edit" do get :edit, id: @criminal assert_response :success end test "should update criminal" do put :update, id: @criminal, criminal: @criminal.attributes assert_redirected_to criminal_path(assigns(:criminal)) end test "should destroy criminal" do assert_difference('Criminal.count', -1) do delete :destroy, id: @criminal end assert_redirected_to criminals_path end end
class DoctorPicturesController < ApplicationController before_action :set_doctor_picture def new @picture = DoctorPicture.new end def create @picture = DoctorPicture.new(doctor_picture_params) @picture.doctor = current_doctor if @picture.save flash[:notice] = "Foto guardada." redirect_to current_doctor else flash[:notice] = "Foto no guardada. Vuelve a intentar en un rato." render action: "new" end def edit end def update if @picture.update(doctor_picture_params) flash[:notice] = "Foto guardada." redirect_to current_doctor else flash[:alert] = "Foto no guardada. Vuelve a intentar en un rato." render action: "edit" end end def destroy @picture.destroy flash[:alert] = "Foto eliminada." redirect_to current_doctor end private def set_doctor_picture @picture = DoctorPictures.find(params[:id]) rescue ActiveRecord::RecordNotFound flash[:alert] = "No encontramos la foto que estabas buscando" redirect_to root_url end def doctor_picture_params params.require(:doctor_pictures).permit(:picture) end end
########################################################################## # Copyright 2022 Thoughtworks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ########################################################################## $stdout.sync = true $stderr.sync = true require 'timeout' require 'json' require 'net/http' require 'rubygems' require 'rubygems/version' PIPELINE_NAME = 'testpipeline'.freeze class GoCDApiVersion V = 'application/vnd.go.cd+json'.freeze V1 = 'application/vnd.go.cd.v1+json'.freeze V2 = 'application/vnd.go.cd.v2+json'.freeze V3 = 'application/vnd.go.cd.v3+json'.freeze V4 = 'application/vnd.go.cd.v4+json'.freeze V5 = 'application/vnd.go.cd.v5+json'.freeze V6 = 'application/vnd.go.cd.v6+json'.freeze V7 = 'application/vnd.go.cd.v7+json'.freeze V8 = 'application/vnd.go.cd.v8+json'.freeze end class Debian include Rake::DSL def repo open('/etc/apt/sources.list.d/gocd.list', 'w') do |f| f.puts('deb https://download.gocd.org /') f.puts('deb https://download.gocd.org/experimental /') end sh('curl --silent --fail --location https://download.gocd.org/GOCD-GPG-KEY.asc | apt-key add -') sh('apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get update') end def install(pkg_name, pkg_version) sh("apt-get -o Dpkg::Options::='--force-confdef' -o Dpkg::Options::='--force-confold' install -y #{pkg_name}=#{pkg_version}") end end class Redhat include Rake::DSL def repo sh('curl --silent --fail --location https://download.gocd.org/gocd.repo -o /etc/yum.repos.d/gocd.repo') sh("dnf clean all && dnf makecache --disablerepo='*' --enablerepo='gocd*'") end def install(pkg_name, pkg_verion) sh("dnf install --assumeyes --enablerepo='gocd*' #{pkg_name}-#{pkg_verion}") end end { 'debian' => Debian, 'centos' => Redhat }.each do |os, klass| namespace os do task :repo do klass.new.repo end task :install_latest_version => [:install_server, :install_agent] task :install_server do sh('pkill -f go-server') if server_running? klass.new.install('go-server', ENV['GO_VERSION']) if File.exist?('/usr/bin/java') sh ('unlink /usr/bin/java') sh ('ln -s -f /home/jdk-11/bin/java /usr/bin/java') end sh(%(echo "wrapper.java.additional.102=-Dgo.server.enable.tls=true" >> /usr/share/go-server/wrapper-config/wrapper-properties.conf)) chmod_R 0o755, '/configure/provision/filesystem/start-stop-gocd-server-agent.sh' sh("./configure/provision/filesystem/start-stop-gocd-server-agent.sh server start") server_status end task :install_agent do unless agent_any?(agent_api_version) klass.new.install('go-agent', ENV['GO_VERSION']) chmod_R 0o755, '/configure/provision/filesystem/start-stop-gocd-server-agent.sh' sh("./configure/provision/filesystem/start-stop-gocd-server-agent.sh agent start") end agent_status end task :install_old_version do klass.new.install('go-server', ENV['GO_INITIAL_VERSION']) if File.exist?('/usr/bin/java') sh ('unlink /usr/bin/java') sh ('ln -s -f /home/jdk-11/bin/java /usr/bin/java') end chmod_R 0o755, '/configure/provision/filesystem/start-stop-gocd-server-agent.sh' sh("./configure/provision/filesystem/start-stop-gocd-server-agent.sh server start") server_status klass.new.install('go-agent', ENV['GO_INITIAL_VERSION']) sh("./configure/provision/filesystem/start-stop-gocd-server-agent.sh agent start") agent_status end def server_running? begin sh(%(curl -I http://127.0.0.1:8153/go/about -o about.txt)) return true if File.readlines('about.txt').any? { |l| l['200 OK'] } rescue StandardError => e return false end false end def wait_to_start puts 'Wait server to come up' Timeout.timeout(120) do loop do begin puts '.' break if server_running? rescue StandardError => e end sleep 5 end end end def server_status wait_to_start end def agent_status puts 'wait for agent to come up' v = agent_api_version Timeout.timeout(180) do loop do break if agent_running?(v) sleep 5 end end end def agent_running?(v) sh "curl http://127.0.0.1:8153/go/api/agents -H 'Accept: #{v}' > temp.txt" agents = JSON.parse(File.read('temp.txt'))['_embedded']['agents'] if agents.any? { |a| a['agent_state'] == 'Idle' } puts 'Agent is up' return true end false end def agent_any?(v) sh "curl http://127.0.0.1:8153/go/api/agents -H 'Accept: #{v}' > temp.txt" agents = JSON.parse(File.read('temp.txt'))['_embedded']['agents'] if agents.any? { |a| ['Idle', 'Missing', 'Lost Contact'].include? a['agent_state'] } puts 'Agent is up' return true end false end def create_pipeline url = 'http://127.0.0.1:8153/go/api/admin/pipelines' puts 'create a pipeline' sh(%(curl --silent --fail --location --dump-header - -X POST -H "Accept: #{pipeline_api_version}" -H "Content-Type: application/json" --data "@/configure/provision/filesystem/pipeline.json" #{url})) end task :create_pipeline_by_config do create_pipeline end def unpause_pipeline url = "http://127.0.0.1:8153/go/api/pipelines/#{PIPELINE_NAME}/unpause" puts 'unpause the pipeline' sh(%(curl --silent --fail --location --dump-header - -X POST -H "Accept: #{pipeline_pause_api_version}" -H "Confirm: true" -H "X-GoCD-Confirm: true" #{url})) end def trigger_pipeline url = "http://127.0.0.1:8153/go/api/pipelines/#{PIPELINE_NAME}/schedule" puts 'trigger the pipeline' sh(%(curl --silent --fail --location --dump-header - -X POST -H "Accept: #{pipeline_schedule_api_version}" -H "Confirm: true" -H "X-GoCD-Confirm: true" #{url})) end task :trigger_pipeline_again do trigger_pipeline end task :check_pipeline_pass_with_label_1 do check_pipeline_in_cctray 1 end task :check_pipeline_pass_with_label_2 do check_pipeline_in_cctray 2 end def check_pipeline_in_cctray(label) cctray_response = nil Timeout.timeout(300) do loop do sh "curl http://127.0.0.1:8153/go/cctray.xml > temp.txt" cctray_response = File.read('temp.txt') status = cctray_response.match(/lastBuildStatus="(\w+)"/) puts "Pipeline build status #{status.captures}" if status if cctray_response.include? %(<Project name="#{PIPELINE_NAME} :: defaultStage" activity="Sleeping" lastBuildStatus="Success" lastBuildLabel="#{label}") puts 'Pipeline completed successfully' break end sleep 2 end end rescue Timeout::Error raise "Pipeline was not built successfully. Wait timed out. The CCTray response was: #{cctray_response}" end def current_gocd_version sh "curl http://127.0.0.1:8153/go/api/version -H 'Accept: #{GoCDApiVersion::V1}' > version.txt" Gem::Version.new(JSON.parse(File.read('version.txt'))['version']) end def agent_api_version if current_gocd_version >= Gem::Version.new('19.8.0') GoCDApiVersion::V else GoCDApiVersion::V4 end end def pipeline_api_version if current_gocd_version >= Gem::Version.new('19.8.0') GoCDApiVersion::V elsif current_gocd_version >= Gem::Version.new('19.6.0') GoCDApiVersion::V8 elsif current_gocd_version >= Gem::Version.new('19.4.0') GoCDApiVersion::V7 elsif current_gocd_version >= Gem::Version.new('18.11.0') GoCDApiVersion::V6 end end def pipeline_pause_api_version if current_gocd_version >= Gem::Version.new('19.8.0') GoCDApiVersion::V else GoCDApiVersion::V1 end end def pipeline_schedule_api_version if current_gocd_version >= Gem::Version.new('19.8.0') GoCDApiVersion::V else GoCDApiVersion::V1 end end def dashboard_api_version if current_gocd_version >= Gem::Version.new('19.8.0') GoCDApiVersion::V else GoCDApiVersion::V2 end end def check_pipeline_status dashboard_response = nil Timeout.timeout(180) do loop do sleep 5 sh "curl http://127.0.0.1:8153/go/api/dashboard -H 'Accept: #{dashboard_api_version}' > temp.txt" dashboard_response = JSON.parse(File.read('temp.txt')) if dashboard_response['_embedded']['pipeline_groups'][0]['_embedded']['pipelines'][0]['_embedded']['instances'][0]['_embedded']['stages'][0]['status'] == 'Passed' puts 'Pipeline completed with success' break end end end rescue Timeout::Error raise "Pipeline was not built successfully. The dashboard response was: #{dashboard_response}" end def server_version sh "curl http://127.0.0.1:8153/go/api/version -H 'Accept: #{GoCDApiVersion::V1}' > temp.txt" versions = JSON.parse(File.read('temp.txt')) "#{versions['version']}-#{versions['build_number']}" end task :fresh => [:repo, :install_latest_version, :create_pipeline_by_config, :check_pipeline_pass_with_label_1] task :setup => [:repo, :install_old_version, :create_pipeline_by_config, :check_pipeline_pass_with_label_1] task :upgrade => [:setup, :install_latest_version, :trigger_pipeline_again, :check_pipeline_pass_with_label_2] task :upgrade_test do upgrade_list = ENV['UPGRADE_VERSIONS_LIST'] p "this is the upgrade list #{upgrade_list}" upgrade_list.split(/\s*,\s*/).each do |version| begin ENV['GO_INITIAL_VERSION'] = version puts "upgrade test. Version FROM: #{ENV['GO_INITIAL_VERSION']} TO: #{ENV['GO_VERSION']}" Rake::Task["#{os}:upgrade"].invoke rescue StandardError => e raise "Installer testing failed. Error message #{e.message}" ensure Rake::Task["#{os}:upgrade"].reenable Rake::Task["#{os}:setup"].reenable Rake::Task["#{os}:repo"].reenable Rake::Task["#{os}:install_old_version"].reenable Rake::Task["#{os}:create_pipeline_by_config"].reenable Rake::Task["#{os}:check_pipeline_pass_with_label_1"].reenable Rake::Task["#{os}:install_server"].reenable Rake::Task["#{os}:trigger_pipeline_again"].reenable Rake::Task["#{os}:check_pipeline_pass_with_label_2"].reenable end end end end end
class SaldoBancarioHistorico < ActiveRecord::Base belongs_to :user belongs_to :saldo_bancario attr_accessible :valor, :valor_cents, :valor_currency, :user_id, :saldo_bancario, :fecha_de_alta monetize :valor_cents, :with_model_currency => :valor_currency validates :user_id, :presence => true validates :saldo_bancario, :presence => true validates :valor, :presence => true, :numericality => true validates :valor_currency, :presence => true validates :fecha_de_alta, :presence => true end
#!/bin/ruby class BotSaves def find_grid(grid, character) element = nil grid.each_with_index{|arr,index| element = [index,arr.index(character)] if arr.include?(character)} element end def displayPathtoPrincess(n,grid) n = n.to_i unless n%2 == 1 return "element should be odd number." end if n > 100 return "element should be less than 100" end unless n*n == grid.flatten.count return "wrong grid structure." end # find princess and boot princess = find_grid(grid, "p") boot = find_grid(grid, "m") if princess.nil? return "Princess not found in Grid" end if boot.nil? return "Bot not found in Grid" end # negative row difference implies UP # negative col difference implies LEFT drows = princess[0] - boot[0] dcols = princess[1] - boot[1] moves = [] if drows < 0 moves << 'UP\n' * (drows.abs) else moves << 'DOWN\n' * drows end if dcols < 0 moves << 'LEFT\n' * (dcols.abs) else moves << 'RIGHT\n' * dcols end moves.join("") end end
class JsonWebToken # Secret to encode/decode token HMAC_SECRET = MyVinylApi::Application.credentials.secret_key_base def self.encode(payload, exp = 24.hours.from_now) # Set expiration to 24 hours from now payload[:exp] = exp.to_i # Sign token with secret JWT.encode(payload, HMAC_SECRET) end def self.decode(token) # Get the paylod from the first index in decoded array body = JWT.decode(token, HMAC_SECRET)[0] HashWithIndifferentAccess.new body # Catch all decode errors rescue JWT::DecodeError => e # Throw a custom token auth error raise ExceptionHandler::InvalidToken, e.message end end
class CreateSavedSearch < ActiveRecord::Migration def change create_table :saved_searches do |t| t.references :user, index: true t.integer :year_min, :year_max t.decimal :price_min, :price_max t.float :length_min, :length_max t.string :length_unit t.string :manufacturer_model t.string :currency t.string :ref_no t.boolean :paid, :unpaid, :fresh, :used t.integer :first_found_boat_id t.datetime :created_at end end end
class AddColomnNamePhoneToUser < ActiveRecord::Migration def change add_column :users, :name, :string add_column :users, :phone, :string add_column :users, :gender, :string add_column :users, :birth, :datetime add_column :users, :address, :string add_column :users, :level, :integer add_column :users, :point, :integer add_column :users, :provider, :string add_column :users, :uid, :string end end
# Use this setup block to configure custom options in SimpleForm. SimpleForm.setup do |config| config.wrappers :wide_horizontal_form, tag: 'div', class: 'form-group', error_class: 'has-error' do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :pattern b.optional :min_max b.optional :readonly b.use :label, class: 'col-sm-6 control-label' b.wrapper tag: 'div', class: 'col-sm-6' do |ba| ba.use :input, class: 'form-control' ba.use :error, wrap_with: { tag: 'span', class: 'help-block' } ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' } end end config.wrappers :wide_horizontal_file_input, tag: 'div', class: 'form-group', error_class: 'has-error' do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :readonly b.use :label, class: 'col-sm-6 control-label' b.wrapper tag: 'div', class: 'col-sm-6' do |ba| ba.use :input, class: 'form-control' ba.use :error, wrap_with: { tag: 'span', class: 'help-block' } ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' } end end config.wrappers :wide_horizontal_boolean, tag: 'div', class: 'form-group', error_class: 'has-error' do |b| b.use :html5 b.optional :readonly b.wrapper tag: 'div', class: 'col-sm-offset-6 col-sm-6' do |wr| wr.wrapper tag: 'div', class: 'checkbox' do |ba| ba.use :label_input, class: 'col-sm-6' end wr.use :error, wrap_with: { tag: 'span', class: 'help-block' } wr.use :hint, wrap_with: { tag: 'p', class: 'help-block' } end end config.wrappers :wide_horizontal_radio_and_checkboxes, tag: 'div', class: 'form-group', error_class: 'has-error' do |b| b.use :html5 b.optional :readonly b.use :label, class: 'col-sm-6 control-label' b.wrapper tag: 'div', class: 'col-sm-6' do |ba| ba.use :input ba.use :error, wrap_with: { tag: 'span', class: 'help-block' } ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' } end end end
module SwellBot module Routing class RouteSet class RouteCollection def initialize() @collection = [] end def append( pattern, responder, action, options ) @collection << { pattern: pattern, responder: responder, action: action, options: options } self end def merge( route_collection ) @collection.concat( route_collection.collection ) end def collection @collection end end class ScopeCollection def initialize() @collection = {} end def append( scope, route_set ) @collection[scope] ||= [] @collection[scope] << route_set self end def merge( scope_collection ) scope_collection.collection.each do |key, route_sets| route_sets.each do |route_set| self.append key, route_set end end end def collection @collection end end def initialize( args = {} ) @default_responder = args[:default_responder] || 'SwellBot::TextResponder' @request_class = args[:request_class] || 'SwellBot::BotRequest' @bot_help = [] @routes = RouteCollection.new @scopes = ScopeCollection.new end def default_responder @default_responder end def default_args { default_responder: @default_responder, request_class: @request_class } end def draw(&block) # clear! #unless @disable_clear_and_finalize eval_block(block) # finalize! unless @disable_clear_and_finalize nil end def eval_block(block) mapper = Mapper.new( self ) mapper.instance_exec(&block) end def bot_help @bot_help end def scopes @scopes end def routes @routes end def merge( route_set ) @scopes.merge( route_set.scopes ) @routes.merge( route_set.routes ) end def build_request( message, session, scope, params, args = {} ) if args[:reply_mode] == 'select_reply' request = SwellBot::BotRequest.where( user: session.user ).friendly.find( message.to_i ) reply_to = request.reply_to else reply_to = args[:reply_to] reply_to ||= SwellBot::BotMessage.friendly.find( params[:reply_to_id] ) if params[:reply_to_id].present? request = @request_class.constantize.new request.reply_to = reply_to request.params = params.dup request.input = message request.scope = scope end request.thread_id = reply_to.try(:thread_id) || reply_to.try(:id) request.status = 'read' request.session = session request.user = session.user route = find_route :reply, request, (request.scope || '').split('/').collect(&:to_sym) if route.present? request.responder = route[:responder] request.action = route[:action] request.options = route[:options].stringify_keys request.route_set = route[:route_set] end request end def to_s "#{self.class.name} #{@routes.collection.to_json} #{@scopes.collection.keys.to_json}" end protected def find_route( type, request, scope_path ) route = nil current_scope = scope_path.shift unless current_scope.blank? request_scopes = @scopes.collection[current_scope] request_scopes.each do |scope| route ||= scope.find_route( type, request, scope_path ) break if route.present? end end route ||= @routes.collection.find{ |route| ( request.input =~ route[:pattern] ).present? } route.merge( route_set: self ) if route.present? end end end end
# frozen_string_literal: true require_relative 'output_presenter.rb' class LogParser # It presents the expected output into a more human readable output class TotalVisitsOutputPresenter < OutputPresenter def present output_sorted.map do |key, value| "#{key} #{value} visits" end end private def visited_pages parsed_file.map do |line| line.split(' ')[0] end end end end
class Organisation < ApplicationRecord SERVICE_OWNER_IATI_REFERENCE = "GB-GOV-13" strip_attributes only: [:iati_reference] has_many :users has_many :funds has_many :reports has_many :org_participations has_many :implementing_org_participations, -> { merge(OrgParticipation.implementing).distinct }, class_name: "OrgParticipation" has_many :activities, through: :org_participations has_many :implemented_activities, through: :implementing_org_participations, class_name: "Activity", source: :activity enum role: { partner_organisation: 0, matched_effort_provider: 1, external_income_provider: 2, implementing_organisation: 3, service_owner: 99 } validates_presence_of :organisation_type, :language_code, :default_currency validates :name, presence: true, uniqueness: {case_sensitive: false} validates :iati_reference, uniqueness: {case_sensitive: false}, presence: true, if: proc { |organisation| organisation.is_reporter? }, format: {with: /\A[a-zA-Z]{2,}-[a-zA-Z]{3}-.+\z/, message: I18n.t("activerecord.errors.models.organisation.attributes.iati_reference.format")} validates :beis_organisation_reference, uniqueness: {case_sensitive: false} validates :beis_organisation_reference, presence: true, if: proc { |organisation| organisation.is_reporter? }, format: {with: /\A[A-Z]{2,5}\z/, message: I18n.t("activerecord.errors.models.organisation.attributes.beis_organisation_reference.format")} scope :sorted_by_active, -> { order(active: :desc) } scope :sorted_by_name, -> { order(name: :asc) } scope :partner_organisations, -> { sorted_by_active.sorted_by_name.where(role: "partner_organisation") } scope :matched_effort_providers, -> { sorted_by_active.sorted_by_name.where(role: "matched_effort_provider") } scope :external_income_providers, -> { sorted_by_active.sorted_by_name.where(role: "external_income_provider") } scope :implementing, -> { where(<<~SQL organisations.id IN ( ( SELECT organisations.id FROM organisations INNER JOIN org_participations ON org_participations.organisation_id = organisations.id WHERE org_participations.role = 3 ) UNION ( SELECT organisations.id FROM organisations WHERE organisations.role = 3 ) ) SQL ) .sorted_by_active.sorted_by_name } scope :reporters, -> { sorted_by_name.where(role: ["partner_organisation", "service_owner"]) } scope :active, -> { where(active: true) } before_validation :ensure_beis_organisation_reference_is_uppercase def self.find_matching(name) where(name: name.strip) .or(where( Organisation .arel_table[:alternate_names] .contains([name]) )) .first end def role # temp hack whilst we figure out how to handle moving role from Org to OrgParticipation return "implementing_organisation" unless read_attribute(:role) super end def ensure_beis_organisation_reference_is_uppercase return unless beis_organisation_reference beis_organisation_reference.upcase! end def is_government? %w[10 11].include?(organisation_type) end def is_reporter? service_owner? || partner_organisation? end def self.service_owner find_by(iati_reference: SERVICE_OWNER_IATI_REFERENCE) end end
class AuthenticationProvider < ActiveRecord::Base has_many :authentication_stats has_many :users, :through => :authentication_stats class << self def [](name) find_by_name name end end end
# The Jak namespace module Jak # The parent Ability class, used to configure scopes to yield for class JakAbility cattr_accessor :yielded_skopes def initialize(resource, &block) @yielded_skopes ||= [] # Indicate what skopes we want included instance_eval(&block) if block_given? end # Add a scope to the list of yielded scopes def yield_skope(my_skope_name) if Jak.skope_manager.named_skopes.include?(my_skope_name) @yielded_skopes.push(my_skope_name) unless @yielded_skopes.include?(my_skope_name) else raise NotImplementedError, "Scope: #{my_skope_name} is not defined!" end end end end
require 'cgi' # unescapeHTML module Plugin::Mastodon::Parser def self.dehtmlize(html) result = html .gsub(%r!</p><p>!) { "\n\n" } .gsub(%r!<span class="ellipsis">([^<]*)</span>!) {|s| $1 + "..." } .gsub(%r!^<p>|</p>|<span class="invisible">[^<]*</span>|</?span[^>]*>!, '') .gsub(/<br[^>]*>|<p>/) { "\n" } .gsub(/&apos;/) { "'" } result end def self.dictate_score(html, mentions: [], emojis: [], media_attachments: [], poll: nil) desc = dehtmlize(html) score = [] pos = 0 anchor_re = %r|<a(?<attr1>[^>]*) href="(?<url>[^"]*)"(?<attr2>[^>]*)>(?<text>[^<]*)</a>| appeared_urls = Set.new while m = anchor_re.match(desc, pos) anchor_begin = m.begin(0) anchor_end = m.end(0) if pos < anchor_begin score << Plugin::Score::TextNote.new(description: CGI.unescapeHTML(desc[pos...anchor_begin])) end url = Diva::URI.new(CGI.unescapeHTML(m["url"])) if m["text"][0] == '#' || (score.last.to_s[-1] == '#') score << Plugin::Mastodon::Tag.new(name: CGI.unescapeHTML(m["text"]).sub(/\A#/, '')) else account = nil if mentions.any? { |mention| mention.url == url } mention = mentions.lazy.select { |mention| mention.url == url }.first acct = Plugin::Mastodon::Account.regularize_acct_by_domain(mention.url.host, mention.acct) account = Plugin::Mastodon::Account.findbyacct(acct) end if account score << account else link_hash = { description: CGI.unescapeHTML(m["text"]), uri: url, mastodon_link_attr: Hash.new, } attrs = m["attr1"] + m["attr2"] attr_pos = 0 attr_re = %r| (?<name>[^=]+)="(?<value>[^"]*)"| while m2 = attr_re.match(attrs, attr_pos) attr_name = m2["name"].to_sym attr_value = m2["value"] if [:class, :rel].include? attr_name link_hash[:mastodon_link_attr][attr_name] = attr_value.split(' ') else link_hash[:mastodon_link_attr][attr_name] = attr_value end attr_pos = m2.end(0) end score << Plugin::Score::HyperLinkNote.new(link_hash) end end appeared_urls << url pos = anchor_end end if pos < desc.size score << Plugin::Score::TextNote.new(description: CGI.unescapeHTML(desc[pos...desc.size])) end # 添付ファイル用のwork around # TODO: mikutter本体側が添付ファイル用のNoteを用意したらそちらに移行する media_attachments.reject { |a| appeared_urls.include?(a.url.to_s) || appeared_urls.include?(a.text_url.to_s) }.each do |attachment| url = attachment.url score << Plugin::Score::TextNote.new(description: "\n") << Plugin::Score::HyperLinkNote.new( description: attachment.text_url || url, uri: url, reference: Plugin.collect(:photo_filter, url).first ) end if poll y = [] poll.options.each do |opt| y << '○ %{title}' % {title: opt.title} end y << '%{count}票' % {count: poll.votes_count} if poll.expires_at y << '%{expire}に終了' % {expire: poll.expires_at.strftime("%Y-%m-%d %H:%M:%S")} end score << Plugin::Score::TextNote.new(description: "\n" + y.join("\n")) end score = score.flat_map do |note| if !note.is_a?(Plugin::Score::TextNote) [note] else emoji_score = Enumerator.new{|y| dictate_emoji(note.description, emojis, y) }.first.to_a if emoji_score.size > 0 emoji_score else [note] end end end description = score.inject('') do |acc, note| desc = note.is_a?(Plugin::Score::HyperLinkNote) ? note.uri.to_s : note.description acc + desc end [description, score] end # 与えられたテキスト断片に対し、emojisでEmojiを置換するscoreを返します。 def self.dictate_emoji(text, emojis, yielder) score = emojis.inject(Array(text)){ |fragments, emoji| shortcode = ":#{emoji.shortcode}:" fragments.flat_map{|fragment| if fragment.is_a?(String) if fragment === shortcode [emoji] else sub_fragments = fragment.split(shortcode).flat_map{|str| [str, emoji] } sub_fragments.pop unless fragment.end_with?(shortcode) sub_fragments end else [fragment] end } }.map{|chunk| if chunk.is_a?(String) Plugin::Score::TextNote.new(description: chunk) else chunk end } if (score.size > 1 || score.size == 1 && !score[0].is_a?(Plugin::Score::TextNote)) yielder << score end end end
require 'spec_helper' require 'reverse/polish/suray/operator/operator' describe Operator do describe '#class methods' do describe '#operators' do it 'should include at least one operator' do expect(Operator.operators.length).to be > 0 end end describe '#operator_symbols' do it 'should include the addition symbol' do expect(Operator.operator_symbols).to include '+' end end describe '#symbols_to_operators' do it 'should map + symbol to Addition class' do expect(Operator.symbols_to_operators['+']).to eq Operator::Addition end end end end
# PSEUDOCODE # Please write your pseudocode here and keep it commented # INPUT: A string for each of the methods # OUPUT: 1) A Boolean # 2) A String # 3) An Array # What are the steps to solve the problem? Write them out in plain english as best you can. # 1) Check if the string has a pattern that matches a Social Security number # 2) Look for the part of a string containing the Social Security number. # Return that Social Security number. # 3) Scan a string and return an array containing all the Social Security number matches. # 4) Locate Social Security numbers occurrences in a string and substitute the first 5 characters for 'X' # 5) Locate 9 numbers series in a string having dashes, points, or nothing in between and format them like a proper SOcial Security number using dashes. # INITIAL CODE: # This is the first version of code to pass the rspec tests and get all green. # Determine whether a string contains a Social Security number. def has_ssn?(string) string.match(/\d{3}-\d{2}-\d{4}/)? true : false end # Return the Social Security number from a string. def grab_ssn(string) if has_ssn?(string) ssn = string.match(/\d{3}-\d{2}-\d{4}/)[0] # Since match returns a Matchdata object, we get only the string from that object using [0] end end # Return all of the Social Security numbers from a string. def grab_all_ssns(string) string.scan(/\d{3}-\d{2}-\d{4}/) end # Obfuscate all of the Social Security numbers in a string. Example: XXX-XX-4430. def hide_all_ssns(string) string.gsub(/\d{3}-\d{2}/, "XXX-XX") end # Ensure all of the Social Security numbers use dashes for delimiters. # Example: 480.01.4430 and 480014430 would both be 480-01-4430. def format_ssns(string) string.gsub(/(\d{3})[-\.]?(\d{2})[-\.]?(\d{4})/, '\1-\2-\3' ) end ## Write some tests puts has_ssn?("please don't share this: 234-60-1422") == true puts has_ssn?("please confirm your identity: XXX-XX-1422") == false puts grab_ssn("please don't share this: 234-60-1422") == "234-60-1422"? true : false puts grab_ssn("please confirm your identity: XXX-XX-1422") == nil puts grab_all_ssns("234-60-1422, 350-80-0744, 013-60-8762") == ["234-60-1422", "350-80-0744", "013-60-8762"] puts grab_all_ssns("please confirm your identity: XXX-XX-1422") == [] # REFACTORED CODE: # see: http://sourcemaking.com/refactoring/introduction-to-refactoring def has_ssn?(string) (/\d{3}-\d{2}-\d{4}/) =~ string # The method =~ returns a boolean so no need for a conditional here end # Return the Social Security number from a string. def grab_ssn(string) string.slice(/\d{3}-\d{2}-\d{4}/) # Slice returns the matched pattern or nil, so no need for conditional here neither. end # Return all of the Social Security numbers from a string. def grab_all_ssns(string) string.scan(/\d{3}-\d{2}-\d{4}/) end # Obfuscate all of the Social Security numbers in a string. Example: XXX-XX-4430. def hide_all_ssns(string) string.gsub(/\d{3}-\d{2}/, "XXX-XX") end # Ensure all of the Social Security numbers use dashes for delimiters. # Example: 480.01.4430 and 480014430 would both be 480-01-4430. def format_ssns(string) string.gsub(/(\d{3})[-\.]?(\d{2})[-\.]?(\d{4})/, '\1-\2-\3' ) # It also looks for dashes optionally to detect also ssn numbers missing a dash end # REVIEW/REFLECT # Reflection is vital to learning and growth. These challenges should not be thought of as items # to check off; they are your opportunities to learn and grow as a programmer. # Use the following questions to reflect on this challenge. # Was your strategy for solving the challenge successful? # What part of your strategy worked? What parts were challenging? # What questions did you have while coding? Did you find answers to them? # Are there any concepts that are still confusing to you? # Did you learn any new skills or ruby tricks? # INCLUDE REFLECTION HERE: # Did this one with Armando and once we discovered we were using backslashes instead # of forward slashes to delimit the RegEx it all went smoothly. # We had read recntly about the methods that use RegEx so it was only a matter of # getting the expression right in Rubular and employing the appropiate method in each case. # We struggled a little in the second method, until we discovered that .match returns a # Matchdata object and we had to extract the match from there. # Refactoring I saw the chance to remove some conditionals and use the proper method instead, # like slice in the second method (I saw Wu was using it)
require "pry" class RotationalCipher LOWER_CASE_ALPHABET = ("a".."z").to_a.freeze UPPER_CASE_ALPHABET = ("A".."Z").to_a.freeze private_constant :LOWER_CASE_ALPHABET, :UPPER_CASE_ALPHABET def self.rotate(...) new(...).rotate end def initialize(input, cipher) @input = input.chars @cipher = cipher end def rotate @input.each_with_object([]) do |char, output| if LOWER_CASE_ALPHABET.include?(char) rotate_char(LOWER_CASE_ALPHABET, char, output) elsif UPPER_CASE_ALPHABET.include?(char) rotate_char(UPPER_CASE_ALPHABET, char, output) else output << char end end.join end private def rotate_char(char_list, char, output) output << char_list[(char_list.index(char) + @cipher) % 26] end end
require 'spec_helper' describe "forum/show.html.erb" do before(:each) do @question = Question.make! render end it "should have Question Title" do rendered.should have_selector("h1", :content => @question.title) end it "should have Question Text" do rendered.should have_selector("div", :id => "question_text", :content => @question.text) end it "should have link to Reply Form" do rendered.should have_selector("a", :content => "Responder") end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) # Added by Refinery CMS Pages extension Refinery::Pages::Engine.load_seed # Added by Refinery CMS Blog engine Refinery::Blog::Engine.load_seed # Added by Refinery CMS Inquiries engine Refinery::Inquiries::Engine.load_seed # Added by Refinery CMS Listings extension Refinery::Listings::Engine.load_seed # Home About Blog Contact Listings # ['Buyers','Communities','Sellers','Property Search','Business Directory'].each do |page| # Refinery::Page.find_or_create_by_title(page) # end # Create all communities and a child page of homes for each one # ['Redding', 'Anderson', 'Cottonwood', 'Shasta Lake City', 'Palo Cedro', 'Lakehead', 'Lake California'].each do |page| # x = Refinery::Page.find_by_title(page) # x.parent_id = 11 # x.save # end # Added by Refinery CMS Businesses extension Refinery::Businesses::Engine.load_seed # Added by Refinery CMS Events extension Refinery::Events::Engine.load_seed
json.array!(@office_blogs) do |office_blog| json.extract! office_blog, :id, :title json.url office_blog_url(office_blog, format: :json) end
require 'spec_helper' describe "Shopping Cart Requests" do let!(:user) { Fabricate(:user) } let!(:product) { Fabricate(:product, :title => "iPod") } let!(:product2) { Fabricate(:product, :title => "Macbook Pro") } context "when logged in as a normal user" do context "and logged in" do before(:each) { login } it "shows the logged in users' cart items " do user.shopping_cart = Fabricate(:shopping_cart) user.shopping_cart.add_item(product.id, 10) visit shopping_cart_path find_link(product.title).visible? end it "allows me to remove an item from my cart" do user.shopping_cart = Fabricate(:shopping_cart) user.shopping_cart.add_item(product.id, 10) user.shopping_cart.add_item(product2.id, 20) visit shopping_cart_path click_link("Remove") page.should_not have_content(product.title) page.should have_content(product2.title) end context "When I check out" do it "brings me to the shipping address page" do user.shopping_cart = Fabricate(:shopping_cart) user.shopping_cart.add_item(product.id, 10) visit shopping_cart_path click_link("Checkout") current_path.should == new_billing_address_path end end end context "When I update the shopping cart" do let(:cart) { Fabricate(:shopping_cart) } before(:each) do login user.shopping_cart = cart cart.add_item(product.id, 10) end let(:text_field_id) { "quantity[#{cart.cart_items.first.id}]" } it "changes the quantity of an item" do visit shopping_cart_path fill_in text_field_id, :with => 3 click_button("Update Shopping cart") find_field(text_field_id).value.should == "3" end it "changes the quantity of multiple item" do cart.add_item(product2.id, 50) visit shopping_cart_path text_field_id2 = "quantity[#{cart.cart_items.second.id}]" fill_in text_field_id, :with => 3 fill_in text_field_id2, :with => 9 click_button("Update Shopping cart") find_field(text_field_id).value.should == "3" find_field(text_field_id2).value.should == "9" end end end context "when not logged in" do it "does not allow checkout" do visit shopping_cart_path page.should_not have_content("Checkout") end end end
include Java java_import Java.hudson.BulkChange java_import Java.hudson.model.listeners.SaveableListener class HelloworldDescriptor < Jenkins::Model::DefaultDescriptor include Jenkins::Model::Descriptor attr_accessor :gname def initialize *a super load end java_signature 'public FormValidation doCheckName(@QueryParameter String value)' def doCheckName value p value Java.FormValidation.ok end def configure req, json parse json save true end def parse form @gname = form["gname"] end def save return if BulkChange.contains self begin File.open(configFile.file.canonicalPath, 'wb') do |f| f.write(to_xml) end SaveableListener.fireOnChange(self, configFile) rescue IOError => e p e.message end end def load return unless configFile.file.exists from_xml(File.read(configFile.file.canonicalPath)) end def to_xml "<?xml version='1.0' encoding='UTF-8'?> <#{id} plugin='hellowolrdbuilder'> <gname>#{@gname}</gname> </#{id}>" end def from_xml xml @gname = xml.scan(/<gname>(.*)<\/gname>/).flatten.first end end
desc 'Setups Google Spreadsheet access' task :setup_google_auth do require 'yaml' require 'signet/oauth_2/client' require "highline/import" say "To use data from Google drive:" say "Create a new project with Google's Developer Platform:" say "<%= color('https://console.developers.google.com/project', :blue) %>" say "Go to the project, select APIs & Auth > APIs from left menu" say "Pick the 'Drive API' and make sure it's enabled." say "Then select APIs & Auth > Credentials from left menu" say "Create new OAuth Client ID" say "Pick 'Installed Application' and fill out information" client_id = ask "<%= color('Enter your Google Drive API Client ID:', :white) %> " client_secret = ask "<%= color('Enter your Google Drive API Client Secret:', :white) %> " auth = Signet::OAuth2::Client.new( :authorization_uri => 'https://accounts.google.com/o/oauth2/auth', :token_credential_uri => 'https://www.googleapis.com/oauth2/v3/token', :client_id => client_id, :client_secret => client_secret, :scope => "https://www.googleapis.com/auth/drive " + "https://spreadsheets.google.com/feeds/", :redirect_uri => 'urn:ietf:wg:oauth:2.0:oob', ) unless system("open '#{auth.authorization_uri}'") say "Open this page in your browser:" say "<%= color('#{auth.authorization_uri}', :blue) %>" end auth.code = ask "<%= color('Enter the authorization code shown in the page:', :white) %> " auth.fetch_access_token! config = YAML::load_file('config.yml') config['google_drive_credentials'] = "#{auth.client_id}:#{auth.client_secret}:#{auth.refresh_token}" File.write('config.yml', config.to_yaml) say "<%= color('OAuth credentials generated and stored in ', :green) %> <%= color('config.yml', :bold) %> " end
class CarsController < ApplicationController respond_to :html, :json, :js before_action :set_car, only:[:show, :edit, :update, :destroy] def index if params[:search_for].present? @cars = Car.search_for(params[:search_for]) else @cars = Car.all end end def show end def new @car= Car.new end def edit end def create @car= Car.new(car_params) respond_to do |format| if @car.save format.html{redirect_to @car} else format.html{render:new} end end end def update respond_to do |format| if @car.update(car_params) format.html{redirect_to @car} else format.html{render:edit} end end end def destroy @car.destroy respond_to do |format| format.html{redirect_to @car} end end private def set_car @car= Car.find(params[:id]) end def car_params params.require(:car).permit(:brand, :model, :registration_number, :colour ) end end
require './lib/db/connect.rb' require './lib/string.rb' require 'uri' require 'digest/sha1' class Peep def self.query(query, db_connection = Connect.initiate(:chitter)) db_connection.exec(query) end def self.keys_and_values @query_keys, @query_values = [], [] end def nth(n) return self[[n.to_i, 0].max] unless self.count <= [n.to_i, 0].max nil end def self.not_an_email_address(key, value) unless (key.to_s.clean_key.downcase == "email") && (value.to_s =~ URI::MailTo::EMAIL_REGEXP) != 0 true else false end end def self.check_key_value_return(value = :NULL, key = :NULL) return if key.to_s.clean_key.downcase == "submit" @query_values << value.to_s.clean_value.to_i if key.to_s.clean_key.downcase == "id" && value.to_s.clean_value.to_i.is_a?(Integer) @query_values << value.to_s.clean_value if key.to_s.clean_key.downcase != "id" @query_keys << key.to_s.clean_key end def self.add(table_column_values_hash = {}) [keys_and_values, table_column_values_hash.each { |key, value| check_key_value_return(value, key) }] return nil if @query_keys.count != @query_values.count || table_column_values_hash.empty? p @query_values p @query_keys users_return = query("INSERT INTO peeps (#{@query_keys.join(",")}) VALUES (#{@query_values.join(",")}) RETURNING id").to_a (users_return.nil? || (users_return.count != 1)) ? nil : users_return end def self.find(id) return nil unless id.to_s.to_i.is_a?(Integer) users_return = query("SELECT * FROM peeps WHERE id = #{id.to_s.to_i}").to_a users_return.map{ |pair| pair.transform_keys(&:to_sym) } end def self.delete(id) [keys_and_values, check_key_value_return(id, :id)] query("DELETE FROM peeps WHERE id = #{@query_values.last}") end def self.all(order_by = 'DESC', limit = 100) users_return = query("SELECT * FROM peeps ORDER BY created_at #{order_by} LIMIT #{limit.to_s}").to_a users_return.map{ |pair| pair.transform_keys(&:to_sym) } end end
# striuct - Struct++ # Copyright (c) 2011-2012 Kenichi Kamiya # @abstract class Striuct class Error < StandardError; end class InvalidOperationError < Error; end end require_relative 'striuct/requirements'
require 'dmtd_vbmapp_data/request_helpers' module DmtdVbmappData # Provides for the retrieving of VB-MAPP Protocol Area information from the VB-MAPP Data Server. class ProtocolArea # @!attribute [r] client # @return [Client] the associated client attr_reader :client # @!attribute [r] area # @return [Symbol] the area of the question (e.g. :milestones, :barriers, :transitions, :eesa) attr_reader :area # Creates an accessor for the VB-MAPP Guide Chapter on the VB-MAPP Data Server # # @note This method does *not* block, simply creates an accessor and returns # # @option opts [Client] :client A client instance # @option opts [Hash] :area_index_json The vbmapp area index json for the VB-Mapp Area in the format described at # {https://datamtd.atlassian.net/wiki/pages/viewpage.action?pageId=18710543 /1/protocol/index - GET REST api - Area Fields} def initialize(opts) @client = opts.fetch(:client) index_json = opts.fetch(:area_index_json) @area = index_json[:area].to_sym @groups_index = index_json[:groups] end # @note This method does *not* block on server access # # @return [Array<ProtocolAreaGroup>] all of the VB-Mapp's {ProtocolAreaGroup} instances def groups @groups = @groups_index.map.with_index do |group_index_json, group_num| ProtocolAreaGroup.new(client: client, area: area, group_index_json: group_index_json) end if @groups.nil? @groups end end end
class AddTpaStartEndDatesToAccounts < ActiveRecord::Migration def change add_column :accounts, :tpa_start_date, :date add_column :accounts, :tpa_end_date, :date end end
class User < ApplicationRecord devise :database_authenticatable, :registerable, :omniauthable, :omniauth_providers => [:facebook] validates_presence_of :email, if: :is_not_from_host?, message: 'Емаилот не може да биде празен' validates_presence_of :password,if: :is_not_from_host?, message: 'Лозинката не може да биде празна' validates_presence_of :name, if: :is_not_from_host?, message: 'Името и Презимето не мозат да бидат празни' def exists_with_email? User.exists?(email: email) end def self.new_with_session(params, session) super.tap do |user| if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"] user.email = data["email"] if user.email.blank? end end end def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.email = auth.info.email user.name = auth.info.name end end def is_not_from_host? !provider.present? end end
#1 PARA n class Aluno def initialize(nome, ra) @nome = nome @ra = ra end def mostrar_dados puts "Nome: #{@nome}" puts "RA: #{@ra}" end end class Disciplina def initialize(nome) @nome = nome @alunos = [] end def trancar(aluno) # JEITO DO RUBY DE GARANTIR QUE EH ALUNO case aluno when Aluno @alunos -= [aluno] else puts "Erro..." end end def matricular(aluno) # JEITO DO RUBY DE GARANTIR QUE EH ALUNO case aluno when Aluno @alunos << aluno else puts "Erro..." end end def listar puts "Disciplina: #{@nome}" for aluno in @alunos aluno.mostrar_dados end end end #Quero 6 alunos e um trancamento em #uma disciplina. #Fazer a chamada dos 5. a1 = Aluno.new("Italo","0050831721016") a2 = Aluno.new("Lucas M","0050831722469") a3 = Aluno.new("Marcus","0050831811001") a4 = Aluno.new("Jordana","0050831722210") a5 = Aluno.new("Teste","0050831720000") a6 = Aluno.new("Teste1","0050831720001") d = Disciplina.new("IDS-001 Desenv p Serv I") d.matricular a1 d.matricular a2 d.matricular a3 d.matricular a4 d.matricular a5 d.matricular a6 d.trancar a5 d.listar
class Board < ApplicationRecord has_many :lists has_many :tasks, through: :lists accepts_nested_attributes_for :lists end
require 'webmock' require 'webmock/rspec' $:.unshift(File.dirname(__FILE__) + '/../lib') require 'imdb' def read_fixture(path) File.read(File.expand_path(File.join(File.dirname(__FILE__), "fixtures", path))) end IMDB_SAMPLES = { "http://www.imdb.com/find?q=Kannethirey+Thondrinal&s=tt" => "search_kannethirey_thondrinal", "http://www.imdb.com/find?q=Matrix+Revolutions&s=tt" => "search_matrix_revolutions", "http://www.imdb.com/find?q=Star+Trek&s=tt" => "search_star_trek", "http://www.imdb.com/title/tt0117731/" => "tt0117731", "http://www.imdb.com/title/tt0095016/" => "tt0095016", "http://www.imdb.com/title/tt0242653/" => "tt0242653", "http://www.imdb.com/title/tt0242653/?fr=c2M9MXxsbT01MDB8ZmI9dXx0dD0xfG14PTIwfGh0bWw9MXxjaD0xfGNvPTF8cG49MHxmdD0xfGt3PTF8cXM9TWF0cml4IFJldm9sdXRpb25zfHNpdGU9ZGZ8cT1NYXRyaXggUmV2b2x1dGlvbnN8bm09MQ__;fc=1;ft=20" => "tt0242653", "http://www.imdb.com/chart/top" => "top_250", "http://www.imdb.com/title/tt0111161/" => "tt0111161", #Die Verurteilten, (image, original title, release date) "http://www.imdb.com/title/tt1352369/" => "tt1352369", #Gurotesuku (long plot) "http://www.imdb.com/title/tt0083987/" => "tt0083987", "http://www.imdb.com/title/tt0036855/" => "tt0036855", #Gaslight "http://www.imdb.com/title/tt0110912/" => "tt0110912", #Pulp Fiction "http://www.imdb.com/title/tt0330508/" => "tt0330508", #Kannethirey Thondrinal (no image) "http://www.imdb.com/title/tt0330508/?fr=c2M9MXxsbT01MDB8ZmI9dXx0dD0xfG14PTIwfGh0bWw9MXxjaD0xfGNvPTF8cG49MHxmdD0xfGt3PTF8cXM9S2FubmV0aGlyZXkgVGhvbmRyaW5hbHxzaXRlPWFrYXxxPUthbm5ldGhpcmV5IFRob25kcmluYWx8bm09MQ__;fc=1;ft=1" => "tt0330508" } def mock_requests IMDB_SAMPLES.each_pair do |url, response| stub_request(:get, url).to_return(:body => read_fixture(response)) end WebMock.after_request do |request_signature, response| #puts "Request #{request_signature} was made." end end unless ENV['LIVE_TEST'] #FakeWeb.allow_net_connect = false WebMock.disable_net_connect! RSpec.configure do |config| config.before(:each) {mock_requests} #config.before(:each) {} #config.after(:all) {} #config.after(:each) {} end end
describe GP do describe "trouver" do context "base de donnees avec plusieurs pieces" do let(:lignes) { IO.readlines("#{REPERTOIRE_TESTS}/piece.txt.2") } let(:attendu) { ['A00001 Info: "INTEL I7" Type : CPU']} it "trouve une piece avec un numero de serie " do avec_fichier '.depot.txt', lignes do genere_sortie( attendu ) do gp( 'trouver A00001' ) end end end end end end
json.array!(@conversations) do |conversation| json.extract! conversation, :theme, :id end
require 'spec_helper' describe Store do it { should validate_presence_of :name } it { should validate_presence_of :token } it { should validate_uniqueness_of :token } end
class AddIdToActorsCategories < ActiveRecord::Migration def change add_column :actors_categories, :id, :primary_key end end
module Offers class GetOffers include Service def initialize(attrs = {}) @params = attrs.fetch(:params) @user = attrs.fetch(:user) end def call #TODO search by ActiveRecord if Elastic is not working Elasticsearch::Search::Offers::GetOffers.new(params: params.merge!(user_id: user.id)).call end end end