text
stringlengths
10
2.61M
require 'spec_helper' describe 'java::default' do let(:chef_run) do runner = ChefSpec::ChefRunner.new( :platform => 'debian', :version => '7.0' ) runner.converge('java::default') end it 'should include the openjdk recipe by default' do expect(chef_run).to include_recipe('java::openjdk') end context 'windows' do let(:chef_run) do runner = ChefSpec::ChefRunner.new( 'platform' => 'windows', 'version' => '2008R2' ) runner.node.set['java']['install_flavor'] = 'windows' runner.node.set['java']['windows']['url'] = 'http://example.com/windows-java.msi' runner.converge('java::default') end it 'should include the windows recipe' do expect(chef_run).to include_recipe('java::windows') end end context 'oracle' do let(:chef_run) do runner = ChefSpec::ChefRunner.new runner.node.set['java']['install_flavor'] = 'oracle' runner.converge('java::default') end it 'should include the oracle recipe' do expect(chef_run).to include_recipe('java::oracle') end end context 'oracle_i386' do let(:chef_run) do runner = ChefSpec::ChefRunner.new runner.node.set['java']['install_flavor'] = 'oracle_i386' runner.converge('java::default') end it 'should include the oracle_i386 recipe' do expect(chef_run).to include_recipe('java::oracle_i386') end end context 'ibm' do let(:chef_run) do runner = ChefSpec::ChefRunner.new runner.node.set['java']['install_flavor'] = 'ibm' runner.node.set['java']['ibm']['url'] = 'http://example.com/ibm-java.bin' runner.converge('java::default') end it 'should include the ibm recipe' do expect(chef_run).to include_recipe('java::ibm') end end context 'ibm_tar' do let(:chef_run) do runner = ChefSpec::ChefRunner.new runner.node.set['java']['install_flavor'] = 'ibm_tar' runner.node.set['java']['ibm']['url'] = 'http://example.com/ibm-java.tar.gz' runner.converge('java::default') end it 'should include the ibm_tar recipe' do expect(chef_run).to include_recipe('java::ibm_tar') end end end
require 'test_helper' class ChefsEditTest < ActionDispatch::IntegrationTest def setup @chef = Chef.create!(chefname: 'Giuseppe', email: 'giuseppe@example.com', password: "password", password_confirmation: "password") @chef2 = Chef.create!(chefname: 'Pluto', email: 'pluto@example.com', password: "password", password_confirmation: "password") @admin_user = Chef.create!(chefname: 'Pluto1', email: 'pluto1@example.com', password: "password", password_confirmation: "password", admin: true) end test "reject an invalid edit" do sign_in_as(@chef, "password") get edit_chef_path(@chef) assert_template 'chefs/edit' patch chef_path, params: { chef: { chefname: " ", email: "giuseppe@esempi.it" } } assert_template 'chefs/edit' assert_select 'h2.panel-title' assert_select 'div.panel-body' end test "accept valid edit" do sign_in_as(@chef, "password") get edit_chef_path(@chef) assert_template 'chefs/edit' patch chef_path, params: { chef: { chefname: "giuseppe1", email: "giuseppe1@esempi.it" } } assert_redirected_to @chef assert_not flash.empty? @chef.reload assert_match "giuseppe1", @chef.chefname assert_match "giuseppe1@esempi.it", @chef.email end test "accept edit attempt by admin user" do sign_in_as(@admin_user, "password") get edit_chef_path(@chef) assert_template 'chefs/edit' patch chef_path(@chef), params: { chef: { chefname: "giuseppe3", email: "giuseppe3@esempio.it" } } assert_redirected_to @chef assert_not flash.empty? @chef.reload assert_match "giuseppe3", @chef.chefname assert_match "giuseppe3@esempio.it", @chef.email end test "redirect edit attempt by another non-admin user" do sign_in_as(@chef2, "password") updated_name = "pippo" updated_email = "pippo@esempio.it" patch chef_path(@chef), params: { chef: { chefname: updated_name, email: updated_email } } assert_redirected_to chefs_path assert_not flash.empty? @chef.reload assert_match "Giuseppe", @chef.chefname assert_match "giuseppe@example.com", @chef.email end end
require 'spec_helper' describe CategoriesController do describe "GET index" do it "should be successful" do get 'index' response.should be_success end it "assigns all categorys as @categorys" do category = FactoryGirl.create(:category) get :index assigns(:categories).should eq([category]) end end describe "GET show" do it "assigns the requested category as @category" do category = FactoryGirl.create(:category) get :show, {:id => category.to_param} assigns(:category).should eq(category) end end end
class Role < ActiveRecord::Base has_many :role_assignments has_many :welcomers, through: :role_assignments end
# frozen_string_literal: true require "test_helper" class SamsungBrowserTest < Minitest::Test test "detects samsung browser" do browser = Browser.new(Browser["SAMSUNG_BROWSER"]) assert browser.webkit? assert browser.samsung_browser? assert_equal "11", browser.version assert_equal :samsung_browser, browser.id assert_equal "11.1", browser.full_version assert_equal "Samsung Browser", browser.name refute browser.chrome? refute browser.safari? end test "detects version by range" do browser = Browser.new(Browser["SAMSUNG_BROWSER"]) assert browser.samsung_browser?(%w[>=11 <12]) end end
module Tokenizer class Lexer module TokenLexers # rubocop:disable Layout/MultilineOperationIndentation def comp_2_gt?(chunk) chunk =~ /\A(大|おお)きければ\z/ || chunk =~ /\A(長|なが)ければ\z/ || chunk =~ /\A(高|たか)ければ\z/ || chunk =~ /\A(多|おお)ければ\z/ || false end # rubocop:enable Layout/MultilineOperationIndentation def tokenize_comp_2_gt(_chunk) close_if_statement [Token.new(Token::COMP_GT)] end end end end
# encoding: utf-8 require 'mongoid' require 'coderay' require 'colorize' module MongoidColors::Colorizer def self.setup return unless Mongoid.logger old_formatter = Mongoid.logger.formatter Mongoid.logger.formatter = lambda do |severity, datetime, progname, msg| m = parse(msg) return if m == :ignore return old_formatter.call(severity, datetime, progname, msg) if m.nil? m[:query].gsub!(/BSON::ObjectId\('([^']+)'\)/, '0x\1') m[:duration] = m[:duration].split('.')[0] if m[:duration] line = "☘ ".green + "MongoDB ".white line << "(#{m[:duration]}ms) " if m[:duration] if m[:database] if m[:collection] line << "[#{m[:database]}::#{m[:collection]}] " else line << "[#{m[:database]}] " end end line << case m[:operation] when /(QUERY|COUNT)/ then "#{m[:operation]} ".colorize(:green) when /(INSERT|UPDATE|MODIFY|DELETE)/ then "#{m[:operation]} ".red else "#{m[:operation]} " end line << CodeRay.scan(m[:query], :ruby).term line << "\n" end end def self.parse(msg) case msg when /^MONGODB \((.*)ms\) (.*)\['(.*)'\]\.(.*)$/ {:duration => $1, :database => $2, :collection => $3, :query => $4} when /^MONGODB (.*)\['(.*)'\]\.(.*)$/ {:database => $1, :collection => $2, :query => $3} when /^ *MOPED: (\S+:\S+) (\S+) +database=(\S+)( collection=(\S+))? (.*[^)])( \((.*)ms\))?$/ res = {:host => $1, :operation => $2, :database => $3, :collection => $5, :query => $6, :duration => $8} if res[:operation] == 'COMMAND' begin command = eval(res[:query]) if command[:count] res[:operation] = 'COUNT' res[:collection] = command.delete(:count) res[:query] = command.inspect end if command[:findAndModify] res[:operation] = 'FIND AND MODIFY' res[:collection] = command.delete(:findAndModify) res[:query] = command.inspect end rescue Exception end end res when /which could negatively impact client-side performance/ :ignore when /COMMAND.*getlasterror/ :ignore end end setup end
require 'bigdecimal' class Store attr_reader :name, :address, :type, :inventory_record def initialize(name, address, type) @name = name @address = address @type = type @inventory_record = [] end def add_inventory(inventory) @inventory_record << inventory end def stock_check(item) inventories = find_inventories_with_item(item) inventory = sort_by_most_recent(inventories).first inventory.items[item] end def find_inventories_with_item(item) inventory_record.find_all do |inventory| inventory.items.keys.include?(item) end end def sort_by_most_recent(inventories) descend = -1 inventories.sort_by do |inventory| descend * inventory.date.to_time.to_i end end def amount_sold(item) unsorted_inventories = find_inventories_with_item(item) inventories = sort_by_most_recent(unsorted_inventories) latest_data = inventories[0].items[item] previous_data = inventories[1].items[item] previous_data["quantity"] - latest_data["quantity"] end def us_order(order) total = us_order_amount(order) "$#{total}" end def us_order_amount(order) order.reduce(0) do |total, pair| item = pair.first quantity = pair.last inventory = find_inventories_with_item(item).first total += (inventory.items[item]["cost"] * quantity) end end def brazilian_order(order) us_total = us_order_amount(order) br_total = (us_total * 3.08).round(2) "R#{br_total}" end end
require File.expand_path("../../../../../base", __FILE__) require Vagrant.source_root.join("plugins/guests/windows/cap/change_host_name") describe "VagrantPlugins::GuestWindows::Cap::ChangeHostName" do let(:described_class) do VagrantPlugins::GuestWindows::Plugin.components.guest_capabilities[:windows].get(:change_host_name) end let(:machine) { double("machine") } let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) } let(:old_hostname) { 'oldhostname' } before do allow(machine).to receive(:communicate).and_return(communicator) end after do communicator.verify_expectations! end describe ".change_host_name" do it "changes the hostname" do communicator.stub_command('if (!($env:ComputerName -eq \'newhostname\')) { exit 0 } exit 1', exit_code: 0) communicator.stub_command('netdom renamecomputer "$Env:COMPUTERNAME" /NewName:newhostname /Force /Reboot:0', exit_code: 0) described_class.change_host_name_and_wait(machine, 'newhostname', 0) end it "raises RenameComputerFailed when exit code is non-zero" do communicator.stub_command('if (!($env:ComputerName -eq \'newhostname\')) { exit 0 } exit 1', exit_code: 0) communicator.stub_command('netdom renamecomputer "$Env:COMPUTERNAME" /NewName:newhostname /Force /Reboot:0', exit_code: 123) expect { described_class.change_host_name_and_wait(machine, 'newhostname', 0) }. to raise_error(VagrantPlugins::GuestWindows::Errors::RenameComputerFailed) end end end
# Public: Tells if a string is empty or not. # # string - The String that might be empty. # # Examples # # is_empty("Tjo!") # # => false # # Returns if the string is empty or not.
class Team < ActiveRecord::Base has_many :players belongs_to :game belongs_to :division before_save :downcase_name validates :name, :presence => true private def downcase_name self.name = self.name.downcase end scope :black, -> { where( color: 'black' ) } end
# frozen_string_literal: true require 'rails_helper' RSpec.describe RelatedProduct, type: :model do it { should belong_to(:product) } it { should belong_to(:related) } end
class SearchController < ApplicationController protect_from_forgery except: :search skip_authorization_check def search @search_results = SphinxSearch.search_results(params[:search_text]) if params[:search_text] end end
#!/usr/bin/env ruby require 'rubygems' require 'bundler' require 'shellwords' require 'appscript' require 'slop' DEBUG = false class Host attr_reader :name, :login def initialize(name, login = ENV['USER']) @name = name @login = login end end class Terminal include Appscript attr_reader :terminal, :current_window def initialize @terminal = app('Terminal') @current_window = terminal.windows.first yield self end def tab(command, mode = 't') app('System Events').application_processes['Terminal.app'].keystroke(mode, :using => :command_down) run command end def maximize # This depends on Divvy app('System Events').application_processes['Terminal.app'].keystroke('m', :using => [:command_down, :option_down, :control_down]) end def run(command) command = command.shelljoin if command.is_a?(Array) if command && !command.empty? terminal.do_script(command, :in => current_window.tabs.last) end end end def hosts hosts = Array.new begin IO.readlines(File.join(File.dirname(__FILE__), 'hosts.conf')).each do |line| # Strip out anything that's a comment line = line.sub(/#.*/, "").strip next if line.empty? if line.include?("@") line = line.split("@") hosts << Host.new(line[1], line[0]) else hosts << Host.new(line) end end rescue Exception => e abort "ERROR: #{e}" end hosts end def cmd_exec(login, name) if @opts.monit? monit_off = 'if [ -x "/usr/sbin/monit" ]; then echo "[MONIT] Unmonitoring all services" && sudo /usr/sbin/monit unmonitor all && sleep 10; fi' monit_on = 'if [ -x "/usr/sbin/monit" ]; then echo "[MONIT] Monitoring all services" && sudo /usr/sbin/monit monitor all; fi' else monit_off = monit_on = 'echo -n' end aptitude = "sudo aptitude update && sudo aptitude dist-upgrade -y && sudo aptitude clean" "ssh #{login}@#{name} -t 'clear && #{monit_off} && #{aptitude} && #{monit_on} && exit' && exit" end def cmd_echo(login, name) "echo TRACE: ssh #{login}@#{name} && sleep 10 && exit" end if DEBUG alias :cmd :cmd_echo else alias :cmd :cmd_exec end @opts = Slop.parse do on :m, :monit, 'Your password', :optional_argument => true end first = true Terminal.new do |t| hosts.each do |h| sleep 1 if first == true t.tab(cmd(h.login, h.name), 'n') t.maximize first = false else t.tab(cmd(h.login, h.name)) end end end
require 'spec_helper' describe SuperRole::ActionAlias do describe '.create' do context 'when the alias does not exist' do it 'should create a new instance of ActionAlias for each resource_types' do expect do SuperRole::ActionAlias.create(['delete', 'remove'], 'destroy', ['Project', 'User']) end.to change { SuperRole::ActionAlias.count }.by(2) SuperRole::ActionAlias.find(:delete, Project).action.should eq 'destroy' SuperRole::ActionAlias.find('remove', 'User').action.should eq 'destroy' end end context 'when the an alias already exist' do before do SuperRole::ActionAlias.create(['delete'], 'destroy', ['Project', 'User']) end it 'should add the alias to the existing aliases' do expect do SuperRole::ActionAlias.create(['remove'], 'destroy', ['Project', 'User']) end.to_not change { SuperRole::ActionAlias.count } SuperRole::ActionAlias.find(:delete, Project).action.should eq 'destroy' SuperRole::ActionAlias.find('remove', 'User').action.should eq 'destroy' end end end end
class CreateBudgetSourcesProjectsJoin < ActiveRecord::Migration def up create_table :budget_sources_projects , :id => false do |t| t.integer "project_id" t.integer "budget_source_id" end end def down end end
class Producer::ApplicationsController < ApplicationController def show @application = Application.find(params["format"]) end def new @design = Design.find(params["format"]) @application = Application.new end def create if current_producer? design = Design.find(params[:design_id]) @application = design.applications.create(application_params) @application.user = current_user if @application.save! redirect_to producer_dashboard_path(current_user) flash[:success] = "Your application to #{@application.design.title} has been submitted!" else redirect_to new_producer_design_application(current_user, @application.design) flash[:danger] = "Your application to #{@application.design} could not be submitted! Please try again!" end end end private def application_params params.require(:application).permit(:production_plan, :due_date, :price) end end
Pod::Spec.new do |s| s.name = "DPWebViewLocalCache" s.version = "1.1.7" s.ios.deployment_target = '7.0' s.summary = "A delightful setting interface framework." s.homepage = "https://github.com/xiayuqingfeng/DPWebViewLocalCache" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "涂鸦" => "13673677305@163.com" } s.source = { :git => "https://github.com/xiayuqingfeng/DPWebViewLocalCache.git", :tag => s.version } s.source_files = "DPWebViewLocalCache_SDK/**/*.{h,m}" s.requires_arc = true end
require 'rails_helper' RSpec.describe User, type: :model do describe 'Validations' do before(:all) do @existingUser = User.create(:email => 'hello@example.com', :password => 'password', :password_confirmation => 'password') end it 'should contain name,email and matching password and password confirmation' do @user = User.create(name: "test", email: "test@example.com", password: "testtest", password_confirmation: "testtest") expect(@user).to be_valid end it 'should have matching password and password confirmation' do @user = User.create(name: "test", email: "test@example.com", password: "testtest", password_confirmation: "doesn't match password") expect(@user.errors.full_messages).to include "Password confirmation doesn't match Password" end it 'should contain name,email and matching password and password confirmation' do @user = User.create(name: "test", email: 'hello@example.com', password: "testtest", password_confirmation: "testtest") expect(@user.errors.full_messages).to include "Email has already been taken" end it 'should contain name,email and matching password and password confirmation' do @user = User.create(name: "test", email: 'test@example.com', password: "test", password_confirmation: "test") expect(@user.errors.full_messages).to include "Password is too short (minimum is 5 characters)" end end describe '.authenticate_with_credentials' do before(:all) do @user = User.create(:email => 'Testy@teSt.com', :password => 'password', :password_confirmation => 'password') end describe 'correct email and password' do it 'should return the user object' do @session = @user.authenticate_with_credentials('testy@test.com', 'password') expect(@session).to eql(@user) end end describe 'incorrect email and password' do it 'should return nil' do @session = @user.authenticate_with_credentials('testy@test.com', 'not the password') expect(@session).to be_nil end end describe 'correct email and password but case insensitive email' do it 'should return the user object' do @session = @user.authenticate_with_credentials('testy@test.COM', 'password') expect(@session).to eql(@user) end end describe 'correct email and password but white space around email' do it 'should return the user object' do @session = @user.authenticate_with_credentials(' testy@test.com ', 'password') expect(@session).to eql(@user) end end after(:all) do User.delete(@user.id) end end end # validates :password, presence: true # validates :passwordconfirmation, presence: true # validates :pwdmatchespwdconfirmation, presence: true # validates :firstname, presence: true # validates :lastname, presence: true # validates :email, presence: true # validates :uniqueemail, presence: true # validates :pwdminlength, presence: true
require 'csv' namespace :checkins do desc "Backfill deltas on weights" task backfill_deltas: :environment do Checkin.find_each do |c| previous_checkin = Checkin.where(person: c.person, event: c.event).where('created_at < ?', c.created_at).last if previous_checkin delta = c.weight - previous_checkin.weight c.delta = delta c.save end end end desc "Load Checkins from CSV" task load_checkins: :environment do # not many people so not worrying about performance CSV.foreach(Rails.root.join('weighins.csv'), headers: true) do |row| person = Person.find_by_name(row["Name"]) sorted_events = person.leagues.map(&:event).sort_by(&:start_date) event = sorted_events.reverse.find { |e| e.start_date < Date.parse(row["Time"]) } Checkin.create!(person: person, event: event, weight: row["Weight"]) end end end
# # オープンクラスのテスト # 自分でeachメソッドを用意してみる # イテレータは"whileキーワードを使った列挙"という動作のラッパに過ぎないと分かる # class Array def my_each #block_given = ブロックの有無 return nil unless block_given? count = 0 limit = self.length while count < limit do # yieldでブロックに評価させたいのはselfの個別の値 yield(self[count]) count += 1 end end end # arrs = [1,2] # arrs.my_each { |arr| puts arr }
class AddPotentialProductAnswersIndices < ActiveRecord::Migration def self.up add_index :potential_product_answers, [:category_id], :name => 'category_id_idx' add_index :potential_product_answers, [:category_id, :covary_group], :name => 'category_id_covary_group_idx' end def self.down remove_index :potential_product_answers, :name => 'category_id_covary_group_idx' remove_index :potential_product_answers, :name => 'category_id_idx' end end
require 'sinatra/base' require 'twitter' require 'mongo' require 'erb' require 'twitter' require 'oauth' require_relative 'helpers' $temp_table = $db_client[:temp] # # Load Twitter app info into a hash called `config` from the environment variables assigned during setup # # See the "Running the app" section of the README for instructions. # TWITTER_CONFIG = { # consumer_key: ENV['TWITTER_CONSUMER_KEY'], # consumer_secret: ENV['TWITTER_CONSUMER_SECRET'] # } # # # Check to see if the required variables listed above were provided, and raise an exception if any are missing. # missing_params = TWITTER_CONFIG.select {|key, value| value.nil?} # if missing_params.any? # error_msg = missing_params.keys.join(", ").upcase # raise "Missing Twitter config variables: #{error_msg}" # end # def get_consumer OAuth::Consumer.new( ENV['TWITTER_CONSUMER_KEY'], ENV['TWITTER_CONSUMER_SECRET'], {:site => 'https://api.twitter.com/'} ) end # Twitter uses OAuth for user authentication. This auth process is performed by exchanging a set of # keys and tokens between Twitter's servers and yours. This process allows the authorizing user to confirm # that they want to grant our bot access to their team. # See https://api.twitter.com/docs/oauth for more information. class TwitterAuth < Sinatra::Base # I want to use sessions, but I can't. Use mongo instead. get '/install_twitter/:team_id/:channel_id' do # TODO validate that these are team_ids and channel_ids we've seen before! team_id = params[:team_id] channel_id = params[:channel_id] consumer = get_consumer request_token = consumer.get_request_token oauth_callback: ('https://' + ENV['HOST'] + '/install_twitter/finish/'+team_id+'/'+channel_id) # Store the request token's details for later $temp_table.update_one({team_id: team_id, channel_id: channel_id}, {team_id: team_id, channel_id: channel_id, request_token: request_token.token, request_secret: request_token.secret}, {upsert: true}) # Hand off to Twitter so the user can authorize us redirect request_token.authorize_url end get '/install_twitter/finish/:team_id/:channel_id' do consumer = get_consumer docs = $temp_table.find({team_id: params[:team_id], channel_id: params[:channel_id]}) request_token = docs.first docs.delete_many puts request_token[:request_token] # Re-create the request token request_token = OAuth::RequestToken.new(consumer, request_token[:request_token], request_token[:request_secret]) # Convert the request token to an access token using the verifier Twitter gave us access_token = request_token.get_access_token oauth_verifier: params[:oauth_verifier] # Store the token and secret that we need to make API calls doc = $tokens.find({team_id: params[:team_id]}).first doc['twitter_tokens'][params[:channel_id]] = {oauth_token: access_token.token, oauth_secret: access_token.secret} $tokens.update_one({team_id: params[:team_id]}, doc) status 200 body "Twitter configured!" end end
class AddMmrToMatches < ActiveRecord::Migration def change add_column :matches, :mmr, :decimal,precision: 10, scale: 6 end end
class AddBedsToRealEstates < ActiveRecord::Migration[5.0] def change add_column :real_estates, :beds, :integer end end
class Path attr_reader :folder_name def initialize(folder_name) @folder_name = folder_name end def get Dir.home.to_s + "/" + folder_name.to_s end end
class RenamePenaltyToPenaltiesInScorecards < ActiveRecord::Migration def change rename_column :scorecards, :penalty, :penalties end end
FactoryGirl.define do factory :event, class: Event do title "Seminario" date Time.zone.now description "Seminario en centro Banamex" # picture "picture" picture_file_name 'picture.jpg' picture_content_type 'image/jpeg' picture_file_size 1.megabyte event_type "seminar" trait :convention do event_type "convention" end end end
FactoryBot.define do factory :match_score do association :match association :player association :beatmap transient do full_combo? { false } end max_combo { full_combo? ? beatmap.max_combo : rand(beatmap.max_combo) } count_300 { rand(max_combo) } count_100 { rand(max_combo - count_300) } count_50 { rand(max_combo - count_300 - count_100) } count_miss { rand(max_combo - count_300 - count_100 - count_50) } count_geki { rand(count_300) } count_katu { rand(count_100) } perfect { max_combo == beatmap.max_combo } accuracy { rand * 100 } # only fail if misses are greater than 0 AND the random boolean says true pass { count_miss > 0 && [true, false].sample } is_full_combo { full_combo? } end end
class AddPhoneToClients < ActiveRecord::Migration def change add_column :clients, :phone, :integer end end
require 'fileutils' $phpmyadmin_version = "3.4" $phpmyadmin_cart_root = "/usr/libexec/stickshift/cartridges/embedded/phpmyadmin-#{$phpmyadmin_version}" $phpmyadmin_hooks = $phpmyadmin_cart_root + "/info/hooks" $phpmyadmin_config = $phpmyadmin_hooks + "/configure" $phpmyadmin_config_format = "#{$phpmyadmin_config} %s %s %s" $phpmyadmin_deconfig = $phpmyadmin_hooks + "/deconfigure" $phpmyadmin_deconfig_format = "#{$phpmyadmin_deconfig} %s %s %s" $phpmyadmin_proc_regex = /httpd -C Include .*phpmyadmin/ Given /^a new phpmyadmin$/ do account_name = @account['accountname'] namespace = @app['namespace'] app_name = @app['name'] command = $phpmyadmin_config_format % [app_name, namespace, account_name] outbuf = [] exit_code = runcon command, $selinux_user, $selinux_role, $selinux_type, outbuf if exit_code != 0 raise "Error running #{command}: returned #{exit_code}" end end Given /^phpmyadmin is (running|stopped)$/ do | status | action = status == "running" ? "start" : "stop" acct_name = @account['accountname'] namespace = @app['namespace'] app_name = @app['name'] daemon_name = 'httpd' command = "#{$phpmyadmin_hooks}/#{action} #{app_name} #{namespace} #{acct_name}" num_daemons = num_procs_like acct_name, $phpmyadmin_proc_regex outbuf = [] case action when 'start' if num_daemons == 0 runcon command, $selinux_user, $selinux_role, $selinux_type, outbuf end exit_test = lambda { |tval| tval > 0 } when 'stop' if num_daemons > 0 runcon command, $selinux_user, $selinux_role, $selinux_type, outbuf end exit_test = lambda { |tval| tval == 0 } # else # raise an exception end # now loop until it's true max_tries = 10 poll_rate = 3 tries = 0 num_daemons = num_procs_like acct_name, $phpmyadmin_proc_regex while (not exit_test.call(num_daemons) and tries < max_tries) tries += 1 sleep poll_rate num_daemons = num_procs_like acct_name, $phpmyadmin_proc_regex end end When /^I configure phpmyadmin$/ do account_name = @account['accountname'] namespace = @app['namespace'] app_name = @app['name'] command = $phpmyadmin_config_format % [app_name, namespace, account_name] outbuf = [] exit_code = runcon command, $selinux_user, $selinux_role, $selinux_type, outbuf if exit_code != 0 raise "Error running #{command}: returned #{exit_code}" end end When /^I deconfigure phpmyadmin$/ do account_name = @account['accountname'] namespace = @app['namespace'] app_name = @app['name'] command = $phpmyadmin_deconfig_format % [app_name, namespace, account_name] exit_code = runcon command, $selinux_user, $selinux_role, $selinux_type if exit_code != 0 raise "Command failed with exit code #{exit_code}" end end When /^I (start|stop|restart) phpmyadmin$/ do |action| acct_name = @account['accountname'] namespace = @app['namespace'] app_name = @app['name'] phpmyadmin_user_root = "#{$home_root}/#{acct_name}/phpmyadmin-#{$phpmyadmin_version}" outbuf = [] command = "#{$phpmyadmin_hooks}/#{action} #{app_name} #{namespace} #{acct_name}" exit_code = runcon command, $selinux_user, $selinux_role, $selinux_type, outbuf if exit_code != 0 raise "Command failed with exit code #{exit_code}" end end Then /^a phpmyadmin http proxy file will( not)? exist$/ do | negate | acct_name = @account['accountname'] app_name = @app['name'] namespace = @app['namespace'] conf_file_name = "#{acct_name}_#{namespace}_#{app_name}/phpmyadmin-#{$phpmyadmin_version}.conf" conf_file_path = "#{$libra_httpd_conf_d}/#{conf_file_name}" if not negate File.exists?(conf_file_path).should be_true else File.exists?(conf_file_path).should be_false end end Then /^a phpmyadmin httpd will( not)? be running$/ do | negate | acct_name = @account['accountname'] acct_uid = @account['uid'] app_name = @app['name'] max_tries = 20 poll_rate = 3 exit_test = negate ? lambda { |tval| tval == 0 } : lambda { |tval| tval > 0 } tries = 0 num_httpds = num_procs_like acct_name, $phpmyadmin_proc_regex while (not exit_test.call(num_httpds) and tries < max_tries) tries += 1 sleep poll_rate end if not negate num_httpds.should be > 0 else num_httpds.should be == 0 end end Then /^the phpmyadmin directory will( not)? exist$/ do | negate | account_name = @account['accountname'] namespace = @app['namespace'] app_name = @app['name'] phpmyadmin_user_root = "#{$home_root}/#{account_name}/phpmyadmin-#{$phpmyadmin_version}" begin phpmyadmin_dir = Dir.new phpmyadmin_user_root rescue Errno::ENOENT phpmyadmin_dir = nil end unless negate phpmyadmin_dir.should be_a(Dir) else phpmyadmin_dir.should be_nil end end Then /^phpmyadmin log files will( not)? exist$/ do | negate | acct_name = @account['accountname'] acct_uid = @account['uid'] app_name = @app['name'] log_dir_path = "#{$home_root}/#{acct_name}/phpmyadmin-#{$phpmyadmin_version}/logs" begin log_dir = Dir.new log_dir_path status = (log_dir.count > 2) rescue status = false end if not negate status.should be_true else status.should be_false end end Then /^the phpmyadmin control script will( not)? exist$/ do | negate | account_name = @account['accountname'] namespace = @app['namespace'] app_name = @app['name'] phpmyadmin_user_root = "#{$home_root}/#{account_name}/phpmyadmin-#{$phpmyadmin_version}" phpmyadmin_startup_file = "#{phpmyadmin_user_root}/#{app_name}_phpmyadmin_ctl.sh" begin startfile = File.new phpmyadmin_startup_file rescue Errno::ENOENT startfile = nil end unless negate startfile.should be_a(File) else startfile.should be_nil end end # Pulls the reverse proxy destination from the proxy conf file and ensures # the path it forwards to is accessible via the external IP of the instance. Then /^the phpmyadmin web console url will be accessible$/ do acct_name = @account['accountname'] app_name = @app['name'] namespace = @app['namespace'] conf_file_name = "#{acct_name}_#{namespace}_#{app_name}/phpmyadmin-#{$phpmyadmin_version}.conf" conf_file_path = "#{$libra_httpd_conf_d}/#{conf_file_name}" # The URL segment for the cart lives in the proxy conf cart_path = `/bin/awk '/ProxyPassReverse/ {printf "%s", $2;}' #{conf_file_path}` # Assemble a test URL for the cart. This seems pretty cheesy. I could query the root, # but we'll get a 302 redirect, and I'm not sure if that's a good test. conf_url = "https://127.0.0.1#{cart_path}/js/sql.js" # Strip just the status code out of the response. Set the Host header to # simulate an external request, exercising the front-end httpd proxy. res = `/usr/bin/curl -k -w %{http_code} -s -o /dev/null -H 'Host: #{app_name}-#{namespace}.dev.rhcloud.com' #{conf_url}` raise "Expected 200 response from #{conf_url}, got #{res}" unless res == "200" end
class AddUniqueReputableBadgingsIndex < ActiveRecord::Migration def self.up execute "ALTER IGNORE TABLE `reputable_badgings` ADD UNIQUE INDEX `index_reputable_badgings_on_user_id_and_badge_id_and_year` (`user_id`,`badge_id`,`year`);" end def self.down execute "DROP INDEX index_reputable_badgings_on_user_id_and_badge_id_and_year ON reputable_badgings;" end end
$depth = 0 def better_log desc, &block depth = ' '*$depth puts depth + "Beginning \"#{desc}\"..." $depth += 1 result = block[] $depth -= 1 puts depth + "...\"#{desc}\" finished, returning: #{result}" end better_log 'outer block' do better_log 'some little block' do better_log 'teeny-tiny block' do 'lOtS oF lOVe'.downcase end 7 * 3 * 2 end better_log 'yet another block' do '!doof naidnI evol I'.reverse end '0' == "0" end # def do_self_importantly some_proc # puts "Everybody just HOLD ON! I'm doing something..." # some_proc.call # puts "OK everyone, I'm done. As you were." # end # # say_hello = Proc.new do # puts 'hello' # end # # say_goodbye = Proc.new do # puts 'goodbye' # end # # do_self_importantly say_hello # do_self_importantly say_goodbye # Output: # Everybody just HOLD ON! I'm doing something... # hello # OK everyone, I'm done. As you were. # Everybody just HOLD ON! I'm doing something... # goodbye # OK everyone, I'm done. As you were.
class PulseOptions ONE_HOUR_IN_SECONDS = 3600 DEFAULT_TIMEOUT_IN_HOURS = 10 DEFAULT_POLLING_TIME_IN_SECONDS = 60 DEFAULT_TOKEN_REFRESH_TIME_IN_SECONDS = 1200 DEFAULT_BUILD_REQUEST_TIME_IN_SECONDS = 60 * 20 CONCOURSE_URL = "https://gpdb.data.pivotal.ci/" attr_reader :url, :project_name, :username, :password, :input_dir, :output_dir, :build_artifact_url, :build_src_code_url, :qautil_url, :gpdb_src_behave_url, :start_time def self.forTriggerJob PulseOptions.new(needs_output_dir: true) end def self.forMonitorJob PulseOptions.new(needs_input_dir: true) end def initialize(options = {}) @input_required = options[:needs_input_dir] @output_required = options[:needs_output_dir] @start_time = Time.now end def read_from_environment @url = ENV['PULSE_URL'] @project_name = ENV['PULSE_PROJECT_NAME'] @username = ENV['PULSE_USERNAME'] @password = ENV['PULSE_PASSWORD'] @input_dir = ENV['INPUT_DIR'] if @input_required @output_dir = ENV['OUTPUT_DIR'] if @output_required ["PULSE_URL", "PULSE_PROJECT_NAME", "PULSE_USERNAME", "PULSE_PASSWORD"].each do |required_var| raise "#{required_var} environment variable required" if ENV[required_var].nil? end raise "INPUT_DIR environment variable required" if @input_dir.nil? && @input_required raise "OUTPUT_DIR environment variable required" if @output_dir.nil? && @output_required end # read the s3 signed URLs from Concourse def read_from_concourse_urls(artifact_url, src_code_url, qa_util_url, behave_url) @build_artifact_url = File.read(artifact_url).strip @build_src_code_url = File.read(src_code_url).strip @qautil_url = File.read(qa_util_url).strip @gpdb_src_behave_url = File.read(behave_url).strip end def print_environment_settings puts "PULSE_URL is #{url}" puts "PULSE_PROJECT_NAME is #{project_name}" puts "BUILD_ARTIFACT_URL:\n#{build_artifact_url}\n" unless build_artifact_url.nil? puts "BUILD_SRC_CODE_URL:\n#{build_src_code_url}\n" unless build_src_code_url.nil? puts "QAUTIL_URL:\n#{qautil_url}\n" unless qautil_url.nil? puts "GPDB_SRC_BEHAVE_URL:\n#{gpdb_src_behave_url}\n" unless gpdb_src_behave_url.nil? end def validate_options directory = @input_required ? input_dir : output_dir if !File.directory?(directory) puts "#{directory} must be a valid directory" exit 1 end end def build_id return @build_id if !@build_id.nil? build_id_file = input_dir + "/build_id" @build_id = File.read(build_id_file).strip.to_i puts "Build ID input: #{@build_id} (read from #{build_id_file})" @build_id end def build_url base_url = URI.parse(url + URI.escape("browse/projects/#{project_name}")).to_s return "#{base_url}/builds/#{build_id}/" end def trigger_options { force: true, properties: { BUILD_ARTIFACT_URL: build_artifact_url, BUILD_SRC_CODE_URL: build_src_code_url, QAUTIL_URL: qautil_url, GPDB_SRC_BEHAVE_URL: gpdb_src_behave_url, }, reason: "Triggered via Concourse #{CONCOURSE_URL}" } end # Pulse builds can take between 20 minutes to 6-7 hours to complete def end_time @start_time + (DEFAULT_TIMEOUT_IN_HOURS * ONE_HOUR_IN_SECONDS) end def timeout DEFAULT_TIMEOUT_IN_HOURS end def polling_time DEFAULT_POLLING_TIME_IN_SECONDS + rand(10) end def build_request_time DEFAULT_BUILD_REQUEST_TIME_IN_SECONDS end # Pulse login tokens expire every 30 minutes; get a new one every 20 minutes def new_token_time(refresh = false) if refresh Time.now + DEFAULT_TOKEN_REFRESH_TIME_IN_SECONDS else start_time + DEFAULT_TOKEN_REFRESH_TIME_IN_SECONDS end end end
class Question < ActiveRecord::Base belongs_to :shopper, class_name: "User", foreign_key: :shopper_id has_many :question_images has_many :question_friends end
require "rails_helper" RSpec.describe AppController, type: :routing do describe "routing" do it "routes to #create" do expect(:post => "/user_contacts").to route_to("user_contacts#create") end end end
class ChangeFieldsOnContentsAndCategories < ActiveRecord::Migration def change add_column :categories,:background_image,:text remove_column :contents, :image_url remove_column :contents, :content_type remove_column :contents, :order end end
class User < ApplicationRecord has_many :private_messages has_many :gossips has_many :comment has_many :likes has_many :tags belongs_to :city end
class LinkBinariesToClient < ActiveRecord::Migration def up add_column :binaries, :client_id, :integer end def down remove_column :binaries, :client_id end end
class TicTacToe def initialize(board = nil) @board = board || Array.new(9, " ") end WIN_COMBINATIONS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [6,4,2] ] def display_board puts " #{@board[0]} | #{@board[1]} | #{@board[2]} " puts "-----------" puts " #{@board[3]} | #{@board[4]} | #{@board[5]} " puts "-----------" puts " #{@board[6]} | #{@board[7]} | #{@board[8]} " end def move(input, character = "X") location = (input.to_i) - 1 @board[location] = character end def position_taken?(location) if @board[location] == nil || @board[location] == " " return false else return true end end def valid_move?(position) if position.to_i.between?(1,9) && position_taken?(position.to_i - 1) == false return true else return false end end def turn puts "Please enter 1-9:" input = gets.strip position = input if valid_move?(position) == true character = current_player move(input, character) else puts "Please enter 1-9:" input = gets.strip position = input end display_board end def turn_count turns_played = 0 @board.each do |space| if space == "X" || space == "O" turns_played += 1 end end turns_played end def current_player if turn_count.to_i % 2 == 0 return "X" else return "O" end end def won? WIN_COMBINATIONS.each do |win_combination| if win_combination.all? {|location| @board[location] == "X" || win_combination.all? {|location| @board[location] == "O"}} return win_combination end end if @board.all? {|spot| spot == "X" || spot == "O"} return false end end def full? if @board.all? {|spot| spot == "X" || spot == "O"} return true end WIN_COMBINATIONS.each do |win_combination| if win_combination.any? {|location| @board[location] == " " || win_combination.any? {|location| @board[location] == "" || win_combination.any? {|location| @board[location] == nil}}} return false end end end def draw? if won? == false && full? == true return true elsif !!won? == false && full? == false return false elsif won? return false end end def over? if !!won? == true || full? == true || draw? == true return true end end def winner WIN_COMBINATIONS.each do |win_combination| if win_combination.all? {|location| @board[location] == "X"} return "X" elsif win_combination.all? {|location| @board[location] == "O"} return "O" end end if !!won? == false return nil end end def play until over? == true turn end if draw? == true puts "Cats Game!" end if won? if winner == "X" puts "Congratulations X!" elsif winner == "O" puts "Congratulations O!" end end end end
# frozen_string_literal: true require "benchmark" namespace :diaverum do namespace :db do namespace :demo do desc "Loads demo seeds from renalware-core then adds renalware-diaverum demo seeds" task seed: :environment do if Rails.env.development? require Renalware::Diaverum::Engine.root.join("demo_data", "seeds") else puts "Task currently only possible in development environment" end end end end end
class BoardTraversal attr_reader :current, :moves_registered, :unprocessed_queue, :solved_states def initialize(target_board) @current = target_board @moves_registered, @unprocessed_queue = [], [] @solved_states = {} end end
module SportsSouth class Image < Base API_URL = 'http://webservices.theshootingwarehouse.com/smart/images.asmx' def self.urls(item_number, options = {}) requires!(options, :username, :password) http, request = get_http_and_request(API_URL, '/GetPictureURLs') request.set_form_data(form_params(options).merge({ ItemNumber: item_number })) response = http.request(request) xml_doc = Nokogiri::XML(sanitize_response(response)) raise SportsSouth::NotAuthenticated if not_authenticated?(xml_doc) images = Hash.new xml_doc.css('Table').each do |image| size = content_for(image, 'ImageSize').to_sym images[size] = content_for(image, 'Link') end images end def self.list_new_pictures(options = {}) requires!(options, :username, :password) http, request = get_http_and_request(API_URL, '/ListNewPictures') request.set_form_data(form_params(options).merge({ DateFrom: (options[:date_from] || (DateTime.now - 1).strftime('%m/%d/%Y')) })) response = http.request(request) xml_doc = Nokogiri::XML(sanitize_response(response)) xml_doc.css('Table').map { |node| { item_number: content_for(node, 'ITEMNO') } } end end end
FactoryBot.define do factory :related_file_group_join do association :source_file_group, factory: :external_file_group association :target_file_group, factory: :bit_level_file_group end end
# Take two parameters of beginning and ending of range (inclusive), # and return sum of all even numbers in range. def sum_even_nums_in_range(start, stop) (start..stop).select(&:even?).sum end
#Navigate to google.co.uk Given(/^I am on the Google homepage$/) do visit 'https://www.google.co.uk/' end #Write "yahoo" search text to the search bar When(/^I will search for "([fusion_builder_container hundred_percent="yes" overflow="visible"][fusion_builder_row][fusion_builder_column type="1_1" background_position="left top" background_color="" border_size="" border_color="" border_style="solid" spacing="yes" background_image="" background_repeat="no-repeat" padding="" margin_top="0px" margin_bottom="0px" class="" id="" animation_type="" animation_speed="0.3" animation_direction="left" hide_on_mobile="no" center_content="no" min_height="none"][^"]*)"$/) do |searchText| fill_in 'lst-ib', :with => searchText end #In the current page, we should see "yahoo" text Then(/^I should see "([^"]*)"$/) do |expectedText| page.should have_content(expectedText) end #Click the yahoo link Then(/^I will click the yahoo link$/) do click_link('Yahoo') end #Wait 10 seconds statically to see yahoo website Then(/^I will wait for (\d+) seconds$/) do |waitTime| sleep (waitTime.to_i) end
require 'calabash-android/calabash_steps' Given(/^I am on the landing screen$/) do check_element_exists "* id:'toolbar' * {text CONTAINS 'Calabash Issue #707'}" end When(/^I click the first photo on the screen$/) do touch "* id:'image_view' index:0" end Then(/^I see a new screen that says "([^"]*)"$/) do |arg| wait_for_elements_exist "* {text CONTAINS '#{arg}'}" end And(/^I choose "([^"]*)" from the toolbar dropdown$/) do |arg| touch "* id:'gallery_selector'" tap_when_element_exists "* {text CONTAINS '#{arg}'}" end
module Eq module RoleAssignments # Eq::RoleAssignments::RoleAssignmentEntityFactory class RoleAssignmentEntityFactory def build(hash) RoleAssignmentEntity.new( id: hash[:id], user: hash[:user], target: hash[:target], role: hash[:role], assigner: hash[:assigner], created_at: hash[:created_at], updated_at: hash[:updated_at] ) end end end end
class UserMailer < ApplicationMailer default from: 'ajesteves@gmail.com' def welcome_mail @url = 'http://example.com/login' mail(to: "ajesteves@gmail.com", subject: 'Welcome to My Awesome Site') end end
class FavoritesController < ApplicationController load_and_authorize_resource # GET /users/:user_id/favorites def index render json: @favorites end # GET /favorites/1 def show render json: @favorite end # POST /users/:user_id/favorites def create if @favorite.save render json: @favorite, status: :created, location: @favorite else render json: @favorite.errors, status: :unprocessable_entity end end # PATCH/PUT /favorites/1 def update if @favorite.update(favorite_params) render json: @favorite else render json: @favorite.errors, status: :unprocessable_entity end end # DELETE /favorites/1 def destroy @favorite.destroy end private def favorite_params params.require(:favorite).permit(:users_id, :public) end end
module CzechName class NameFactory attr_reader :raw, :parsed def initialize(name) @raw = name @parsed = @raw && @raw.split(' ') end def create return nil if raw.nil? || raw.empty? case when any_name_is_female_first? then create_female_name when all_names_are_female? then create_female_name when all_names_are_male? then create_male_name else nil end end private def any_name_is_female_first? parsed.any? { |name| female_first_name_database.include?(name) } end def all_names_are_female? parsed.all? { |name| female_first_name_database.include?(name) || female_last_name_database.include?(name) } end def all_names_are_male? parsed.all? { |name| male_first_name_database.include?(name) || male_last_name_database.include?(name) } end def create_female_name first_names, names = parsed.partition { |fm| female_first_name_database.include?(fm) } first_names_in_vocative = first_names.map { |fm| female_first_name_database.vocative(fm) } last_names, names = names.partition { |fm| female_last_name_database.include?(fm) } last_names_in_vocative = last_names.map { |fm| female_last_name_database.vocative(fm) } male_last_names, names = names.partition { |fm| male_last_name_database.include?(fm) } return nil unless names.empty? vocative = [first_names_in_vocative, last_names_in_vocative, male_last_names].flatten.join(' ') FemaleName.new(@raw, vocative) end def create_male_name first_names, names = parsed.partition { |fm| male_first_name_database.include?(fm) } first_names_in_vocative = first_names.map { |fm| male_first_name_database.vocative(fm) } last_names, names = names.partition { |fm| male_last_name_database.include?(fm) } last_names_in_vocative = last_names.map { |fm| male_last_name_database.vocative(fm) } return nil unless names.empty? vocative = [first_names_in_vocative, last_names_in_vocative].flatten.join(' ') MaleName.new(@raw, vocative) end def male_first_name_database Database.new(Configuration.male_first_name_database_file_path) end def male_last_name_database Database.new(Configuration.male_last_name_database_file_path) end def female_first_name_database Database.new(Configuration.female_first_name_database_file_path) end def female_last_name_database Database.new(Configuration.female_last_name_database_file_path) end end end
# The class Computer acts as an interface class Computer def Clone raise NotImplementedError, 'CLone() must be defined in subclass' end end # The class Laptop1 inherits from Computer class Laptop1 < Computer def Clone return self.clone end def Functionality puts "Laptop 1" end end # The class Laptop2 inherits from Computer class Laptop2 < Computer def Clone return self.clone end def Functionality puts "Laptop 2" end end # Object creation for each clone laptopObj1 = Laptop1.new laptopObj2 = Laptop2.new # Calling the first Laptop1 class and executing the function lpObj = laptopObj1.Clone lpObj.Functionality # Calling the first Laptop2 class and executing the function lpObj = laptopObj2.Clone lpObj.Functionality
class User < ActiveRecord::Base has_secure_password has_many :adventurers validates :username, :name, presence: true validates :username, uniqueness: true # def randomize # Adventurer.create( # name: [Faker::FunnyName.two_word_name, Faker::FunnyName.three_word_name, Faker::FunnyName.four_word_name].sample, # fantasy_origin: Faker::Games::DnD.race, # class: Faker::Games::DnD.klass, # hometown: Faker::Games::DnD.city, # background: Faker::Games::DnD.background, # weapon: [Faker::Games::DnD.melee_weapon, Faker::Games::DnD.ranged_weapon].sample, # nemesis: Faker::Games::DnD.monster, # experience_level: rand(1..20), # user_id: self.id # ) # end end
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe 'awaited hello' do min_server_fcv '4.4' # If we send the consecutive hello commands to different mongoses, # they have different process ids, and so the awaited one would return # immediately. require_no_multi_mongos let(:client) { authorized_client } it 'waits' do # Perform a regular hello to get topology version resp = client.database.command(hello: 1) doc = resp.replies.first.documents.first tv = Mongo::TopologyVersion.new(doc['topologyVersion']) tv.should be_a(BSON::Document) elapsed_time = Benchmark.realtime do resp = client.database.command(hello: 1, topologyVersion: tv.to_doc, maxAwaitTimeMS: 500) end doc = resp.replies.first.documents.first elapsed_time.should > 0.5 end end
# Author:: Tor E Hagemann <hagemt@rpi.edu> # Copyright:: Copyright (c) 2012 onetooneandonto require 'rubygems' require 'dm-core' # Buzzline Model module Buzzline class Buzzline include DataMapper::Resource property :id, Serial property :date, String property :email, String property :who, String property :when, String property :what, String property :where, String property :why, String property :how, String end end # FIXME REMOVE #b = Buzzline.new # TODO lawl WTF does this do? #DataMapper.auto_upgrade! # Buzzline Tests require 'test/unit' module Buzzline class BuzzlineUnitTestCase < Test::Unit::TestCase def setup @buzzline = Buzzline.new end def test_db raise "Cannot construct Buzzline" unless @buzzline end end end
class CreateInfractions < ActiveRecord::Migration def change create_table :infractions do |t| t.string :owner_name t.string :owner_identifier t.string :owner_zip_code t.string :owner_address t.string :owner_address_number t.string :owner_address_complement t.string :owner_district t.string :owner_city t.string :owner_state t.string :owner_ddd_mobile t.string :owner_mobile t.string :owner_ddd_phone t.string :owner_phone t.string :property_zone t.string :property_zip_code t.string :property_address t.string :property_address_number t.string :property_address_complement t.string :property_district t.string :property_city t.string :property_state t.string :property_meter t.string :property_block t.string :property_allotment t.string :property_observation t.string :notify_description t.string :regulation t.string :state t.integer :regularization t.references :users, index: true t.timestamps end end end
class Function < ActiveRecord::Base has_many :business_unit_functions has_many :business_units, through: :business_unit_functions has_many :function_cost_centers has_many :cost_centers, through: :function_cost_centers end
json.array!(@slbigforms) do |slbigform| json.extract! slbigform, :id, :first_name, :second_name, :date_of_birth, :sex, :edu, :about, :music, :phone, :email, :photo, :site, :agree json.url slbigform_url(slbigform, format: :json) end
class ProductsController < ApplicationController def index @products = Product.all.paginate(:page => params[:page], :per_page => 9) end def usa @usa_products = Product.made_in_usa end def most_reviews @most_reviews_products = Product.most_reviews end def most_recent @most_recent_products = Product.most_recent end def show @product = Product.find(params[:id]) @reviews = @product.reviews end def new @product = Product.new end def create @product = Product.new(product_params) if @product.save redirect_to products_path else render :new end end def edit @product = Product.find(params[:id]) end def update @product = Product.find(params[:id]) if @product.update(product_params) redirect_to products_path else render :edit end end def destroy @product = Product.find(params[:id]) @product.destroy redirect_to products_paths end private def product_params params.require(:product).permit(:name, :cost, :origin) end end
class RenameExplanationColumnToDeals < ActiveRecord::Migration def change rename_column :deals, :explanation, :deal_detail end end
# frozen_string_literal: true # Unit of measurement class Unit < ApplicationRecord has_many :range_parameters, dependent: :delete_all has_many :integer_parameters, dependent: :delete_all validates :name, :short, presence: true end
require 'rails_helper' RSpec.describe "investigationclassifications/show", type: :view do before(:each) do @investigationclassification = assign(:investigationclassification, Investigationclassification.create!( investigation: nil, subclassification: nil )) end it "renders attributes in <p>" do render expect(rendered).to match(//) expect(rendered).to match(//) end end
class BookController < ApplicationController skip_before_action :verify_authenticity_token def create @book = Book.new(book_params) if @book.save render json: {status: '200 OK', data: @book} else render json: {status: '400 Bad Request', data: @book.errors} end end def read @book = Book.find(params[:id]) render json: {status: '200 OK', data:@book} end def list @books = Book.all render json: {status: '200 OK', data:@books} end def update @book = Book.find(params[:id]) if @book.update(book_params) render json: {status: '200 OK', data:@book} else render json: {status: '400 Bad Request', data:@book.errors} end end def delete Book.find(params[:id]).destroy render json: {status: '200 OK'} end private def book_params params.permit(:B_title, :Author, :Publisher, :Year) end end
#encoding utf-8 namespace :foowcn do desc "add foowable stores to foowcn, or remove unfoowable stores from foowcn" task :add_foowable_stores => :environment do foowcn = Instance.find_by_name 'foowcn' Store.all.each do |store| foowcn.stores << store if !foowcn.stores.include?(store) && store.foowable? end end task :remove_unfoowable_stores => :environment do foowcn = Instance.find_by_name 'foowcn' foowcn.operations.each do |opr| opr.destroy if !opr.store.foowable? end end # def pcounts drt ucount = User.where(created_at: drt).count icount = Instance.where(created_at: drt).count scount = Store.where(created_at: drt).count ccount = Customer.where(created_at: drt).count bcount = Order.where(created_at: drt).count ocount = Order.where(submit_at: drt).count amount = Order.where(submit_at: drt).sum(:amount).round info = "\n-------------------------------\nnew created #{drt}\n" info += "users|instances|stores|customers|browsing|order|amount\n" info += "#{ucount}|#{icount}|#{scount}|#{ccount}|#{bcount}|#{ocount}|#{amount}\n" return info end #列出新注册用户 def pusrs drt usrs=User.where(created_at: drt) info = "\n-------------------------------\nnew usrs info #{drt}\n" usrs.each do |usr| nicks = '' phones = '' usr.instances.each do |is| nicks += is.nick phones += is.phone end info += "#{usr.id}|#{usr.name}|#{usr.email}|#{nicks}|#{phones}\n" end return info end def pactive drt, cond ods = Order.where(created_at: drt) if cond=='created_at' ods ||= Order.where(submit_at: drt) info = "\n-------------------------------\nactived #{drt} #{cond}\n" ulist=Hash.new ilist=Hash.new slist=Hash.new clist=Hash.new ods.each do |od| ulist[od.instance.creator.id] = 0 if od.instance && od.instance.creator && ulist[od.instance.creator.id].nil? ilist[od.instance.id] = 0 if od.instance && ilist[od.instance.id].nil? slist[od.store.id] = 0 if od.store && slist[od.store.id].nil? clist[od.customer.id] = 0 if od.customer && clist[od.customer.id].nil? ulist[od.instance.creator.id] +=1 if od.instance && od.instance.creator ilist[od.instance.id] += 1 if od.instance clist[od.customer.id] += 1 if od.customer slist[od.store.id] += 1 if od.store end ulist=Hash[ulist.sort_by{|k,v| v}.reverse] ilist=Hash[ilist.sort_by{|k,v| v}.reverse] slist=Hash[slist.sort_by{|k,v| v}.reverse] clist=Hash[clist.sort_by{|k,v| v}.reverse] info += "users|instances|stores|customers\n" info += "#{ulist.count}|#{ilist.count}|#{slist.count}|#{clist.count}\n" info += "top5 ilist\n" ilist.take(5).each do |id,count| ist = Instance.find(id) info += "#{count}|#{id}|#{ist.nick}|#{ist.phone}|#{ist.email}\n" end return info end task :dash => :environment do ysd = Time.now.yesterday drt_all = Date.new(2013,4,1).beginning_of_day..ysd.end_of_day drt_week = ysd.end_of_day.ago(6.days).beginning_of_day..ysd.end_of_day drt_month = Date.new(2014,3,1).beginning_of_day..ysd.end_of_day drt_ysd = ysd.beginning_of_day..ysd.end_of_day info = "\n===============================\nfoowcn dash task info\n" info += "===============================\n" info += pusrs drt_ysd info += pcounts drt_all info += pcounts drt_week info += pcounts drt_ysd info += pactive drt_week, 'created_at' info += pactive drt_week, 'submit_at' info += pactive drt_ysd, 'created_at' info += pactive drt_ysd, 'submit_at' info += "\n" info += "=============================== searched review\n" info += searched_review drt_ysd info += "=============================== comments review\n" info += comments_review drt_ysd info += "=============================== hottest searched\n" info += hottest_searched info += "=============================== subscribed stats\n" foo_report = InstanceReport.new(Instance.find(38), drt_ysd) info += foo_report.scan_report info += foo_report.unsub_report info += foo_report.village_items_report ReportMailer.dash(info).deliver update_vscore update_meta remove_employee_data end def update_meta str = '' VillageItem.all.each do |vi| vi.sub_tags.each do |st| if vi.meta vi.meta += " #{st.name}" unless vi.meta.include? st.name end end vi.tags.each do |tg| if vi.meta vi.meta += " #{tg.name}" unless vi.meta.include? tg.name end end #str += "#{vi.meta} \n" vi.save end str end #vscore is updated periodly via crontab def update_vscore VillageItem.find_each do |vi| vi.update commenters_count: vi.comments.group(:customer_id).length print "update #{vi.name}..\n" end vis = VillageItem.all vis_count = vis.count vis_count += 1 click_sum = vis.sum(:click_count) favor_sum = vis.sum(:favor_count) call_sum = vis.sum(:call_count) commenter_sum = 0 vis.each { |v| commenter_sum +=v.commenters_count } average_wfc = 100.0*favor_sum / ( click_sum + call_sum + 1) average_score = (favor_sum*4+call_sum*2+click_sum*1+commenter_sum*3+1)/(vis.count+1) vis.each do |vi| #using 14 days as age unit age = (Time.now-vi.created_at)/24/60/60/14 age = 1 if age < 1 ldrt = (Time.now-14.days)..Time.now show_event = CustomerEvent.where(target_id: vi.id, name: "customer_click_village_item", event_type: "show_event", created_at: ldrt).count view_event = CustomerEvent.where(target_id: vi.id, name: "customer_click_village_item", event_type: "view_event", created_at: ldrt).count call_event = CustomerEvent.where(target_id: vi.id, name: "customer_click_village_item", event_type: "call_event", created_at: ldrt).count favor_event = CustomerEvent.where(target_id: vi.id, name: "customer_click_village_item", event_type: "favor_event", created_at: ldrt).count unfavor_event = CustomerEvent.where(target_id: vi.id, name: "customer_click_village_item", event_type: "unfavor_event", created_at: ldrt).count shop_event = CustomerEvent.where(target_id: vi.id, name: "customer_click_village_item", event_type: "shop_event", created_at: ldrt).count cs_count = CustomerEvent.where(target_id: vi.id, name: "customer_click_village_item", created_at: ldrt).pluck(:customer_id).uniq.count recent_score = show_event + 2*view_event + 2*call_event + 2*shop_event + 3*cs_count + 4*favor_event - 4*unfavor_event + (vi.approved? ? 2 : 1 ) history_score = ( vi.favor_count*4+vi.call_count*2+vi.click_count*1+3*vi.commenters_count + ( vi.approved? ? 2 : 1 ) ) wfc = ( 100.0*vi.favor_count ) / ( vi.click_count + vi.call_count + 1 ) weight = wfc/average_wfc vscore = recent_score * 0.5 + ( history_score - average_score ) * 0.2 + ( weight * age ) * 0.3 vi.update_attribute(:vscore, vscore) if vi.level == 2 || vi.level == 3 || vi.level == 4 || vi.level == 5 vi.update_attribute(:level, 1) if vi.approved_end_at && Time.now > vi.approved_end_at end end end def approve_public_items end #100.times { |i| update_vscore; sleep 789 } # def employee_cids; [18061,18299,22267,58957,60418,132346,201912,188921,18032,18013,194162] end def remove_employee_data employee_cids.each do |cid| searched = Record.where(customer_id: cid) searched.destroy_all end #Record.pluck(:content).uniq end def is_internal_cid eid; employee_cids.include? eid end def searched_review drt rcds=Record.where(created_at: drt).order(:result_count) rtr="记录号 || 搜索词 || 结果数 || 客户号 || 客户名 || 服务号 || 服务名 || 处理结果 \n" rcds.each do |rcd| cst = rcd.customer ins = rcd.instance rtr += "#{rcd.id} || #{rcd.content} || #{rcd.result_count} || #{cst.id} || #{cst.nickname} || #{ins.id} || #{ins.nick} || \n" if !(is_internal_cid cst.id) end #puts rtr return rtr end def comments_review drt cmts=Comment.where(created_at: drt).order(:id).reverse str="记录号 || 评论词 || 客户号 || 客户名 || 商店号 || 商店名 || 处理结果 \n" cmts.each do |cmt| if cmt.commentable_type == 'VillageItem' cst = cmt.customer vtm = VillageItem.find cmt.commentable_id str += "#{cmt.id} || #{cmt.content} || #{cst.id} || #{cst.nickname} || #{vtm.id} || #{vtm.name} || \n" if !(is_internal_cid cst.id) end end #puts str #这个每天运行发送给运营者 return str end def hottest_searched key_list=Record.pluck(:content).uniq hots={} key_list.each do |key| hots[key] = Record.where(content: key).count end hots.keys.sort { |a,b| hots[b] <=> hots[a] } keys = hots.keys.sort_by{|a| hots[a]}.reverse[1..10] ktr="优先级 || 搜索词 || 搜索数 || 处理结果 \n" nm=1 keys.each { |key| ktr += "#{nm} || #{key} || #{Record.where(content: key).count} || \n"; nm+=1 } return ktr end def hottest_review rcds=Record.pluck(:content,:result_count,:customer_id) hots={} rcds.each do |rcd| if !is_internal_cid(rcd[3]) hots[rcd[0]] = 0 if hots[rcd[0]].nil? hots[rcd[0]] += rcd[1] end end hots.keys.sort { |a,b| hots[b] <=> hots[a] } keys=hots.keys.sort_by{|a| hots[a]}.reverse[1..10] nm=1 ktr="优先级 || 搜索词 || 搜索数 || 处理结果 \n" keys.each { |key| ktr += "#{nm} || #{key} || #{hots[key]} || \n"; nm+=1 } #puts ktr return ktr end def clean_zombie_instances drt=Date.new(2013,3,1).beginning_of_day..(Date.today-30.days).end_of_day str='' Instance.where(created_at: drt).each do |ii| if ii.customers.count == 0 && ii.orders.count == 0 && ii.nick == '示例公众号' ii.stores.each do |ss| if ss.name == '示例商店' && ss.orders.count == 0 ss.wesell_items.destroy_all ss.destroy else str += "ii #{ii.id} del ss #{ss.id} #{ss.name} #{ss.orders.count} #{ss.wesell_items.pluck(:name).join('')}\n" end end ii.destroy else str += "ii #{ii.id} more: #{ii.nick} #{ii.customers.count} #{ii.stores.pluck(:name).join(' ')}\n" end end str end #drt=Time.now.yesterday.beginning_of_day...Time.now.yesterday.end_of_day def vl_rep drt str = "#{drt}\n\n" str += "#{comments_review drt}\n" str += "#{searched_review drt} \n" str += "#{hottest_searched} \n" end end
class AddCometitionToSeason < ActiveRecord::Migration[5.1] def change add_reference :seasons, :competition, foreign_key: true end end
class AddOmniauthFirstTime < ActiveRecord::Migration def change add_column :users, :first_time_omniauth, :integer end end
module HumanLogic def request_guess "#{current_player.name}: Make your guess! Choose four of the following colors: #{board.colors}" end def get_human_guess #NEED TO CHECK FOR VALID INPUT puts "First color:" first_color = gets.chomp puts "Second color:" second_color = gets.chomp puts "Third color:" third_color = gets.chomp puts "Fourth color:" fourth_color = gets.chomp guess = [first_color, second_color, third_color, fourth_color] guess.each do |element| if !board.colors.include?(element) #NEED TO FIX THIS CHECK puts "Oops! Something isn't right there. Let's try again." end end end def human_turn(turn) #for human breaker only current_row = board.grid[turn] puts "Turn #{turn + 1}" puts request_guess player_guess = get_human_guess set_guess(current_row, player_guess) comparison = compare_guess(player_guess) set_comparison(current_row, comparison) board.display game_over?(player_guess) end end
Gem::Specification.new do |s| s.name = 'optics-agent' s.version = '0.5.5' s.summary = "An Agent for Apollo Optics" s.description = "An Agent for Apollo Optics, http://optics.apollodata.com" s.authors = ["Meteor Development Group"] s.email = 'vendor+optics@meteor.com' s.files = Dir["{lib}/**/*", "LICENSE", "README.md"] s.test_files = Dir["{spec}/**/*"] s.homepage = 'http://rubygems.org/gems/optics-agent' s.license = 'MIT' s.add_runtime_dependency 'graphql', '~> 1.1' s.add_runtime_dependency 'google-protobuf', '~> 3.2' s.add_runtime_dependency 'faraday', '~> 0.9.0', '< 0.12' s.add_runtime_dependency 'net-http-persistent', '~> 2.0' s.add_runtime_dependency 'hitimes', '~> 1.2' s.add_development_dependency 'rake', '~> 12' s.add_development_dependency 'rspec', '~> 3.5' end
require 'test_helper' class ItemsControllerTest < ActionController::TestCase # test "the truth" do # assert true # end def setup @item = Item.new end test "Create Item" do get :create assert_response :success end test "New Item" do get :new assert_response :success end test "Show Item" do get :show, id: @item.id assert_response :success end test "Update Item" do get :update assert_response :success end test "Index Item" do get :index assert_response :success end test "Destroy Item" do get :destroy, id: @item.id assert_response :success end end
require "pry" require_relative "./ConvertPosition" require_relative "./ConvertPieces" require_relative "./WriteFile" require_relative "./Pieces" require_relative "./Grid" require_relative "./Moves" class Game include ConvertPosition include ConvertPieces include WriteFile def initialize @board = Grid.new.grid @moves = Moves.new.moves file = File.new "simple_results.txt","a+" end def list_positions @initial_pos = [] @final_pos = [] @moves.each do |movement| @initial_pos << convert_position(movement[0..1]) @final_pos << convert_position(movement[3..4]) end end def list_pieces @pieces = [] @initial_pos.each do |pos| @pieces << @board[pos[0]].split(" ")[pos[1]] end end def check(pieces, start, final) type_piece(pieces, start).check_move(final) end def play list_positions list_pieces (0..@initial_pos.length-1).each do |pos| if @board[@final_pos[pos][0]].split(" ")[@final_pos[pos][1]] != "--" write_move("ILLEGAL\n") else check(@pieces[pos], @initial_pos[pos], @final_pos[pos]) end end end end game = Game.new.play
## # 제일 작은 수 제거하기 # 문제 설명 # 정수를 저장한 배열, arr 에서 가장 작은 수를 제거한 배열을 리턴하는 함수, solution을 완성해주세요. 단, 리턴하려는 배열이 빈 배열인 경우엔 배열에 -1을 채워 리턴하세요. 예를들어 arr이 [4,3,2,1]인 경우는 [4,3,2]를 리턴 하고, [10]면 [-1]을 리턴 합니다. # # 제한 조건 # arr은 길이 1 이상인 배열입니다. # 인덱스 i, j에 대해 i ≠ j이면 arr[i] ≠ arr[j] 입니다. # 입출력 예 # arr return # [4,3,2,1] [4,3,2] # [10] [-1] def solution(arr = []) return [-1] if arr.length == 1 minIdx = arr.each_with_index.min { |(aVal, aIdx), (bVal, bIdx)| aVal<=>bVal }[1] arr.reject.each_with_index { |val, idx| idx == minIdx } end
require 'random-port' require 'rack' require 'et_azure_insights/adapters/rack' # A shared context for managing multiple rack servers. # This will start all servers registered before the context and # stop them after the context. # Access to the base_url is available using rack_servers.base_url_for(key) # # @example # # include_context 'rack servers' do # rack_servers.register(:app1) do |env| # [200, {}, ['OK from rack app 1']] # end # rack_servers.register(:app2) do |env| # [200, {}, ['OK from rack app 2']] # end # end # # The example above will register app1 and app2 # Before the context starts, a webrick server will be created for each and # the rack middleware for this project is included. # RSpec.shared_context 'rack servers' do |*args| class ServerCollection def initialize self.rack_apps = {} self.random_port_pool = RandomPort::Pool::SINGLETON end def register(key, &block) wrapped_rack_app = Rack::Builder.new do use ::EtAzureInsights::Adapters::Rack run block end rack_apps[key] = { app: wrapped_rack_app } end def start_all rack_apps.each_pair do |key, value| value[:port] = random_port_pool.acquire value[:rack_server] = Rack::Server.new( app: value[:app], server: 'webrick', Port: value[:port] ) value[:thread] = Thread.new do value[:rack_server].start end end end def stop_all rack_apps.values.each do |v| v[:thread].kill end end def base_url_for(key) "http://localhost:#{port_for(key)}" end def port_for(key) raise KeyError, "'#{key}' is not registered" unless rack_apps.key?(key) rack_apps[key][:port] end def get_request(key, path, disable_tracking: true) uri = URI.parse("#{base_url_for(key)}#{path}") headers = {} headers['et-azure-insights-no-track'] = 'true' if disable_tracking request = Net::HTTP::Get.new(uri, headers) http = Net::HTTP.new uri.hostname, uri.port http.open_timeout = 500 http.read_timeout = 500 http.max_retries = 0 response = http.request(request) http.finish if http.started? response end private attr_accessor :rack_apps, :random_port_pool end cattr_accessor :rack_servers self.rack_servers = ServerCollection.new def random_port_pool @random_port_pool ||= RandomPort::Pool.new end def rack_servers self.class.rack_servers end before(:all) do rack_servers.start_all sleep 1 end after(:all) do rack_servers.stop_all end end
class HomeController < ApplicationController def index if current_user.has_any_role? Role.super_role, Role.admin_role redirect_to events_path elsif current_user.has_role? Role.receptionist_role redirect_to work_center_events_path(current_user&.receptionist&.work_center) elsif current_user.has_role? Role.doctor_role redirect_to user_events_path(current_user) else render plain: 'Not Found', status: :not_found end end end
module Faceter module Nodes # The node describes adding prefix from tuples' keys # # @api private # class AddPrefix < ChangePrefix private def __operation__ :add_prefix end end # class AddPrefix end # module Nodes end # module Faceter
class AddLanguageToArticles < ActiveRecord::Migration def change add_column :articles, :language, :string, limit: 10 end end
# == Schema Information # # Table name: module_instances # # id :integer not null, primary key # created_at :datetime not null # updated_at :datetime not null # module_template_id :integer # cell_id :integer # amount :float # name :string(255) # class ModuleInstance < ActiveRecord::Base attr_accessible :id, :module_template_id, :cell_id, :module_values_attributes, :name, :amount has_many :module_values, :dependent => :destroy has_many :module_parameters, :through => :module_template belongs_to :module_template belongs_to :cell accepts_nested_attributes_for :module_values, :allow_destroy => true validates :module_template_id, :presence => true validates :cell_id, :presence => true validates :name, :presence => true after_create :create_parameters private def create_parameters self.module_template.module_parameters.each { |param| ModuleValue.create( {:value => nil, :module_instance_id => self.id, :module_parameter_id => param.id } ) } end end
class CreateCoursesCategories < ActiveRecord::Migration[5.1] def change create_table :categories_courses do |t| t.integer:course_id, null: false t.integer:category_id, null: false end end end
require_relative './stack.rb' # Time Complexity: O(n), push and pop should be O(1) operations since the linked list has both a head and tail pointer # Space Complexity: O(n) if the string is not balanced and comprised wholly of open brackets, also O(n) if it actually closes def balanced(string) return false if string.length % 2 == 1 return true if string.length == 0 stack = Stack.new string.each_char do |char| case char when "{" stack.push("}") when "[" stack.push("]") when "(" stack.push(")") when "}" return false if stack.pop != "}" when "]" return false if stack.pop != "]" when ")" return false if stack.pop != ")" else return false end end return stack.empty? end # Time Complexity: O(n) # Space Complexity: O(n) def evaluate_postfix(postfix_expression) return nil if postfix_expression.length == 0 stack = Stack.new postfix_expression.each_char do |char| int_conversion = char.to_i if int_conversion > 0 stack.push(int_conversion) elsif int_conversion == 0 && char == "0" stack.push(int_conversion) else postfix_operation(char, stack) end end return stack.pop end def postfix_operation(operator, stack) operand_2 = stack.pop operand_1 = stack.pop case operator when "+" stack.push(operand_1 + operand_2) when "-" stack.push(operand_1 - operand_2) when "*" stack.push(operand_1 * operand_2) when "/" raise ArgumentError, 'Cannot divide by 0' if (operand_1 == 0 || operand_2 == 0) stack.push(operand_1 / operand_2) end end
module ChapterExtension def format_publish_message(story, options={}) if options[:success] if story.published data = { button: I18n.t('actions.unpublish'), message: I18n.t('actions.publish_success') } else data = { button: I18n.t('actions.publish'), message: I18n.t('actions.unpublish_success') } end else if story.published data = { message: I18n.t('actions.unpublish_fail') } else data = { message: I18n.t('actions.publish_fail') } end end data end def get_errors(story) errors = [] story.errors.full_messages.each do |error| errors << error end errors end def get_chapters_with_errors(story) chapters = "" story.chapters.each do |chapter| if chapter.errors.any? chapters << chapter.reference + ", " end end chapters[0...-2] end def add_chapters_by_quantity(story, num_chapters) if story.chapters.present? last_known_reference = story.chapters.last.reference.to_i + 1 else last_chapter_reference = 1 end quantity = num_chapters - 1 last_chapter_reference = last_known_reference + quantity ActiveRecord::Base.transaction do (last_known_reference..last_chapter_reference).each do |i| Chapter.create(story: story, reference: i) end end story.chapter_numbers = story.chapters.last.reference.to_i story.save case num_chapters when 5 message = I18n.t('actions.messages.five_more') when 10 message = I18n.t('actions.messages.ten_more') when 20 message = I18n.t('actions.messages.twenty_more') when 50 message = I18n.t('actions.messages.fifty_more') end message end def remove_chapters_by_quantity(story, num_chapters) story.chapters.last(num_chapters).each(&:destroy) if story.chapters.count >= num_chapters case num_chapters when 5 message = I18n.t('actions.messages.five_less') when 10 message = I18n.t('actions.messages.ten_less') when 20 message = I18n.t('actions.messages.twenty_less') when 50 message = I18n.t('actions.messages.fifty_less') end message end def generate_chapters(chapter_numbers) if @story.chapters.empty? if chapter_numbers.present? @story.build_chapters(chapter_numbers) else chapter = @story.chapters.build chapter.decisions.build end end end end
module Vhod module Config REPOSITORY_BASE = '/opt/vhod/repositories/' SVN_BASE = 'svn://vhod/' REPOSITORY_LAYOUT = ['root'] MIN_LOG_MESSAGE_LENGTH = 2 VHOD_PATH = '/opt/vhod/webapp/current' end end
require 'test/unit' require 'network' class TestNetwork < Test::Unit::TestCase def setup @nn = NeuralNetwork.new("test") @l = NetworkLayer.new(2) end def test_push_input_layer assert_raise ArgumentError do @nn.pushInputLayer end assert(true, @nn.pushInputLayer(@l)) end def test_push_output_layer assert_raise ArgumentError do @nn.pushOutputLayer end assert(true, @nn.pushOutputLayer(@l)) end def test_push_hidden_layer assert_raise ArgumentError do @nn.pushHiddenLayer end assert(true, @nn.pushHiddenLayer(@l)) end def test_network_run assert_nil(@nn.run) @nn.pushInputLayer(@l) @nn.pushHiddenLayer(@l) @nn.pushOutputLayer(@l) assert(true, @nn.run) assert(true, @nn.run(@l)) end def test_network_output @nn.pushInputLayer(@l) @nn.pushHiddenLayer(@l) @nn.pushOutputLayer(@l) assert_kind_of(NetworkLayer, @nn.run) @nn.return_vector = true assert_kind_of(Array, @nn.run) end end
class Youth < ActiveRecord::Base has_one :youth_room_assignment belongs_to :member_type belongs_to :family validates_presence_of :family_id validates_presence_of :member_type_id validates_presence_of :first_name validates_presence_of :family_name validates_presence_of :gender validates_presence_of :age validates_presence_of :parent_name validates_presence_of :with_parents validates_presence_of :need_ride validates_presence_of :ride_at_church, :if => "need_ride == 1", :message => "required if you need a ride" validates_presence_of :emergency_contact_name validates_presence_of :emergency_contact_phone validates_format_of :cell_phone, :with => /[0-9]{10}/, :message => "Must be 10 digit phone number", :allow_nil => true, :allow_blank => true validates_format_of :emergency_contact_phone, :with => /[0-9]{10}/, :message => "Must be 10 digit phone number" validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :allow_nil => true, :allow_blank => true validates_numericality_of :age, :only_integer => true, :greater_than => 0, :less_than => 100, :message => "Invalid age", :allow_nil => true, :allow_blank => true end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo class Cluster # A manager that calls a method on each of a cluster's pools to close idle # sockets. # # @api private # # @since 2.5.0 class SocketReaper # Initialize the SocketReaper object. # # @example Initialize the socket reaper. # SocketReaper.new(cluster) # # @param [ Mongo::Cluster ] cluster The cluster whose pools' idle sockets # need to be reaped at regular intervals. # # @since 2.5.0 def initialize(cluster) @cluster = cluster end # Execute the operation to close the pool's idle sockets. # # @example Close the idle sockets in each of the cluster's pools. # socket_reaper.execute # # @since 2.5.0 def execute @cluster.servers.each do |server| server.pool_internal&.close_idle_sockets end true end # When the socket reaper is garbage-collected, there's no need to close # idle sockets; sockets will be closed anyway when the pools are # garbage collected. # # @since 2.5.0 def flush end end end end
class ToggleCallQualityIssueMutation < Types::BaseMutation description "Toggles whether a user reported call quality issues" argument :call_id, ID, required: true field :call, Outputs::CallType, null: true field :errors, resolver: Resolvers::Error policy ApplicationPolicy, :logged_in? policy CallPolicy, :manage? def resolve call = Call.find(input.call_id) authorize call if call.update(quality_issue: !call.quality_issue) {call: call, errors: []} else {call: nil, errors: call.errors} end end end
CLEAR = %x{clear} class Calculator def initialize print CLEAR @message = puts " This program is a calculator emulator. Your options for functions are: ADD - to add two numbers, SUBTRACT - to subtract the first number from the second, SUM - to add multiple numbers, MULTIPLY - to multiply any amount of numbers together, DIVIDE - to divide the first number by the second number, POWER - to multiply the first number by the power of the second number, FACTORIAL - all the numbers between that one and 1 multiplied" end def run Operations.new.do end END {print CLEAR} end class Input def main input = "nothing" inputs = ["add", "subtract", "sum", "multiply", "divide", "power", "factorial", "exit", "a", "s", "sub", "m", "d", "p", "f", "+", "++", "-", "*", "^", "/", " ", "!"] until inputs.include?(input) puts puts "Options are: add, subtract, sum, multiply, divide, power, factorial, exit" print "What function would you like to do? " input = gets.chomp.downcase if inputs.include?(input) == false puts "That is not a valid option! Please try again." end end input end def getx x = nil until x.is_a?(Fixnum) puts print "Please enter the first number: " x = gets.chomp if begin Float(x) x = x.to_f break rescue ArgumentError end else puts "That's not a number!" end end x end def gety y = nil until y.is_a?(Fixnum) puts print "Please enter the second number: " y = gets.chomp if begin Float(y) y = y.to_f break rescue ArgumentError end else puts "That's not a number!" end end y end def multin b = "nothing" numbers = [] puts puts "Enter as many numbers as you want to separately then enter 'done' when you are finished." while b != " " puts print "Please enter a number: " b = gets.chomp if b == " " || b == "done" b = " " break elsif begin Float(b) numbers.push Float(b) rescue ArgumentError end else puts "That's not a number!" end end numbers end def singin n = nil until n.is_a?(Fixnum) do puts print "Please enter a number: " n = Integer(gets) rescue nil end n end end class Operations def do function = {"add" => Add.new, "a" => Add.new, "+" => Add.new, "subtract" => Subtract.new, "sub" => Subtract.new, "-" => Subtract.new, "divide" => Divide.new, "d" => Divide.new, "/" => Divide.new, "power" => Power.new, "p" => Power.new, "^" => Power.new, "sum" => Sum.new, "s" => Sum.new, "++" => Sum.new, "multiply" => Multiply.new, "m" => Multiply.new, "*" => Multiply.new, "factorial" => Factorial.new, "f" => Factorial.new, "!" => Factorial.new} input = until input == " " || input == "exit" input = Input.new.main unless input == " " || input == "exit" op = function[input] op.do_op end end end def result(z) print CLEAR print "The answer is: " if z == Integer(z) z = z.to_i end puts z end end class Add < Operations def do_op x = Input.new.getx y = Input.new.gety z = x + y result(z) end end class Subtract < Operations def do_op x = Input.new.getx y = Input.new.gety z = x - y result(z) end end class Sum < Operations def do_op numbers = Input.new.multin n = 0 if numbers == [] 0 else numbers.each {|a| n += a} end result(n) end end class Multiply < Operations def do_op numbers = Input.new.multin n = 1 if numbers == [] n = 0 else numbers.each {|a| n *= a} end result(n) end end class Divide < Operations def do_op @x = Input.new.getx @y = Input.new.gety @z = @x.to_f / @y.to_f if @z.to_s == "Infinity" @z = "Undefined You cannot divide numbers by 0!" end if @y != 0 @d = @x.to_i / @y.to_i @r = @x.to_i % @y.to_i end result end def result print CLEAR print "The answer is: " if @z != @z.to_i if @x == @x.to_i && @y == @y.to_i if @r != nil puts @z.to_s + " -or- #{@d} with a remainder of #{@r}" else puts @z end else puts @z end else if @z == @z.to_i @z = @z.to_i end puts @z end end end class Power < Operations def do_op x = Input.new.getx y = Input.new.gety z = x ** y result(z) end end class Factorial < Operations def do_op n = Input.new.singin i = 1 i *= n while n > 1 n -= 1 i *= n end if i == 0 i = 1 end result(i) end end g = Calculator.new g.run
require 'spec_helper' describe BalloonsController do let(:balloon) { Balloon.create!(name: 'Ted') } subject { response } describe 'GET #index' do it 'does not break' do get :index expect(response).to be_success end end describe 'GET #new' do before do get :new end it 'instantiates a new Balloon object' do expect(assigns(:balloon).new_record?).to be_true expect(assigns(:balloon).class).to eq Balloon end it { should be_success } end describe 'POST #create' do context 'with valid attributes' do it 'successfully creates balloon' do expect { post :create, balloon: { name: 'Boberino' } }.to change(Balloon, :count).by(1) expect(response).to redirect_to balloons_path end end context 'with INvalid attributes' do it 'does not create a balloon and redirects' do expect { post :create, balloon: { name: nil } }.to_not change(Balloon, :count) expect(response).to render_template :new end end end describe 'GET #edit' do before do get :edit, id: balloon end it 'assigns the balloon variable' do expect(assigns(:balloon)).to eq balloon expect(response).to be_success end end end
Rails.application.routes.draw do get 'airports/show' get 'countries/index' get 'airlines/index' get 'claims/index' get 'claims/create' get 'claims/new' get 'claims/edit' get 'claims/show' get 'claims/update' get 'claims/destroy' get 'claims/letter/:id', to: 'claims#letter', as: 'claims_letter' get 'claims/letter/pdf/:id', to: 'claims#pdf', as: 'claims_pdf' get 'pages/home' get 'pages/about' get 'pages/contact' get 'pages/support' root 'pages#home' resources :claims, :airlines, :countries, :airports # API namespace :api, defaults: {format: :json} do namespace :v1 do get 'airports/search', to: 'airports#search', as: 'search' resources :airports, :airlines, :countries end end end
# encoding: UTF-8 require 'rubygems' begin require 'bundler/setup' rescue LoadError puts 'You must `gem install bundler` and `bundle install` to run rake tasks' end require 'rake' require 'rake/rdoctask' require 'rspec/core' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) Rake::RDocTask.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'Acts As EAV Model' rdoc.options << '--line-numbers' << '--inline-source' rdoc.rdoc_files.include('README.rdoc') rdoc.rdoc_files.include('lib/**/*.rb') end begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "acts_as_eav_model" gem.summary = %Q{Entity Attribute Value Implementation for inclusion in ActiveRecord models.} gem.description = %Q{Entity-attribute-value model (EAV) is a data model that is used in circumstances where the number of attributes (properties, parameters) that can be used to describe a thing (an "entity" or "object") is potentially very vast, but the number that will actually apply to a given entity is relatively modest.} gem.email = "" gem.homepage = "http://github.com/g5search/acts_as_eav_model" gem.has_rdoc=true gem.authors = ["Marcus Wyatt"] # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end task :default => :spec
class Thor module Actions # Injects the given content into a file. Different from append_file, # prepend_file and gsub_file, this method is reversible. By this reason, # the flag can only be strings. gsub_file is your friend if you need to # deal with more complex cases. # # ==== Parameters # destination<String>:: Relative path to the destination root # data<String>:: Data to add to the file. Can be given as a block. # flag<String>:: Flag of where to add the changes. # log_status<Boolean>:: If false, does not log the status. True by default. # If a symbol is given, uses it as the output color. # # ==== Examples # # inject_into_file "config/environment.rb", "config.gem thor", :after => "Rails::Initializer.run do |config|\n" # # inject_into_file "config/environment.rb", :after => "Rails::Initializer.run do |config|\n" do # gems = ask "Which gems would you like to add?" # gems.split(" ").map{ |gem| " config.gem #{gem}" }.join("\n") # end # def inject_into_file(destination, *args, &block) if block_given? data, flag = block, args.shift else data, flag = args.shift, args.shift end log_status = args.empty? || args.pop action InjectIntoFile.new(self, destination, data, flag, log_status) end class InjectIntoFile #:nodoc: attr_reader :base, :destination, :relative_destination, :flag, :replacement def initialize(base, destination, data, flag, log_status=true) @base, @log_status = base, log_status behavior, @flag = flag.keys.first, flag.values.first self.destination = destination data = data.call if data.is_a?(Proc) @replacement = if behavior == :after @flag + data else data + @flag end end def invoke! say_status :inject replace!(flag, replacement) end def revoke! say_status :deinject replace!(replacement, flag) end protected # Sets the destination value from a relative destination value. The # relative destination is kept to be used in output messages. # def destination=(destination) if destination @destination = ::File.expand_path(destination.to_s, base.destination_root) @relative_destination = base.relative_to_absolute_root(@destination) end end # Shortcut to say_status shell method. # def say_status(status) base.shell.say_status status, relative_destination, @log_status end # Adds the content to the file. # def replace!(regexp, string) unless base.options[:pretend] content = File.read(destination) content.gsub!(regexp, string) File.open(destination, 'wb') { |file| file.write(content) } end end end end end
module ChainReactor::Parsers # Parse the string using the xml simple library. class XmlSimpleParser < Parser require 'xmlsimple' # Parse an XML string, returning the result as a hash. # # Raises a ParseError on failure. def do_parse(string) begin @log.debug { "Parsing XML string #{string.inspect}" } XmlSimple.xml_in(string) rescue StandardError => e raise ParseError, "Data from client is not a valid XML string: #{string}, #{e.class.name} error: #{e.message}, data: #{string}" end end end end
class Event < ApplicationRecord belongs_to :user before_save do if event_is_free? self.price = 0 end end validates_presence_of :title, :status, :description validates :price, absence: {message: "must be empty if event is free please" }, if: :event_is_free? def event_is_free? status == "free" end end
class AddProductToOrderProduct < ActiveRecord::Migration[5.0] def change add_reference :order_products, :product, foreign_key: true end end
require 'optparse' require 'ostruct' require 'helpers' class Options < OpenStruct def initialize super defaults parse end private def defaults self.proto = 'http' self.host = 'localhost' self.port = 8080 self.user = 'admin' self.passwd = 'admin' self.output = '.' self.inituser = false self.upload = false self.webhdfs = 'http://localhost:50075' self.datanode = 'localhost:8020' self.force = false end def parse OptionParser.new do |opts| opts.banner = "Usage: #{File.basename($0)} -h <host> -p <port>" opts.on('-i', '--initialze', 'initialize the users?') do self.inituser = true end opts.on('-r', '--file-upload', 'upload the data files') do self.upload = true end opts.on('-f', '--force', 'force updating configuration') do self.force = true end opts.on('-h', '--host HOST', 'datameer hostname HOST') do |arg| self.host = arg end opts.on('-p', '--port PORT', 'datameer port PORT') do |arg| self.port = arg end opts.on('-u', '--user USER', 'datameer user USER') do |arg| self.user = arg end opts.on('-c', '--passwd PASSWORD', 'datameer password PASSWORD') do |arg| self.passwd = arg end opts.on('-s', '--proto PROTO', 'datameer protocol PROTO') do |arg| self.proto = arg end opts.on('-w', '--webhdfs URL', 'hadoop webhdfs URL') do |arg| self.webhdfs = arg end opts.on('-d', '--datanode URL', 'hadoop datanode URL') do |arg| self.datanode = arg end opts.on('-o', '--output DIRECTORY', 'configuration output DIRECTORY') do |arg| self.output = File.expand_path(arg) begin mkdir output rescue SystemCallError puts "#{arg} unable to create directory" puts opts exit -1 end end end.parse! end end
require 'rails_helper' RSpec.describe "comment_accounts/new", type: :view do before(:each) do assign(:comment_account, CommentAccount.new( :owner_id => 1 )) end it "renders new comment_account form" do render assert_select "form[action=?][method=?]", comment_accounts_path, "post" do assert_select "input[name=?]", "comment_account[owner_id]" end end end
class Critter attr_accessor :attack, :evade, :health, :damage, :name, :alive def fight(other_critter) my_attack = Dice.roll + self.attack their_evade = Dice.roll + other_critter.evade if my_attack >= their_evade current_damage = self.damage if current_damage < 1 current_damage = 1 end other_critter.temp_health -= current_damage puts "#{self.name} hits #{other_critter.name} for #{current_damage}" puts "#{other_critter.name} is #{other_critter.status} @ #{other_critter.temp_health}" else puts "#{self.name} missed #{other_critter.name}" end end def heal self.temp_health = self.health end def alive temp_health > 0 end def dead !alive end def status if self.alive "alive" else "dead" end end def temp_health if @temp_health.nil? @temp_health = self.health end @temp_health end def temp_health=(value) @temp_health = value end def reproduce offspring = Critter.new offspring.attack = up_or_down self.attack offspring.evade = up_or_down self.evade offspring.health = up_or_down self.health offspring.damage = up_or_down self.damage offspring.name = "#{self.name}_#{$total}" $total += 1 puts "#{self.name} sired #{offspring.name}" offspring end def up_or_down(original) adjust = (rand * 7).to_i - 3 original + adjust end end
Recaptcha.configure do |config| config.public_key = ENV["RECAPTCHA_PUBLIC"] config.private_key = ENV["RECAPTCHA_PRIVATE"] config.proxy = "http://brymck.herokuapp.com" end
# == Schema Information # # Table name: users # # id :integer not null, primary key # name :string(255) # email :string(255) # gender_id :string(255) # created_at :datetime # updated_at :datetime # modelling_agency :string(255) # phone_number :string(255) # country :string(255) # town :string(255) # class User < ActiveRecord::Base belongs_to :gender has_one :measurement has_many :photos validates_presence_of :name, :email, :gender, :modelling_agency, :phone_number, :country, :town validates_uniqueness_of :email end
module Helpstation module Processors # Helps to run processors in parallel # # All output from the processors are merged and then returned. This means # that if two fetchers return results with the same key then one will # overwrite the other. # # @example # process ParallelProcessor[ # OperatorFetcher, # VisitorFetcher # ], NOT_FOUND_ERROR # class ParallelProcessor < Processor def self.[](*processors) new(processors) end def initialize(processors) @processors = processors end def call(request) results = process_parallel(request) if first_failure = results.detect {|result| !result.success?} first_failure else request.success(results.reduce(request.input, &method(:compose))) end end private def process_parallel(request) @processors.map do |processor| Thread.new { processor.call(request) } end.map(&:join).map(&:value) end def compose(input, result) input.merge(result.output) end end # Helps to run one chain or another depending on a request # # @example # success_chain = substation.chain do # # success action # end # # fallback_chain = substation.chain do # # fallback action # end # # process ConditionalProcessor[ # -> (request) { request.input.has_key?(:optional_key) }, # success_chain, # fallback_chain # ] # class ConditionalProcessor < Processor def self.[](condition, success_chain, fallback_chain) Proc.new do |request| result = if condition.call(request) success_chain.call(request) else fallback_chain.call(request) end if result.is_a?(Substation::Response) result else request.success(result.input) end end end end end end
class AddAnnounceCallAgentsToAutomaticCallDistributors < ActiveRecord::Migration def change add_column :automatic_call_distributors, :announce_call_agents, :boolean end end
require 'test_helper' describe 'Stat' do describe 'relations' do it 'has_one season through season stat' do create :season_stat stat = Stat.first season = Season.first Stat.count.must_equal 1 Season.count.must_equal 1 stat.season.must_equal season end it 'has_one player through season stat' do create :season_stat stat = Stat.first player = Player.first Stat.count.must_equal 1 Player.count.must_equal 1 stat.player.must_equal player end end describe 'defaults' do it 'will return 0 for games if there are none' do stat = create :stat, games: nil stat.games.must_equal 0 end it 'will return 0 for at_bats if there are none' do stat = create :stat, at_bats: nil stat.at_bats.must_equal 0 end it 'will return 0 for runs_scored if there are none' do stat = create :stat, runs_scored: nil stat.runs_scored.must_equal 0 end it 'will return 0 for hits if there are none' do stat = create :stat, hits: nil stat.hits.must_equal 0 end it 'will return 0 for doubles if there are none' do stat = create :stat, doubles: nil stat.doubles.must_equal 0 end it 'will return 0 for triples if there are none' do stat = create :stat, triples: nil stat.triples.must_equal 0 end it 'will return 0 for home_runs if there are none' do stat = create :stat, home_runs: nil stat.home_runs.must_equal 0 end it 'will return 0 for runs_batted_in if there are none' do stat = create :stat, runs_batted_in: nil stat.runs_batted_in.must_equal 0 end it 'will return 0 for stolen_bases if there are none' do stat = create :stat, stolen_bases: nil stat.stolen_bases.must_equal 0 end it 'will return 0 for times_caught_steeling if there are none' do stat = create :stat, times_caught_steeling: nil stat.times_caught_steeling.must_equal 0 end end describe '#singles' do it 'will return the number of hits subtracted by the sum of doubles triples and home runs' do stat = create :stat, hits: 10, doubles: 1, triples: 1, home_runs: 1 stat.singles.must_equal 10 - 3 end end describe 'validations' do it 'will validate the presence of player_identifier' do stat = build :stat, player_identifier: nil stat.valid?.must_equal false stat.errors.size.must_equal 1 stat.errors.full_messages.must_equal ["Player identifier can't be blank"] end it 'will validate the presence of season_identifier' do stat = build :stat, season_identifier: nil stat.valid?.must_equal false stat.errors.size.must_equal 1 stat.errors.full_messages.must_equal ["Season identifier can't be blank"] end it 'will validate the presence of player_identifier' do stat = build :stat, team_identifier: nil stat.valid?.must_equal false stat.errors.size.must_equal 1 stat.errors.full_messages.must_equal ["Team identifier can't be blank"] end end end