text
stringlengths
10
2.61M
require 'rails_helper' RSpec.describe 'Data', type: :request do describe 'GET /api/v1/data' do before do FactoryBot.create_list(:c14, 10) get '/api/v1/data' end it 'returns all C14s' do expect(json.size).to eq(C14.count) end it 'returns status code 200' do expect(response).to have_http_status(:success) end specify do expect(json.count).to eq C14.count expect(json).to match_response_schema('apiv1') end it 'processes a site without site' do this_date = FactoryBot.create(:c14) this_date.context.site = nil get '/api/v1/data' expect(response).to have_http_status(:success) end it 'processes a site without site_types' do this_date = FactoryBot.build(:c14) this_date.sample.context.site.site_types = [] this_date.save get '/api/v1/data' expect(response).to have_http_status(:success) end end end
namespace :export do desc "Prints all ActiveModel data in seed.rb file." task :seed_format => :environment do Contract.order(:id).all.each do |contract| #puts "Contract.create(#{contract.serializable_hash.delete_if {|key, value| ['created_at', 'updated_at', 'id'].include?(key)}.to_s.gsub(/[{}]/,"")})" puts "Contract.create(#{contract.serializable_hash.delete_if {|key, value| ['created_at', 'updated_at', 'id'].include?(key)}.to_s})" end end end
class Group < ActiveRecord::Base has_many :reservations belongs_to :user acts_as_paranoid end
class Weight < ActiveRecord::Base validates :weight, presence: {message: 'You must enter a weight'} validates :date_weighed, presence: {message: 'You must enter a date for when you were weighed'} end
require 'sketchup.rb' require 'extensions.rb' folder_path = '/Users/vivek/SkpDesk/Current' folder_path = '/Users/vivek/Desktop/sdesk_lib' loader = File.join(folder_path, 'skpdesk_loader.rb') title = 'SKP Design Kit' ext = SketchupExtension.new(title, loader) ext.version = '1.0.0' ext.copyright = 'Skpdesk - 2020' ext.creator = 'Skpdesk.com' Sketchup.register_extension(ext, true)
class SumOfMultiples def self.to(limit) new(3, 5).to(limit) end def initialize(*factors) @factors = factors end def to(limit) (1...limit).select do |int| @factors.any? { |factor| int % factor == 0 } end.sum end end # Initial solution # def to(limit) # multiples = [] # (1...limit).each do |int| # @factors.each do |factor| # multiples << int if int % factor == 0 # end # end # multiples.uniq.sum # end
class CreateBoatCategories < ActiveRecord::Migration def change create_table :boat_categories do |t| t.string :name, index: true t.boolean :active, index: true, default: false t.timestamps null: false end add_column :boats, :category_id, :integer, index: true, foreign_key: true end end
class CreateCentralityNodes < ActiveRecord::Migration[5.1] def change create_table :centrality_nodes do |t| t.string :label t.integer :size t.integer :x_pos t.integer :y_pos t.integer :results_id t.integer :centrality_result_set_id t.timestamps end end end
class RestaurantsController < ApplicationController before_action :set_restaurant, only: [:show, :edit, :update, :destroy, :edit_gallery, :add_photo] before_action :set_restaurant_destroy_photo, only: [:destroy_photo] before_action :set_location, only: [:new, :edit, :create] before_action :authenticate_user!, except: [:index, :show] before_action :verify_user, except: [:index, :show] # GET /restaurants # GET /restaurants.json def index @restaurants = Restaurant.all end # GET /restaurants/1/edit_gallery def edit_gallery @restaurant_gallery = RestaurantGallery.new @restaurant_galleries = @restaurant.restaurant_galleries end # POST /restaurants/1/edit_gallery/add_photo def add_photo if(@restaurant.restaurant_galleries.size<10) @photo = RestaurantGallery.new(:photo=>params[:photo], :restaurant_id=>params[:id]) respond_to do |format| if(@photo.save) format.js { head :ok } end end end end # DELETE /destroy_photo_pousada/1 def destroy_photo @photo = RestaurantGallery.find(params[:id]) @photo.destroy redirect_to edit_gallery_restaurant_path(@photo.restaurant) end # GET /restaurants/1 # GET /restaurants/1.json def show end # GET /restaurants/new def new @restaurant = Restaurant.new end # GET /restaurants/1/edit def edit end def update_cities_restaurant @cidades = Cidade.where("estado_id = ?", params[:estado_id]) if @cidades.length > 0 @cidades = @cidades.sort end respond_to do |format| format.js end end def update_estados_restaurant @estados = Estado.where("pais_id = ?", params[:pais_id]) @cidades = [] if @estados.length > 0 @cidades = Cidade.where("estado_id = ?", @estados.first.id).sort end @locais = [@estados, @cidades] respond_to do |format| format.js end end # POST /restaurants # POST /restaurants.json def create @restaurant = Restaurant.new(restaurant_params) @restaurant.user_id = current_user.id respond_to do |format| if @restaurant.save format.html { redirect_to @restaurant, notice: 'Restaurant was successfully created.' } format.json { render :show, status: :created, location: @restaurant } else format.html { render :new } format.json { render json: @restaurant.errors, status: :unprocessable_entity } end end end # PATCH/PUT /restaurants/1 # PATCH/PUT /restaurants/1.json def update respond_to do |format| if @restaurant.update(restaurant_params) format.html { redirect_to @restaurant, notice: 'Restaurant was successfully updated.' } format.json { render :show, status: :ok, location: @restaurant } else format.html { render :edit } format.json { render json: @restaurant.errors, status: :unprocessable_entity } end end end # DELETE /restaurants/1 # DELETE /restaurants/1.json def destroy @restaurant.restaurant_galleries.each do |i| i.destroy end @restaurant.destroy respond_to do |format| format.html { redirect_to restaurants_url, notice: 'Restaurant was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_restaurant @restaurant = Restaurant.find(params[:id]) end def set_restaurant_destroy_photo @restaurant = RestaurantGallery.find(params[:id]).restaurant end # Never trust parameters from the scary internet, only allow the white list through. def restaurant_params params.require(:restaurant).permit(:nome, :pais_id, :estado_id, :cidade_id, :rua, :numero, :descricao, :logo, :restaurant_galleries_attributes => [:photo]) end def set_location @cidades = Cidade.all @estados = Estado.all @paises = Pais.all end def verify_user if(current_user.prioridade != 0 && current_user.prioridade != 4) redirect_to root_path elsif(current_user.prioridade == 4) if(current_user.restaurant[0]) if(!@restaurant || current_user.restaurant[0].id != @restaurant.id) redirect_to root_path end else if(@restaurant) redirect_to root_path end end end end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant::Config.run do |config| # Every Vagrant virtual environment requires a box to build off of. config.vm.box = "precise64" # Forward a port from the guest to the host, which allows for outside # computers to access the VM, whereas host only networking does not. # config.vm.forward_port 80, 8080 config.vm.forward_port 27017, 27017 config.vm.forward_port 8080, 8125 # Enable provisioning with chef solo, specifying a cookbooks path (relative # to this Vagrantfile), and adding some recipes and/or roles. config.vm.provision :chef_solo do |chef| chef.cookbooks_path = [ "cookbooks" ] chef.add_recipe "mongodb-10gen::single" chef.add_recipe "java" chef.add_recipe "setup-mongo::default" chef.add_recipe "tomcat" chef.add_recipe "setup-tomcat" # # You may also specify custom JSON attributes: # chef.json = { :mysql_password => "foo" } end end
class Leaders::EvaluationsController < ApplicationController include ActionView::Layouts include ActionController::MimeResponds acts_as_token_authentication_handler_for User before_action :leader? before_action :set_evaluation, only: [:show, :update] respond_to :json def index page = params[:page] || 1 per_page = params[:per_page] || 10 @evaluations = current_user.evaluations.paginate(page: page, per_page: per_page) respond_with(@evaluations) end def show respond_with(@evaluation) end # def create # @evaluation = Leader::Evaluation.new(evaluation_params) # @evaluation.save # respond_with(@evaluation) # end def update @evaluation.already_edited = true @evaluation.update(evaluation_params) respond_with @evaluation, template: "leaders/evaluations/show", status: 201 end # def destroy # @evaluation.destroy # respond_with(@evaluation) # end private def leader? @error = '用户没有访问权限' render @error, status: 401, template: "error" unless current_user.right_type?('leader') end def set_evaluation @evaluation = current_user.evaluations.find(params[:id]) end def evaluation_params params.require(:evaluation).permit( :duties, :thought_morals, :upright_incorruptiable, :evaluation_totality ) end end
class Product < ApplicationRecord belongs_to :supplier scope :by_name, -> { order(:name) } end
def number_to_digits(n) n.to_s.split('').map(&:to_i) end def digits_to_number(arr) arr.map(&:to_s).reduce(:+).to_i end def grayscale_histogram(image) arr = (0..255).map { 0 }.to_a image.flatten.each { |x| arr[x] += 1 } arr end def sum_matrix(m) m.flatten.reduce(:+) end def max_scalar_product(v1, v2) sorted1 = v1.sort sorted2 = v2.sort (0..(v1.size - 1)).map { |i| sorted1[i] * sorted2[i] }.reduce(:+) end def max_span(numbers) unique = numbers.uniq reversed_numbers = numbers.reverse spans = [] unique.each do |num| first_index = numbers.find_index(num) last_index = numbers.count - reversed_numbers.find_index(num) span = last_index - first_index spans.push span end spans.max end def _bombard(row, col, m) bomb = m[row][col] damage = 0 (-1..1).each do |row_offset| (-1..1).each do |col_offset| is_the_same_cell = row_offset.zero? && col_offset.zero? target = { row: row + row_offset, col: col + col_offset } next unless !is_the_same_cell && _in_range(target[:row], target[:col], m) damage += _calculate_damage(m[target[:row]][target[:col]], bomb) end end damage end def _calculate_damage(target, bomb) target >= bomb ? bomb : target end def _in_range(row, col, m) in_row_range = 0 <= row && row <= m.size - 1 in_col_range = 0 <= col && col <= m[0].size - 1 in_row_range && in_col_range end def matrix_bombing_plan(m) matrix_sum = m.flatten.reduce(:+) result = {} m.size.times do |row| m[0].size.times do |col| result[[row, col]] = matrix_sum - _bombard(row, col, m) end end result end def max_consecutive(items) max = curr_max = 0 (0..items.size - 2).each do |i| current = items[i] following = items[i + 1] if current == following curr_max = curr_max.zero? ? 2 : curr_max + 1 else max = curr_max if curr_max > max curr_max = 0 end end max > curr_max ? max : curr_max end def group(items) return 'edge case' if items.count <= 2 main_arr = [] i = 0 while i < items.size sequence = _count_equal_consecutive_elements(items, i) main_arr.push(Array.new(sequence, items[i])) i += sequence end main_arr end def _count_equal_consecutive_elements(items, i) size = items.size last_index = size - 1 before_last_index = size - 2 # предпоследен return 0 if size.zero? || i >= size return 1 if i == last_index if i == before_last_index return (items[before_last_index] == items[last_index] ? 2 : 1) end arr = items.slice(i, items.size) _count_equal_elements_from_the_beginning(arr) end def _count_equal_elements_from_the_beginning(arr) count = 1 i = 0 while arr[i] == arr[i + 1] count += 1 i += 1 end count end
require_relative 'boot' require 'rails' require 'active_model/railtie' require 'active_job/railtie' require 'active_record/railtie' require 'active_storage/engine' require 'action_controller/railtie' require 'action_mailer/railtie' require 'action_view/railtie' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module CodeChallengeRails class Application < Rails::Application config.middleware.use Rack::Deflater config.load_defaults 6.0 config.i18n.available_locales = %i[en] config.i18n.default_locale = :en config.exceptions_app = routes # Tell Zeitwerk to ignore the vue directory for autoloading Rails.autoloaders.main.ignore(Rails.root.join('app/vue')) # Source: https://guides.rubyonrails.org/v5.0/security.html#default-headers config.action_dispatch.default_headers = { 'X-Frame-Options' => 'DENY', 'X-XSS-Protection' => '1; mode=block', 'X-Content-Type-Options' => 'nosniff', } config.generators do |g| g.test_framework :rspec g.fixture_replacement :factory_bot, dir: 'spec/factories' g.orm :active_record, primary_key_type: :uuid end end end
class AddMissingImportsAttributes < ActiveRecord::Migration[4.2] def change add_column :imports, :publish, :boolean add_column :imports, :default_namespace, :string end end
class Post < ActiveRecord::Base validates :title, presence: true validates :content, length: {minimum: 250} validates :summary, length: {maximum: 250} validates :category, inclusion: %w(Fiction Non-Fiction) validate :contains_clickbait? def contains_clickbait? unless self.title == nil || self.title.match(/((Won't Believe)|(Secret)|(Top)|(Guess))/i) errors.add(:title, "must contain clickbait") end end end
get '/' do @posts = Post.order("created_at DESC").limit(10) erb :index end get '/posts/:id/' do @post = Post.find(params[:id]) @title = @post.title @content = @post.content erb :'posts/show' end get '/posts/new' do @title = 'Create new post' erb :'posts/create' end post '/posts/new' do params.delete 'submit' @post = Post.create(params) if @post.save redirect to '/' else 'Post was not save' end end get ('/about/?') do @title = 'About me' erb :about end not_found do @title = 'Page not found' erb :'404' end error do @error = request.env['sinatra_error'].name erb :'500' end get '/posts/:id/edit/' do @title = 'Update post' @post = Post.find(params[:id]) erb :'posts/edit' end put '/posts/:id/edit/' do @post = Post.find(params[:id]) if @post.update_attributes(params[:post]) redirect to '/' else erb :'posts/edit' end end get '/posts/:id/delete/' do @title = 'Confirm deletion of article ##{params[:id]}' @post = Post.find(params[:id]) erb :'posts/delete' end delete '/posts/:id/' do Post.find(params[:id]).destroy redirect to '/' end get 'users' do @users User.all erb :"/users/index" end
# -*- encoding: utf-8 -*- require File.expand_path("../lib/js-client-bridge/version", __FILE__) Gem::Specification.new do |s| s.name = "js-client-bridge" s.version = JsClientBridge::VERSION s.platform = Gem::Platform::RUBY s.authors = ['Rolly Fordham'] s.email = ['rolly@luma.co.nz'] s.homepage = "http://rubygems.org/gems/js-client-bridge" s.summary = "Standardised way of talking between a service and javascript" s.description = "Little library that encapsulates a (particular) standardised way of talking between a service and javascript. Probably not the best way of doing things, but it's been handy in a pinch." s.required_rubygems_version = ">= 1.3.6" s.rubyforge_project = "js-client-bridge" s.add_dependency "json_pure", ">= 1.4.6" s.add_development_dependency "bundler", ">= 1.0.21" s.add_development_dependency "rspec", "~> 2.0.0" s.add_development_dependency "rcov", "~> 0.9.8" s.add_development_dependency "mocha", "~> 0.9.8" DM_VERSION = "~> 1.0.2" s.add_development_dependency "dm-core", DM_VERSION s.add_development_dependency 'dm-aggregates', DM_VERSION s.add_development_dependency 'dm-migrations', DM_VERSION s.add_development_dependency 'dm-timestamps', DM_VERSION s.add_development_dependency 'dm-validations', DM_VERSION s.add_development_dependency 'dm-types', DM_VERSION s.add_development_dependency 'dm-sqlite-adapter', DM_VERSION if RUBY_VERSION > '1.9.0' s.add_development_dependency "ruby-debug19", "~> 0.11.6" else s.add_development_dependency "ruby-debug", "~> 0.10.3" end s.files = [".rspec", "Gemfile", "Gemfile.lock", "README.rdoc", "Rakefile", "js-client-bridge.gemspec", "lib/js-client-bridge.rb", "lib/js-client-bridge/responses.rb", "lib/js-client-bridge/responses/error.rb", "lib/js-client-bridge/responses/exception.rb", "lib/js-client-bridge/responses/ok.rb", "lib/js-client-bridge/responses/validation.rb", "lib/js-client-bridge/version.rb", "spec/error_responses_spec.rb", "spec/exception_responses_spec.rb", "spec/ok_responses_spec.rb", "spec/rcov.opts", "spec/spec.opts", "spec/spec_helper.rb", "spec/validation_responses_spec.rb", "tasks/rspec.rake"] #`git ls-files`.split("\n") # s.executables = `git ls-files`.split("\n").map{|f| f =~ /^bin\/(.*)/ ? $1 : nil}.compact s.require_path = 'lib' end
class Composite < ActiveRecord::Base has_many :composites_properties has_many :properties, :through => :composites_properties end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # module ActionController module UploadedFile def self.included(base) base.class_eval do attr_accessor :original_path, :content_type alias_method :local_path, :path end end def self.extended(object) object.class_eval do attr_accessor :original_path, :content_type alias_method :local_path, :path end end # Take the basename of the upload's original filename. # This handles the full Windows paths given by Internet Explorer # (and perhaps other broken user agents) without affecting # those which give the lone filename. # The Windows regexp is adapted from Perl's File::Basename. def original_filename unless defined? @original_filename @original_filename = unless original_path.blank? if original_path =~ /^(?:.*[:\\\/])?(.*)/m $1 else File.basename original_path end end end @original_filename end end class UploadedStringIO < StringIO include UploadedFile end class UploadedTempfile < Tempfile include UploadedFile end end
# == Schema Information # # Table name: choices # # id :bigint(8) not null, primary key # motherboard_id :bigint(8) # topic_id :string # option_id :string # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe Choice, type: :model do let(:user) { FactoryBot.create(:user, :with_motherboard) } let(:motherboard) { user.motherboards.first } let(:choice) { FactoryBot.create(:choice, motherboard: motherboard) } let(:topic) { Motherboard.find_topic(choice.topic_id) } it 'should respond with corresponding topic as json if it has selection' do expect(choice.to_json).to eq(topic.to_json) end end
class CreateBusinesses < ActiveRecord::Migration def change create_table :businesses do |t| t.string :yelp_id t.string :name t.string :url t.string :mobile_url t.string :image_url t.decimal :rating t.string :rating_img_url t.string :rating_img_url_small t.string :rating_img_url_large t.integer :review_count t.string :address_1 t.string :address_2 t.string :address_3 t.string :city t.string :state_code t.string :postal_code t.string :country_code t.float :latitude t.float :longitude t.string :phone t.string :snippet_text t.string :snippet_image_url t.timestamps end end end
#!/usr/bin/env ruby # ensure that there is a path (even a slash will do) after the script name unless ENV['PATH_INFO'] and not ENV['PATH_INFO'].empty? print "Status: 301 Moved Permanently\r\n" print "Location: #{ENV['SCRIPT_URL']}/\r\n" print "\r\n" exit end $LOAD_PATH.unshift File.realpath(File.expand_path('../../lib', __FILE__)) require 'json' require 'net/http' require 'time' # for httpdate PAGETITLE = "Apache TLP Website Checks" # Wvisible:sites,brand SITE_PASS = 'label-success' SITE_WARN = 'label-warning' SITE_FAIL = 'label-danger' cols = %w( uri events foundation image license sponsorship security thanks copyright trademarks ) CHECKS = { 'uri' => %r{https?://[^.]+\.apache\.org}, 'copyright' => %r{[Cc]opyright [^.]+ Apache Software Foundation}, # Do we need '[Tt]he ASF'? 'foundation' => %r{.}, 'image' => %r{.}, # TODO more checks needed here, e.g. ASF registered and 3rd party marks 'trademarks' => %r{trademarks of [Tt]he Apache Software Foundation}, 'events' => %r{^https?://.*apache.org/events/current-event}, 'license' => %r{^https?://.*apache.org/licenses/$}, # should link to parent license page only 'sponsorship' => %r{^https?://.*apache.org/foundation/sponsorship}, 'security' => %r{^https?://.*apache.org/[Ss]ecurity}, 'thanks' => %r{^https?://.*apache.org/foundation/thanks}, } DOCS = { 'uri' => ['https://www.apache.org/foundation/marks/pmcs#websites', 'The homepage for any ProjectName must be served from http://ProjectName.apache.org'], 'copyright' => ['https://www.apache.org/legal/src-headers.html#headers', 'All website content SHOULD include a copyright notice for the ASF.'], 'foundation' => ['https://www.apache.org/foundation/marks/pmcs#navigation', 'All projects must feature some prominent link back to the main ASF homepage at http://www.apache.org/'], 'image' => ['https://www.apache.org/img/', 'Projects SHOULD include a 212px wide copy of their logo in https://www.apache.org/img/ to be included in ASF homepage.'], 'trademarks' => ['https://www.apache.org/foundation/marks/pmcs#attributions', 'All project or product homepages must feature a prominent trademark attribution of all applicable Apache trademarks'], 'events' => ['https://www.apache.org/events/README.txt', 'Projects SHOULD include a link to any current ApacheCon event, as provided by VP, Conferences.'], 'license' => ['https://www.apache.org/foundation/marks/pmcs#navigation', '"License" should link to: http://www.apache.org/licenses/'], 'sponsorship' => ['https://www.apache.org/foundation/marks/pmcs#navigation', '"Sponsorship" or "Donate" should link to: http://www.apache.org/foundation/sponsorship.html'], 'security' => ['https://www.apache.org/foundation/marks/pmcs#navigation', '"Security" should link to either to a project-specific page [...], or to the main http://www.apache.org/security/ page'], 'thanks' => ['https://www.apache.org/foundation/marks/pmcs#navigation', '"Thanks" should link to: http://www.apache.org/foundation/thanks.html'], } DATAURI = 'https://whimsy.apache.org/public/site-scan.json' def analyze(sites) success = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) } counts = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) } CHECKS.each do |nam, pat| success[nam] = sites.select{ |k, site| site[nam] =~ pat }.keys counts[nam][SITE_PASS] = success[nam].count counts[nam][SITE_WARN] = 0 # Reorder output counts[nam][SITE_FAIL] = sites.select{ |k, site| site[nam].nil? }.count counts[nam][SITE_WARN] = sites.size - counts[nam][SITE_PASS] - counts[nam][SITE_FAIL] end [ counts, { SITE_PASS => '# Sites with links to primary ASF page', SITE_WARN => '# Sites with link, but not an expected ASF one', SITE_FAIL => '# Sites with no link for this topic' }, success ] end def getsites local_copy = File.expand_path('../public/site-scan.json', __FILE__).untaint if File.exist? local_copy crawl_time = File.mtime(local_copy).httpdate # show time in same format as last-mod sites = JSON.parse(File.read(local_copy)) else response = Net::HTTP.get_response(URI(DATAURI)) crawl_time = response['last-modified'] sites = JSON.parse(response.body) end return sites, crawl_time end sites, crawl_time = getsites() analysis = analyze(sites) # Allow CLI testing, e.g. "PATH_INFO=/ ruby www/site.cgi >test.json" # SCRIPT_NAME will always be set for a CGI invocation unless ENV['SCRIPT_NAME'] puts JSON.pretty_generate(analysis) exit end # Only required for CGI use # if these are required earlier, the code creates an unnecessary 'assets' directory require 'whimsy/asf/themes' require 'wunderbar' require 'wunderbar/bootstrap' require 'wunderbar/jquery/stupidtable' # Determine the color of a given table cell, given: # - overall analysis of the sites, in particular the third column # which is a list projects that successfully matched the check # - list of links for the project in question # - the column in question (which indicates the check being reported on) # - the name of the project def label(analysis, links, col, name) if not links[col] SITE_FAIL elsif analysis[2].include? col and not analysis[2][col].include? name SITE_WARN else SITE_PASS end end def displayProject(project, links, cols, analysis) _whimsy_panel_table( title: "Site Check For Project - #{links['display_name']}", helpblock: -> { _a href: '../', aria_label: 'Home to site checker' do _span.glyphicon.glyphicon_home :aria_hidden end _span.glyphicon.glyphicon_menu_right _ ' Results for project: ' _a links['display_name'], href: links['uri'] _ ' Check Results column is the actual text found on the project homepage for this check (when applicable).' } ) do _table.table.table_striped do _tbody do _thead do _tr do _th! 'Check Type' _th! 'Check Results' _th! 'Check Description' end end cols.each do |col| cls = label(analysis, links, col, project) _tr do _td do _a col.capitalize, href: "../check/#{col}" end if links[col] =~ /^https?:/ _td class: cls do _a links[col], href: links[col] end else _td links[col], class: cls end _td do if cls != SITE_PASS if CHECKS.include? col _ 'Expected to match regular expression: ' _code CHECKS[col].source if DOCS.include? col _ ' ' _a DOCS[col][1], href: DOCS[col][0] end else _ '' end end end end end end end end end def displayError(path) _whimsy_panel_table( title: "ERROR", helpblock: -> { _a href: '../', aria_label: 'Home to site checker' do _span.glyphicon.glyphicon_home :aria_hidden end _span.glyphicon.glyphicon_menu_right _span.text_danger "ERROR: The path #{path} is not a recognized command for this tool, sorry! " } ) do _p.bold 'ERROR - please try again.' end end _html do _head do _style %{ .table td {font-size: smaller;} } end _body? do _whimsy_body( title: PAGETITLE, subtitle: 'Checking TLP Websites For required content', related: { "/committers/tools" => "Whimsy Tool Listing", "https://www.apache.org/foundation/marks/pmcs#navigation" => "Required PMC Links Policy", "https://github.com/apache/whimsy/blob/master/www#{ENV['SCRIPT_NAME']}" => "See This Source Code", "mailto:dev@whimsical.apache.org?subject=[SITE] Website Checker Question" => "Questions? Email Whimsy PMC" }, helpblock: -> { _p do _ 'This script periodically crawls all Apache project websites to check them for a few specific links or text blocks that all projects are expected to have.' _ 'The checks include verifying that all ' _a 'required links', href: 'https://www.apache.org/foundation/marks/pmcs#navigation' _ ' appear on a project homepage, along with an "image" check if project logo files are in apache.org/img' end _p! do _a 'View the crawler code', href: 'https://github.com/apache/whimsy/blob/master/tools/site-scan.rb' _ ', ' _a 'website display code', href: 'https://github.com/apache/whimsy/blob/master/www/site.cgi' _ ', and ' _a 'raw JSON data', href: DATAURI _ '.' _br _ "Last crawl time: #{crawl_time} over #{sites.size} websites." end } ) do if path_info =~ %r{/project/(.+)} # details for an individual project project = $1 if sites[project] displayProject(project, sites[project], cols, analysis) else displayError(path_info) end elsif path_info =~ %r{/check/(.+)} # details for a single check col = $1 _whimsy_panel_table( title: "Site Check Of Type - #{col.capitalize}", helpblock: -> { _a href: '../', aria_label: 'Home to site checker' do _span.glyphicon.glyphicon_home :aria_hidden end _span.glyphicon.glyphicon_menu_right if CHECKS.include? col _ ' Check Results are expected to match the regular expression: ' _code CHECKS[col].source if DOCS.include? col _ ' ' _a DOCS[col][1], href: DOCS[col][0] end _li.small " Click column badges to sort" else _span.text_danger "WARNING: the site checker may not understand type: #{col}, results may not be complete/available." end } ) do _table.table.table_condensed.table_striped do _thead do _tr do _th! 'Project', data_sort: 'string-ins' _th! data_sort: 'string' do _ 'Check Results' _br analysis[0][col].each do |cls, val| _ ' ' _span.label val, class: cls end end end end _tbody do sites.each do |n, links| _tr do _td do _a links['display_name'], href: "../project/#{n}" end if links[col] =~ /^https?:/ _td class: label(analysis, links, col, n) do _a links[col], href: links[col] end else _td links[col], class: label(analysis, links, col, n) end end end end end end else # overview _whimsy_panel_table( title: "Site Check - All Projects Results", helpblock: -> { _ul.list_inline do _li.small "Data key: " analysis[1].each do |cls, desc| _li.label desc, class: cls end _li.small " Click column badges to sort" end } ) do _table.table.table_condensed.table_striped do _thead do _tr do _th! 'Project', data_sort: 'string-ins' cols.each do |col| _th! data_sort: 'string' do _a col.capitalize, href: "check/#{col}" _br analysis[0][col].each do |cls, val| _ ' ' _span.label val, class: cls end end end end end sort_order = { SITE_PASS => 1, SITE_WARN => 2, SITE_FAIL => 3 } _tbody do sites.each do |n, links| _tr do _td do _a "#{links['display_name']}", href: "project/#{n}" end cols.each do |c| cls = label(analysis, links, c, n) _td '', class: cls, data_sort_value: sort_order[cls] end end end end end end # of _whimsy_panel_table end end _script %{ var table = $(".table").stupidtable(); table.on("aftertablesort", function (event, data) { var th = $(this).find("th"); th.find(".arrow").remove(); var dir = $.fn.stupidtable.dir; var arrow = data.direction === dir.ASC ? "&uarr;" : "&darr;"; th.eq(data.column).append('<span class="arrow">' + arrow +'</span>'); }); } end end
class RenamePositionIdToCompoundId < ActiveRecord::Migration[5.1] def change rename_column :related_positions, :position_id, :compound_id end end
# encoding: utf-8 require 'skiima/db/helpers/mysql' unless defined? Skiima::Db::Helpers::Mysql require 'skiima/db/connector/active_record/base_connector' unless defined? Skiima::Db::Connector::ActiveRecord::BaseConnector require 'active_record/connection_adapters/mysql2_adapter' unless defined? ActiveRecord::ConnectionAdapters::Mysql2Adapter module Skiima module Db module Connector module ActiveRecord class Mysql2Connector < Skiima::Db::Connector::ActiveRecord::BaseConnector delegate [:table_exists?, :index_exists?, :proc_exists?, :view_exists?, :schema_exists?] => :adapter class << self delegate mysql2_connection: :active_record_resolver_klass def create_adapter(config, logger, pool) case ::ActiveRecord::VERSION::MAJOR when 3,4 then send('mysql2_connection', config) end end def helpers_module Skiima::Db::Helpers::Mysql end end end end end end end ## encoding: utf-8 #require 'skiima/db_adapters/base_mysql_adapter' # #gem 'mysql2', '~> 0.3.10' #require 'mysql2' # #module Skiima # def self.mysql2_connection(logger, config) # config = Skiima.symbolize_keys(config) # config[:username] = 'root' if config[:username].nil? # # if Mysql2::Client.const_defined? :FOUND_ROWS # config[:flags] = Mysql2::Client::FOUND_ROWS # end # # client = Mysql2::Client.new(config) # options = [config[:host], config[:username], config[:password], config[:database], config[:port], config[:socket], 0] # Skiima::DbAdapters::Mysql2Adapter.new(client, logger, options, config) # end # # module DbAdapters # class Mysql2Adapter < BaseMysqlAdapter # ADAPTER_NAME = 'Mysql2' # # def initialize(connection, logger, connection_options, config) # super # configure_connection # end # # def supports_explain? # true # end # # def error_number(exception) # exception.error_number if exception.respond_to?(:error_number) # end # # def active? # return false unless @connection # @connection.ping # end # # def reconnect! # disconnect! # connect # end # # # Disconnects from the database if already connected. # # Otherwise, this method does nothing. # def disconnect! # unless @connection.nil? # @connection.close # @connection = nil # end # end # # def reset! # disconnect! # connect # end # # def execute(sql, name = nil) # # make sure we carry over any changes to ActiveRecord::Base.default_timezone that have been # # made since we established the connection # # @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone # # # relying on formatting inside the file is precisely what i wanted to avoid... # results = sql.split(/^--={4,}/).map do |spider_monkey| # super(spider_monkey) # end # # results.first # end # # def exec_query(sql, name = 'SQL', binds = []) # result = execute(sql, name) # ActiveRecord::Result.new(result.fields, result.to_a) # end # # alias exec_without_stmt exec_query # # private # # def connect # @connection = Mysql2::Client.new(@config) # configure_connection # end # # def configure_connection # @connection.query_options.merge!(:as => :array) # # variable_assignments = get_var_assignments # execute("SET #{variable_assignments.join(', ')}", :skip_logging) # # version # end # # def get_var_assignments # # By default, MySQL 'where id is null' selects the last inserted id. # # Turn this off. http://dev.rubyonrails.org/ticket/6778 # variable_assignments = ['SQL_AUTO_IS_NULL=0'] # encoding = @config[:encoding] # # # make sure we set the encoding # variable_assignments << "NAMES '#{encoding}'" if encoding # # # increase timeout so mysql server doesn't disconnect us # wait_timeout = @config[:wait_timeout] # wait_timeout = 2592000 unless wait_timeout.is_a?(Fixnum) # variable_assignments << "@@wait_timeout = #{wait_timeout}" # end # # end # end #end
class PagesController < ApplicationController before_action :authenticate_user! layout 'page_layout' def index @workspaces = current_user.workspaces.all if @workspaces respond_to do |format| format.json { render json: @workspaces } format.html { render :index } end else end end end
#This is a dirty, imprecise way to dump some html for validation. We can probably do better, but # this is okay for a start. require 'singleton' require 'set' class HtmlDumper include Singleton attr_accessor :dump_number, :seen cattr_accessor :active attr_accessor :dump_number, :seen def initialize() FileUtils.rm_rf(dump_dir) FileUtils.mkdir_p(dump_dir) self.dump_number = 0 self.seen = Set.new end def activate self.class.active = true end def dump_dir @dump_dir ||= File.join(Rails.root, 'tmp', 'html_dump') end def dump(page) return unless self.class.active if page.present? and page.html.start_with?('<!DOCTYPE html>') md5 = Digest::MD5.hexdigest(page.html) return if self.seen.include?(md5) self.seen << md5 self.dump_number += 1 target_file = File.join(dump_dir, "#{dump_number}.html") FileUtils.mkdir_p(File.dirname(target_file)) File.open(target_file, 'wb') {|f| f.puts page.html} File.open(File.join(dump_dir, 'manifest'), 'a') {|f| f.puts "#{dump_number}: #{page.current_url}"} end end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :conference_room do capacity 1 building "MyString" vtc false name "MyString" end end
class ProductsController < ApplicationController before_action :authenticate_user! , only: [:new ,:show, :edit, :update, :destroy] layout "index" before_action :set_product, only: [:show, :edit, :update, :destroy] # GET /products # GET /products.json def index @products = Product.all.paginate(:page => params[:page], :per_page => 3) end # GET /products/1 # GET /products/1.json def show @product_picture = ProductPicture.all @comments = @product.comments.all @comment = @product.comments.build @product = Product.find_by(id: params[:id]) if @product.nil? render action: "index" end end def list_category end # GET /products/new def new @projects = Project.all @category =ProductCategory.all @product = Product.new end # GET /products/1/edit def edit end # POST /products # POST /products.json def create @product = Product.new(product_params) @product.project_id=params[:id] respond_to do |format| if !params[:images] @product.errors.add(:images, ' can not be empty') format.html { render :new } format.json { render :show, status: :created, location: @product } elsif params[:images].length > 4 @product.errors.add(:images, 'You Can not add more than 4 images') format.html { render :new } format.json { render :show, status: :created, location: @product } else if @product.save if params[:images]&&params[:images].length < 4 #===== The magic is here ;) params[:images].each { |image| @product.product_pictures.create(image: image) } end format.html { redirect_to @product , notice: 'product was successfully created.' } format.json { render :show, status: :created, location: @product } else format.html { render :new } format.json { render json: @product.errors, status: :unprocessable_entity } end end end end # PATCH/PUT /products/1 # PATCH/PUT /products/1.json def update respond_to do |format| if @product.update(product_params) format.html { redirect_to @product, notice: 'Product was successfully updated.' } format.json { render :show, status: :ok, location: @product } else format.html { render :edit } format.json { render json: @product.errors, status: :unprocessable_entity } end end end # DELETE /products/1 # DELETE /products/1.json def destroy @product.destroy respond_to do |format| format.html { redirect_to products_url, notice: 'Product was successfully deleted.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_product @product = Product.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def product_params params.require(:product).permit(:product_name, :product_price, :product_count, :product_description,:photo).merge(:product_category_id => params[:product_category_id][:id]) end def add_product end def remove_product end def promote_product end def report_product end def suspend_product end end
class DropTable < ActiveRecord::Migration def down drop_table :questions drop_table :deparments end end
# == Schema Information # # Table name: searches # # id :integer not null, primary key # created_at :datetime not null # updated_at :datetime not null # lat :float not null # long :float not null # radius :integer not null # class SearchesController < ApplicationController def new @search = Search.new end def create @search = Search.new(search_params) if @search.save @search.fetch_instagram_data(session[:access_token]) redirect_to posts_url(search: @search) else flash[:errors] = @search.errors.full_messages render :new end end private def search_params params.require(:search).permit(:lat, :long, :radius) end end
source 'https://rubygems.org' git_source(:github) do |repo_name| repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?('/') "https://github.com/#{repo_name}.git" end gem 'dotenv-rails', groups: %i[development test] gem 'rails', '~> 5.0.3' gem 'active_model_serializers', '~> 0.8.0' gem 'bootstrap-sass', '~> 3.3.6' # TWBS styles gem 'cancancan', '~> 1.10' # User abilities gem 'carrierwave', '~> 0.9' # Handle Photo Uploads gem 'carrierwave-dropbox' # Carrierwave adapter for Dropbox gem 'coderay' # Ruby Syntax Highlighting gem 'coffee-rails', '~> 4.2' # Use CoffeeScript for .coffee assets and views gem 'devise' # User Authentication gem 'haml-rails', '~> 0.9' # Use HAML for the views gem 'jquery-rails' # Use jquery as the JavaScript library gem 'kaminari' # Pagination gem 'koala' # Facebook API gem 'pg', '~> 0.18' # Use postgresql as the database for Active Record gem 'puma', '~> 3.0' # Use Puma as the app server gem 'redcarpet' # Markdown Parser gem 'sass-rails', '~> 5.0' # Use SCSS for stylesheets gem 'sidekiq' # Queue adapter for Jobs gem 'simple_form' # Simple Form Rails gem 'turbolinks', '~> 5' # Faster page loads gem 'uglifier', '>= 1.3.0' # Use Uglifier as compressor for JavaScript assets group :development, :test do gem 'factory_girl_rails' # Test Factories gem 'faker', github: 'stympy/faker' # Fake data gem 'pry-rails' # Pry as rails console gem 'rspec-rails', '~> 3.5' # Specs as test framework end group :test do gem 'capybara-webkit' gem 'cucumber-rails', require: false gem 'database_cleaner' gem 'rails-controller-testing' gem 'shoulda-matchers', '~> 3.1' # 1 line Rails tests end group :development do gem 'better_errors' # Exactly what it says gem 'binding_of_caller' # Provide REPL/IRB and stack trace gem 'guard' # Automate tests and page refeshes gem 'guard-cucumber' # Run features on file save gem 'guard-livereload', '~> 2.5', require: false # Hot reload rails server on view saves gem 'guard-rspec', require: false # Run specs on file save gem 'hirb' # Pretty Formatting for the console gem 'listen', '~> 3.0.5' gem 'spring' gem 'spring-commands-rspec' gem 'spring-watcher-listen', '~> 2.0.0' end
class CreateAttachedDocuments < ActiveRecord::Migration def change create_table :attached_documents do |t| t.string :file t.integer :container_id t.string :container_type t.string :filename t.string :content_type t.integer :size t.references :user end add_index :attached_documents, :user_id end end
# frozen_string_literal: true # Copyright (c) 2019 Danil Pismenny <danil@brandymint.ru> # Machines web controller (JSON) # # # Использую haname-action только ради обработки ошибок # module Machines HEADERS = { 'Content-Type' => 'application/json', 'X-App-Version' => AppVersion.to_s, 'X-App-Env' => ENV['RACK_ENV'] }.freeze # Сборник утилит, лучше выделить в concern module FetchConnection private def fetch_connection(id) yield $tcp_server.connections.fetch id.to_i rescue KeyError self.status = 404 self.body = { error: 'No such machine online' }.to_json end end # Общий статус брокера class Root include Hanami::Action def call(_params) headers.merge! HEADERS self.status = 200 self.body = { env: ENV['RACK_ENV'], threads_count: Thread.list.count, connections_count: $tcp_server.connections.size, version: AppVersion.to_s, up_time: Time.now - $started_at }.to_json end end # Список подключенных машин class Index include Hanami::Action def call(_params) headers.merge! HEADERS self.status = 200 self.body = { machines: $tcp_server.connections.keys }.to_json end end # Запрос на смену статуса машины class ChangeStatus include Hanami::Action include FetchConnection # rubocop:disable Metrics/AbcSize def call(params) headers.merge! HEADERS machine_id = params[:id] fetch_connection machine_id do |connection| work_time = params[:work_time].to_i state = params[:state].to_i sent_message = connection.build_message state: state, work_time: work_time commant_sent = Time.now sid = connection.channel.subscribe do |message| data = { connected_at: connection.connected_at, last_activity_at: connection.last_activity, last_activity_elapsed: Time.now - connection.last_activity, sent: sent_message.to_h, received: message.to_h } @_env['async.callback'].call [201, HEADERS, data.to_json] $influx.write_point 'call', tags: { machine_id: machine_id }, values: { work_time: work_time, wait: Time.now - commant_sent } connection.channel.unsubscribe sid end connection.send_message sent_message throw :async end end # rubocop:enable Metrics/AbcSize end # Получение статуса машины class GetStatus include Hanami::Action include FetchConnection def call(params) headers.merge! HEADERS fetch_connection params[:id] do |connection| self.status = 200 self.body = { connected_at: connection.connected_at, machine_id: connection.machine_id, last_activity_at: connection.last_activity, last_activity_elapsed: Time.now - connection.last_activity }.to_json end end end end
class AttackScore OFFENSIVE_TRICK_MULTIPLIER = 100 BASE_SCORES = { Card.suits[:spades] => 40, Card.suits[:clubs] => 60, Card.suits[:diamonds] => 80, Card.suits[:hearts] => 100, Card.suits[:no_suit] => 120 } def initialize(attempted_number_of_tricks:, attempted_suit:, number_of_tricks_won:) @attempted_number_of_tricks = attempted_number_of_tricks @number_of_tricks_won = number_of_tricks_won @attempted_suit = attempted_suit end def score @number_of_tricks_won >= @attempted_number_of_tricks ? score_for_attack : -score_for_attack end private def score_for_attack BASE_SCORES[Card.suits[@attempted_suit]] + ((@attempted_number_of_tricks - Bid::MIN_TRICKS) * OFFENSIVE_TRICK_MULTIPLIER) end end
# encoding: utf-8 class Product < ActiveRecord::Base acts_as_taggable after_initialize :default_values after_update :delete_cache attr_accessible :code, :description, :keywords, :name, :origin_price, :product_type, :sale_price, :view_num, :product_type, :click_num, :img_path, :user_name, :status, :effect_type, :effect_str, :onlined_at, :created_at, :expired_at, :tag_list, :tree_group_data, :speaker_teachers, :product_text_attributes, :praise_num, :product_classworks, :exam_type_id, :type_id, :skxx_id, :sale, :mobile_description, :available, :exam_level_id, :sortrank belongs_to :product_text, :dependent => :destroy #has_many :product_tree_datas #has_many :product_tree_groups, :through => :product_tree_datas has_many :speaker_teachers, :as => :teacherable has_many :product_classworks has_paper_trail accepts_nested_attributes_for :product_text validates_uniqueness_of :code, :on => :create, :message => "编码必须唯一!" def speaker_teachers_string self.speaker_teachers.collect! {|speaker_teacher| {"id" => speaker_teacher.teacher_id, "text" => speaker_teacher.teacher_name}}.to_s.gsub("=>", ":") end def classworks_string self.product_classworks.collect! {|classwork| {"id" => classwork.classwork_id, "text" => classwork.classwork_name}}.to_s.gsub("=>", ":") end def tree_group_data_array if self.tree_group_data.nil? || self.tree_group_data == '' [] else eval(self.tree_group_data.gsub(":", "=>")) end end def click_num_from_cache APP_CACHE.fetch("products_click_num_#{self.id}", 0) do self.click_num end end def incr_click_num _p_n = APP_CACHE.fetch("products_click_num_#{self.id}", 0) do self.click_num end _p_n = _p_n + 1 APP_CACHE.set("products_click_num_#{self.id}", _p_n, 0) if _p_n%10 == 0 self.update_attribute(:click_num, _p_n) end return _p_n end def praise_num_from_cache APP_CACHE.fetch("products_praise_num_#{self.id}", 0) do self.praise_num end end def incr_praise_num _p_n = APP_CACHE.fetch("products_praise_num_#{self.id}", 0) do self.praise_num end _p_n = _p_n + 1 APP_CACHE.set("products_praise_num_#{self.id}", _p_n, 0) if _p_n%10 == 0 self.update_attribute(:praise_num, _p_n) end return _p_n end def total_course_num _total_course_num = 0 tree_group_data_array.each do |tgd| ptg = ProductTreeGroup.find_from_cache(tgd["id"]) ptg.node_knowledge_tree_data_hash.each do |k,v| _total_course_num = _total_course_num + ptg.knowledges_course_sum(k) unless v.empty? end unless ptg.nil? end return _total_course_num end def self.product_type_hash {1 => "截止有效期", 2 => "有效天数"} end def effect_str_date if self.effect_type == 1 self.effect_str + " 23:59:59" elsif self.effect_type == 2 (DateTime.now + self.effect_str.to_i).strftime("%Y-%m-%d %H:%M:%S") else DateTime.now.strftime("%Y-%m-%d %H:%M:%S") end end def tree_group_data_array if self.tree_group_data.nil? || self.tree_group_data == '' [] else eval(self.tree_group_data.gsub(":", "=>")) end end def self.find_from_cache(id) APP_CACHE.fetch("products_#{id}", 0) do Product.where("id = ?", id).first end end def effect_str_datetime dates = self.effect_str.split("-") DateTime.new(dates[0].to_i,dates[1].to_i,dates[2].to_i,23,59,59) end def effective? if self.deleted return false else if self.effect_type == 1 && DateTime.now.to_i >= effect_str_datetime.to_i return false end return true end end def self.exam_type_id_hash {1 => "教师资格", 2 => "教师招考", 3 => "特岗教师"} end def self.exam_level_id_hash {1 => "中学", 2 => "小学", 3 => "幼儿园"} end def self.type_id_hash {1 => "笔试课程", 2 => "面试课程", 3 => "教材"} end def self.skxx_id_hash {1 => "面授课程", 2 => "网校课程", 3 => "教材"} end private def default_values if self.new_record? self.praise_num = 1 if self.praise_num.nil? self.sale = 1 if self.sale.nil? self.mobile_description = '' if self.mobile_description.nil? self.available = 0 if self.available.nil? self.exam_type_id = 0 if self.exam_type_id.nil? self.type_id = 0 if self.type_id.nil? self.skxx_id = 0 if self.skxx_id.nil? self.exam_level_id = '' if self.exam_level_id.nil? self.tree_group_data = '[]' if self.tree_group_data.nil? self.sortrank = 5 if self.sortrank.nil? end end def delete_cache APP_CACHE.delete("products_#{self.id}") end end
class Animal #clase animal clase padre attr_accessor :name #atributo accesor def initialize (name) definir constructor @name= name #asignarlo a la variable de instancia end end class Cat < Animal #clase gato que va a heredar de naimal def talk #definir metodo talk "miaaaau" #sonido que retorna metodo talk end end class Dog < Animal #clase perro que hereda de Animal def talk #definir metodo talk "guaaaau" #sonido que retorna el metodo talk end end popi = Dog.new("Popi") #popi es igual a una instancia de la clase dog. y recibe un nombre bicho = Cat.new("Bicho") #crear objeto de tipo gat. nuestro gato se llama bicho puts popi.talk puts bicho.talk
class Show < ActiveRecord::Base def Show::highest_rating self.maximum(:rating) end def Show::most_popular_show self.find_by(rating: highest_rating) end def Show::lowest_rating self.minimum(:rating) end def self.least_popular_show self.find_by(rating: lowest_rating) end def Show::ratings_sum self.sum(:rating) end def Show::popular_shows self.where("rating > 5") end def Show::shows_by_alphabetical_order self.order(:name) end end
class MessagesController < ApplicationController def contact @message = Message.new end def create @message = Message.new(message_params) captcha_message = "Big Error!" if verify_recaptcha(recaptcha_response: "There was a mistake in your captcha" ) && @message.valid? MessageMailer.message_me(@message).deliver_now redirect_to contact_path flash[:success] = "Message sent" elsif !verify_recaptcha flash[:error] = "Something went wrong with the captcha. Are you human?" else flash[:error] = "You must be missing information" end end private def message_params params.require(:message).permit(:name, :email, :subject, :content) end end
class CreateComments < ActiveRecord::Migration def change create_table :comments do |t| t.text :comment_body t.boolean :anonymous_comment t.references :user, index: true, foreign_key: 'user_id' t.references :post, index: true, foreign_key: 'post_id' t.timestamps null: false end add_index :comments, [:post_id, :created_at] end end
describe 'adapter_client' do before :all do start_server(Moneta::Adapters::Memory.new) end moneta_build do Moneta::Adapters::Client.new end moneta_specs ADAPTER_SPECS end
def reverse_each_word(sentence) sentence.split(" ").collect {|word| word.reverse}.join(" ") end #def reverse_each_word(sentence) # sentence_array = sentence.split(" ") # reversed_array = sentence_array.collect do |word| # word.reverse # end # reversed_array.join(" ") #end #def reverse_each_word(sentence) # sentence_array = sentence.split(" ") # reversed = [] # sentence_array.each do |word| # reversed << "#{word.reverse}" # end # reversed.join(" ") #end
class CoordinateService def self.for_location(location) { "Financial District, Milk and Kilby Streets" => "42.3571787,-71.0573071", "Clarendon St at Trinity Church" => "42.3500752,-71.0776725", "Financial District, Pearl Street at Franklin" => "42.3560843,-71.0570633", "Stuart St. at Trinity Place" => "42.3486086,-71.0775693", "City Hall Plaza, Fisher Park" => "42.359903,-71.0604875", "Hurley Building, New Chardon and Cambridge St" => "42.3620412,-71.0657414", "West End, Blossom St at Emerson Place, behind MGH" => "42.3650571,-71.0710883", "NEU, on Opera Place at Huntington Ave" => "42.3398106,-71.0913604", "Prudential, in front of Christian Science Center's Children's Fountain" => "42.3451299,-71.0881027", "East, on Commonwealth Ave at Silber Way" => "42.3493903,-71.1027633", "Boston Public Library" => "42.3492782,-71.0816086", "Innovation District, Seaport Blvd at Boston Wharf Rd" => "", "Harrison Ave and East Concord St, by BMC" => "42.3364781,-71.0754173", "Charlestown Navy Yard at Baxter Road" => "42.3733756,-71.0549069", "Chinatown, Boylston St near Washington St" => "42.352304,-71.0635862", "Innovation District, Seaport Blvd at Boston Wharf Rd" => "42.3494448,-71.0599241", }[location] || "" end end
class Editar_empregado < SitePrism::Page element :pim_button, '#menu_pim_viewPimModule' element :view_button, '#menu_pim_viewEmployeeList' element :id_field, '#empsearch_id' element :search_button, '#searchBtn' element :result_link, :css, '#resultTable > tbody > tr > td:nth-child(2) > a' element :edit_button, '#btnSave' element :middlename_field, '#personal_txtEmpMiddleName' element :lastname_field, '#personal_txtEmpLastName' element :save_button, '#btnSave' elements :success, '.inner' def editar (id, middle, last) pim_button.click view_button.click id_field.set(id) search_button.click result_link.click edit_button.click middlename_field.set(middle) lastname_field.set(last) save_button.click end def validar_editar success.first.text end end
require_relative '../support/helpers/helper' RSpec.describe PagseguroRecorrencia do let!(:payload) { new_plan_payload } before(:each) do new_configuration end context 'when call new_plan() method' do it 'when request all fields return success' do response = PagseguroRecorrencia.new_plan(payload) expect(response.class).to eq(Hash) expect(response.key?(:code)).to be_truthy expect(response.key?(:message)).to be_truthy expect(response.key?(:body)).to be_truthy expect(response[:body].key?(:code)).to be_truthy expect(response[:body].key?(:date)).to be_truthy expect(response[:code]).to eq('200') expect(response[:message]).to eq('OK') expect(response[:body][:code]).to eq('5A408BD29494B1523E4AA4F21124198897ADE2') expect(valid_date?(response[:body][:date])).to equal true end it 'when request all fields with empty :plan_name return error' do tmp_payload = payload tmp_payload[:plan_name] = '' response = PagseguroRecorrencia.new_plan(tmp_payload) expect(response.class).to eq(Hash) expect(response.key?(:code)).to be_truthy expect(response.key?(:message)).to be_truthy expect(response.key?(:body)).to be_truthy expect(response[:body].key?(:error)).to be_truthy expect(response[:body][:error].key?(:code)).to be_truthy expect(response[:body][:error].key?(:message)).to be_truthy expect(response[:body][:error][:code]).to eq('11088') expect(response[:body][:error][:message]).to eq('preApprovalName is required') end it 'when request all fields with empty :plan_charge return raise error' do tmp_payload = payload tmp_payload[:charge_type] = '' expect do PagseguroRecorrencia.new_plan(tmp_payload) end.to raise_error(StandardError, '[VALUE_ERROR] :charge_type can only receive these values (:manual, :auto)') end it 'when request all fields with empty :amount_per_payment return error' do tmp_payload = payload tmp_payload[:amount_per_payment] = '' response = PagseguroRecorrencia.new_plan(tmp_payload) expect(response.class).to eq(Hash) expect(response.key?(:code)).to be_truthy expect(response.key?(:message)).to be_truthy expect(response.key?(:body)).to be_truthy expect(response[:body].key?(:error)).to be_truthy expect(response[:body][:error].key?(:code)).to be_truthy expect(response[:body][:error].key?(:message)).to be_truthy expect(response[:body][:error][:code]).to eq('11106') expect(response[:body][:error][:message]).to eq('preApprovalAmountPerPayment invalid value.') end it 'when request return 404 not found' do tmp_payload = payload tmp_payload[:plan_name] = '404' # only for sinatra fake_pagseguro match response = PagseguroRecorrencia.new_plan(tmp_payload) expect(response.class).to eq(Hash) expect(response.key?(:code)).to be_truthy expect(response.key?(:message)).to be_truthy expect(response.key?(:body)).to be_truthy expect(response[:code]).to eq('404') expect(response[:message]).to eq('Not Found') expect(response[:body]).to be_nil end it 'when request return 500 internal server error' do tmp_payload = payload tmp_payload[:plan_name] = '500' # only for sinatra fake_pagseguro match response = PagseguroRecorrencia.new_plan(tmp_payload) expect(response.class).to eq(Hash) expect(response.key?(:code)).to be_truthy expect(response.key?(:message)).to be_truthy expect(response.key?(:body)).to be_truthy expect(response[:code]).to eq('500') expect(response[:message]).to eq('Internal Server Error') expect(response[:body]).to eq('ERROR 500 - Internal Server Error') end it 'when call create() method without set configuration befored' do PagseguroRecorrencia::PagCore.reset payload = { plan_name: 'TEST - 1', charge_type: :manual, period: :monthly, cancel_url: '', amount_per_payment: '200.00', membership_fee: '150.00', trial_period_duration: '28', expiration_value: '10', expiration_unit: :months, max_uses: '500', plan_identifier: 'TEST123' } expect do PagseguroRecorrencia::PagRequests::NewPlan.new.create(payload) end.to raise_error(RuntimeError, '[WRONG_ENVIRONMENT] environment: receive only (:sandbox :production), you pass :') end end end
class LinkedActivityValidator < ActiveModel::Validator attr_accessor :activity, :error_translations def validate(activity) @activity = activity @error_translations = I18n.t("activerecord.errors.models.activity.attributes.linked_activity_id") return if activity.linked_activity.nil? return unless validate_not_fund return unless validate_same_level return unless validate_ispf return unless validate_oda_type return unless validate_link_does_not_have_other_link return unless validate_same_extending_organisation return unless validate_no_linked_child_activities validate_parents_are_linked end private def validate_not_fund if activity.fund? activity.errors.add(:linked_activity_id, error_translations[:fund]) return false end true end def validate_same_level if activity.level != activity.linked_activity.level activity.errors.add(:linked_activity_id, error_translations[:different_level]) return false end true end def validate_ispf ispf_source_fund_code = Fund.by_short_name("ISPF").id if activity.source_fund_code != ispf_source_fund_code || activity.linked_activity.source_fund_code != ispf_source_fund_code activity.errors.add(:linked_activity_id, error_translations[:incorrect_fund]) return false end true end def validate_oda_type if activity.is_oda == activity.linked_activity.is_oda activity.errors.add(:linked_activity_id, error_translations[:same_oda_type]) return false end true end def validate_link_does_not_have_other_link if activity.linked_activity.linked_activity.present? && activity.linked_activity.linked_activity != activity activity.errors.add(:linked_activity_id, error_translations[:proposed_linked_has_other_link]) return false end true end def validate_same_extending_organisation if activity.extending_organisation != activity.linked_activity.extending_organisation activity.errors.add(:linked_activity_id, error_translations[:different_extending_organisation]) return false end true end def validate_no_linked_child_activities attempting_to_change_linked_activity = activity.linked_activity.linked_activity != activity if activity.linked_child_activities.present? && attempting_to_change_linked_activity activity.errors.add(:linked_activity_id, error_translations[:linked_child_activities]) false end true end def validate_parents_are_linked if !activity.programme? && activity.parent.linked_activity != activity.linked_activity.parent activity.errors.add(:linked_activity_id, error_translations[:unlinked_parents]) false end true end end
# encoding: utf-8 # control "V-72061" do title "The system must use a separate file system for /var." desc "The use of separate file systems for different paths can protect the system from failures resulting from a file system becoming full or failing." impact 0.3 tag "check": "Verify that a separate file system/partition has been created for \"/var\". Check that a file system/partition has been created for \"/var\" with the following command: # grep /var /etc/fstab UUID=c274f65f /var ext4 noatime,nobarrier 1 2 If a separate entry for \"/var\" is not in use, this is a finding." tag "fix": "Migrate the \"/var\" path onto a separate file system." describe mount('/var') do it { should be_mounted } end end
class PlanesController < ApplicationController # Skip authentication for this controller skip_before_action :authenticate_user! def index @address = params['user_input_autocomplete_address'] @range = params['range'].to_i @planes=Plane.near(@address, @range) # @booking = @pl.planes.build @booking = Booking.new # Let's DYNAMICALLY build the markers for the view. @markers = Gmaps4rails.build_markers(@planes) do |plane, marker| marker.lat plane.latitude marker.lng plane.longitude marker.picture({ url: view_context.image_path("logo.svg"), width: 100, height: 100}) marker.title plane.price.to_s end end def show @plane = Plane.find(params[:id]) @plane_coordinates = { lat: @plane.latitute, lng: @plane.longitude } end private def plane_params params.require(:plane).permit(:description, :aeroclub, :price, :available, :picture, :second_picture, :third_picture, :seat, :user_id) end end
class CreateClubUsers < ActiveRecord::Migration[6.0] def change create_table :club_users, id: :uuid do |t| t.references :club, foreign_key: true, type: :uuid, null: false t.references :user, foreign_key: true, type: :uuid, null: false t.integer :status, default: 0, null: false t.boolean :admin, default: 0, null: false t.timestamps end add_index :club_users, [:club_id, :user_id], unique: true end end
require_relative 'interface.rb' require_relative 'user' require_relative 'gamer' require_relative 'deck' class Game attr_reader :gamer, :interface, :dealer, :deck ACTIONS_MENU = { 1 => :dealers_turn, 2 => :extra_card, 3 => :open_cards }.freeze def initialize @interface = Interface.new @gamer = Gamer.new(interface.lets_go) @dealer = User.new start_game end def start_game return @interface.lose_money unless money? @deck = Deck.new @dealers_turned = false round @interface.show_cards_score(@gamer) gamers_turn end def money? (@gamer.money > 10) && (@dealer.money > 10) end def round @deck.cards.shuffle! @gamer.bet @dealer.bet @gamer.current_cards.clear @dealer.current_cards.clear @gamer.card_distribution(@deck) @dealer.card_distribution(@deck) end def gamers_turn @interface.gamers_turn choice = @interface.chose_action send ACTIONS_MENU[choice] if ACTIONS_MENU[choice] open_cards end def can_extra? @gamer.current_cards.length < 3 end def dealer_can_extra? @dealer.current_cards.length < 3 end def extra_card @gamer.take_card(@deck) if can_extra? @interface.player_extra dealers_turn end def dealer_extra @dealer.take_card(@deck) @interface.dealer_extra open_cards end def dealers_turn @dealers_turned = true @interface.dealers_turn sleep(1) return open_cards if @dealer.count_score >= 17 dealer_extra if dealer_can_extra? && @gamer.count_score < 22 end def open_cards @interface.dealers_turned? unless @dealers_turned return gamers_turn unless @dealers_turned @interface.show_player(@gamer) @interface.show_cards_score(@gamer) @interface.show_player(@dealer) @interface.show_cards_score(@dealer) calc_results play_again? end def calc_results case winner when @gamer @gamer.money += 20 @interface.gamer_won when @dealer @dealer.money += 20 @interface.dealer_won when 'draw' @gamer.money += 10 @dealer.money += 10 @interface.draw end @interface.current_money(@gamer.money) end def winner return @dealer if @gamer.score > 21 return @gamer if @dealer.score > 21 return @gamer if @gamer.score > @dealer.score && @gamer.score <= 21 return @dealer if @dealer.score > @gamer.score && @dealer.score <= 21 'draw' if @dealer.score == @gamer.score end def play_again? @interface.play_again? choice = @interface.chose_action start_game if choice == 1 exit if choice == 2 play_again? end end game = Game.new game
#rules: two arguments, positive integer and boolean, calculate the bonus. #if boolean true, bonus will be half of integer #if boolean is false, bonus should be 0 #input:boolean and integer. what if wrong input, what if empty? #output: a integer 0 or positive def calculate_bonus(salary, bonus) bonus ? (salary/2) : 0 end puts calculate_bonus(2800, true) == 1400 puts calculate_bonus(1000, false) == 0 puts calculate_bonus(50000, true) == 25000
require "minitest/autorun" require "minitest/pride" require "pry" require "./lib/customer" require "./spec/helpers/customer_helper" class CustomerSpec < MiniTest::Spec before do @customer = CustomerHelper.customer @customer2 = CustomerHelper.customer2 @product = @customer.product_loaned Customer.delete_all end describe Customer do it "should have a first name" do @customer.first_name.wont_be_nil end it "should have a last name" do @customer.last_name.wont_be_nil end it "should have a full name" do @customer.full_name.must_equal "Alexas Krauss" end it "should have an email address" do @customer.email_address.wont_be_nil end it "should have a phone number" do @customer.phone_number.wont_be_nil end it "should have a product object stored once they have loaned a product" do Customer.add(@customer) @customer.product_loaned.must_equal @product end describe "CRUD methods" do it "should load customers" do original_count = Customer.count Customer.add(@customer) Customer.add(@customer2) Customer.load("./customers.yml") Customer.count.must_equal original_count + 2 end it "should save customers" do File.delete("./customers.yml") if File.exist?("./customers.yml") original_count = Customer.count Customer.add(@customer) Customer.add(@customer2) Customer.save("./customers.yml") Customer.count.must_equal original_count + 2 File.exist?("./customers.yml").must_equal true end it "should be possible to update a customer" do Customer.add(@customer) @customer.edit({first_name: "Andrew", last_name: "Eldritch"}) @customer.first_name.must_equal "Andrew" @customer.last_name.must_equal "Eldritch" end it "should be able to delete a customer" do Customer.add(@customer) Customer.add(@customer2) Customer.delete(@customer.id) Customer.all.wont_include(@customer) end it "should be able to find a customer by ID" do Customer.add(@customer) Customer.find(@customer.id).first_name.must_equal "Alexas" end it "should be able to find customers by first name" do Customer.add(@customer) Customer.add(@customer2) Customer.find_by_first_name("Ale").first.id.must_equal @customer.id end it "should be able to find customers by last name" do Customer.add(@customer) Customer.add(@customer2) Customer.find_by_last_name("Ta").first.id.must_equal @customer2.id end end end end
class FlashCard < ActiveRecord::Base attr_accessible :word, :definition, :pronunciation has_many :decks def info {:word => word, :definition => definition, :pronunciation => pronunciation, :usage => usage} end # add datestudied to the array of cards # container for all cards # access all cards end
class Rink < ActiveRecord::Base has_many :rinkconditions has_many :rinknotes end
class AddFieldsToUser < ActiveRecord::Migration def change add_column :users, :facebook_image, :boolean, default: false add_column :users, :usr_image, :string end end
class RegistrationsController < Devise::RegistrationsController def edit @users = User.all_except(current_user) if current_user.facebook.access_token if current_user.provider == "twitter" @cover = current_user.avatar else @cover = current_user.facebook.get_object("me?fields=cover")["cover"]["source"] end end end private def sign_up_params params.require(:user).permit(:name, :email, :password, :password_confirmation, :avatar) end def account_update_params params.require(:user).permit(:name, :email, :password, :password_confirmation, :current_password, :avatar) end # Allow update resource without password confirmation def update_resource(resource, params) resource.update_without_password(params) end end
class SiteController < ApplicationController # The main page def index # All the servers added in the database @servers = Server.all # The statuses that can be displayed @statuses = Status.all # Messages that are displayed as bootstrap notifications @messages = Message.all # The posts to display incidents @posts = Post.order('id desc') end end
class AddCurrencyIncomeColumnsToUsersTable < ActiveRecord::Migration[5.1] def change add_column :users, :btc_net_income, :decimal, precision: 25, scale: 12, default: 0.0 add_column :users, :ltc_net_income, :decimal, precision: 25, scale: 12, default: 0.0 add_column :users, :bch_net_income, :decimal, precision: 25, scale: 12, default: 0.0 end end
require File.dirname(__FILE__) + '/../test_helper' class ExpenseTest < Test::Unit::TestCase fixtures :expenses def test_should_get_a_price assert_equal expenses(:wnh).price, 29.95 end def test_should_tag_expense assert_difference Tag, :count, 2 do assert expenses(:agile_web_dev).tag_list.empty? expenses(:agile_web_dev).tag_list = "Funny, Silly" expenses(:agile_web_dev).save assert !expenses(:agile_web_dev).tag_list.empty? end end end
class ServiceLinkExistsValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) return unless value.present? && record.respond_to?(:template) value.each do |link| next if template_image_names_for(record).include? link['service'] record.errors[attribute] << 'linked service must exist' break end end def template_image_names_for(model) model.template ? model.template.images.map(&:name) : [] end end
# TODO: SHOULD USE 'REDIRECT BACK TO' FROM SESSIONS INSTEAD OF HARD CODING class LineItemsController < ApplicationController before_action :set_cart before_action :set_line_item, only: [:show, :edit, :update, :destroy] def index @line_items = LineItem.all end def show end def new @line_item = LineItem.new end def edit end def create product = Product.find(params[:product_id]) @line_item = @cart.add_product(product.id) respond_to do |format| if @line_item.save format.html { redirect_to cart_path(@cart) } format.js { @current_item = @line_item } format.json { render :show, status: :created, location: @line_item } else format.html { render :new } format.json { render json: @line_item.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @line_item.update(line_item_params) format.html { redirect_to cart_path(@cart), flash: { success: 'Your cart has been updated.' } } format.json { render :show, status: :ok, location: @line_item } else format.html { render :edit } format.json { render json: @line_item.errors, status: :unprocessable_entity } end end end def destroy @line_item.destroy respond_to do |format| # Current used in editing the contents of a cart # need to make this truely dynamic in incorportate # storing a users location before and redirecting them back. # ajax would probably be even a better option format.html { redirect_to @cart, flash: { success: 'Product has been removed.' } } format.json { head :no_content } end end private def set_line_item begin @line_item = LineItem.find(params[:id]) rescue redirect_to root_path, flash: { warning: "Line item does not exist" } end end def line_item_params params.require(:line_item).permit(:product_id, :quantity) end end
source 'https://rubygems.org' ruby '2.3.1' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.2.4' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use jquery as the JavaScript library gem 'jquery-rails' gem 'jquery-ui-rails' gem 'bootstrap-datepicker-rails', '~> 1.6', '>= 1.6.1.1' gem 'jquery-turbolinks' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'turbolinks' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~> 0.4.0', group: :doc # Use ActiveModel has_secure_password gem 'bcrypt', '~> 3.1.7' # The administration framework for Ruby on Rails gem 'activeadmin', github: 'gregbell/active_admin' # Flexible authentication solution for Rails with Warden gem 'devise' # Simple authorization solution for Rails which is decoupled from user roles. All permissions are stored in a single location. gem 'cancan' # Draper adds an object-oriented layer of presentation logic to your Rails apps. gem 'draper' # Object oriented authorization for Rails applications gem 'pundit' # Kaminari is a Scope & Engine based, clean, powerful, agnostic, customizable and sophisticated paginator for Rails 3+ gem 'kaminari' # Faster Faker, generates dummy data. gem 'ffaker' # will_paginate provides a simple API for performing paginated queries with Active Record, DataMapper and Sequel, and includes helpers for rendering pagination links in Rails, Sinatra and Merb web apps. gem 'will_paginate', '~> 3.0.7' # Hooks into will_paginate to format the html to match Twitter Bootstrap styling. Extension code was originally written by Isaac Bowen (https://gist.github.com/1182136). gem 'bootstrap-will_paginate', '~> 0.0.10' # Twitter's Bootstrap, converted to Sass and ready to drop into Rails or Compass gem 'bootstrap-sass', '~> 3.3.5.1' # Font-Awesome SASS gem for use in Ruby projects gem 'font-awesome-sass', '~> 4.4.0' gem 'sprockets' # The official AWS SDK for Ruby. Provides both resource oriented interfaces and API clients for AWS services. gem 'aws-sdk' # Making it easy to serialize models for client-side use gem 'active_model_serializers' # Rails engine for cache-friendly, client-side local time gem 'local_time' # Pg is the Ruby interface to the {PostgreSQL RDBMS} gem 'pg' gem 'rack-cache' gem 'wicked_pdf' gem 'wkhtmltopdf-heroku' gem 'wkhtmltopdf-binary' gem 'country_select' gem "ckeditor" gem 'paperclip', '~> 4.3.5' gem 'paperclip-ghostscript' gem "cocaine" gem 'paperclip-ffmpeg' gem 'aws-sdk-v1' gem 'faraday', '~> 0.8.8' gem 'httparty' gem 'mvaayoo' gem 'Instamojo-rb', '~> 1.1.0' group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug' end group :development do # Access an IRB console on exception pages or by using <%= console %> in views gem 'web-console' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' end group :production do gem 'yui-compressor' gem 'heroku-deflater' # This gem enables serving assets in production and setting your logger to standard out gem 'rails_12factor' # Puma is a simple, fast, threaded, and highly concurrent HTTP 1.1 server for Ruby/Rack applications. # Puma is intended for use in both development and production environments. # In order to get the best throughput, it is highly recommended that you use a Ruby implementation with real threads like Rubinius or JRuby. gem 'puma' end
# filename: ex353.ru PREFIX ab: <http://learningsparql.com/ns/addressbook#> PREFIX d: <http://learningsparql.com/ns/data#> DROP GRAPH <http://learningsparql.com/graphs/courses> ; INSERT DATA { GRAPH <http://learningsparql.com/graphs/courses> { d:course34 ab:courseTitle "Modeling Data with RDFS and OWL" . d:course71 ab:courseTitle "Enhancing Websites with RDFa" . d:course59 ab:courseTitle "Using SPARQL with non-RDF Data" . d:course85 ab:courseTitle "Updating Data with SPARQL" . d:course86 ab:courseTitle "Querying and Updating Named Graphs" . } }
require File.dirname(__FILE__) + '/column' module SQL class Table attr_accessor :name, :columns def initialize(adapter, table_name) @columns = [] adapter.query_table(table_name).each do |col_struct| @columns << SQL::Column.new(col_struct) end end def to_s name end def column(column_name) @columns.select { |c| c.name == column_name.to_s }.first end end end
class CreatePhotoInCollections < ActiveRecord::Migration def change create_table :photo_in_collections, :id => false do |t| t.string :uuid, :limit => 36, :primary => true t.references :collection t.references :photo t.timestamps end add_index :photo_in_collections, :collection_id add_index :photo_in_collections, :photo_id end end
class KeywordsController < ApplicationController respond_to :json def index respond_with Template.all_keywords end end
class CreateVehicles < ActiveRecord::Migration def change create_table :vehicles do |t| t.string :stock_number t.string :vin, :limit => 17 t.integer :year, :limit => 4 # 4 bytes enough to store a year t.string :make, :limit => 50 t.string :model, :limit => 50 t.string :status, :limit => 20 t.decimal :price, :precision => 9, :scale => 2 t.references :dealer t.references :customer t.timestamps end end end
class SearchResult attr_reader :full_title, :id, :title, :primary_artist def initialize(full_title, id, title, primary_artist) @full_title = full_title @id = id @title = title @primary_artist = primary_artist end def self.all(query) results = GeniusApiWrapper.list_search_results(query) return results end end
xml.instruct! xml.feed "xmlns" => "http://www.w3.org/2005/Atom", 'xmlns:news' => 'http://itunes.apple.com/2011/Newsstand' do xml.updated @issues.collect(&:updated_at).max.xmlschema @issues.each do |issue| xml.entry do xml.id issue.issue_id xml.updated issue.updated_at.xmlschema xml.published issue.published_date.xmlschema xml.summary issue.summary xml.news :end_date do if issue.end_date.present? xml.text! issue.end_date.xmlschema end end xml.news :cover_art_icons do |art| if issue.cover_art.present? art.news :cover_art_icon, {"size" => "SOURCE", "src" => qualified_url(issue.cover_art.url)} end end end end end
class Song < ActiveRecord::Base # add associations here has_many :notes belongs_to :artist belongs_to :genre def artist_name=(name) self.artist = Artist.find_or_create_by(name: name) end def artist_name self.artist ? self.artist.name : nil end def song_notes_content=(notes_array) notes_array.each do |note_ele| # gets access to the table? note = Note.create(content: note_ele,song_id: self.id) self.notes << note end end end
require 'test_helper' class PostsControllerTest < ActionDispatch::IntegrationTest test "should return successfully with required tags query and no optional parameters" do get "/api/posts/?tags=tech" assert_response :success end test "should error 200 on api call without query" do get api_posts_path assert_response :bad_request end test "should error 200 on api call with invalid sort field" do get "/api/posts/?tags=tech&sortBy=nothing" assert_response :bad_request end test "should error 200 on api call with invalid direction field" do get "/api/posts/?tags=tech&direction=nowhere" assert_response :bad_request end end
class AddStatusToLostAndFoundItems < ActiveRecord::Migration def change add_column :lost_items, :found, :boolean, :default => false add_column :found_items, :found, :boolean, :default => false end end
#!/usr/bin/env ruby require_relative '../lib/git_run' require 'optparse' OptionParser.new do |opts| opts.banner = "Usage: git run [options] <revision> <command>" opts.on("-h", "--help", "Show this message") do puts opts exit end if opts.default_argv.length < 2 puts opts exit end end.parse! revision = ARGV.shift begin print GitRun.run(revision, ARGV.join(' ')) rescue GitRun::Error => e $stderr.puts e.message end
class CreateBackgrounds < ActiveRecord::Migration def change create_table :backgrounds do |t| t.references :consultant, index: true t.boolean :citizen, null: false t.boolean :convicted, null: false t.boolean :parole, null: false t.boolean :illegal_drug_use, null: false t.boolean :illegal_purchase, null: false t.boolean :illegal_prescription, null: false t.timestamps end end end
class Admin::ArticleController < Admin::BaseController load_and_authorize_resource ActionController::Base.prepend_view_path("app/themes/#{$layout}") before_action :assign_search, only: [:index, :search] before_action :fetch_article, only: [:edit, :update, :destroy, :show] before_action :fetch_available_dates, only: [:new, :create, :edit, :update] def index article_scope = Article.order(date: :desc).includes(:category, :issue) @article = article_scope.issued.page(params[:page]) @nonis_article = article_scope.non_issued.page(params[:ni_page]) end def new @article=Article.new end def search @article = @q.result(distinct: true).order("date DESC"). page(params[:page]).per(20) end def create @article = Article.new(article_params) @article.build_ordering @article.ordering.cat_pos=99 if @article.preview == "1" && @article.valid? show elsif @article.save redirect_to(admin_articles_path, :notice => 'Page was successfully created.') else render :action => "new" end end def edit end def update if article_params[:preview] == "1" && @article.valid? show elsif @article.update_attributes(article_params) redirect_to(admin_articles_path, :notice => 'Page was successfully updated.') else render :action => "edit" end end def destroy @article.destroy redirect_to(admin_articles_path) end def show @issue = @article.issue || Setting.current_issue || Issue.first render "/article/issued_article", layout: $layout end private def assign_search @q = Article.search(params[:q], auth_object: 'admin') end def fetch_article @article = Article.find(params[:id]) end def fetch_available_dates @available_dates = AvailableDatesPresenter.new(date: @article.issue.try(:date)) end def article_params params.require(:article).permit! end end
require "rails_helper" RSpec.describe TwilioCapabilityTokenGenerator do describe "#call" do it "creates a token" do token = described_class.new("test-identifier").call decoded_token = decode_token(token) incoming_token, outgoing_token = decoded_token.split expect(incoming_token).to include("test-identifier") expect(outgoing_token).to include("test-identifier") end end def decode_token(token) JWT.decode(token, token_secret).first["scope"] end def token_secret Rails.application.credentials.dig(Rails.env.to_sym, :twilio, :auth_token) end end
class AddForiegnKeyToEpisode < ActiveRecord::Migration[5.0] def change add_column :episodes, :show_id, :integer end end
class App generator_for :name, :start => 'App 000001' end
class Game < ApplicationRecord belongs_to :round belongs_to :home_team, class_name: 'Team' belongs_to :guest_team, class_name: 'Team' has_one :game_result scope :finished, -> { where(finished: true) } scope :by_tournament, lambda { |tournament_id| joins(:round).where(rounds: { tournament_id: tournament_id }) } scope :by_team, lambda { |team_id| where('guest_team_id = ? OR home_team_id = ?', team_id, team_id) } def score game_result ? "#{game_result.home_team_goals}-#{game_result.guest_team_goals}" : "-" end end
class ChangeNullnessOnCategories < ActiveRecord::Migration[5.0] def change def disallow_null(column, type) change_column :categories, column, type, :null => false end disallow_null :name, :string change_column :categories, :description, :string, :null => false rename_column :categories, :max_loan, :loan_length_seconds disallow_null :loan_length_seconds, :integer add_column :categories, :enabled, :boolean, :default => true end end
require 'spec_helper' describe "contracts/edit.html.erb" do before(:each) do @contract = assign(:contract, stub_model(Contract, :customer_id => 1, :collector_id => 1, :account_id => 1, :business_type_id => 1, :number => "MyString", :type => "", :block_flag => false, :invoicing_freq => 1, :invoicing_months => "MyString" )) end it "renders the edit contract form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form", :action => contracts_path(@contract), :method => "post" do assert_select "input#contract_customer_id", :name => "contract[customer_id]" assert_select "input#contract_collector_id", :name => "contract[collector_id]" assert_select "input#contract_account_id", :name => "contract[account_id]" assert_select "input#contract_business_type_id", :name => "contract[business_type_id]" assert_select "input#contract_number", :name => "contract[number]" assert_select "input#contract_type", :name => "contract[type]" assert_select "input#contract_block_flag", :name => "contract[block_flag]" assert_select "input#contract_invoicing_freq", :name => "contract[invoicing_freq]" assert_select "input#contract_invoicing_months", :name => "contract[invoicing_months]" end end end
# == Schema Information # # Table name: adventurer_chapters # # id :integer not null, primary key # adventurer_id :integer # chapter_id :integer # created_at :datetime # updated_at :datetime # require 'spec_helper' describe AdventurerChapter do let(:adventurer_chapter) {FactoryGirl.create(:adventurer_chapter)} describe "Attributes" do it {should have_attribute :adventurer_id} it {should have_attribute :chapter_id} end describe "Relationships" do it {should respond_to :adventurer} it {should respond_to :chapter} end end
Spree::Product.class_eval do belongs_to :supplier, touch: true def add_supplier!(supplier) self.supplier = supplier self.save! end # Returns true if the product has a drop shipping supplier. def supplier? supplier.present? end end
require "rubygems" require_relative "../Libraries/TweetTrawler" require "date" # Elizabeth Blair # Last Edited: 3/14/14 # 3/10/14: Created # 3/12/14: Added some error handling, fixed timer, added access info generation # 3/14/14: Added code for search and user modes, moved parsing to individual subs # 3/31/14: Fixed transition bug in getTweet # This script contains a set of methods to gather Twitter data from various sections of the # Twitter API. The currently availble modes are 'tweet', 'user', and 'search'. Each mode has # different required arguments and output style, but tweets are always stored in the format # {{ID=###}}{{USER=###}}\n(tweet text)\n<ENDOFTWEET>. During execution, if the connection times # out or API rate limits are hit the script will wait. To leave, type exit and hit enter; within # 15 seconds the script will terminate. # - Tweet: Given tweet IDs (one per line), pull those tweets using the statuses/show call. If a # tweet is not available, the tweet ID will still be given but the user will not and the text area # will be filled with <Tweet not available>. Output is stored in one given file, with each # tweet on the line following the last. # - User: Given user IDs, pull the users' timelines, up to (depth*200) tweets. This call # pulls a maximum of ~3000 tweets, minus retweets and those containing URLs. Users # who set their profile to private will have one line in their file: <Not authorized>. # The ID file should have one user ID per line, and anything following a tab is removed. # Each user's tweets will be stored in a .txt file named after them in the output directory. # - Search: Given files containing search queries in certain categories, run the terms # infinitely through the search call, grabbing up to 200 recent tweets per search sans those # with explicit retweets or URLs. The search also filters for the given language and # location, which must be set up in the geocodes variable. The query files should have the # category name on the first line, and each following line should be one query. Anything # following a tab will be removed. Output is stored in a file named 'category_term # in file'.txt # inside of a directory named with the timestamp 'year-month-day_hour-minute' when the search # was done which is created in the output directory. # USAGE: # ruby tweetPull.rb tweet <out file> <ID file> # ruby tweetPull.rb user <out dir> <user file> <user depth multiple> # ruby tweetPull.rb search <out dir> <language> <location> <query file> [more query files...] # Application API key and secret for my CoRAL account application # [Probably shouldn't be published without a password or something] apikey="SLtBEJkuwDTqsJdLYCsEBA" apisecret="fbZ6Lyh4V35I6TVsw9f17gEy8Ytu6JEd8X1p4L2dSA" # Geocodes for areas covering certain state locations (ATM, Texas and California) @geocodes = { 'TX' => "31.37,-98.899,600km", # 600km radius from center of Texas 'CA' => "35.936802,-121.350174,900km" # 900km radius from around the mid-left edge of CA } # Error/Exception class that should only be used if a trawl call needs to be repeated # because it was skipped. It behaves no differently than a normal exception. class NilTextError < StandardError end # getTimeline(user,maxID,trawler) # Inputs: user ID, tweet ID to start at, TweetTrawler # Outputs: string of formatted tweets, lowest tweet ID the trawler reached, # # queries remaining, time to rate limit reset # Description: Use the trawler to gather the most recent 200 tweets from the user's timeline, # starting from the given maximium tweet ID. Filter out retweets and tweets containing URLs. # Return all of the tweets in one string, along with the earliest tweet's ID (or nil if no tweets # were processed), the number of timeline queries left, and the time when the rate limit will reset. # 9^35 is used as a very large number to compare tweet IDs to when finding the lowest one. No existing # tweet should have an ID near this, nor should one for a very long time. def getTimeline(user,maxID,trawler) criteria = nil if maxID.nil? then criteria = URI.encode_www_form( "user_id" => user, "count" => 200, "include_rts" => false) else criteria = URI.encode_www_form( "user_id" => user, "count" => 200, "max_id" => maxID, "include_rts" => false) end puts "Running user #{user} on max ID #{maxID}" results,limitLeft,timeReset = trawler.trawl(criteria) newMax = nil tweets = "" if results == '<Not authorized>' then tweets = results elsif !results.nil? then lowestid = 9 ** 35 data.each do |tweet| text = tweet["text"] if tweet["id"] < lowestid then lowestid = tweet["id"] end if text =~ /^RT(.{1,5})@|http:|https:|pic\.twitter/ # Discard the tweet else tweets = "#{tweets}\{\{ID=#{tweet["id"]}\}\}\{\{USER=#{tweet["user"]["id"]}\}\}\n#{tweet["text"]}\n<ENDOFTWEET>\n" end end if lowestid == 9 ** 35 then lowestid = nil end end return tweets,newMax,limitLeft,timeReset end # getSearchTweets(query,lang,loc,trawler) # Inputs: search query (text), language, location (must be a key in geocodes), TweetTrawler # Outputs: string of formatted tweets, # queries remaining, time to rate limit reset # Description: Use the trawler to gather up to 200 of the most recent tweets containing the # given query, flagged by Twitter as being in the given language, and posted from # within the given location. Discard explicit retweets and those containing URLs. # Return a string of all the formatted tweets, along with the number of remaining # queries and the time when the rate limit will reset. def getSearchTweets(query,lang,loc,trawler) criteria = URI.encode_www_form( "q" => "#{query} -http -https -pic.twitter", "count" => 200, "geocode" => @geocodes[loc], "result_type" => "recent", "lang" => lang) results,limitLeft,timeReset = trawler.trawl(criteria) tweets = '' if !results.nil? then results["statuses"].each do |tweet| text = tweet["text"] if text =~ /^RT(.{1,5})@|http:|https:|pic\.twitter/ # Discard the tweet else tweets = "#{tweets}\{\{ID=#{tweet["id"]}\}\}\{\{USER=#{tweet["user"]["id"]}\}\}\n#{tweet["text"]}\n<ENDOFTWEET>\n" end end else tweets = nil end return tweets,limitLeft,timeReset end # getTweet(id,trawler) # Inputs: tweet ID, TweetTrawler # Outputs: formatted tweet (string), # queries remaining, time to rate limit reset # Description: Use the trawler to get the given tweet and return the text in the script's # format. If the tweet isn't accessible, excludes the user and replaces the # text field with <Tweet not available>. Also returns the number of remaining # queries and the time when the rate limit will reset. def getTweet(id,trawler) criteria = URI.encode_www_form("id" => id) puts "Running tweet #{id}" results,limitLeft,timeReset = trawler.trawl(criteria) if (results == '<Tweet not available>' or results == '<Not authorized>') then results = "\{\{ID=#{id}\}\}\n<Tweet not available>\n<ENDOFTWEET>\n" elsif (!results.nil?) then results = "\{\{ID=#{results["id"]}\}\}\{\{USER=#{results["user"]["id"]}\}\}\n#{results["text"]}\n<ENDOFTWEET>\n" end return results,limitLeft,timeReset end # getAccessData(file) # Inputs: access data storage file # Outputs: array of access data # Description: If the access file exists, pull the access data from it. The first line of # the file is the access token and the second is the access secret. The array's # elements are in the same order. If the file does not exist, use TweetTrawler to # generate the access data for the hardcoded application. (This will open a web # browser and requires a Twitter account.) Write the access data to the file before # returning it. def getAccessData(data_file) accessData = Array.new if !File.exists?(data_file) then puts "Generating your access token..." accessData[0],accessData[1] = TweetTrawler.genAccessToken(apikey,apisecret,"https://api.twitter.com") # also write out to file accessOut = File.open(data_file,"w") accessOut << "#{accessData[0]}\n#{accessData[1]}" accessOut.close else File.readlines(data_file).each do |line| line.chomp! accessData.push(line) end end return accessData end # MAIN CODE mode = ARGV.shift out = ARGV.shift # Generate or pull authentication data for the user from hard-coded access_token.txt accessData = getAccessData('access_token.txt') limitLeft = nil timeReset = nil case mode when 'tweet' inFile = ARGV.shift # Make the single-tweet trawler path = "/1.1/statuses/show.json" trawler = TweetTrawler.new(path,apikey,apisecret,accessData[0],accessData[1]) # Pull tweet for each ID in the input file, print formatted tweet to out file outFileHan = File.open(out,"w") File.readlines(inFile).each do |id| id.chomp! begin # Wait if needed if !limitLeft.nil? and limitLeft.to_i < 1 then waitTime = (timeReset.to_i-Time.now.to_i)+30; # Add 30 seconds to wait time to be sure there's a new query window trawler.wait(waitTime) end results,limitLeft,timeReset = getTweet(id,trawler) if (!results.nil?) then outFileHan << results else raise NilTextError.new() end rescue NilTextError => e retry end end outFileHan.close when 'user' inFile = ARGV.shift # Make the user trawler path = "/1.1/statuses/user_timeline.json" trawler = TweetTrawler.new(path,apikey,apisecret,accessData[0],accessData[1]) depth = ARGV.shift.to_i File.readlines(inFile).each do |line| line.chomp! id, *rest = line.split(/\t/) maxID = nil allTweets = "" depth.times do begin # Wait if needed if !limitLeft.nil? and limitLeft.to_i < 1 then waitTime = (timeReset.to_i-Time.now.to_i)+30; # Add 30 seconds to wait time to be sure there's a new query window trawler.wait(waitTime) end # Get tweets from the user at current ID depth tweets,newID,limitLeft,timeReset = getTimeline(id,maxID,trawler) if tweets.nil? then raise NilTextError.new() end unless newID.nil? then newID = newID.to_i - 1 end allTweets = "#{allTweets}#{tweets}" if newID.nil? or newID == maxID then break end maxID = newID rescue NilTextError => e retry end end # Only make a file for the user if they had non-discarded tweets (or weren't accessible) if allTweets != "" then outFileHan = File.open("#{out}/#{id}.txt","w") outFileHan << allTweets outFileHan.close end end when 'search' lang = ARGV.shift location = ARGV.shift path = "/1.1/search/tweets.json" trawler = TweetTrawler.new(path,apikey,apisecret,accessData[0],accessData[1]) termCats = Hash.new ARGV.each do |file| key = nil File.readlines(file).each_with_index do |line,ind| line = line.chomp if ind == 0 then key = line termCats[key] = Array.new else term, *rest = line.split(/\t/) termCats[key].push(term) end end end # Infinitely looping search - exit during the wait periods loop do termCats.each_key do |cat| puts "Running terms of category #{cat}..." termCats[cat].each_with_index do |query,ind| begin # Wait if needed if !limitLeft.nil? and limitLeft.to_i < 1 then waitTime = (timeReset.to_i-Time.now.to_i)+30; # Add 30 seconds to wait time to be sure there's a new query window trawler.wait(waitTime) end # Get tweets from the user at current ID depth time = Time.new tweets,limitLeft,timeReset = getSearchTweets(query,lang,location,trawler) if tweets.nil? then raise NilTextError.new() end # Output the data to the correct location timestamp = "#{time.year}-#{time.month}-#{time.day}_#{time.hour}-#{time.min}" Dir.mkdir("#{out}/#{timestamp}") unless File.exists?("#{out}/#{timestamp}") outFileHan = File.open("#{out}/#{timestamp}/#{cat}_#{ind}.txt","w") outFileHan << tweets outFileHan.close rescue NilTextError => e retry end end end end else abort "Unsupported mode #{mode} - use tweet, user, or search" end # Set up the limit data properly and print out remaining limit information if limitLeft.nil? then limitLeft = 'unknown' end if timeReset.nil? then timeReset = 'unknown' else timeReset = Time.at(timeReset.to_i).to_datetime end puts "Remaining queries: #{limitLeft}" puts "Time until reset: #{timeReset}" nil
require 'spec_helper' describe "kind_accounts/edit" do before(:each) do @kind_account = assign(:kind_account, stub_model(KindAccount, :owner_name => "MyText", :number => "MyText", :bank_id => 1 )) end it "renders the edit kind_account form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form[action=?][method=?]", kind_account_path(@kind_account), "post" do assert_select "textarea#kind_account_owner_name[name=?]", "kind_account[owner_name]" assert_select "textarea#kind_account_number[name=?]", "kind_account[number]" assert_select "input#kind_account_bank_id[name=?]", "kind_account[bank_id]" end end end
require 'shared_examples/node' shared_examples 'a collection node of' do |member_klass| it_behaves_like 'a node' it { expect(subject).to_not be_empty } specify do subject.each do |node| expect(node).to_not be_nil expect(node).to be_a_kind_of member_klass end end end
require 'test_helper' class ShipImagesControllerTest < ActionDispatch::IntegrationTest setup do @ship_image = ship_images(:one) end test "should get index" do get ship_images_url, as: :json assert_response :success end test "should create ship_image" do assert_difference('ShipImage.count') do post ship_images_url, params: { ship_image: { ship_id: @ship_image.ship_id, url: @ship_image.url } }, as: :json end assert_response 201 end test "should show ship_image" do get ship_image_url(@ship_image), as: :json assert_response :success end test "should update ship_image" do patch ship_image_url(@ship_image), params: { ship_image: { ship_id: @ship_image.ship_id, url: @ship_image.url } }, as: :json assert_response 200 end test "should destroy ship_image" do assert_difference('ShipImage.count', -1) do delete ship_image_url(@ship_image), as: :json end assert_response 204 end end
class AddCreatedByUserToManufacturer < ActiveRecord::Migration def change add_reference :manufacturers, :created_by_user, index: true add_reference :models, :created_by_user, index: true add_reference :fuel_types, :created_by_user, index: true add_reference :engine_manufacturers, :created_by_user, index: true add_reference :engine_models, :created_by_user, index: true add_reference :drive_types, :created_by_user, index: true end end
require "rails_helper" RSpec.describe Api::V3::UsersController, type: :controller do require "sidekiq/testing" let(:facility) { create(:facility) } let!(:owner) { create(:admin, :power_user) } let!(:supervisor) { create(:admin, :manager, :with_access, resource: facility.facility_group) } let!(:organization_owner) { create(:admin, :manager, :with_access, resource: facility.organization) } describe "#register" do describe "registration payload is invalid" do let(:request_params) { {user: FactoryBot.attributes_for(:user).slice(:full_name, :phone_number)} } it "responds with 400" do post :register, params: request_params expect(response.status).to eq(400) end end describe "registration payload is valid" do let(:user_params) { register_user_request_params(registration_facility_id: facility.id) } let(:phone_number) { user_params[:phone_number] } let(:password_digest) { user_params[:password_digest] } it "creates a user, and responds with the created user object and their access token" do post :register, params: {user: user_params} parsed_response = JSON(response.body) created_user = User.find_by(full_name: user_params[:full_name]) expect(response.status).to eq(200) expect(created_user).to be_present expect(created_user.phone_number_authentication).to be_present expect(created_user.phone_number_authentication.phone_number).to eq(user_params[:phone_number]) expect(parsed_response["user"].except("created_at", "updated_at", "facility_ids").with_int_timestamps) .to eq(created_user.attributes .except( "role", "organization_id", "device_updated_at", "device_created_at", "created_at", "updated_at" ) .merge("registration_facility_id" => facility.id, "phone_number" => phone_number, "password_digest" => password_digest) .as_json .with_int_timestamps) expect(parsed_response["user"]["registration_facility_id"]).to eq(facility.id) expect(parsed_response["access_token"]).to eq(created_user.access_token) end it "sets the user status to requested" do post :register, params: {user: user_params} created_user = User.find_by(full_name: user_params[:full_name]) expect(created_user.sync_approval_status).to eq(User.sync_approval_statuses[:requested]) expect(created_user.sync_approval_status_reason).to eq(I18n.t("registration")) end it "sets the user status to approved if auto_approve_users feature is enabled" do Flipper.enable(:auto_approve_users) post :register, params: {user: user_params} created_user = User.find_by(full_name: user_params[:full_name]) expect(created_user.sync_approval_status).to eq(User.sync_approval_statuses[:allowed]) end context "registration_approval_email in a production environment" do before { stub_const("SIMPLE_SERVER_ENV", "production") } it "sends an email to a list of owners and supervisors" do Sidekiq::Testing.inline! do post :register, params: {user: user_params} end approval_email = ActionMailer::Base.deliveries.last expect(approval_email.to).to include(supervisor.email) expect(approval_email.cc).to include(organization_owner.email) expect(approval_email.body.to_s).to match(Regexp.quote(user_params[:phone_number])) end it "sends an email with owners in the bcc list" do Sidekiq::Testing.inline! do post :register, params: {user: user_params} end approval_email = ActionMailer::Base.deliveries.last expect(approval_email.bcc).to include(owner.email) end it "sends an approval email with list of accessible facilities" do Sidekiq::Testing.inline! do post :register, params: {user: user_params} end approval_email = ActionMailer::Base.deliveries.last facility.facility_group.facilities.each do |facility| expect(approval_email.body.to_s).to match(Regexp.quote(facility.name)) end end it "sends an email using sidekiq" do Sidekiq::Testing.fake! do expect { post :register, params: {user: user_params} }.to change(Sidekiq::Extensions::DelayedMailer.jobs, :size).by(1) end end end end end describe "#find" do let(:phone_number) { Faker::PhoneNumber.phone_number } let(:facility) { create(:facility) } let!(:db_users) { create_list(:user, 10, registration_facility: facility) } let!(:user) { create(:user, phone_number: phone_number, registration_facility: facility) } it "lists the users with the given phone number" do get :find, params: {phone_number: phone_number} expect(response.status).to eq(200) expect(JSON(response.body).with_int_timestamps) .to eq(Api::V3::UserTransformer.to_response(user).with_int_timestamps) end it "lists the users with the given id" do get :find, params: {id: user.id} expect(response.status).to eq(200) expect(JSON(response.body).with_int_timestamps) .to eq(Api::V3::UserTransformer.to_response(user).with_int_timestamps) end it "returns 404 when user is not found" do get :find, params: {phone_number: Faker::PhoneNumber.phone_number} expect(response.status).to eq(404) end end describe "#request_otp" do let(:user) { create(:user) } it "returns 404 if the user with id doesn't exist" do post :request_otp, params: {id: SecureRandom.uuid} expect(response.status).to eq(404) end it "updates the user otp and sends an sms to the user's phone number with the new otp" do existing_otp = user.otp expect(RequestOtpSmsJob).to receive_message_chain("set.perform_later").with(user) post :request_otp, params: {id: user.id} user.reload expect(user.otp).not_to eq(existing_otp) end it "uses a sensible default when the OTP delay is not configured" do ENV["USER_OTP_SMS_DELAY_IN_SECONDS"] = nil existing_otp = user.otp expect(RequestOtpSmsJob).to receive_message_chain("set.perform_later").with(user) post :request_otp, params: {id: user.id} user.reload expect(user.otp).not_to eq(existing_otp) end it "does not send an OTP if fixed_otp is enabled" do Flipper.enable(:fixed_otp) expect(RequestOtpSmsJob).not_to receive(:set) post :request_otp, params: {id: user.id} end end describe "#reset_password" do let(:facility_group) { create(:facility_group) } let(:facility) { create(:facility, facility_group: facility_group) } let(:user) { create(:user, registration_facility: facility, organization: facility.organization) } before(:each) do request.env["HTTP_X_USER_ID"] = user.id request.env["HTTP_X_FACILITY_ID"] = facility.id request.env["HTTP_AUTHORIZATION"] = "Bearer #{user.access_token}" end it "Resets the password for the given user with the given digest" do new_password_digest = BCrypt::Password.create("1234").to_s post :reset_password, params: {id: user.id, password_digest: new_password_digest} user.reload expect(response.status).to eq(200) expect(user.password_digest).to eq(new_password_digest) expect(user.sync_approval_status).to eq("requested") expect(user.sync_approval_status_reason).to eq(I18n.t("reset_password")) end it "leaves the user approved if auto approve is enabled" do Flipper.enable(:auto_approve_users) new_password_digest = BCrypt::Password.create("1234").to_s post :reset_password, params: {id: user.id, password_digest: new_password_digest} user.reload expect(response.status).to eq(200) expect(user.password_digest).to eq(new_password_digest) expect(user.sync_approval_status).to eq("allowed") end it "Returns 401 if the user is not authorized" do request.env["HTTP_AUTHORIZATION"] = "an invalid access token" post :reset_password, params: {id: user.id} expect(response.status).to eq(401) end it "Returns 401 if the user is not present" do request.env["HTTP_X_USER_ID"] = SecureRandom.uuid post :reset_password, params: {id: SecureRandom.uuid} expect(response.status).to eq(401) end it "Sends an email to a list of owners and supervisors" do Sidekiq::Testing.inline! do post :reset_password, params: {id: user.id, password_digest: BCrypt::Password.create("1234").to_s} end approval_email = ActionMailer::Base.deliveries.last expect(approval_email).to be_present expect(approval_email.to).to include(supervisor.email) expect(approval_email.cc).to include(organization_owner.email) expect(approval_email.body.to_s).to match(Regexp.quote(user.phone_number)) expect(approval_email.body.to_s).to match("reset") end it "does not send an email if users are auto approved" do Flipper.enable(:auto_approve_users) Sidekiq::Testing.inline! do post :reset_password, params: {id: user.id, password_digest: BCrypt::Password.create("1234").to_s} end approval_email = ActionMailer::Base.deliveries.last expect(approval_email).to be_nil end it "sends an email using sidekiq" do Sidekiq::Testing.fake! do expect { post :reset_password, params: {id: user.id, password_digest: BCrypt::Password.create("1234").to_s} }.to change(Sidekiq::Extensions::DelayedMailer.jobs, :size).by(1) end end end end
require "vagrant/util/counter" module VagrantPlugins module Puppet module Config class Puppet < Vagrant.plugin("2", :config) extend Vagrant::Util::Counter attr_accessor :facter attr_accessor :hiera_config_path attr_accessor :manifest_file attr_accessor :manifests_path attr_accessor :module_path attr_accessor :options attr_accessor :synced_folder_type attr_accessor :temp_dir attr_accessor :working_directory def initialize super @hiera_config_path = UNSET_VALUE @manifest_file = UNSET_VALUE @manifests_path = UNSET_VALUE @module_path = UNSET_VALUE @options = [] @facter = {} @synced_folder_type = UNSET_VALUE @temp_dir = UNSET_VALUE @working_directory = UNSET_VALUE end def nfs=(value) puts "DEPRECATION: The 'nfs' setting for the Puppet provisioner is" puts "deprecated. Please use the 'synced_folder_type' setting instead." puts "The 'nfs' setting will be removed in the next version of Vagrant." if value @synced_folder_type = "nfs" else @synced_folder_type = nil end end def merge(other) super.tap do |result| result.facter = @facter.merge(other.facter) end end def finalize! super if @manifests_path == UNSET_VALUE @manifests_path = [:host, "manifests"] end if @manifests_path && !@manifests_path.is_a?(Array) @manifests_path = [:host, @manifests_path] end @manifests_path[0] = @manifests_path[0].to_sym @hiera_config_path = nil if @hiera_config_path == UNSET_VALUE @manifest_file = "default.pp" if @manifest_file == UNSET_VALUE @module_path = nil if @module_path == UNSET_VALUE @synced_folder_type = nil if @synced_folder_type == UNSET_VALUE @temp_dir = nil if @temp_dir == UNSET_VALUE @working_directory = nil if @working_directory == UNSET_VALUE # Set a default temp dir that has an increasing counter so # that multiple Puppet definitions won't overwrite each other if !@temp_dir counter = self.class.get_and_update_counter(:puppet_config) @temp_dir = "/tmp/vagrant-puppet-#{counter}" end end # Returns the module paths as an array of paths expanded relative to the # root path. def expanded_module_paths(root_path) return [] if !module_path # Get all the paths and expand them relative to the root path, returning # the array of expanded paths paths = module_path paths = [paths] if !paths.is_a?(Array) paths.map do |path| Pathname.new(path).expand_path(root_path) end end def validate(machine) errors = _detected_errors # Calculate the manifests and module paths based on env this_expanded_module_paths = expanded_module_paths(machine.env.root_path) # Manifests path/file validation if manifests_path[0].to_sym == :host expanded_path = Pathname.new(manifests_path[1]). expand_path(machine.env.root_path) if !expanded_path.directory? errors << I18n.t("vagrant.provisioners.puppet.manifests_path_missing", path: expanded_path.to_s) else expanded_manifest_file = expanded_path.join(manifest_file) if !expanded_manifest_file.file? && !expanded_manifest_file.directory? errors << I18n.t("vagrant.provisioners.puppet.manifest_missing", manifest: expanded_manifest_file.to_s) end end end # Module paths validation this_expanded_module_paths.each do |path| if !path.directory? errors << I18n.t("vagrant.provisioners.puppet.module_path_missing", path: path) end end { "puppet provisioner" => errors } end end end end end
class ChangeOnlineDefaultValueOnProducts < ActiveRecord::Migration def change change_column_default :products, :on_sale, false end end
## -*- Ruby -*- ## URLopen ## 1999 by yoshidam ## ## TODO: This module should be writen by Ruby instead of wget/lynx. module WGET PARAM = { 'wget' => nil, 'opts' => nil, 'http_proxy' => nil, 'ftp_proxy' => nil } def open(url, *rest) raise TypeError.new("wrong argument type #{url.inspect}" + " (expected String)") if url.class != String if url =~ /^\/|^\./ || (url !~ /^http:|^ftp:/ && FileTest.exist?(url)) File::open(url, *rest) else ENV['http_proxy'] = PARAM['http_proxy'] if PARAM['http_proxy'] ENV['ftp_proxy'] = PARAM['ftp_proxy'] if PARAM['ftp_proxy'] IO::popen(PARAM['wget'] + ' ' + PARAM['opts'] + ' ' + url) end end module_function :open end [ '/usr/local/bin/wget', '/usr/bin/wget', '/usr/local/bin/lynx', '/usr/bin/lynx', '/usr/local/bin/lwp-request', '/usr/bin/lwp-request' ].each do |p| if FileTest.executable?(p) WGET::PARAM['wget'] = p case p when /wget$/ WGET::PARAM['opts'] = '-q -O -' when /lynx$/ WGET::PARAM['opts'] = '-source' when /lwp-request$/ WGET::PARAM['opts'] = '-m GET' end break end end raise "wget not found" if !WGET::PARAM['wget']
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable has_many :reviews, :dependent => :destroy has_many :ratings, :dependent => :destroy has_and_belongs_to_many :places devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable,:token_authenticatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :firstname, :country, :mobile_no before_save :ensure_authentication_token validates :firstname, :presence => { :message => "First Name Required"} validates :mobile_no, numericality: true def name self.firstname end end
# # Copyright (c) 2013, 2021, Oracle and/or its affiliates. # # 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. # Puppet::Type.type(:link_properties).provide(:solaris) do desc "Provider for managing Oracle Solaris link properties" confine :operatingsystem => [:solaris] defaultfor :osfamily => :solaris, :kernelrelease => ['5.11'] commands :dladm => '/usr/sbin/dladm' mk_resource_methods def initialize(value={}) super(value) @linkprops = {} end def self.instances links = Hash.new{ |h,k| h[k] = {} } dladm("show-linkprop", "-c", "-o", 'LINK,PROPERTY,PERM,VALUE,DEFAULT,POSSIBLE'). each_line do |line| line = line.gsub('\\:','%colon%') link,prop,perm,value,_default,_possible = line.split(":") next if perm != 'rw' value = value.gsub('%colon%',':') if value.empty? value = :absent value = _default unless _default.empty? end links[link][prop] = value end links.each_pair.collect do |link,props| new(:name => link, :ensure => :present, :properties => props) end end def self.prefetch(resources) instances.each do |prov| if resource = resources[prov.name] resource.provider = prov end end end def properties=(value) dladm("set-linkprop", *add_properties(value), @resource[:name]) end def add_properties(props=@resource[:properties]) a = [] props.each do |key, value| a << "#{key}=#{value}" end properties = Array["-p", a.join(",")] end def exists? @property_hash[:ensure] == :present end def create # Cannot create link props. They must already exist fail("Link must exist for properties to be set.") end end
require 'test_helper' class Piece15sControllerTest < ActionController::TestCase setup do @piece15 = piece15s(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:piece15s) end test "should get new" do get :new assert_response :success end test "should create piece15" do assert_difference('Piece15.count') do post :create, piece15: { name: @piece15.name, pnameform_id: @piece15.pnameform_id, user_id: @piece15.user_id } end assert_redirected_to piece15_path(assigns(:piece15)) end test "should show piece15" do get :show, id: @piece15 assert_response :success end test "should get edit" do get :edit, id: @piece15 assert_response :success end test "should update piece15" do patch :update, id: @piece15, piece15: { name: @piece15.name, pnameform_id: @piece15.pnameform_id, user_id: @piece15.user_id } assert_redirected_to piece15_path(assigns(:piece15)) end test "should destroy piece15" do assert_difference('Piece15.count', -1) do delete :destroy, id: @piece15 end assert_redirected_to piece15s_path end end
#encoding: UTF-8 xml.instruct! :xml, :version => "1.0" xml.rss "xmlns:itunes" => "http://www.itunes.com/dtds/podcast-1.0.dtd", "xmlns:media" => "http://search.yahoo.com/mrss/", :version => "2.0" do xml.channel do xml.title "Radio Show" xml.link radio_show_url xml.language "en" xml.itunes :title, 'Radio Show' xml.itunes :author, 'Tom Wilson Properties' for video in @videos xml.item do xml.title video['snippet']['title'] xml.description video['snippet']['description'] xml.itunes :title, video['snippet']['title'] xml.itunes :description, video['snippet']['description'] xml.itunes :guid, video['id']['videoId'] link = 'https://www.youtube.com/watch?v=' + video['id']['videoId'] xml.itunes :link, link end end end end
require 'ocr/scanned_characters' require 'ocr/errors' module OCR class ScannedNumber include ScannedCharacters attr_reader :scanned_lines attr_reader :value def initialize(lines) @scanned_lines = lines normalize_line_lengths check_proper_number_of_lines check_for_illegal_characters check_line_lengths @value = calculate_value end def legible? ! illegible? end def illegible? contains_illegible_digit?(value) end def ==(other) scanned_lines == other.scanned_lines end def to_s value end def show to_s end def alternatives result = [] prefix = [] suffix = scanned_chars.dup while !suffix.empty? ch = suffix.shift RECOGNIZER.guess(ch, 1).each do |guess| digits = recognize(prefix) + guess.guessed_char + recognize(suffix) result << digits unless contains_illegible_digit?(digits) end prefix.push(ch) end result end def self.from_digits(string) first, *rest = string.chars.map { |nc| FROM_DIGIT[nc] || [" |", " |", " |"] } lines = first.zip(*rest).map { |f| f.join } new(lines) end def scanned_chars @scanned_chars ||= begin tops, mids, bots = scanned_lines.map { |ln| by_width(ln) } tops.zip(mids, bots).map { |en| en.join } end end private def contains_illegible_digit?(string) string =~ /[?]/ end def calculate_value recognize(scanned_chars) end def recognize(scanned_characters) scanned_characters.map { |sc| RECOGNIZER.recognize(sc) }.join end def by_width(string) ScannedCharacters.by_width(string) end def normalize_line_lengths max_length = scanned_lines.map { |str| str.size }.max scanned_lines.each do |str| if str.size < max_length str << " " * (max_length - str.size) end end end def check_proper_number_of_lines if scanned_lines.length != 3 die("Must be three lines in #{show_error_lines}") end end def check_for_illegal_characters unless scanned_lines.all? { |string| string =~ /^[ |_]+$/ } die("Illegal characters in #{show_error_lines}") end end def check_line_lengths lengths = scanned_lines.map { |ln| ln.length }.uniq if lengths.size > 1 die("Mismatching line lengths in #{show_error_lines}") end if (lengths.first % 3) != 0 die("Line lengths must be divisible by 3 in #{show_error_lines}") end end def die(message) fail IllformedScannedNumberError.new(message) end def show_error_lines "\n=============================\n" + scanned_lines.map { |ln| "> #{ln}\n" }.join + "=============================\n" end end end
class String def self.mutable_primitive_instances? true end end
class CreateMeasures < ActiveRecord::Migration def change create_table :measures do |t| t.string :name t.string :abbreviation t.text :description t.string :units t.decimal :value, :precision => 8, :scale => 2 t.integer :operator t.integer :places, :default => 0, :null => false t.timestamps null: false end end end
class Section include Mongoid::Document has_one :site belongs_to :directory, class_name: "AbstractDirectory" belongs_to :parent, class_name: "Section" has_many :children, class_name: "Section" field :path def sync! directory.directories.each do |dir| section_path = path + dir.name section = children.where(:path => section_path) unless section # TODO OOk ander soort sections maken, aan de hand van dir.extension section = SimpleSection.new(:path => section_path, :directory => dir) children << section end section.sync! end end def section_map [{:path => path, :section => self}, children.map(&:section_map)].flatten end end