text
stringlengths
10
2.61M
class ElementsController < ApplicationController before_filter :set_element, :only => [:create] before_filter :get_topic, :only => [:index,:create,:topic] def index @element_types = ElementType.find(:all).collect{|et| et unless @topic.element_types.include? et }.compact render :layout => false end def create if @topic.attach @element render :text => "Test" end end def destroy @element.destroy render :noting => true end private def get_topic @topic = Topic.find(params[:topic_id]) end def get_type @type = ElementType.find(params[:type_id]) end def set_element get_type @element = Element.set(@type, current_user, params) end end
require 'spec_helper' describe EssayDetail::Transcript do let(:issue) { double(Issue, id: 1, friendly_id: 'fid')} let(:essay) { double(Essay, embed: "embed", alt_body: double(MarkdownContent, content: "alt_body"), issue: issue) } subject { described_class.new(essay) } describe 'self_render' do it "instanciates itself and renders" do described_class.any_instance.should_receive(:render) described_class.render(essay) end end it "has an essay " do expect(subject.essay).to eq(essay) end it "returns the markdown" do expect(subject.markdown).to match "<p>alt_body</p>" end describe 'display_body?' do context 'has_a_body' do it "returns true if the markdown_detail says it is there and the format is text " do subject.stub(:essay_format).and_return(double(EssayFormat, media?: true)) subject.stub(:markdown_object).and_return(double(MarkdownDetail, present?: true)) expect(subject.send(:display_body?)).to be_truthy end it "returns false if there is a body and the format is not text" do subject.stub(:essay_format).and_return(double(EssayFormat, media?: true)) subject.stub(:markdown_object).and_return(double(MarkdownDetail, present?: false)) expect(subject.send(:display_body?)).to be_falsey end end context 'no_body' do it "returns false if there is no body and the format is text" do subject.stub(:essay_format).and_return(double(EssayFormat, media?: false)) subject.stub(:markdown_object).and_return(double(MarkdownDetail, present?: true)) expect(subject.send(:display_body?)).to be_falsey end it "retruns false if there is no body and the format is not text" do subject.stub(:essay_format).and_return(double(EssayFormat, media?: false)) subject.stub(:markdown_object).and_return(double(MarkdownDetail, present?: false)) expect(subject.send(:display_body?)).to be_falsey end end end describe 'render' do context 'display_body?' do before(:each) do subject.stub(:display_body?).and_return(true) end it "renders the template " do expect(subject).to receive(:render_to_string).with('/essays/transcript', { object: subject }) subject.render end it "renders with out error " do expect { subject.render }.to_not raise_error end end context 'no_embed' do before(:each) do subject.stub(:display_body?).and_return(false) end it "does not render the template" do expect(subject).to_not receive(:render_to_string) subject.render end end end end
require 'rails_helper' describe BankStatement do context 'with invalid attribute' do before :all do @bank_statement = BankStatement.new end it 'should not be valid' do @bank_statement.valid? @bank_statement.errors.full_messages.should match_array([ "Bank code is missing", "Iban is missing" ]) end it 'should not have any versions' do @bank_statement.versions.should == [] end end context 'with valid attributes' do before do @bank_statement = create(:bank_statement) end it 'should be valid' do @bank_statement.valid? @bank_statement.errors.full_messages.should match_array([]) end it 'should be valid twice' do @bank_statement = create(:bank_statement) @bank_statement.valid? @bank_statement.errors.full_messages.should match_array([]) end it 'should not bind transactions with invalid match data' do r = create(:registrar, reference_no: '1234') create(:account, registrar: r, account_type: 'cash', balance: 0) r.issue_prepayment_invoice(200, 'add some money') bs = create(:bank_statement, bank_transactions: [ create(:bank_transaction, { sum: 240.0, # with vat reference_no: 'RF7086666662', description: 'Invoice no. 1' }), create(:bank_transaction, { sum: 240.0, reference_no: '1234', description: 'Invoice no. 4948934' }) ]) bs.bank_transactions.count.should == 4 AccountActivity.count.should == 0 bs.bind_invoices AccountActivity.count.should == 0 r.cash_account.balance.should == 0.0 bs.bank_transactions.unbinded.count.should == 4 bs.not_binded?.should == true end it 'should have one version' do with_versioning do @bank_statement.versions.should == [] @bank_statement.bank_code = 'new_code' @bank_statement.save @bank_statement.errors.full_messages.should match_array([]) @bank_statement.versions.size.should == 1 end end end end
class Community::BaseController < ApplicationController layout 'community' #before_filter :parse_query, :filter_customer_cid before_filter :parse_query, :authenticate_openid!, :except => [ :select_instance, :echo ] before_filter :oauth_38, :only => [ :echo ] after_filter :track_logger helper_method :current_customer, :current_instance rescue_from ActiveRecord::RecordNotFound do |e| logger.info e.message logger.info e.backtrace no_permission end rescue_from NoMethodError do |e| logger.info e.message logger.info e.backtrace no_permission end protected def track_logger; logger.info "---- community base controller: instance s#{session[:instance_id_4]} c#{current_instance.try(:id)}, customer s#{session[:instance_id_4]} c#{current_customer.try(:id)} ----" end def parse_query instance = Instance.find_by(id: params[:instance_id]) if params[:instance_id] instance ||= Village.find_by(id: params[:village_id]).try(:instance) if params[:village_id] instance ||= VillageItem.find_by(id: params[:village_item_id]).try(:instance) if params[:village_item_id] instance ||= Customer.find_by(id: params[:customer_id]).try(:instance) if params[:customer_id] instance ||= Instance.find_by(id: params[:id]) if params[:controller] == 'community/instances' && params[:id].present? instance ||= Village.find_by(id: params[:id]).try(:instance) if params[:controller] == 'community/villages' && params[:id].present? instance ||= VillageItem.find_by(id: params[:id]).try(:instance) if params[:controller] == 'community/village_items' && params[:id].present? instance ||= Customer.find_by(id: params[:id]).try(:instance) if params[:controller] == 'community/customers' && params[:id].present? return set_current_instance(instance) if instance.present? instance ||= Instance.find_by id: session[:instance_id_4] if session[:instance_id_4] if instance.present? logger.info("---- recover instance id from session: #{instance.id}----") return set_current_instance(instance) end logger.info("---- community parse error: no instance id available ----") redirect_to '/select_instance' #/community/customers/xxx/favor will get trouble if xxx is not exists! #no_permission if params[:controller] != 'community/tags' end def oauth_38 ii=Instance.find 38 appid = ii.app_id appsc = ii.app_secret oidkey = "wx_38_oid" if session[oidkey].blank? code = params[:code] # 如果code参数为空,则为认证第一步,重定向到微信认证 if code.nil? logger.info("---- oauth38 step 1 redirect ----") redirect_to "https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{appid}&redirect_uri=#{request.url}&response_type=code&scope=snsapi_base&state=#{request.url}#wechat_redirect" end #如果code参数不为空,则认证到第二步,通过code获取openid,并保存到session中 begin url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=#{appid}&secret=#{appsc}&code=#{code}&grant_type=authorization_code" session[oidkey] = JSON.parse(URI.parse(url).read)["openid"] logger.info("---- oauth38 step 2, session[#{oidkey}] #{session[oidkey]} ----") rescue Exception => e logger.info("---- oauth38 step 2 exception: #{e.to_s} using old method ----") end end end def authenticate_openid! # 判断是否使用oauth we_agent = request.user_agent.include?('MicroMessenger') || request.user_agent.include?('Windows Phone') return filter_customer_cid if !current_instance.present? || !we_agent || !current_instance.wechat_auth? logger.info("---- oauth start: instance #{current_instance} ----") # 当session中没有对应instance的openid时,则为非登录状态 iid = current_instance.id appid = current_instance.app_id appsc = current_instance.app_secret oidkey = "wx_#{iid}_oid" if session[oidkey].blank? code = params[:code] # 如果code参数为空,则为认证第一步,重定向到微信认证 if code.nil? logger.info("---- oauth step 1 redirect ----") redirect_to "https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{appid}&redirect_uri=#{request.url}&response_type=code&scope=snsapi_base&state=#{request.url}#wechat_redirect" end #如果code参数不为空,则认证到第二步,通过code获取openid,并保存到session中 begin url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=#{appid}&secret=#{appsc}&code=#{code}&grant_type=authorization_code" session[oidkey] = JSON.parse(URI.parse(url).read)["openid"] logger.info("---- oauth step 2, session[#{oidkey}] #{session[oidkey]} ----") rescue Exception => e logger.info("---- oauth step 2 exception: #{e.to_s} using old method ----") return filter_customer_cid end end customer = Customer.find_by openid: session[oidkey] if !customer.present? customer = current_instance.customers.create(subscribed: false, openid: session[oidkey]) logger.info("---- create new customer: #{customer} ----") end set_current_customer(customer) end def filter_customer_cid if params[:customer_cid].present? customer = Customer.find_by cid: params[:customer_cid] if customer.present?; set_current_customer customer else logger.info "---- filter customer failed #{params[:customer_cid]} ----" end redirect_to request.url.gsub(/customer_cid=\w{32}/, '') end end def current_customer return @current_customer if @current_customer customer = @current_instance.customers.find_by(id: session[:customer_id_4]) if session[:customer_id_4] && @current_instance if customer.present?; return set_current_customer(customer) else logger.info "---- restore customer failed 1 #{session[:customer_id_4]} ----" end customer = @current_instance.customers.create(subscribed: false) if @current_instance if customer.present?; return set_current_customer(customer) else logger.info "---- restore customer failed 2 #{current_instance} ----" end logger.info "---- current_customer is nil #{@current_instance.try(:id)} ----" #ss line resturn true @current_customer = nil end def set_current_customer(customer) session[:customer_id_4] = customer.id old_ip = customer.current_visit_ip customer.update_attributes(current_visit_ip: request.remote_ip, last_visit_ip: old_ip) @current_customer = customer end def current_instance return @current_instance if @current_instance instance = Instance.find_by id: session[:instance_id_4] if session[:instance_id_4] if instance.present?; return set_current_instance(instance) else logger.info "---- restore instance failed 1 #{session[:instance_id_4]} ----" end customer = Customer.find_by(id: session[:customer_id_4]) if session[:customer_id_4] instance = customer.instance if customer.present? if instance.present?; return set_current_instance(instance) else logger.info "---- restore instance failed 2 ----" end logger.info "---- current_instance is nil ----" @current_instance = nil end def set_current_instance(instance) session[:instance_id_4] = instance.id @current_instance = instance end def no_permission render "errors/westore_404" end end
module Bosh::Director::Links class LinksParser include Bosh::Director::ValidationHelper MANUAL_LINK_KEYS = %w[instances properties address].freeze class LinkProvidersParser include Bosh::Director::ValidationHelper def initialize @logger = Bosh::Director::Config.logger @link_helper = LinkHelpers.new end def parse_migrated_from_providers_from_job( manifest_job_spec, deployment_model, current_template_model, manifest_details = {} ) job_properties = manifest_details.fetch(:job_properties, {}) instance_group_name = manifest_details.fetch(:instance_group_name, nil) migrated_from = manifest_details.fetch(:migrated_from, []) migrated_from.each do |migration_block| job_name = safe_property(manifest_job_spec, 'name', class: String) providers = Bosh::Director::Models::Links::LinkProvider.find( deployment: deployment_model, instance_group: migration_block['name'], name: job_name, type: 'job', ) instance_group_name = migration_block['name'] unless providers.nil? end parse_providers_from_job( manifest_job_spec, deployment_model, current_template_model, job_properties: job_properties, instance_group_name: instance_group_name, ) end def parse_providers_from_job(manifest_job_spec, deployment_model, current_release_template_model, manifest_details = {}) job_properties = manifest_details.fetch(:job_properties, {}) instance_group_name = manifest_details.fetch(:instance_group_name, nil) @links_manager = Bosh::Director::Links::LinksManager.new(deployment_model.links_serial_id) manifest_provides_links = Bosh::Common::DeepCopy.copy(safe_property(manifest_job_spec, 'provides', class: Hash, optional: true, default: {})) custom_manifest_providers = Bosh::Common::DeepCopy.copy(safe_property(manifest_job_spec, 'custom_provider_definitions', class: Array, optional: true, default: [])) job_name = safe_property(manifest_job_spec, 'name', class: String) @link_helper.validate_custom_providers(custom_manifest_providers, current_release_template_model.provides, job_name, instance_group_name, current_release_template_model.release.name) errors = [] errors.concat( process_custom_providers( current_release_template_model, custom_manifest_providers, manifest_provides_links, deployment_model, job_properties: job_properties, instance_group_name: instance_group_name, ), process_release_providers( current_release_template_model, manifest_provides_links, deployment_model, instance_group_name, job_properties, ), ) unless manifest_provides_links.empty? warning = 'Manifest defines unknown providers:' manifest_provides_links.each_key do |link_name| warning << "\n - Job '#{job_name}' does not define link provider '#{link_name}' in the release spec" end @logger.warn(warning) end raise errors.join("\n") unless errors.empty? end def parse_provider_from_disk(disk_spec, deployment_model, instance_group_name) @links_manager = Bosh::Director::Links::LinksManager.new(deployment_model.links_serial_id) disk_name = disk_spec['name'] # All the parsing we need provider = @links_manager.find_or_create_provider( deployment_model: deployment_model, instance_group_name: instance_group_name, name: instance_group_name, type: 'disk', ) create_disk_provider_intent(deployment_model, disk_name, provider) end private def create_disk_provider_intent(deployment_model, disk_name, provider) provider_intent = @links_manager.find_or_create_provider_intent( link_provider: provider, link_original_name: disk_name, link_type: 'disk', ) provider_intent.shared = false provider_intent.name = disk_name provider_intent.content = Bosh::Director::DeploymentPlan::DiskLink.new(deployment_model.name, disk_name).spec.to_json provider_intent.save end def process_providers(release_properties, provider_definitions, manifest_provides_links, deployment_model, job_details = {}) job_properties = job_details.fetch(:job_properties, {}) instance_group_name = job_details.fetch(:instance_group_name, nil) job_name = job_details.fetch(:job_name, nil) are_custom_definitions = job_details.fetch(:are_custom_definitions, false) provider = @links_manager.find_or_create_provider( deployment_model: deployment_model, instance_group_name: instance_group_name, name: job_name, type: 'job', ) errors = process_provider_definitions( manifest_provides_links, provider, provider_definitions, release_properties, are_custom_definitions: are_custom_definitions, instance_group_name: instance_group_name, job_name: job_name, job_properties: job_properties, ) errors end def process_provider_definitions( manifest_provides_links, provider, provider_definitions, release_properties, manifest_details = {} ) are_custom_definitions, instance_group_name, job_name, job_properties = @link_helper.extract_provider_definition_properties(manifest_details) errors = [] provider_definitions.each do |provider_definition| provider_intent_params = { 'original_name' => provider_definition['name'], 'type' => provider_definition['type'], 'alias' => provider_definition['name'], 'shared' => false, 'consumable' => true, } if manifest_provides_links.key?(provider_definition['name']) manifest_source = manifest_provides_links.delete(provider_definition['name']) validation_errors = @link_helper.validate_provide_link( manifest_source, provider_definition['name'], job_name, instance_group_name ) errors.concat(validation_errors) next unless validation_errors.empty? provider_intent_params = @link_helper.generate_provider_intent_params(manifest_source, provider_intent_params) end mapped_properties, properties_errors = @link_helper.process_link_properties( job_properties, provider_definition['properties'], release_properties, job_name ) errors.concat(properties_errors) next unless properties_errors.empty? create_provider_intent(are_custom_definitions, mapped_properties, provider, provider_intent_params) end errors end def create_provider_intent(are_custom_definitions, mapped_properties, provider, provider_intent_params) provider_intent = @links_manager.find_or_create_provider_intent( link_provider: provider, link_original_name: provider_intent_params['original_name'], link_type: provider_intent_params['type'], ) provider_intent.name = provider_intent_params['alias'] provider_intent.shared = provider_intent_params['shared'] is_custom = are_custom_definitions || false provider_intent.metadata = { mapped_properties: mapped_properties, custom: is_custom, dns_aliases: provider_intent_params['dns_aliases'], }.to_json provider_intent.consumable = provider_intent_params['consumable'] provider_intent.save end def process_custom_providers( current_release_template_model, custom_manifest_providers, manifest_provides_links, deployment_model, manifest_details = {} ) job_properties = manifest_details.fetch(:job_properties, {}) instance_group_name = manifest_details.fetch(:instance_group_name, nil) return [] if custom_manifest_providers.empty? process_providers( current_release_template_model.properties, custom_manifest_providers, manifest_provides_links, deployment_model, job_properties: job_properties, instance_group_name: instance_group_name, job_name: current_release_template_model.name, are_custom_definitions: true, ) end def process_release_providers( current_release_template_model, manifest_provides_links, deployment_model, instance_group_name, job_properties ) job_name = current_release_template_model.name return [] if current_release_template_model.provides.empty? process_providers( current_release_template_model.properties, current_release_template_model.provides, manifest_provides_links, deployment_model, job_properties: job_properties, instance_group_name: instance_group_name, job_name: job_name, are_custom_definitions: false, ) end end class LinkConsumersParser include Bosh::Director::ValidationHelper def initialize @logger = Bosh::Director::Config.logger @link_helper = LinkHelpers.new end def parse_migrated_from_consumers_from_job( manifest_job_spec, deployment_model, current_release_template_model, instance_group_details = {} ) instance_group_name = instance_group_details.fetch(:instance_group_name, nil) migrated_from = instance_group_details.fetch(:migrated_from, []) migrated_from.each do |migration_block| old_instance_group_name = migration_block['name'] job_name = safe_property(manifest_job_spec, 'name', class: String) consumers = Bosh::Director::Models::Links::LinkConsumer.find( deployment: deployment_model, instance_group: old_instance_group_name, name: job_name, type: 'job', ) instance_group_name = migration_block['name'] unless consumers.nil? end parse_consumers_from_job( manifest_job_spec, deployment_model, current_release_template_model, instance_group_name: instance_group_name, ) end def parse_consumers_from_job( manifest_job_spec, deployment_model, current_release_template_model, instance_group_details = {} ) instance_group_name = instance_group_details.fetch(:instance_group_name, nil) @links_manager = Bosh::Director::Links::LinksManager.new(deployment_model.links_serial_id) consumes_links = Bosh::Common::DeepCopy.copy(safe_property(manifest_job_spec, 'consumes', class: Hash, optional: true, default: {})) job_name = safe_property(manifest_job_spec, 'name', class: String) errors = [] unless current_release_template_model.consumes.empty? errors.concat( process_release_template_consumes( consumes_links, current_release_template_model, deployment_model, instance_group_name, job_name, ), ) end unless consumes_links.empty? warning = 'Manifest defines unknown consumers:' consumes_links.each_key do |link_name| warning << "\n - Job '#{job_name}' does not define link consumer '#{link_name}' in the release spec" end @logger.warn(warning) end raise errors.join("\n") unless errors.empty? end private def process_release_template_consumes( consumes_links, current_release_template_model, deployment_model, instance_group_name, job_name ) consumer = @links_manager.find_or_create_consumer( deployment_model: deployment_model, instance_group_name: instance_group_name, name: job_name, type: 'job', ) errors = create_consumer_intent_from_template_model( consumer, consumes_links, current_release_template_model, instance_group_name, job_name ) errors end def create_consumer_intent_from_template_model( consumer, consumes_links, current_release_template_model, instance_group_name, job_name ) errors = [] current_release_template_model.consumes.each do |consumes| metadata = {} consumer_intent_params = { 'original_name' => consumes['name'], 'alias' => consumes['name'], 'blocked' => false, 'type' => consumes['type'], } if !consumes_links.key?(consumes['name']) metadata['explicit_link'] = false else consumer_intent_params, metadata, err = generate_explicit_link_metadata( consumer, consumer_intent_params, consumes_links, metadata, consumed_link_original_name: consumes['name'], job_name: job_name, instance_group_name: instance_group_name, ) unless err.empty? errors.concat(err) next end end create_consumer_intent(consumer, consumer_intent_params, consumes, metadata) end errors end def generate_explicit_link_metadata( consumer, consumer_intent_params, consumes_links, metadata, names = {} ) consumed_link_original_name = names.fetch(:consumed_link_original_name, nil) job_name = names.fetch(:job_name, nil) instance_group_name = names.fetch(:instance_group_name, nil) errors = [] manifest_source = consumes_links.delete(consumed_link_original_name) new_errors = @link_helper.validate_consume_link( manifest_source, consumed_link_original_name, job_name, instance_group_name ) errors.concat(new_errors) return consumer_intent_params, metadata, errors unless new_errors.empty? metadata['explicit_link'] = true if manifest_source.eql? 'nil' consumer_intent_params['blocked'] = true elsif @link_helper.manual_link? manifest_source metadata['manual_link'] = true process_manual_link(consumer, consumer_intent_params, manifest_source) else consumer_intent_params['alias'] = manifest_source.fetch('from', consumer_intent_params['alias']) metadata['ip_addresses'] = manifest_source['ip_addresses'] if manifest_source.key?('ip_addresses') metadata['network'] = manifest_source['network'] if manifest_source.key?('network') validate_consumes_deployment( consumer_intent_params, errors, manifest_source, metadata, instance_group_name: instance_group_name, job_name: job_name, ) end [consumer_intent_params, metadata, errors] end def validate_consumes_deployment(consumer_intent_params, errors, manifest_source, metadata, instance_group_details = {}) return unless manifest_source['deployment'] instance_group_name = instance_group_details.fetch(:instance_group_name, nil) job_name = instance_group_details.fetch(:job_name, nil) from_deployment = Bosh::Director::Models::Deployment.find(name: manifest_source['deployment']) metadata['from_deployment'] = manifest_source['deployment'] from_deployment_error_message = "Link '#{consumer_intent_params['alias']}' in job '#{job_name}' from instance group"\ " '#{instance_group_name}' consumes from deployment '#{manifest_source['deployment']}',"\ ' but the deployment does not exist.' errors.push(from_deployment_error_message) unless from_deployment end def create_consumer_intent(consumer, consumer_intent_params, consumes, metadata) consumer_intent = @links_manager.find_or_create_consumer_intent( link_consumer: consumer, link_original_name: consumer_intent_params['original_name'], link_type: consumer_intent_params['type'], new_intent_metadata: metadata, ) consumer_intent.name = consumer_intent_params['alias'].split('.')[-1] consumer_intent.blocked = consumer_intent_params['blocked'] consumer_intent.optional = consumes['optional'] || false consumer_intent.save end def process_manual_link(consumer, consumer_intent_params, manifest_source) manual_provider = @links_manager.find_or_create_provider( deployment_model: consumer.deployment, instance_group_name: consumer.instance_group, name: consumer.name, type: 'manual', ) manual_provider_intent = @links_manager.find_or_create_provider_intent( link_provider: manual_provider, link_original_name: consumer_intent_params['original_name'], link_type: consumer_intent_params['type'], ) content = {} MANUAL_LINK_KEYS.each do |key| content[key] = manifest_source[key] end content['deployment_name'] = consumer.deployment.name manual_provider_intent.name = consumer_intent_params['original_name'] manual_provider_intent.content = content.to_json manual_provider_intent.save end end class LinkHelpers def process_link_properties(job_properties, link_property_list, release_properties, job_name) errors = [] link_property_list ||= [] mapped_properties = {} default_properties = { 'properties' => release_properties, 'template_name' => job_name, } link_property_list.each do |link_property| property_path = link_property.split('.') result = find_property(property_path, job_properties) if !result['found'] if (property = default_properties['properties'][link_property]) mapped_properties = update_mapped_properties(mapped_properties, property_path, property['default']) else errors.push("Link property #{link_property} in template #{default_properties['template_name']}"\ ' is not defined in release spec') end else mapped_properties = update_mapped_properties(mapped_properties, property_path, result['value']) end end [mapped_properties, errors] end def validate_custom_providers( manifest_defined_providers, release_defined_providers, job_name, instance_group_name, release_name ) errors = [] providers_grouped_by_name = manifest_defined_providers.group_by do |provider| provider['name'] end duplicate_manifest_provider_names = providers_grouped_by_name.select do |_, val| val.size > 1 end manifest_defined_providers.each do |custom_provider| errors.concat(validate_custom_provider_definition(custom_provider, job_name, instance_group_name)) if release_defined_providers.detect { |provider| provider['name'] == custom_provider['name'] } errors.push("Custom provider '#{custom_provider['name']}' in job '#{job_name}' in instance group"\ " '#{instance_group_name}' is already defined in release '#{release_name}'") end end duplicate_manifest_provider_names.each_key do |duplicate_name| errors.push("Custom provider '#{duplicate_name}' in job '#{job_name}' in instance group"\ " '#{instance_group_name}' is defined multiple times in manifest.") end raise errors.join("\n") unless errors.empty? end def validate_custom_provider_definition(provider, job_name, instance_group_name) errors = [] if !provider['name'].is_a?(String) || provider['name'].empty? errors.push("Name for custom link provider definition in manifest in job '#{job_name}' in instance group"\ " '#{instance_group_name}' must be a valid non-empty string.") end if !provider['type'].is_a?(String) || provider['type'].empty? errors.push("Type for custom link provider definition in manifest in job '#{job_name}' in instance group"\ " '#{instance_group_name}' must be a valid non-empty string.") end errors end def generate_provider_intent_params(manifest_source, provider_intent_params) if manifest_source.eql? 'nil' provider_intent_params['consumable'] = false else provider_intent_params['alias'] = manifest_source['as'] if manifest_source.key?('as') provider_intent_params['shared'] = double_negate_value(manifest_source['shared']) provider_intent_params['dns_aliases'] = manifest_source['aliases'] if manifest_source.key?('aliases') end provider_intent_params end def validate_provide_link(source, link_name, job_name, instance_group_name) return [] if source.eql? 'nil' unless source.is_a?(Hash) return ["Provider '#{link_name}' in job '#{job_name}' in instance group '#{instance_group_name}'"\ " specified in the manifest should only be a hash or string 'nil'"] end errors = [] if source.key?('name') || source.key?('type') errors.push("Cannot specify 'name' or 'type' properties in the manifest for link '#{link_name}'"\ " in job '#{job_name}' in instance group '#{instance_group_name}'."\ ' Please provide these keys in the release only.') end errors end def manual_link?(consume_link_source) MANUAL_LINK_KEYS.any? do |key| consume_link_source.key? key end end def find_property(property_path, job_properties) current_node = job_properties property_path.each do |key| return { 'found' => false, 'value' => nil } if !current_node || !current_node.key?(key) current_node = current_node[key] end { 'found' => true, 'value' => current_node } end def update_mapped_properties(mapped_properties, property_path, value) current_node = mapped_properties property_path.each_with_index do |key, index| if index == property_path.size - 1 current_node[key] = value else current_node[key] = {} unless current_node.key?(key) current_node = current_node[key] end end mapped_properties end def extract_provider_definition_properties(manifest_details) are_custom_definitions = manifest_details.fetch(:are_custom_definitions, nil) instance_group_name = manifest_details.fetch(:instance_group_name, nil) job_name = manifest_details.fetch(:job_name, nil) job_properties = manifest_details.fetch(:job_properties, {}) [are_custom_definitions, instance_group_name, job_name, job_properties] end def validate_consume_link(manifest_source, link_name, job_name, instance_group_name) return [] if manifest_source.eql? 'nil' unless manifest_source.is_a?(Hash) return ["Consumer '#{link_name}' in job '#{job_name}' in instance group '#{instance_group_name}'"\ " specified in the manifest should only be a hash or string 'nil'"] end errors = [] blacklist = [%w[instances from], %w[properties from]] blacklist.each do |invalid_props| if invalid_props.all? { |prop| manifest_source.key?(prop) } errors.push("Cannot specify both '#{invalid_props[0]}' and '#{invalid_props[1]}' keys for link"\ " '#{link_name}' in job '#{job_name}' in instance group '#{instance_group_name}'.") end end verify_consume_manifest_source_properties_instances(manifest_source, errors, link_name, job_name, instance_group_name) verify_consume_manifest_source_ip_addresses(manifest_source, errors, link_name, job_name, instance_group_name) verify_consume_manifest_source_name_type(manifest_source, errors, link_name, job_name, instance_group_name) errors end def verify_consume_manifest_source_properties_instances(source, errors, link_name, job_name, instance_group_name) error_message = "Cannot specify 'properties' without 'instances' for link '#{link_name}' in job '#{job_name}'"\ " in instance group '#{instance_group_name}'." errors.push(error_message) if source.key?('properties') && !source.key?('instances') end def verify_consume_manifest_source_ip_addresses(source, errors, link_name, job_name, instance_group_name) # The first expression makes it TRUE or FALSE then if the second expression is neither TRUE or FALSE it will return FALSE ip_addresses_error_message = "Cannot specify non boolean values for 'ip_addresses' field for link '#{link_name}'"\ " in job '#{job_name}' in instance group '#{instance_group_name}'." valid_property = (double_negate_value(source['ip_addresses']) != source['ip_addresses']) not_true_false = source.key?('ip_addresses') && valid_property errors.push(ip_addresses_error_message) if not_true_false end def verify_consume_manifest_source_name_type(source, errors, link_name, job_name, instance_group_name) name_type_error_message = "Cannot specify 'name' or 'type' properties in the manifest for link '#{link_name}'"\ " in job '#{job_name}' in instance group '#{instance_group_name}'."\ ' Please provide these keys in the release only.' errors.push(name_type_error_message) if source.key?('name') || source.key?('type') end def double_negate_value(value) (value && [true, false].include?(value)) || false end end def initialize @link_providers_parser = LinkProvidersParser.new @link_consumers_parser = LinkConsumersParser.new end def parse_migrated_from_providers_from_job( manifest_job_spec, deployment_model, current_template_model, manifest_details = {} ) @link_providers_parser.parse_migrated_from_providers_from_job( manifest_job_spec, deployment_model, current_template_model, manifest_details ) end def parse_providers_from_job(manifest_job_spec, deployment_model, current_release_template_model, manifest_details = {}) @link_providers_parser.parse_providers_from_job( manifest_job_spec, deployment_model, current_release_template_model, manifest_details ) end def parse_provider_from_disk(disk_spec, deployment_model, instance_group_name) @link_providers_parser.parse_provider_from_disk( disk_spec, deployment_model, instance_group_name ) end def parse_migrated_from_consumers_from_job( manifest_job_spec, deployment_model, current_release_template_model, instance_group_details = {} ) @link_consumers_parser.parse_migrated_from_consumers_from_job( manifest_job_spec, deployment_model, current_release_template_model, instance_group_details ) end def parse_consumers_from_job(manifest_job_spec, deployment_model, current_release_template_model, instance_group_details = {}) @link_consumers_parser.parse_consumers_from_job( manifest_job_spec, deployment_model, current_release_template_model, instance_group_details ) end def parse_consumers_from_variable(variable_spec, deployment_model) return unless variable_spec.key? 'consumes' @links_manager = Bosh::Director::Links::LinksManager.new(deployment_model.links_serial_id) variable_name = variable_spec['name'] variable_type = variable_spec['type'] errors = [] variable_spec['consumes'].each do |key, value| original_name = key local_error = validate_variable(variable_name, variable_type, original_name) unless local_error.nil? errors << local_error next end from_name = value['from'] || original_name consumer = @links_manager.find_or_create_consumer( deployment_model: deployment_model, instance_group_name: '', name: variable_name, type: 'variable', ) metadata = { 'explicit_link' => true } wildcard_needed = !value['properties'].nil? && value['properties']['wildcard'] == true metadata = metadata.merge('wildcard' => wildcard_needed) consumer_intent = @links_manager.find_or_create_consumer_intent( link_consumer: consumer, link_original_name: original_name, link_type: value['link_type'] || 'address', new_intent_metadata: metadata, ) consumer_intent.name = from_name consumer_intent.save end raise errors.join("\n") unless errors.empty? end private def validate_variable(variable_name, variable_type, original_name) acceptable_combinations = { 'certificate' => %w[alternative_name common_name] } unless acceptable_combinations.key?(variable_type) return "Variable '#{variable_name}' can not define 'consumes' key for type '#{variable_type}'" end unless acceptable_combinations[variable_type].include?(original_name) acceptable_combination_string = acceptable_combinations[variable_type].join(', ') return "Consumer name '#{original_name}' is not a valid consumer for variable '#{variable_name}'."\ " Acceptable consumer types are: #{acceptable_combination_string}" end nil end end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2018-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 module Operation # Shared behavior of applying transaction error label to execution result. # # @note This module should be included after ExecutableNoValidate, # if both are included in a class. # # @api private module ExecutableTransactionLabel end end end
class TranslateForm include ActiveModel::Model FIELDS = %i[column_name locale column_value].freeze attr_accessor :record, *FIELDS def initialize(attributes) super self.locale ||= I18n.locale self.column_value ||= record.send("#{column_name}_backend").read(locale) end def save record.send("#{column_name}_backend").write(locale, column_value) record.save! true end def new_record? false end end
class UserMailer < ApplicationMailer # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.user_mailer.signup.subject # def signup(user) @user = user @greeting = "Thanks for signing up! Your email address is #{@user.email}." mail( to: @user.email, from: 'amy@momentumlearn.com', subject: 'Welcome to this app!' ) end end
class ExpensesController < ApplicationController def expenses @category = 'gerais' @expenses = Expense.where(category: @category) @report = true @title = 'Despesas' render :index end def advances @category = 'vale funcionario' @expenses = Expense.where(category: @category) @report = true @title = 'Vales' render :index end def devolutions @category = 'devolucao' @expenses = Expense.where(category: @category) @report = true @title = 'Devoluções' render :index end def index @expenses = Expense.all @expenses = @expenses.order :id @title = 'Minhas Despesas' @report = true end def new @expense = Expense.new @category = 'gerais' end def advance @expense = Expense.new @category = 'vale funcionario' end def devolution @expense = Expense.new @category = 'devolucao' end def create values = params.require(:expense).permit! @expense = Expense.create values @expense.update(user_id: current_user.id) if @expense.save redirect_to expenses_expenses_day_path, notice: 'Despesa Salva com Sucesso!' end end def edit @expense = Expense.find(params[:id]) @category = @expense.category end def update values = params.require(:expense).permit! @expense = Expense.find(params[:id]) @expense.update values redirect_to expenses_expenses_day_path, notice: 'Despesa Alterada com Sucesso!' end def filter_date @category = params[:category] @report = true if @category != "" @expenses = Expense.where(category: @category) else @expenses = Expense.all end @begin_date = params[:begin_date] @end_date = params[:end_date] @filter = [] if @begin_date > @end_date render :index else @expenses.each do |expense| if expense.created_at.strftime("%Y-%m-%d") == @begin_date @filter << expense elsif expense.created_at.strftime("%Y-%m-%d") > @begin_date && expense.created_at.strftime("%Y-%m-%d") < @end_date @filter << expense elsif expense.created_at.strftime("%Y-%m-%d") == @end_date @filter << expense end end @expenses = @filter end end def expenses_day @title = 'Despesas do Dia' @expenses = Expense.all @expenses = filter_day(@expenses) end def show @expense = Expense.find(params[:id]) end def destroy id = params[:id] Expense.destroy id redirect_to expenses_path, notice: 'Despesa Excluída com Sucesso' end end
require './canhelplib' require 'csv' module CanhelpPlugin include Canhelp def self.get_teacher_count( canvas_url=prompt(:canvas_url), account_id=prompt(:account_id), teacher_role_id = prompt(:teacher_role_id) ) token = get_token subaccount_ids = get_json_paginated(token, "#{canvas_url}/api/v1/accounts/#{account_id}/sub_accounts", "recursive=true").map{|s| s['id']} subaccount_ids << account_id puts "\t" puts "Grabbing enrollments from courses in the following accounts:" subaccount_ids.each do |subaccount| puts "- #{subaccount}" end all_teacher_enrollments = [] subaccount_ids.each do |subaccount_id| courses = get_json_paginated( token, "#{canvas_url}/api/v1/accounts/#{subaccount_id}/courses", "include[]=teachers&include[]=total_students&state[]=available&state[]=claimed&state[]=created&state[]=completed" ) courses.each do |course| course_ids = course['id'] enrollments = get_json_paginated( token, "#{canvas_url}/api/v1/courses/#{course_ids}/enrollments", "state[]=active&state[]=completed&role[]=TeacherEnrollment" ) course_name = course['name'] course_state = course['workflow_state'] total_students = course['total_students'] puts puts "Course Name: #{course_name}" puts "- State: #{course_state}" puts "- Total number of students: #{total_students}" enrollments.each do |enrollment| if enrollment['role_id'].to_s == "#{teacher_role_id}" all_teacher_enrollments << enrollment teacher_name = enrollment['user']['name'] puts "- Teacher's Name: #{teacher_name}" end end end end teacher_ids = all_teacher_enrollments.map { |enrollment| enrollment['user_id'] }.uniq all_teacher_info = teacher_ids.map do |id| teacher_enrollment = all_teacher_enrollments.find { |enrollment| enrollment['user_id'] == id } next if teacher_enrollment.nil? [teacher_enrollment['user']['name'],teacher_enrollment['user_id'],teacher_enrollment['created_at'], teacher_enrollment['updated_at']] end.sort_by { |info_row| info_row[0].downcase } total_teacher_count = teacher_ids.count puts puts "Total number of TeacherEnrollments: #{total_teacher_count}" puts puts "All Teachers' Names: " CSV.open("../csv_help/csv/write_here.csv", "wb") do |csv| all_teacher_info.each do |info_row| csv << info_row #puts "- #{name}" end end puts "CSV done" end end
if node.has_key?(:website) website = node[:website] directory website[:log_dir] do owner "root" group "root" mode "0755" action :create not_if "test #{website[:log_dir]}" end web_app website[:server_name] do template "site.conf.erb" server_name website[:server_name] server_aliases website[:aliases] docroot website[:docroot] application_env website[:application_env] log_level website[:log_level] rewrite_log_level website[:rewrite_log_level] log_dir website[:log_dir] end apache_site "default" do enable false end template "#{website[:docroot]}/robots.txt" do owner "root" group "root" source "robots.txt.erb" mode "0644" end end
# ============================================================================== # test - active record test # ============================================================================== require 'test_helper' require 'active_record' db = :sqlite3 silence_warnings do ActiveRecord::Migration.verbose = false ActiveRecord::Base.logger = Logger.new(nil) ActiveRecord::Base.configurations = { 'sqlite3' => { 'adapter' => 'sqlite3', 'database' => ':memory:' }, } ActiveRecord::Base.establish_connection(db) end ActiveRecord::Base.connection.instance_eval do create_table :users do |t| t.string :name t.string :encrypted_email t.text :encrypted_phrase end end class User < ActiveRecord::Base extend EncryptedGate encrypted_column :email, salt_column: :name encrypted_column :phrase, salt_column: :name end describe EncryptedGate do shared_examples_for 'An Adapter' do it "uses #{@cipher_mode}" do assert_equal Settings.encryptor.cipher, @cipher_mode end it 'stores values as cipher and decrypt it' do @name = 'John Doe' @email = 'email@example.com' @phrase = 'Hello, World!' user = User.new(name: @name, email: @email, phrase: @phrase) user.save! user = User.find(user.id) assert_equal user.email, @email assert_equal user.phrase, @phrase refute_equal user.encrypted_email, nil refute_equal user.encrypted_phrase, nil end it 'return nil if nothins is set to the attribute' do user = User.new() assert_nil user.email assert_nil user.phrase end end describe 'aes-256-gcm' do before do @cipher_mode = 'aes-256-gcm' encryptor = Config::Options encryptor.stubs(:cipher).returns(@cipher_mode) encryptor.stubs(:digest).returns('SHA512') encryptor.stubs(:key).returns('this_is_key') Settings.stubs(:encryptor).returns(encryptor) end it_behaves_like 'An Adapter' describe 'gcm works without digest' do before do @cipher_mode = 'aes-256-gcm' encryptor = Config::Options encryptor.stubs(:cipher).returns(@cipher_mode) encryptor.stubs(:digest).returns(nil) encryptor.stubs(:key).returns('this_is_key') Settings.stubs(:encryptor).returns(encryptor) end it_behaves_like 'An Adapter' end end describe 'aes-256-cbc' do before do @cipher_mode = 'aes-256-cbc' encryptor = Config::Options encryptor.stubs(:cipher).returns(@cipher_mode) encryptor.stubs(:digest).returns('SHA512') encryptor.stubs(:key).returns('this_is_key') Settings.stubs(:encryptor).returns(encryptor) end it_behaves_like 'An Adapter' end end
class AddOwnerRanks < ActiveRecord::Migration[5.2] def change create_table "draft_owner_ranks", id: :integer, force: :cascade do |t| t.integer "owner_id", default: 0 t.integer "draft_player_id", default: 0 t.integer "overall", default: 9999 t.datetime "created_at" t.datetime "updated_at" t.index ["owner_id", "draft_player_id"], name: "draft_owner_rank_owner_player_ndx", unique: true end end end
log " ********************************************** * * * Recipe:#{recipe_name} * * * ********************************************** " thisdir = node[:clone12_2][:machprep][:workingdir] directory "Make_the_dir_#{thisdir}" do path thisdir owner 'root' group node[:root_group] mode '0755' action :create end
class CreateServices < ActiveRecord::Migration[5.1] def change create_table :services do |t| t.string :name t.references :equipment, foreign_key: true t.references :company, foreign_key: true t.references :costumer, foreign_key: true t.date :done_at t.date :next_service t.timestamps end end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # name :string not null # description :text # created_at :datetime not null # updated_at :datetime not null # icon_image :string # email :string not null # crypted_password :string # salt :string # remember_me_token :string # remember_me_token_expires_at :datetime # city_id :integer # class User < ActiveRecord::Base include RegexDefinition ### relation has_many :reports belongs_to :city mount_uploader :icon_image, ImageUploader ### before ### before_validation do self.email_for_index = email.downcase if email end ### verify ### ## required validates_presence_of :name, :email, :city ## digits # string validates_length_of :name, maximum: 255 validates_length_of :description, maximum: 10000 validates_length_of :password, minimum: 6, allow_blank: true, allow_nil: true, :on => :create_pw # integer ## uniqueness validates_uniqueness_of :email_for_index ## format validates_confirmation_of :password validates_presence_of :password, :on => :create_pw validates_format_of :email, with: REG_EMAIL, allow_blank: true, allow_nil: true validates_format_of :password, with: REG_HANKAKU_EISU_WITH_ALL_MARK_WITHOUT_SPACE, allow_blank: true, allow_nil: true, :on => :create_pw ## other ### add properties ### authenticates_with_sorcery! def icon_image_url if self.icon_image.url return self.icon_image.user.url else return '/images/no_image_user.png' end end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # class Module # Declares an attribute reader backed by an internally-named instance variable. def attr_internal_reader(*attrs) attrs.each do |attr| module_eval "def #{attr}() #{attr_internal_ivar_name(attr)} end" end end # Declares an attribute writer backed by an internally-named instance variable. def attr_internal_writer(*attrs) attrs.each do |attr| module_eval "def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end" end end # Declares an attribute reader and writer backed by an internally-named instance # variable. def attr_internal_accessor(*attrs) attr_internal_reader(*attrs) attr_internal_writer(*attrs) end alias_method :attr_internal, :attr_internal_accessor private mattr_accessor :attr_internal_naming_format self.attr_internal_naming_format = '@_%s' def attr_internal_ivar_name(attr) attr_internal_naming_format % attr end end
class ChatShuttleGenerator < Rails::Generators::NamedBase source_root File.expand_path('../templates', __FILE__) hook_for :orm end
module VotableControllerMixin def submit_upvote(model, user) vote(model, user, 'up') end def submit_downvote(model, user) vote(model, user, 'down') end private def vote(model, user, direction) # Make sure we've specified a direction raise "No direction parameter specified to #vote action." unless direction # Make sure the direction is valid unless ["up", "down"].member? direction raise "Direction '#{direction}' is not a valid direction for vote method." end model.vote_by voter: user, vote: direction end end
$imported = {} if $imported == nil $imported["H87_Escape"] = true #=============================================================================== # ** Probabilità di fuga ** # Versione: 1.1 (19/11/2019) # Difficoltà utente: ★★ #=============================================================================== # DESCRIZIONE: # Questo script permette di modificare le probabilità di fuga grazie ad # equipaggiamenti e stati alterati. Inoltre modifica il calcolo delle # probabilità di fuga, considerando solo i nemici (e gli alleati) attualmente # in grado di muoversi. Questo significa che sarà molto più facile fuggire con # nemici addormentati o paralizzati, e più difficile se lo stesso è con gli # alleati. #=============================================================================== # UTILIZZO: # Installare lo script sotto Materials e prima del Main. # Inserire, nel riquadro delle note dello stato o dell'equipaggiamento, la # seguente etichetta: # <fuga: x> dove x è il valore (valori positivi aumentano le probabilità, valori # negativi le diminuiscono) (max 100: probabilità sicura). # I bonus sono cumulativi. # Se vuoi far fuggire il gruppo, basta che scrivi in un chiama script: # force_escape # puoi creare abilità che chiamano un evento comune con questa skill. La fuga # non funzionerà contro i boss. # force_escape(true) fa fuggire gli eroi dall'incontro anche se si tratta di un # boss. #=============================================================================== # COMPATIBILITA': # Compatibile con quasi tutti gli script. #=============================================================================== module H87_Escape # IMPOSTAZIONI #Cambia il valore di questa costante per aggiustare il valore base delle #probabilità di fuga: ESCAPE_ADJUSTER = 15 #=============================================================================== # ** FINE CONFIGURAZIONE ** # Attenzione: Non modificare ciò che c'è oltre, a meno che tu non sappia ciò che # fai! #=============================================================================== EB = /<(?:FUGA|fuga):[ ]*(\d+)>/i end module EscapeBonusItem attr_reader :escape_bonus def escape_bonus @escape_bonus end def carica_cache_personale_esc return if @cache_caricatae @cache_caricatae=true @escape_bonus = 0 self.note.split(/[\r\n]+/).each { |riga| case riga when H87_Escape::EB @escape_bonus += $1.to_i else # type code here end } end end #=============================================================================== # ** Game_Actor #=============================================================================== class Game_Actor < Game_Battler # restituisce il bonus di fuga def escape_bonus features_sum :escape_bonus end end # game_actor #=============================================================================== # ** Classe Armi #=============================================================================== class RPG::Weapon include EscapeBonusItem end #=============================================================================== # ** Classe Armature #=============================================================================== class RPG::Armor include EscapeBonusItem end #=============================================================================== # ** Classe Status #=============================================================================== class RPG::State include EscapeBonusItem end #============================================================================== # ** Scene_Title #============================================================================== class Scene_Title < Scene_Base #----------------------------------------------------------------------------- # *Alias metodo load_bt_database #----------------------------------------------------------------------------- alias l_bt_de load_bt_database unless $@ def load_bt_database l_bt_de setup_escape_states setup_escape_armors setup_escape_weapons end #----------------------------------------------------------------------------- # *Alias metodo load_database #----------------------------------------------------------------------------- alias ld_de load_database unless $@ def load_database ld_de setup_escape_states setup_escape_armors setup_escape_weapons end #----------------------------------------------------------------------------- # *Inizializza nel caricamento #----------------------------------------------------------------------------- def setup_escape_states $data_states.each do |state| next if state == nil state.carica_cache_personale_esc end end #----------------------------------------------------------------------------- # *setup_escape_armors #----------------------------------------------------------------------------- def setup_escape_armors $data_armors.each do |armor| next if armor == nil armor.carica_cache_personale_esc end end #----------------------------------------------------------------------------- # *setup_escape_weapons #----------------------------------------------------------------------------- def setup_escape_weapons $data_weapons.each do |weapon| next if weapon == nil weapon.carica_cache_personale_esc end end end # scene_title class Game_Unit def total_agi members.select {|member| member.movable?}.inject(0) { |s, m| s + m.agi } end end #============================================================================== # ** Scene_Battle #============================================================================== class Scene_Battle < Scene_Base #----------------------------------------------------------------------------- # *Alias metodo start #----------------------------------------------------------------------------- alias re_start start unless $@ def start re_start @sure_escape = false end #----------------------------------------------------------------------------- # * cambia le prob. di fuga #----------------------------------------------------------------------------- def make_escape_ratio actors_agi = $game_party.total_agi enemies_agi = $game_troop.total_agi @escape_ratio = 150 - 100 * enemies_agi / actors_agi @escape_ratio += H87_Escape::ESCAPE_ADJUSTER @escape_ratio += actors_escape_bonus end #----------------------------------------------------------------------------- # * controlla il bonus di fuga degli eroi #----------------------------------------------------------------------------- def actors_escape_bonus bonus = $game_party.members.inject(0) { |b, member| b + member.escape_bonus } bonus += 999999 if @sure_escape bonus end #----------------------------------------------------------------------------- # * viene eseguito quando la fuga è obbligata da eventi. #----------------------------------------------------------------------------- def ensure_escape @sure_escape = true make_escape_ratio process_escape end end # scene_battle #============================================================================== # ** Game_Interpreter #============================================================================== class Game_Interpreter def force_escape(boss_also = false) if $scene.is_a?(Scene_Battle) $scene.ensure_escape if boss_also or $game_troop.can_escape end end end #game_interpreter
# 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. require 'mongo/auth/credential_cache' require 'mongo/auth/stringprep' require 'mongo/auth/conversation_base' require 'mongo/auth/sasl_conversation_base' require 'mongo/auth/scram_conversation_base' require 'mongo/auth/user' require 'mongo/auth/roles' require 'mongo/auth/base' require 'mongo/auth/aws' require 'mongo/auth/cr' require 'mongo/auth/gssapi' require 'mongo/auth/ldap' require 'mongo/auth/scram' require 'mongo/auth/scram256' require 'mongo/auth/x509' require 'mongo/error/read_write_retryable' require 'mongo/error/labelable' module Mongo # This namespace contains all authentication related behavior. # # @since 2.0.0 module Auth extend self # The external database name. # # @since 2.0.0 # @api private EXTERNAL = '$external'.freeze # Constant for the nonce command. # # @since 2.0.0 # @api private GET_NONCE = { getnonce: 1 }.freeze # Constant for the nonce field. # # @since 2.0.0 # @api private NONCE = 'nonce'.freeze # Map the symbols parsed from the URI connection string to strategies. # # @note This map is not frozen because when mongo_kerberos is loaded, # it mutates this map by adding the Kerberos authenticator. # # @since 2.0.0 SOURCES = { aws: Aws, gssapi: Gssapi, mongodb_cr: CR, mongodb_x509: X509, plain: LDAP, scram: Scram, scram256: Scram256, } # Get an authenticator for the provided user to authenticate over the # provided connection. # # @param [ Auth::User ] user The user to authenticate. # @param [ Mongo::Connection ] connection The connection to authenticate over. # # @option opts [ String | nil ] speculative_auth_client_nonce The client # nonce used in speculative auth on the specified connection that # produced the specified speculative auth result. # @option opts [ BSON::Document | nil ] speculative_auth_result The # value of speculativeAuthenticate field of hello response of # the handshake on the specified connection. # # @return [ Auth::Aws | Auth::CR | Auth::Gssapi | Auth::LDAP | # Auth::Scram | Auth::Scram256 | Auth::X509 ] The authenticator. # # @since 2.0.0 # @api private def get(user, connection, **opts) mechanism = user.mechanism raise InvalidMechanism.new(mechanism) if !SOURCES.has_key?(mechanism) SOURCES[mechanism].new(user, connection, **opts) end # Raised when trying to authorize with an invalid configuration # # @since 2.11.0 class InvalidConfiguration < Mongo::Error::AuthError; end # Raised when trying to get an invalid authorization mechanism. # # @since 2.0.0 class InvalidMechanism < InvalidConfiguration # Instantiate the new error. # # @example Instantiate the error. # Mongo::Auth::InvalidMechanism.new(:test) # # @param [ Symbol ] mechanism The provided mechanism. # # @since 2.0.0 def initialize(mechanism) known_mechanisms = SOURCES.keys.sort.map do |key| key.inspect end.join(', ') super("#{mechanism.inspect} is invalid, please use one of the following mechanisms: #{known_mechanisms}") end end # Raised when a user is not authorized on a database. # # @since 2.0.0 class Unauthorized < Mongo::Error::AuthError include Error::ReadWriteRetryable include Error::Labelable # @return [ Integer ] The error code. attr_reader :code # Instantiate the new error. # # @example Instantiate the error. # Mongo::Auth::Unauthorized.new(user) # # @param [ Mongo::Auth::User ] user The unauthorized user. # @param [ String ] used_mechanism Auth mechanism actually used for # authentication. This is a full string like SCRAM-SHA-256. # @param [ String ] message The error message returned by the server. # @param [ Server ] server The server instance that authentication # was attempted against. # @param [ Integer ] The error code. # # @since 2.0.0 def initialize(user, used_mechanism: nil, message: nil, server: nil, code: nil ) @code = code configured_bits = [] used_bits = [ "auth source: #{user.auth_source}", ] if user.mechanism configured_bits << "mechanism: #{user.mechanism}" end if used_mechanism used_bits << "used mechanism: #{used_mechanism}" end if server used_bits << "used server: #{server.address} (#{server.status})" end used_user = if user.mechanism == :mongodb_x509 'Client certificate' else "User #{user.name}" end if configured_bits.empty? configured_bits = '' else configured_bits = " (#{configured_bits.join(', ')})" end used_bits = " (#{used_bits.join(', ')})" msg = "#{used_user}#{configured_bits} is not authorized to access #{user.database}#{used_bits}" if message msg += ': ' + message end super(msg) end end end end
class ShowProgramTag < ActiveRecord::Base belongs_to :show_program belongs_to :tag belongs_to :api_user attr_accessible :show_program, :tag, :api_user validates :show_program, :presence => true validates :tag, :presence => true validates :api_user, :presence => true # validates :api_user, :length => {:minimum => 1, :message=>"Show Program Tag must have at least 1 user who tagged it."} end
class CreateHistories < ActiveRecord::Migration def change create_table :histories do |t| t.belongs_to :clinic t.belongs_to :patient t.text :pathological t.text :nonpathological t.text :family t.text :surgical t.text :allergies t.text :medicines t.float :weight t.float :size t.timestamps null: false end add_index :histories, :clinic_id add_index :histories, :patient_id end end
require 'rails_helper' feature 'Confirm step' do let!(:address) { create(:address, address_type: 'both') } let!(:book) { create(:book) } let!(:order_item) { create(:order_item, book: book) } background do @user = create(:user) login_as(@user, scope: :user) @order = create(:order, order_items: [order_item], addresses: [address], user: @user) allow_any_instance_of(CheckoutsController).to receive(:current_order).and_return(@order) visit checkouts_path(id: :complete, done: true) end scenario 'show complete order info' do expect(page).to have_content('Thank You for your Order!') expect(page).to have_content("An order confirmation has been sent to #{@user.email}") expect(page).to have_content(address.first_name + " " + address.last_name) expect(page).to have_content(address.address_name) expect(page).to have_content(address.city) expect(page).to have_content(address.phone) expect(page).to have_content(address.country) expect(page).to have_content(book.title) expect(page).to have_content("€#{book.price}") expect(page).to have_content(book.description.slice(0, 137)) expect(page).to have_content(@order.created_at.strftime('%m/%d/%Y')) expect(page).to have_content("Order ##{@order.track_number}") end scenario 'redirect to catalog' do category = create(:category) click_link('Go to Shop') expect(current_path).to eq(category_path(category.id)) end end
# frozen_string_literal: true # == Schema Information # # Table name: stations # # id :bigint not null, primary key # free_bikes :integer # latitude :float # longitude :float # name :string # sid :string # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_stations_on_latitude_and_longitude (latitude,longitude) # index_stations_on_sid (sid) # FactoryBot.define do factory :station do sid { Faker::Internet.password(32) } name { "#{Faker::Ancient.primordial} - #{Faker::Ancient.hero}" } latitude { 48.881991 } longitude { 2.371773 } free_bikes { Random.rand(1..8) } end end
ActiveAdmin.register Genre do permit_params :genre end
#### # # AccountDebit # # Debits due on an account - structure used for display in a view page # #### # class AccountDebit include Comparable attr_reader :amount, :date_due, :charge_type, :property_refs def initialize(date_due:, charge_type:, property_ref:, amount:) @date_due = date_due @charge_type = charge_type @property_refs = Consecutize.new elements: [property_ref] @amount = amount end def key [date_due, charge_type] end def property_refs_to_s @property_refs.to_s end def merge(account_debit) @property_refs.merge account_debit.property_refs end def <=> other return nil unless other.is_a?(self.class) [date_due, charge_type] <=> [other.date_due, other.charge_type] end def to_s "key: #{key} - value: due: #{date_due}, charge: #{charge_type}, "\ "refs: #{property_refs_to_s}" end end
# frozen_string_literal: true require "active_support/core_ext/module/attribute_accessors" module ActiveRecord module AttributeMethods module Dirty extend ActiveSupport::Concern include ActiveModel::Dirty included do if self < ::ActiveRecord::Timestamp raise "You cannot include Dirty after Timestamp" end class_attribute :partial_writes, instance_writer: false, default: true after_create { changes_applied } after_update { changes_applied } # Attribute methods for "changed in last call to save?" attribute_method_affix(prefix: "saved_change_to_", suffix: "?") attribute_method_prefix("saved_change_to_") attribute_method_suffix("_before_last_save") # Attribute methods for "will change if I call save?" attribute_method_affix(prefix: "will_save_change_to_", suffix: "?") attribute_method_suffix("_change_to_be_saved", "_in_database") end # <tt>reload</tt> the record and clears changed attributes. def reload(*) super.tap do @previously_changed = ActiveSupport::HashWithIndifferentAccess.new @mutations_before_last_save = nil @attributes_changed_by_setter = ActiveSupport::HashWithIndifferentAccess.new @mutations_from_database = nil end end # Did this attribute change when we last saved? This method can be invoked # as +saved_change_to_name?+ instead of <tt>saved_change_to_attribute?("name")</tt>. # Behaves similarly to +attribute_changed?+. This method is useful in # after callbacks to determine if the call to save changed a certain # attribute. # # ==== Options # # +from+ When passed, this method will return false unless the original # value is equal to the given option # # +to+ When passed, this method will return false unless the value was # changed to the given value def saved_change_to_attribute?(attr_name, **options) mutations_before_last_save.changed?(attr_name, **options) end # Returns the change to an attribute during the last save. If the # attribute was changed, the result will be an array containing the # original value and the saved value. # # Behaves similarly to +attribute_change+. This method is useful in after # callbacks, to see the change in an attribute that just occurred # # This method can be invoked as +saved_change_to_name+ in instead of # <tt>saved_change_to_attribute("name")</tt> def saved_change_to_attribute(attr_name) mutations_before_last_save.change_to_attribute(attr_name) end # Returns the original value of an attribute before the last save. # Behaves similarly to +attribute_was+. This method is useful in after # callbacks to get the original value of an attribute before the save that # just occurred def attribute_before_last_save(attr_name) mutations_before_last_save.original_value(attr_name) end # Did the last call to +save+ have any changes to change? def saved_changes? mutations_before_last_save.any_changes? end # Returns a hash containing all the changes that were just saved. def saved_changes mutations_before_last_save.changes end # Alias for +attribute_changed?+ def will_save_change_to_attribute?(attr_name, **options) mutations_from_database.changed?(attr_name, **options) end # Alias for +attribute_change+ def attribute_change_to_be_saved(attr_name) mutations_from_database.change_to_attribute(attr_name) end # Alias for +attribute_was+ def attribute_in_database(attr_name) mutations_from_database.original_value(attr_name) end # Alias for +changed?+ def has_changes_to_save? mutations_from_database.any_changes? end # Alias for +changes+ def changes_to_save mutations_from_database.changes end # Alias for +changed+ def changed_attribute_names_to_save changes_to_save.keys end # Alias for +changed_attributes+ def attributes_in_database changes_to_save.transform_values(&:first) end private def write_attribute_without_type_cast(attr_name, _) result = super clear_attribute_change(attr_name) result end def _update_record(*) partial_writes? ? super(keys_for_partial_write) : super end def _create_record(*) partial_writes? ? super(keys_for_partial_write) : super end def keys_for_partial_write changed_attribute_names_to_save & self.class.column_names end end end end
require "rails_helper" describe DealCards, type: :service do fixtures :all let(:game) { Game.create! } let(:base_round) { game.rounds.create!(odd_players_score: 0, even_players_score: 0, order_in_game: 0) } let(:round) { base_round } let(:deck) { BuildDeck.new.call } let(:fresh_deck) { BuildDeck.new.call } let(:deal_cards) { DealCards.new(base_round, deck) } let(:players) { game.players } before { 4.times { |n| JoinGame.new(game: game, user: users("user#{n+1}")).call } } describe "#call" do before { deal_cards.call } context "when the dealing is successful" do it "deals all the cards into the round" do expect(round.cards.count).to eq(fresh_deck.count) end it "deals 10 cards to each player" do game.players.each do |player| expect(player.cards.count).to eq(Game::HAND_SIZE) end end it "leaves 3 cards without a player" do expect(round.cards.where(player: nil).count).to eq(3) end end end end
# frozen_string_literal: true require 'structures/queue' RSpec.describe Structures::Queue do context 'when empty' do subject(:empty_queue) { described_class.new } it 'is empty' do expect(empty_queue).to be_empty end describe '#poll' do it 'raises an error' do expect { empty_queue.poll }.to raise_error('Empty Queue') end end describe '#peek' do it 'raises an error' do expect { empty_queue.peek }.to raise_error('Empty Queue') end end end context 'with elements' do subject(:queue) do list_queue = described_class.new list_queue.offer(first_item) list_queue.offer(last_item) list_queue end let(:first_item) { 13 } let(:last_item) { 69 } let(:another_item) { 42 } describe '#offer' do it 'increases the size' do expect { queue.offer(another_item) }.to change(queue, :size).from(2).to(3) end it 'returns updated size' do expect(queue.offer(another_item)).to eq(3) end end describe '#poll' do it 'decreases the size' do expect { queue.poll }.to change(queue, :size).from(2).to(1) end it 'returns an item' do expect(queue.poll).to eq(first_item) end end describe '#peek' do it 'does nothing with size' do expect { queue.peek }.not_to change(queue, :size).from(2) end it 'returns an item' do expect(queue.peek).to eq(first_item) end end describe '#search' do it 'returns an index of element' do expect(queue.search(last_item)).to eq(1) end end end end
class AddUpdatedAt < MassMigrator::Migration def up add_column table_name, :updated_at, DateTime end def down drop_column table_name, :updated_at end end
require 'spec_helper' describe PartnerAccount do subject { FactoryGirl.create :partner_account } it 'always subscribes to unlimited plan by default' do subject.subscription.plan.should be_unlimited end end
Given /^Navigate to Index Page$/ do visit root_path end When /^I click on Organization Menu and click on Create New Organization sub menu$/ do within("#org") do click_link 'orga' end within("#neworg") do click_link 'orgnew' end end Then /^I should see Organization Form$/ do page.should have_content('City') end When /^I fill all the fields on the Form and click on Create Button$/ do fill_in 'orgname', with:'Org2' fill_in 'orgcity', with:'Kkd' fill_in 'orgstate', with:'AP' fill_in 'orgph', with:'256565' fill_in 'orgemail', with:'veebu@gmail.com' fill_in 'orgweb', with:'www.vee.com' click_button 'Save' page.should have_content('Success') end Then /^one organization is created$/ do @organization = Organization.first if !@organization puts "Not stored in Database" else puts "Stored on the Database" end end
require 'prawn_charts/components/component' module PrawnCharts module Components # Component used to limit other visual components to a certain area on the graph. class Viewport < Component include PrawnCharts::Helpers::Canvas def initialize(*args, &block) super(*args) self.components = [] block.call(self.components) if block end def draw(pdf, bounds, options={}) self.components.each do |component| sub_bounds = bounds_for([bounds[:width], bounds[:height]], component.position, component.size) pdf.bounding_box([bounds[:x]+sub_bounds[:x],bounds[:y]+bounds[:height]-sub_bounds[:y]], :width => sub_bounds[:width], :height => sub_bounds[:height]) do component.render(pdf, bounds_for([bounds[:width], bounds[:height]], [0.0,0.0], component.size), options) end end end end # Viewport end # Components end # PrawnCharts
module Student::BookBorrow::BookBorrowHelper def pre_processing case action_name when 'create' @action = Create.new(params: params) when 'index' @action = Index.new(params: params) when 'destroy' @action = Destroy.new(params: params) end implementation end def implementation @action.process end class Base attr_reader :status def initialize(options) @params = options[:params] end end class Create < Base include Student::BookBorrow::CreateHelper def initialize(options) super(options) end end class Index < Base include Student::BookBorrow::IndexHelper def initialize(options) super(options) end end class Destroy < Base include Student::BookBorrow::DestroyHelper def initialize(options) super(options) end end end
# A representation of the database view for Q-V Mapping # # This cannot be used for creating, updating or deleting, but provides # a quick way to view question-variable mapping. # # === Properties # * id # * source # * variable class QvMapping < ReadOnlyRecord # Use id as a primary key self.primary_key = :id # Each QV mapping can only belong to one {Dataset} belongs_to :dataset # Each QV mapping can only belong to one {Instrument} belongs_to :instrument # Return question reference with grid cell reference # # @return [String] Question reference def question_with_cell self.question + ((self.x.nil? || self.y.nil?) ? '' : "$#{self.x};#{self.y}") end end
module Microprocess module Protocol PROTOCOL_LINE_MAX = 1.kilobytes macro_def :line do |options| i = options.fetch(:i, :chunk) o = options.fetch(:o, :line) max = options.fetch(:max, PROTOCOL_LINE_MAX) @line_buffer = "" on i do |chunk| if chunk.nil? emit(o, @line_buffer) unless @line_buffer.empty? emit(o, nil) else @line_buffer << chunk if @line_buffer.size > max emit(o, :max) end lines = @line_buffer.lines last = lines.pop lines.each do |line| emit(o, line) end if last.end_with?("\n") emit(o, last) @line_buffer.clear else @line_buffer = last end end end o end end end
require "rails_helper" feature "react finds questionsets_controller" do before(:each) do Paragraphtype.create(name: "Introduction") Questionset.create( paragraphtype_id: 1, name: "Vassar HIST 454 Penguin Introduction" ) end scenario "#new has correct path" do visit new_questionset_path expect(page).to have_current_path('/questionsets/new') end scenario "#new has correct div" do visit new_questionset_path expect(page).to have_css('div#app') end scenario "#show has correct path" do visit questionset_path(1) expect(page).to have_current_path('/questionsets/1') end scenario "#show has correct div" do visit questionset_path(1) expect(page).to have_css('div#app') end scenario "#edit has correct path" do visit edit_questionset_path(1) expect(page).to have_current_path('/questionsets/1/edit') end scenario "#edit has the correct div" do visit edit_questionset_path(1) expect(page).to have_css('div#app') end end
require 'test_helper' class IncidentfollowupsControllerTest < ActionDispatch::IntegrationTest setup do @incidentfollowup = incidentfollowups(:one) end test "should get index" do get incidentfollowups_url assert_response :success end test "should get new" do get new_incidentfollowup_url assert_response :success end test "should create incidentfollowup" do assert_difference('Incidentfollowup.count') do post incidentfollowups_url, params: { incidentfollowup: { comment: @incidentfollowup.comment, date: @incidentfollowup.date, incident: @incidentfollowup.incident, status: @incidentfollowup.status } } end assert_redirected_to incidentfollowup_url(Incidentfollowup.last) end test "should show incidentfollowup" do get incidentfollowup_url(@incidentfollowup) assert_response :success end test "should get edit" do get edit_incidentfollowup_url(@incidentfollowup) assert_response :success end test "should update incidentfollowup" do patch incidentfollowup_url(@incidentfollowup), params: { incidentfollowup: { comment: @incidentfollowup.comment, date: @incidentfollowup.date, incident: @incidentfollowup.incident, status: @incidentfollowup.status } } assert_redirected_to incidentfollowup_url(@incidentfollowup) end test "should destroy incidentfollowup" do assert_difference('Incidentfollowup.count', -1) do delete incidentfollowup_url(@incidentfollowup) end assert_redirected_to incidentfollowups_url end end
#GET request get '/sample-8-how-to-return-a-url-representing-a-single-page-of-a-document' do haml :sample08 end #POST request post '/sample-8-how-to-return-a-url-representing-a-single-page-of-a-document' do #Set variables set :client_id, params[:clientId] set :private_key, params[:privateKey] set :guid, params[:guid] set :page_number, params[:pageNumber] set :source, params[:source] set :file_id, params[:fileId] set :base_path, params[:basePath] begin #Check required variables raise 'Please enter all required parameters' if settings.client_id.empty? or settings.private_key.empty? #Prepare base path if settings.base_path.empty? base_path = 'https://api.groupdocs.com' elsif settings.base_path.match('/v2.0') base_path = settings.base_path.split('/v2.0')[0] else base_path = settings.base_path end #Configure your access to API server GroupDocs.configure do |groupdocs| groupdocs.client_id = settings.client_id groupdocs.private_key = settings.private_key #Optionally specify API server and version groupdocs.api_server = base_path # default is 'https://api.groupdocs.com' end file = nil doc = nil metadata = nil #Get document by file GUID case settings.source when 'guid' file = GroupDocs::Storage::File.new({:guid => settings.file_id}) when 'local' #Construct path filepath = "#{Dir.tmpdir}/#{params[:file][:filename]}" #Open file File.open(filepath, 'wb') { |f| f.write(params[:file][:tempfile].read) } #Make a request to API using client_id and private_key file = GroupDocs::Storage::File.upload!(filepath, {}) when 'url' file = GroupDocs::Storage::File.upload_web!(settings.url) else raise 'Wrong GUID source.' end doc = file.to_document metadata = doc.metadata!() #Get document page images images = doc.page_images!(800, 400, {:first_page => 0, :page_count => metadata.views_count}) #Result unless images.empty? image = images[Integer(settings.page_number)] end rescue Exception => e err = e.message end #Set variables for template haml :sample08, :locals => {:clientId => settings.client_id, :privateKey => settings.private_key, :guid => settings.guid, :pageNumber => settings.page_number, :image => image, :err => err} end
require 'spec_helper' require 'kintone/api/guest' require 'kintone/api' describe Kintone::Api::Guest do let(:target) { Kintone::Api::Guest.new(space, api) } let(:space) { 1 } let(:api) { Kintone::Api.new("example.cybozu.com", "Administrator", "cybozu") } describe "#get_url" do subject { target.get_url(command) } context "" do let(:command) { "path" } it { expect(subject).to eq("/k/guest/1/v1/path.json") } end end end
# encoding: utf-8 class CreateMailTemplates < ActiveRecord::Migration def change create_table :mail_templates do |t| t.string :title, null: false, default: "" t.text :content, null: false, default: "" t.datetime :opened_at, null: true t.datetime :closed_at, null: true t.string :from, null: false t.string :reply_to, null: false t.string :bcc, null: false t.boolean :public, null: false, default: false t.timestamps end end end
require 'test_helper' class TodoitemTest < ActiveSupport::TestCase test 'Should not save todoitem without todo' do todo = Todoitem.new assert_not todo.save end test 'Should save valid todo item' do todo = Todoitem.new todo.todo = 'sample checklist' todo.task_id = tasks(:two).id assert todo.save end end
class Manual < ActiveRecord::Base belongs_to :tag validates_presence_of :tag_id, :iteration_id, :scenario validates_numericality_of :jira, :allow_nil => true # validates_numericality_of :bug, :allow_nil => true validates_numericality_of :count, :allow_nil => true named_scope :fail, :conditions => {:status => [false]} named_scope :pass, :conditions => {:status => true} named_scope :blocked, :conditions => {:blocked => true} named_scope :untested, :conditions => {:untested => true} do def reset each { |x| x .update_attribute(:untested, false) } end end named_scope :green_scenarios, :conditions => {:status => true } do def reset each { |x| x .update_attribute(:status, false) } end end end
class AdminController < ApplicationController before_filter :authenticate def authenticate authenticate_or_request_with_http_basic('Administration') do |username, password| password = Digest::MD5.hexdigest(password) username == 'username' && password == '5f4dcc3b5aa765d61d8327deb882cf99' end end def index @articles = Article.all end end
#Some of the basic math methods you will need for simple to more complex calculations puts 5 ** 2 # exponent so 5 to the 2nd power is 25 puts 16 ** 0.5 # output will be 4 -- to get the square root of any number..( number to the power of 0.5) puts 7 / 3 # out put will give you 2 as 3 goes in to 7 a total of 2 times clean, will not return a remainder puts 7 % 3 # output will be 1 as % will ONLY give the remainder puts 365 % 7 #output will be 1 as that is the remainder when divided puts (5-2).abs # output of 3 as this stands for the ABSOLUTE VALUE of equation puts (2-5).abs # output of 3 as this stands for the ABSOLUTE VALUE of equation #.RAND method puts "***********************" puts rand #without any parameters rand will give you a random float >= 0.0 and < 1.0 puts rand puts rand puts(rand(100))# with a parameter number >= 0 and < number(100) provided puts(rand(100)) puts(rand(100)) puts(rand(1))#will always return 0 puts(rand(1)) puts(rand(1)) puts(rand(9999999999999999999999999999999999999)) puts('The weatherman said there is a') puts(rand(101).to_s + '% chance of rain,') # random number from 1 to a 100 puts('but you can never trust a weatherman.') # SRAND method #Sometimes you might want rand to return the same random numbers in the same sequence on two different runs of your program. #In order to do this, you need to set the seed, which you can do with srand: puts "***********************" srand 1976 #will print out below the same set of random numbers generated here and store them in srand 1976 puts(rand(100)) puts(rand(100)) puts(rand(100)) puts(rand(100)) puts '' srand 1976 puts(rand(100)) puts(rand(100)) puts(rand(100)) puts(rand(100)) #Some additional math methods that are important when it comes to making calculations puts "***********************" puts(Math::PI) puts(Math::E) puts(Math.cos(Math::PI/3)) puts(Math.tan(Math::PI/4)) puts(Math.log(Math::E**2)) puts((1 + Math.sqrt(5))/2)
class UserRegistrationType < User attr_accessible :password, :password_confirmation validates :password, presence: true validates :password_confirmation, presence: true validates :email, presence: true, email: true end
class Customer < User has_many :events def event_requests events.inject([]) {|requests, e| requests += e.event_requests} end end
require_relative 'spec_helper' describe 'call_next' do context 'the prototyped object has an internal prototype' do context 'with params' do it 'calls the next implementation' do saludador_normal = prototyped saludador_normal.saludar = proc { |nombre| "Hola #{nombre}." } expect(saludador_normal.saludar('Erlang')).to eq('Hola Erlang.') saludador_extra = prototyped.set(saludador_normal) saludador_extra.saludar = proc { |nombre| call_next(:saludar, nombre) + ' Como te va?' } expect(saludador_extra.saludar('Ruby')).to eq('Hola Ruby. Como te va?') saludador_loco = prototyped.set(saludador_extra) saludador_loco.saludar = proc { |nombre| call_next(:saludar, nombre) + ' Que agradable sujeto.' } expect(saludador_loco.saludar('Matz')).to eq('Hola Matz. Como te va? Que agradable sujeto.') end it 'delegates any given method to its prototype' do libro = prototyped do context.titulo = 'El naufrago' context.autor = 'Cesar Aira' end proto = prototyped proto.leer = ->(l) { "leyendo #{l.titulo}, de #{l.autor}" } proto.dormir = ->(horas) { "durmiendo unas #{horas} horas" } sub_prototype = prototyped.set(proto) sub_prototype.leer = ->(_) { 'cualquier vegetal' } sub_prototype.dormir = ->(_) { 'un reloj digital' } sub_prototype.metodo = lambda do "#{call_next(:leer, libro)} o #{call_next(:dormir, 7)}" end expect(sub_prototype.metodo).to eq('leyendo El naufrago, de Cesar Aira o durmiendo unas 7 horas') end end context 'without params' do it 'calls the next implementation' do proto = prototyped proto.metodo = proc { 7 } sub_prototype = proto.set(proto) sub_prototype.metodo = proc { call_next(:metodo) * 2 } expect(sub_prototype.metodo).to eq(14) test_prototype = proto.set(sub_prototype) test_prototype.metodo = proc { call_next(:metodo) + 6 } expect(test_prototype.metodo).to eq(20) other_prototype = proto.set(test_prototype) other_prototype.metodo = proc { call_next(:metodo) + 22 } expect(other_prototype.metodo).to eq(42) end end it 'delegates any given method to its prototype' do proto = prototyped proto.leer = proc { 'leyendo' } proto.dormir = proc { 'durmiendo' } sub_prototype = prototyped.set(proto) sub_prototype.leer = -> { 'cualquier vegetal' } sub_prototype.dormir = -> { 'un reloj digital' } sub_prototype.metodo = lambda do "#{call_next(:leer)} o #{call_next(:dormir)}" end expect(sub_prototype.metodo).to eq('leyendo o durmiendo') end end context "the prototyped object doesn't have an internal prototype" do it 'raises a descriptive error' do proto = prototyped proto.metodo = proc { call_next(:metodo) * 10 } expect { proto.metodo }.to( raise_error( NoMethodError, "#The prototype can't handle #metodo" ) ) end end end
class RawCommand def initialize(unit, options = {}) @unit = unit @command = options[:invoked_command] || :raws end def help "/#{self.command} <text to send> - sends the specified text 'raw'." end def command @command end def opmsg? false end # TODO: can we eliminate complete_target and target from the method signature? def execute(cmd_string, complete_target = true, target = nil, sel = nil) #DebugTools.log_outbound_command(self.command, cmd_string, complete_target, target) @unit.send_raw(cmd_string.token!, cmd_string) return true end end
class RegistrationsController < ApplicationController def create @event = Event.find(params[:event_id]) @user = User.find(params[:user_id]) registration = @event.registrations.create(user_id: @user.id) if registration.save flash[:success] = "You're going to #{@event.name}!" redirect_to event_path(@event) else flash[:danger] = "There was an error creating your registration." render :new end end end
class Dentist < ActiveRecord::Base has_many :patients has_secure_password validates_uniqueness_of :username validates_presence_of :name, :username, :email, :password end
module RSence module Plugins # Include this module in your plugin class to automatically create, update and connect/disconnect a sqlite database file. # # The Plugin instances including this module will have a +@db+ Sequel[http://sequel.rubyforge.org/] object referring to the sqlite database automatically created. # module PluginSqliteDB # Extends {Plugin__#init Plugin#init} to specify +@db_path+ as the name of the bundle with a +.db+ suffix in the project environment +db+ path. # # Calls {#create_db_tables} (extend with your own method), if no database is found (typically on the first run in an environment) # # @example If your plugin bundle is named +my_app+, a +db/my_app.db+ database is created under your project environment. # # @return [nil] def init super db_dir = File.join( RSence.args[:env_path], 'db' ) @db_path = File.join( db_dir, "#{@name}.db" ) unless File.exist?( @db_path ) @db = Sequel.sqlite( @db_path ) create_db_tables @db.disconnect end end # Extends {PluginBase#open PluginBase#open} to open the sqlite database from +@db_path+ as a +@db+ instance variable. # # Calls {#update_db} (extend with your own method) after the database object is created. # # @return [nil] def open @db = Sequel.sqlite( @db_path ) update_db super end # Extends {PluginBase#close PluginBase#close} to close (disconnect) the database object. # # Calls {#flush_db} (extend with your own method) before closing the database object. # # @return [nil] def close flush_db @db.disconnect super end # Extend this method to do something immediately after the +@db+ object is created. # # An usage scenario would be updating some tables or deleting some junk rows. # # @return [nil] def update_db end # Extend this method to do something immediately before the +@db+ object is disconnected. # # An usage scenario would be deleting some junk rows or writing some pending data in memory into the database. # # @return [nil] def flush_db end # Extend this method to define tables or initial data for the tables. # It's called once, when the database is created. # # @example Creates a table named +:my_table+ and inserts one row. # def create_db_tables # @db.create_table :my_table do # primary_key :id # String :my_text_column # end # my_table = @db[:my_table] # my_table.insert(:my_text_column => 'Some text') # end # # @return [nil] def create_db_tables end end end end
require 'formula' class Gflags < Formula homepage 'http://code.google.com/p/google-gflags/' url 'https://gflags.googlecode.com/files/gflags-2.0.tar.gz' sha1 'dfb0add1b59433308749875ac42796c41e824908' def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make install" end end
class Oystercard attr_reader :balance attr_reader :in_use attr_reader :entry_station attr_reader :exit_station attr_accessor :journeys LIMIT = 90 MINIMUM_FARE = 1 def initialize @balance = 0 @in_use = false #@entry_station = nil #@exit_station = nil @journeys = nil end def top_up(amount) @balance + amount > LIMIT ? limit_error : @balance += amount end def limit_error raise "Error: top up will exceed balance limit of £#{LIMIT}" end def in_journey? @in_use end def touch_in(entry_station) if @balance < MINIMUM_FARE raise "Not enough money" end @entry_station = entry_station @in_use = true end def touch_out(exit_station) deduct_fare(MINIMUM_FARE) @exit_station = exit_station @in_use = false @journeys = {entry_station: entry_station, exit_station: exit_station} end private def deduct_fare(amount) @balance -= amount end end
class Project < ApplicationRecord has_and_belongs_to_many :tags scope :filter, -> (tag_id) { joins(:tags).where("tags.id = ?", tag_id) } # Scope eh uma ferramenta fornecida pelo rails em que podemos criar um metodo # (nesse caso filter) para fazermos uma "query". # Então se escrevermos Project.filter(3) teremos todos os projetos que possuem # uma tag_id = 3, ou seja, o rails selecionara todo os projetos que possuem # um relacionamento com a tag de id informado. # ATENCAO: notem que utilizo "joins(:tags)" para ter acesso a todas as tags # a partir do model de Project. end
class UsersController < ApplicationController def new @user = User.new end def create @user = User.new @user.password = params[:user][:password] @user.username = params[:user][:username] if @user.save redirect_to root_path, notice: "User account created!" else render 'new' end end def show @user = current_user @created_less_than_a_week_ago = @user.created_at > 1.week.ago end end
class Card < ApplicationRecord has_many :cards, through: :decks end
module API module V1 class Base < Dispatch format :json version 'v1' default_error_formatter :json content_type :json, 'application/json' rescue_from :all do |e| eclass = e.class.to_s status = case when eclass.match('RecordNotFound'), e.message.match(/unable to find/i).present? 404 when eclass.match('RecordInvalid'), e.message.match(/Validation failed/i).present? 400 when eclass.match('Pundit::NotAuthorizedError') opts = { error: "You have insuficient permissions." } 403 else (e.respond_to? :status) && e.status || 500 end opts ||= { error: "#{e.message}" } opts[:trace] = e.backtrace[0,10] unless Rails.env.production? Rack::Response.new(opts.to_json, status, { 'Content-Type' => "application/json", 'Access-Control-Allow-Origin' => '*', 'Access-Control-Request-Method' => '*', }).finish end mount API::V1::Properties mount API::V1::Users end end end
# frozen_string_literal: true require_relative '../helpers/spec_helper.rb' require_relative '../helpers/vcr_helper.rb' require_relative '../helpers/database_helper.rb' describe 'Integration Tests of MLB API and Database' do VcrHelper.setup_vcr DatabaseHelper.setup_database_cleaner before do VcrHelper.configure_vcr_for_mlb end after do VcrHelper.eject_vcr end describe 'Retrieve and store project' do before do DatabaseHelper.wipe_database end it 'HAPPY: should be able to create gcm and have correct inning number' do game_pk = MLBAtBat::MLB::ScheduleMapper .new .get_gamepk(GAME_DATE, SEARCH_TEAM_NAME) whole_game = MLBAtBat::Mapper::WholeGame.new.get_whole_game(game_pk) _(whole_game.innings.length).must_equal(9) _(whole_game.home_runs).must_equal(CORRECT['live_games'][0] \ ['home_team_status']['runs']) _(whole_game.away_runs).must_equal(CORRECT['live_games'][0] \ ['away_team_status']['runs']) _(whole_game.home_team_name).must_equal(CORRECT['live_games'][0] \ ['home_team_name']) _(whole_game.away_team_name).must_equal(CORRECT['live_games'][0] \ ['away_team_name']) end end end
class Answer < ActiveRecord::Base belongs_to :question belongs_to :user has_many :likes, dependent: :destroy has_many :liked_by, through: :likes, source: :user validates_length_of :contents, minimum: 1, allow_blank: false, message: "is required" def accept self.accepted = true self.user.add_points 25 self.save end def unaccept self.accepted = false self.user.add_points -15 self.save end def fix_likes self.likes_count = likes.count self.save end def like user self.user.add_points 5 self.likes_count += 1 self.likes.create user_id: user.id self.save end def unlike user self.user.add_points -5 self.likes_count -= 1 self.likes.find_by(user_id: user.id).destroy self.save end def points self.likes_count end def liked_by? user liked_by.include?(user) end end
# frozen_string_literal: true class DateTimePickerInput < InputGroupInput def new_html_options super.merge(autocomplete: 'off', data: { bs_datepicker: 'date' }) end def prepend_icon 'calendar' end def input_group_append @builder.text_field("#{attribute_name}_time", new_html_options.merge(data: { mask: 'time' })) end def custom_attribute_name "#{attribute_name}_at" end end
Given /^I visit (.*?) page$/ do |path| case path when 'sign up' then visit(new_user_registration_path) when 'sign in' then visit(new_user_session_path) when 'refinery' then visit('/refinery') else visit(eval("#{path}_path")) end end
require 'spec_helper' describe APICoder::Registry do subject { described_class.new(:Test) } it { should delegate_method(:key?).to(:items) } it { should delegate_method(:clear).to(:items) } it { should delegate_method(:find).to(:values) } it { should delegate_method(:each).to(:values) } it 'should alias #registerd? to #key?' do expect(subject.method(:registered?)).to eq subject.method(:key?) end end
class CreateSites < ActiveRecord::Migration def change create_table :sites do |t| t.string :name #t.string :subdomain_name # I do not know if domain name should be separated out. But I will separate the storage for convenience. t.string :hostname # Avoiding using the naked word domain/subdomain out of superstition of conflicts in methods etc. t.timestamps end end end
class Reservation < ActiveRecord::Base belongs_to :restaurant belongs_to :user #validate :date validate :not_in_past validate :availability validates :party_size, :presence=>true, :numericality => {:only_integer=>true} private def availability if !restaurant.availability(party_size, party_time) errors.add(:base, "Sorry, restaurant is full for your party-size") end end def date t = party_time expectation = (t.month!="month" && t.day!="day" && t.hour!="hour") if !expectation errors.add(:base, "Please double check your reservation date and time") end end def not_in_past t = party_time n = DateTime.now expectation = (t.month >= n.month) if t.month == n.month expectation = t.day >= n.day end if !expectation errors.add(:base, "This reservation is in the past #{t.year}") end end end
class CardMailer < ApplicationMailer def cards_for_review @users = User.with_unreviewed_cards @users.each do |user| @user = user mail(to: @user.email, subject: 'You have cards for review') end end end
namespace :menu do namespace :allmenus do desc "Add menus for a city" task :import_city do city = ENV["CITY"].to_s # e.g. chicago state = ENV["STATE"].to_s # e.g. il isleep = ENV["SLEEP"] ? ENV["SLEEP"].to_i : 3 limit = ENV["LIMIT"] ? ENV["LIMIT"].to_i : 10 if city.blank? or state.blank? puts "[error] missing city or state" exit end state = State.find_by_code(state.titleize) city = state.cities.find_by_name(city.titleize) if state if city.blank? or state.blank? puts "[error] missing city or state" exit end url = "http://www.allmenus.com/#{state.code.downcase}/#{city.name.downcase}/view-all" agent = WWW::Mechanize.new searched = 0 matched = 0 agent.get(url) # search for cuisine urls urls = agent.page.search("div#content_left div#location_view_all_left ul li a").inject([]) do |array, a| href = a['href'] # make sure its a real cuisine, e.g. it ends with /bagel/ and not /-/ if href.match(/\/\w+\/$/) abs_path = root_url(url) + href puts "*** url: #{abs_path}" array.push(abs_path) end array end puts "[ok] found #{urls.size} cuisines for #{city.name}:#{state.code}" urls.each do |cuisine_url| menu_urls = get_cuisine_menus(agent, cuisine_url) menu_urls.each do |menu_url| searched += 1 location = import_menu(agent, menu_url) matched += 1 if location sleep(isleep) end end puts "#{Time.now}: [completed] #{searched} searched, #{matched} matched" end desc "Add cuisine menus" task :import_cuisine do url = ENV["URL"] isleep = ENV["SLEEP"] ? ENV["SLEEP"].to_i : 3 agent = WWW::Mechanize.new searched = 0 matched = 0 menu_urls = get_cuisine_menus(agent, url) menu_urls.each do |menu_url| searched += 1 location = import_menu(agent, menu_url) matched += 1 if location sleep(isleep) end puts "#{Time.now}: [completed]" end desc "Add menu" task :import_menu do url = ENV["URL"] agent = WWW::Mechanize.new if url.blank? puts "[error] missing url" exit end location = import_menu(agent, url) puts "#{Time.now}: [completed]" end desc "Parse menu error log" task :check_menu_errors do file = ENV["FILE"] ? ENV["FILE"] : 'log/menu.error.log' url = '' count = 0 imported = 0 agent = WWW::Mechanize.new File.open(file).readlines.each do |line| # look for object hash, e.g {"name" => "Pizza Place", ... } if match = line.match(/(\{.*\})/) object = eval(match[1]) locations = LocationFinder.match_phone(object, :log => 1) count += 1 puts "found #{locations.size} locations" next if locations.size != 1 location = locations.first # skip if location already has a menu next if location.preferences[:menu] == url puts "[mapping] #{location.company_name}:#{location.id}:#{location.street_address}:#{location.city}" puts "[mapping] #{url}" puts "*** type 'y' to import" cmd = STDIN.readline.downcase.strip if cmd == 'y' import_menu(agent, url, :id => location.id) imported += 1 end elsif match = line.match(/(http.*\/)/) url = match[1] end end end # desc "Add menu links from allmenus.com" # task :import_from_allmenus do # start_url = ENV["URL"] ? ENV["URL"] : "http://www.allmenus.com/il/chicago/" # isleep = ENV["SLEEP"] ? ENV["SLEEP"].to_i : 3 # limit = ENV["LIMIT"] ? ENV["LIMIT"].to_i : 10 # menu_urls = [] # # agent = WWW::Mechanize.new # searched = 0 # matched = 0 # # # get start page # agent.get(start_url) # # # search for top restaurant links # agent.page.search("div#location_left_online ul li").children.each do |menu_link| # href = menu_link['href'] # next unless href.match(/\/menu\/$/) # url = root_url(start_url) + href # puts "*** url: #{url}" # menu_urls.push(url) # end # # # search for restaurant search results # agent.page.search("div#std_results div.result div.result_restaurant").xpath("h6/a[@href]").each do |menu_link| # href = menu_link['href'] # next unless href.match(/\/menu\/$/) # url = root_url(start_url) + href # puts "*** url: #{url}" # menu_urls.push(url) # end # # puts "#{Time.now}: [completed] #{searched} searched, #{matched} matched" # end end # allmenus # get all menus for a specific cuisine # e.g. http://www.allmenus.com/il/chicago/-/bagels/ def get_cuisine_menus(agent, url) puts "*** getting cuisine menus: #{url}" # get and parse url agent.get(url) # search for restaurant search results urls = agent.page.search("div#std_results div.result div.result_restaurant").xpath("h6/a[@href]").inject([]) do |array, a| href = a['href'] if href.match(/\/menu\/$/) abs_path = root_url(url) + href puts "*** url: #{abs_path}" array.push(abs_path) end array end urls end # skip certain *bad* menus # e.g. http://www.allmenus.com/md/chicago/185356-the-blue-agave-tequila-bar--restaurant/menu/ - causes a redirect loop def skip_menu?(url) ["http://www.allmenus.com/md/chicago/185356-the-blue-agave-tequila-bar--restaurant/menu/", "http://www.allmenus.com/nj/new-york/20247-le-bistro-deli/menu/"].include?(url) end # import menu # e.g. http://www.allmenus.com/il/chicago/272001-portillos-hot-dogs/menu/ def import_menu(agent, url, options={}) # check if this is a valid url return nil if skip_menu?(url) puts "**** importing menu: #{url}" # get and parse url agent.get(url) # parse and map to a location location = options[:id] ? Location.find_by_id(options[:id]) : parse_menu_geo(agent, url) if location add_menu(location, agent, url) end location end # map a url lik 'http://www.allmenus.com/il/chicago/-/bagels' to 'http://www.allmenus.com' def root_url(s) match = s.match(/(http:\/\/[\w.]*)\//) match ? match[1] : '' end def add_menu(location, agent, url) # check page for 'no_menu' div if agent.page.search("div#restaurantmenu").xpath("div[@id='no_menu']").size == 0 # there is a menu puts "[ok] adding menu" location.company.tag_list.add('menu') location.preferences[:menu] = url else # no menu end # check page for reviews tab agent.page.search("div#restaurant_tabs div.tab").each do |tab| tab.xpath("a").each do |a| href = a['href'] if href.match(/\/reviews\/$/) puts "[ok] adding reviews" # found a reviews tag, mark the location with the url's full path root_url = root_url(url) # e.g. http://www.allmenus.com location.preferences[:reviews] = root_url + href elsif href.match(/\/info\/$/) end end end # check page for cuisines agent.page.search("meta").xpath("//meta[@name='cuisines']").each do |element| tags = element['content'].split(",").map{ |s| s.strip.downcase } puts "[ok] adding tags #{tags.inspect}" location.tag_list.add(tags) end # check page for order online agent.page.search("meta").xpath("//meta[@name='features']").each do |element| features = element['content'] if features.match(/order online/i) puts "[ok] adding order online" location.tag_list.add('order online') location.preferences[:order_online] = url end end # commit all changes location.save end def parse_menu_geo(agent, url, options={}) # parse url for city and state match = url.match(/http:\/\/www.allmenus.com\/(\w+)\/(\w+)/) state = match[1] city = match[2] # get location name and address name = agent.page.at("div#restaurant_info h1").text().strip # e.g. Portillo's Hot Dogs address = agent.page.at("div#restaurant_info address").text().match(/(.*\d{5,5})/)[1] # e.g 100 W Ontario St, CHICAGO, IL 60610 phone_and_online = agent.page.at("div#restaurant_heading_left div#phone").text().strip # e.g. (312) 587-8910  |  Order Online phone = PhoneNumber.format(phone_and_online.split("|").first.strip) # puts "*** name and address: #{name}:#{address}" # find city and state city = address.split(",")[1].strip.downcase # e.g. chicago state = address.split(",")[2].strip.slice(0,2).downcase # e.g. il # find street hash = StreetAddress.components(address.split(",")[0]) street = "#{hash[:housenumber]} #{hash[:streetname]}" # build object hash using name, street, city, state object = Hash["name" => name, "key" => name, "address" => street, "city" => city, "state" => state, "phone" => phone] # map to a location locations = LocationFinder.match(object, :log => 1) if locations.empty? puts "[error] no location found" MENU_ERROR_LOGGER.debug("[error] #{url}") MENU_ERROR_LOGGER.debug("[error] #{object.inspect}") return nil elsif locations.size > 1 puts "[error] #{locations.size} found" MENU_ERROR_LOGGER.debug("[error] #{url}") MENU_ERROR_LOGGER.debug("[error] #{object.inspect}") return nil end locations.first end end
class Admin::VenuesController < Admin::BaseController before_action :_set_venue, except: %i[index new create] def index @venues = Venue.all end def show; end def new @venue = Venue.new render partial: 'form', layout: false end def edit render partial: 'form', layout: false end # JS def create @venue = Venue.new update_and_render_or_redirect_in_js @venue, _venue_params, ->(venue) { admin_venue_path(venue) } end # JS def update update_and_render_or_redirect_in_js @venue, _venue_params, admin_venue_path(@venue) end def destroy @venue.destroy! redirect_to admin_venues_path, notice: helpers.t_notice('successfully_deleted', Venue) end def _set_venue @venue = Venue.find params[:id] end def _venue_params params.require(:venue).permit( *Venue::FIELDS ) end end
# Suspect: skin, eye, gender, hair, name # Guess_who: number_of_guesses, guilty person, suspects # Guess_who # 1. Creates suspects, put into suspects array # 2. Randomly selects guilty person # 1. Print out list of suspects # 2. User chooses an attribute (skin, eye, gender, or hair) # 3. Choose _eye_ color (brown, blue, black) # 4. Check against guilty person; if yes, return yes attributes; if no, return no attributes # 5. User makes a guess; if yes, you win; if no, remove wrong guess and minus 1 guess # 6. Repeat 1 to 5. class Suspect attr_reader :name, :hair_color, :gender, :eye_color, :skin_color def initialize(record) attributes = record.split @name = attributes[0] @gender = attributes[1] @skin_color = attributes[2] @hair_color = attributes[3] @eye_color = attributes[4] end end class GuessWho attr_reader :suspects, :guilty_one attr_accessor :guess_count def initialize @guess_count = 3 play_game end private def create_suspects @suspects = [] suspects << Suspect.new("rachel girl black auburn brown") suspects << Suspect.new("mac boy white black brown") suspects << Suspect.new("nick boy white brown blue") suspects << Suspect.new("angie girl white auburn green") suspects << Suspect.new("theo boy white blonde brown") suspects << Suspect.new("joshua boy white black brown") suspects << Suspect.new("emily girl white blonde blue") suspects << Suspect.new("jason boy white blonde green") suspects << Suspect.new("john boy white brown blue") suspects << Suspect.new("grace girl black black brown") suspects << Suspect.new("jake boy white brown brown") suspects << Suspect.new("megan girl white blonde green") suspects << Suspect.new("ryan boy white auburn brown") suspects << Suspect.new("brandon boy white blonde brown") suspects << Suspect.new("beth girl white blonde brown") suspects << Suspect.new("diane girl black brown brown") suspects << Suspect.new("chris boy white black green") suspects << Suspect.new("david boy black black brown") suspects << Suspect.new("michelle girl black brown brown") suspects << Suspect.new("tyson boy black black brown") suspects << Suspect.new("ursula girl white auburn green") end def set_guilty_one @guilty_one = suspects.shuffle.last end def play_game create_suspects set_guilty_one start_game end def start_game puts "? ? ? ? ? WELCOME TO GUESS WHO ? ? ? ? ?" print_list_of_suspects while guess_count > 0 puts "------------------------------------------------------------------------------------" puts "To identify the guilty person by attribute, choose one: hair / gender / eyes / skin." puts "You will then be prompted to take a guess about that attribute. Or type exit." choice = gets.chomp.downcase puts "Invalid command" if !['hair', 'gender', 'eyes', 'skin', 'exit'].include?(choice) return false if choice == "exit" or ask_questions(choice) == false end end def print_list_of_suspects puts "----------------" puts "LIST OF SUSPECTS" puts "----------------" suspects.each do |suspect| puts suspect.name.capitalize end end def ask_questions(choice) case choice when "hair" ask_about_hair when "gender" ask_about_gender when "eyes" ask_about_eye when "skin" ask_about_skin when "exit" false end end def ask_about_hair puts "\nChoose a hair color: brown / black / blonde / auburn" hair = gets.chomp.downcase if hair != guilty_one.hair_color suspects.reject! { |suspect| suspect.hair_color == hair } puts "\nThe suspect's hair color is not #{hair}." puts "Here are the remaining suspects who do not have #{hair} hair:" print_list_of_suspects end if hair == guilty_one.hair_color suspects.keep_if { |suspect| suspect.hair_color == hair } puts "\nYes, the suspect's hair color is #{hair}." puts "Here are the suspects with #{hair} hair:" print_list_of_suspects end take_a_guess end def ask_about_gender puts "\nChoose a gender: girl / boy" gender = gets.chomp.downcase if gender != guilty_one.gender suspects.reject! { |suspect| suspect.gender == gender } puts "\nThe suspect's gender is not a #{gender}." puts "Here are the remaining suspects who are not #{gender}s:" print_list_of_suspects end if gender == guilty_one.gender suspects.keep_if { |suspect| suspect.gender == gender } puts "\nYes, the suspect is a #{gender}." puts "Here are the suspects who are #{gender}s:" print_list_of_suspects end take_a_guess end def ask_about_eye puts "\nChoose an eye color: blue / brown / green" eyes = gets.chomp.downcase if eyes != guilty_one.eye_color suspects.reject! { |suspect| suspect.eye_color == eyes } puts "\nThe suspect's eye color is not #{eyes}." puts "Here are the remaining suspects who do not have #{eyes} eyes:" print_list_of_suspects end if eyes == guilty_one.eye_color suspects.keep_if { |suspect| suspect.eye_color == eyes } puts "\nYes, the suspect's eye color is #{eyes}." puts "Here are the suspects who have #{eyes} eyes:" print_list_of_suspects end take_a_guess end def ask_about_skin puts "\nChoose a skin color: black / white" skin = gets.chomp.downcase if skin != guilty_one.skin_color suspects.reject! { |suspect| suspect.skin_color == skin } puts "\nThe suspect's skin color is not #{skin}." puts "Here are the remaining suspects whose skin color is not #{skin}:" print_list_of_suspects end if skin == guilty_one.skin_color suspects.keep_if { |suspect| suspect.skin_color == skin } puts "\nYes, the suspect's skin color is #{skin}." puts "Here are the suspects whose skin color is #{skin}:" print_list_of_suspects end take_a_guess end def take_a_guess puts "\nPlease guess the name of the guilty person:" name = gets.chomp.downcase if name == guilty_one.name.downcase puts "\nYou have selected the guilty person. You win!" @guess_count = 0 return elsif name != guilty_one.name.downcase @guess_count -= 1 puts "\nThe suspect is not #{name.capitalize}. You have #{@guess_count} #{@guess_count == 1 ? 'guess' : 'guesses'} left.\n\n" if @guess_count == 0 puts "The guilty one is #{guilty_one.name.capitalize}." if @guess_count > 0 start_game end end end end GuessWho.new puts "The game is done!" end
# frozen_string_literal: true ROM::SQL.migration do up do alter_table :coin_insertions do drop_column :coin_id end drop_table :coins rename_table :coin_insertions, :coins alter_table :coins do add_column :denomination, String, null: false, index: true end end down do rename_table :coins, :coin_insertions create_table :coins do primary_key :id column :denomination, String, null: false, index: true column :value, BigDecimal, null: false, size: [20, 10] end alter_table :coin_insertions do drop_column :denomination add_column :coin_id, Integer, null: true, index: true add_foreign_key [:coin_id], :coins end end end
require 'rails_helper' describe 'A visitor' do context 'visits stations show page with station name url' do it 'sees stations with name, dock count, city, installation date, longitude and latitude' do station_1 = Station.create!(name: 'City hall', dock_count: 20, city: 'San Jose', installation_date: Time.now, created_at: 2018-02-21, updated_at: 2018-03-21) visit '/city-hall' expect(page).to have_content(station_1.name) expect(page).to have_content(station_1.dock_count) expect(page).to have_content(station_1.city) expect(page).to have_content(station_1.installation_date.strftime('%b %d %Y')) end end context 'a registered user visiting station show' do before :each do @user = create(:user) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(@user) end it 'sees number of rides started and ended at this station' do station_1 = create(:station) station_2 = create(:station, name: 'hooplah') trip_1 = create(:trip, start_station_id: station_1.id, end_station_id: station_2.id) trip_2 = create(:trip, start_station_id: station_1.id, end_station_id: station_2.id) trip_3 = create(:trip,start_station_id: station_2.id, end_station_id: station_1.id) visit station_path(station_1) expect(page).to have_content("Trips started at this station 2") expect(page).to have_content("Trips ended at this station 1") end it 'sees the most frequent destination for rides that begin at this station' do station_1 = create(:station) station_2 = create(:station, name: 'Union') station_3 = create(:station, name: 'Moes') trip_1 = create(:trip, start_station_id: station_1.id, end_station_id: station_2.id) trip_2 = create(:trip, start_station_id: station_1.id, end_station_id: station_2.id) trip_3 = create(:trip, start_station_id: station_1.id, end_station_id: station_3.id) trip_4 = create(:trip,start_station_id: station_3.id, end_station_id: station_1.id) visit station_path(station_1) expect(page).to have_content("Most frequent destination station from here #{station_2.name}") end it 'sees the most frequent origin for rides that end at this station' do station_1 = create(:station) station_2 = create(:station, name: 'Union') station_3 = create(:station, name: 'Moes') trip_1 = create(:trip, start_station_id: station_2.id, end_station_id: station_1.id) trip_2 = create(:trip, start_station_id: station_2.id, end_station_id: station_1.id) trip_3 = create(:trip, start_station_id: station_2.id, end_station_id: station_1.id) trip_4 = create(:trip,start_station_id: station_3.id, end_station_id: station_1.id) visit station_path(station_1) expect(page).to have_content("Most frequent origin station to here #{station_2.name}") end it 'seees the date with the most trips starting at the station' do station_1 = create(:station) station_2 = create(:station, name: 'Union') trip_1 = create(:trip, start_station_id: station_1.id, end_station_id: station_2.id, start_date: Date.today) trip_2 = create(:trip, start_station_id: station_1.id, end_station_id: station_2.id, start_date: Date.today) trip_3 = create(:trip,start_station_id: station_1.id, end_station_id: station_2.id, start_date: Date.yesterday) visit station_path(station_1) yuh = Date.today expect(page).to have_content("Date with the highest number of trips started here #{yuh.strftime('%b %d %Y')}") end it 'sees the most frequent zip code users entered on trips starting at this station' do station_1 = create(:station) station_2 = create(:station, name: 'Union') trip_1 = create(:trip, start_station_id: station_1.id, end_station_id: station_2.id, zip_code: 38112) trip_2 = create(:trip, start_station_id: station_1.id, end_station_id: station_2.id, zip_code: 38112) trip_3 = create(:trip, start_station_id: station_1.id, end_station_id: station_2.id, zip_code: 38104) visit station_path(station_1) expect(page).to have_content("Most Frequent Zip Code 38112") end it 'sees the bike id most frequently starting trips at the station' do station_1 = create(:station) station_2 = create(:station, name: 'Union') trip_1 = create(:trip, start_station_id: station_1.id, end_station_id: station_2.id, bike_id: 1) trip_2 = create(:trip, start_station_id: station_1.id, end_station_id: station_2.id, bike_id: 1) trip_3 = create(:trip, start_station_id: station_1.id, end_station_id: station_2.id, bike_id: 2) visit station_path(station_1) expect(page).to have_content("ID of bike most frequently starting trips here 1") end end end
require 'test_helper' class EmployerInfosControllerTest < ActionController::TestCase setup do @employer_info = employer_infos(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:employer_infos) end test "should get new" do get :new assert_response :success end test "should create employer_info" do assert_difference('EmployerInfo.count') do post :create, employer_info: { city: @employer_info.city, client_id: @employer_info.client_id, companyName: @employer_info.companyName, state: @employer_info.state } end assert_redirected_to employer_info_path(assigns(:employer_info)) end test "should show employer_info" do get :show, id: @employer_info assert_response :success end test "should get edit" do get :edit, id: @employer_info assert_response :success end test "should update employer_info" do patch :update, id: @employer_info, employer_info: { city: @employer_info.city, client_id: @employer_info.client_id, companyName: @employer_info.companyName, state: @employer_info.state } assert_redirected_to employer_info_path(assigns(:employer_info)) end test "should destroy employer_info" do assert_difference('EmployerInfo.count', -1) do delete :destroy, id: @employer_info end assert_redirected_to employer_infos_path end end
class AddAuthenticateToUsers < ActiveRecord::Migration[5.1] def self.up change_table :users do |t| t.string :encrypted_password, limit: 128 t.string :session_token, limit: 128 t.datetime :current_sign_in_at t.string :current_sign_in_ip, limit: 128 t.datetime :last_sign_in_at t.string :last_sign_in_ip, limit: 128 t.integer :sign_in_count end add_index :users, :email, unique: true add_index :users, :session_token end def self.down change_table :users do |t| t.remove :encrypted_password, :session_token, :current_sign_in_at, :current_sign_in_ip, :last_sign_in_at, :last_sign_in_ip, :sign_in_count end end end
def line(katz_deli) if katz_deli.count == 0 puts "The line is currently empty." else line = "The line is currently:" katz_deli.each_with_index do |value, index| line << " #{index + 1}. #{value}" end puts line end end def take_a_number(katz_deli, name) katz_deli.push(name) greeting = [] katz_deli.each_with_index do |name, position| greeting = "Welcome, #{name}. You are number #{position + 1} in line." end puts greeting end def now_serving(katz_deli) if katz_deli.count == 0 puts "There is nobody waiting to be served!" else first_name = katz_deli.shift() puts "Currently serving #{first_name}." end end
require "helpers/integration_test_helper" class TestRoutes < FogIntegrationTest def setup @subject = Fog::Compute[:google].routes end def test_all assert_operator(@subject.all.size, :>=, 2, "Number of all routes should be greater or equal than 2 - default GW and default routes") end def test_get @subject.all do |route| refute_nil @subject.get(route.name) end end def test_bad_get assert_nil @subject.get("bad-name") end def test_enumerable assert_respond_to @subject, :each end end
require 'test_helper' class GuarderiaControllerTest < ActionDispatch::IntegrationTest setup do @guarderium = guarderia(:one) end test "should get index" do get guarderia_url assert_response :success end test "should get new" do get new_guarderium_url assert_response :success end test "should create guarderium" do assert_difference('Guarderium.count') do post guarderia_url, params: { guarderium: { BUSQUEDA_CLIENTES_ADMINISTRADOR_IdAdministrador: @guarderium.BUSQUEDA_CLIENTES_ADMINISTRADOR_IdAdministrador, BUSQUEDA_CLIENTES_IdCliente: @guarderium.BUSQUEDA_CLIENTES_IdCliente, BUSQUEDA_IdBusqueda: @guarderium.BUSQUEDA_IdBusqueda, BUSQUEDA_PACIENTES_CLIENTES_ADMINISTRADOR_IdAdministrador: @guarderium.BUSQUEDA_PACIENTES_CLIENTES_ADMINISTRADOR_IdAdministrador, BUSQUEDA_PACIENTES_CLIENTES_IdCliente: @guarderium.BUSQUEDA_PACIENTES_CLIENTES_IdCliente, BUSQUEDA_PACIENTES_IdPacientes: @guarderium.BUSQUEDA_PACIENTES_IdPacientes, Codigo_Paciente: @guarderium.Codigo_Paciente, IdGuarderia: @guarderium.IdGuarderia, Nombre_Cliente: @guarderium.Nombre_Cliente, Nombre_Paciente: @guarderium.Nombre_Paciente, Tiempo_Estadia: @guarderium.Tiempo_Estadia } } end assert_redirected_to guarderium_url(Guarderium.last) end test "should show guarderium" do get guarderium_url(@guarderium) assert_response :success end test "should get edit" do get edit_guarderium_url(@guarderium) assert_response :success end test "should update guarderium" do patch guarderium_url(@guarderium), params: { guarderium: { BUSQUEDA_CLIENTES_ADMINISTRADOR_IdAdministrador: @guarderium.BUSQUEDA_CLIENTES_ADMINISTRADOR_IdAdministrador, BUSQUEDA_CLIENTES_IdCliente: @guarderium.BUSQUEDA_CLIENTES_IdCliente, BUSQUEDA_IdBusqueda: @guarderium.BUSQUEDA_IdBusqueda, BUSQUEDA_PACIENTES_CLIENTES_ADMINISTRADOR_IdAdministrador: @guarderium.BUSQUEDA_PACIENTES_CLIENTES_ADMINISTRADOR_IdAdministrador, BUSQUEDA_PACIENTES_CLIENTES_IdCliente: @guarderium.BUSQUEDA_PACIENTES_CLIENTES_IdCliente, BUSQUEDA_PACIENTES_IdPacientes: @guarderium.BUSQUEDA_PACIENTES_IdPacientes, Codigo_Paciente: @guarderium.Codigo_Paciente, IdGuarderia: @guarderium.IdGuarderia, Nombre_Cliente: @guarderium.Nombre_Cliente, Nombre_Paciente: @guarderium.Nombre_Paciente, Tiempo_Estadia: @guarderium.Tiempo_Estadia } } assert_redirected_to guarderium_url(@guarderium) end test "should destroy guarderium" do assert_difference('Guarderium.count', -1) do delete guarderium_url(@guarderium) end assert_redirected_to guarderia_url end end
class Category < ApplicationRecord has_many :items validates :name, uniqueness: true end
#!/usr/bin/ruby require "mysql2" require_relative "SampleWeights" class WaterSample def initialize(id, site, chloroform = 0, bromoform = 0, bromodichloromethane = 0, dibromichloromethane = 0) @id = id @site = site @chloroform = chloroform @bromoform = bromoform @bromodichloromethane = bromodichloromethane @dibromichloromethane = dibromichloromethane @factors = {} end attr_reader :id attr_reader :site attr_reader :chloroform attr_reader :bromoform attr_reader :bromodichloromethane attr_reader :dibromichloromethane def self.find(sample_id) begin connection = Mysql2::Client.new(:host => "localhost", :username => "carjam", :password => "XYZ") #consider external connection pooling for extensibility dao = WaterSampleDAO.new(connection) return dao.findWhereIdEquals(sample_id) rescue Mysql2::Error => e puts e.errno puts e.error ensure connection.close if connection end end # get the calc'd factor by the given id for weights def factor(weight_id) cachedVal = @factors[weight_id] if(cachedVal) return cachedVal else #go get the weights from the DB by id weights = SampleWeights.find(weight_id) #calculate and add to collection if not nil calcVal = calculateFactor(weights) if(calcVal) @factors[weight_id] = calcVal end return calcVal end end def to_hash #get all weights from DB allWeights = SampleWeights.find(nil) #we should consider adding a versioning mechanism to make sure our data is not out of data - is this the schema_migration table? #add all new values to the collection allWeights.each do |row| cachedVal = @factors[row.id] unless(cachedVal) calcVal = calculateFactor(row) if(calcVal) @factors[row.id] = calcVal end end end #now convert to hash and return using reflection return Hash[*instance_variables.map { |v| [v.to_sym, instance_variable_get(v)] }.flatten] end private #formula is assumed - need to confirm requirements def calculateFactor(weights) if(weights) calcdFactor = (weights.chloroform_weight * @chloroform) + (weights.bromoform_weight * @bromoform) + (weights.bromodichloromethane_weight * @bromodichloromethane) + (weights.dibromichloromethane_weight * @dibromichloromethane) return calcdFactor else return nil #a nil return value for nil input gives us more information than returning a 0 end end end
require_relative 'train' class PassangerTrain < Train def initialize(company_name, number) @type = :passenger_train super end def add_wagon(company_name = 'unknown') if speed.zero? wagon = PassangerWagon.new(company_name) self.wagon << wagon else puts 'Поезд всё еще в движении, не возможно добавить вагон' end end end
class Panel::BaseController < ApplicationController layout 'application_panel' before_action :authenticate_user! end
class HomeController < ApplicationController def index if guest_signed_in? @home_bg = 'home-in-bg' @title = "Welcome, #{current_guest.first_name}" else @title = 'Home' @home_bg = 'home-bg' end end end
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::ActiveRecordEnum, active_record: true do it_behaves_like 'a generic field type', :string_enum_field describe '#pretty_value' do context 'when column name is format' do before do class FormatAsEnum < FieldTest enum format: {Text: 'txt', Markdown: 'md'} end end let(:field) do RailsAdmin.config(FormatAsEnum).fields.detect do |f| f.name == :format end.with(object: FormatAsEnum.new(format: 'md')) end it 'does not break' do expect(field.pretty_value).to eq 'Markdown' end end end end
class Step100Proc < ActiveRecord::Migration def up connection.execute(%q{ CREATE OR REPLACE FUNCTION public.proc_step_100( process_representative integer, experience_period_lower_date date, experience_period_upper_date date, current_payroll_period_lower_date date, current_payroll_period_upper_date date) RETURNS void AS $BODY$ DECLARE run_date timestamp := LOCALTIMESTAMP; BEGIN /* UPDATED FROM NEW PIRS FILES MONDAY, DECEMBER 5, 2015 */ -- STEP 1 A -- CREATE FINAL EMPLOYER DEMOGRAPHICS INSERT INTO final_employer_demographics_informations ( representative_number, policy_number, valid_policy_number, current_coverage_status, coverage_status_effective_date, federal_identification_number, business_name, trading_as_name, valid_mailing_address, mailing_address_line_1, mailing_address_line_2, mailing_city, mailing_state, mailing_zip_code, mailing_zip_code_plus_4, mailing_country_code, mailing_county, valid_location_address, location_address_line_1, location_address_line_2, location_city, location_state, location_zip_code, location_zip_code_plus_4, location_country_code, location_county, currently_assigned_clm_representative_number, currently_assigned_risk_representative_number, currently_assigned_erc_representative_number, currently_assigned_grc_representative_number, immediate_successor_policy_number, immediate_successor_business_sequence_number, ultimate_successor_policy_number, ultimate_successor_business_sequence_number, employer_type, coverage_type, policy_employer_type, policy_coverage_type, data_source, created_at, updated_at ) (Select representative_number, policy_number, valid_policy_number, REGEXP_REPLACE(current_coverage_status, '\s+$', ''), coverage_status_effective_date, federal_identification_number, REGEXP_REPLACE(business_name, '\s+$', ''), REGEXP_REPLACE(trading_as_name, '\s+$', ''), valid_mailing_address, REGEXP_REPLACE(mailing_address_line_1, '\s+$', ''), REGEXP_REPLACE(mailing_address_line_2, '\s+$', ''), REGEXP_REPLACE(mailing_city, '\s+$', ''), REGEXP_REPLACE(mailing_state, '\s+$', ''), mailing_zip_code, mailing_zip_code_plus_4, mailing_country_code, mailing_county, valid_location_address, REGEXP_REPLACE(location_address_line_1, '\s+$', ''), REGEXP_REPLACE(location_address_line_2, '\s+$', ''), REGEXP_REPLACE(location_city, '\s+$', ''), REGEXP_REPLACE(location_state, '\s+$', ''), location_zip_code, location_zip_code_plus_4, location_country_code, location_county, currently_assigned_clm_representative_number, currently_assigned_risk_representative_number, currently_assigned_erc_representative_number, currently_assigned_grc_representative_number, immediate_successor_policy_number, immediate_successor_business_sequence_number, ultimate_successor_policy_number, ultimate_successor_business_sequence_number, employer_type, coverage_type, CASE WHEN employer_type = 'PA ' THEN 'private_account' WHEN employer_type = 'PEC' THEN 'public_employer_county' WHEN employer_type = 'PES' THEN 'public_employer_state' end as policy_employer_type, CASE WHEN coverage_type = 'SF' THEN 'state_fund' WHEN coverage_type = 'SI' THEN 'self_insured' WHEN coverage_type = 'BL' THEN 'black_lung' WHEN coverage_type = 'ML' THEN 'marine_fund' end as policy_coverage_type, 'bwc' as data_source, run_date as created_at, run_date as updated_at FROM public.pdemo_detail_records WHERE representative_number = process_representative ); -- STEP 1B -- CREATE POLICY COVERAGE HISTORY FROM SC220 Insert into process_policy_coverage_status_histories ( representative_number, policy_number, coverage_status, coverage_effective_date, coverage_end_date, data_source, created_at, updated_at ) (SELECT representative_number, policy_number, coverage_status, coverage_status_effective_date, coverage_status_end_date, 'bwc' as data_source, run_date as created_at, run_date as updated_at FROM pcovg_detail_records WHERE coverage_status_effective_date is not null and representative_number = process_representative ORDER BY policy_number, coverage_status_effective_date DESC ); -- UPDATE LAPSE PERIOD Update public.process_policy_coverage_status_histories pcsh set (lapse_days, updated_at) = (t2.lapse_days, t2.updated_at) FROM (SELECT a.representative_number, a.policy_number, a.coverage_effective_date, a.coverage_end_date, a.coverage_status, (CASE WHEN a.coverage_status = 'LAPSE' and a.coverage_end_date is not null Then (a.coverage_end_date - a.coverage_effective_date) WHEN a.coverage_status = 'LAPSE' and a.coverage_end_date is null THEN (run_date::date - a.coverage_effective_date) WHEN a.coverage_status = 'LAPSE' and a.coverage_end_date is null THEN (run_date::date - a.coverage_effective_date) ELSE '0'::integer END) as lapse_days, run_date as updated_at FROM public.process_policy_coverage_status_histories a WHERE a.representative_number = process_representative ) t2 WHERE pcsh.representative_number = t2.representative_number and pcsh.policy_number = t2.policy_number and pcsh.coverage_effective_date = t2.coverage_effective_date and pcsh.coverage_end_date = t2.coverage_end_date and pcsh.coverage_status = t2.coverage_status; -- UPDATE current coverage status periods that are lapse with the number of days they have been lapse. Update public.process_policy_coverage_status_histories pcsh set (lapse_days, updated_at) = (t2.lapse_days, t2.updated_at) FROM (SELECT a.representative_number, policy_type, a.policy_number, a.coverage_effective_date, a.coverage_end_date, a.coverage_status, (run_date::date - a.coverage_effective_date) as lapse_days, run_date as updated_at FROM public.process_policy_coverage_status_histories a WHERE a.coverage_end_date is null and a.coverage_status = 'LAPSE' and a.representative_number = process_representative ) t2 WHERE pcsh.policy_number = t2.policy_number and pcsh.coverage_effective_date = t2.coverage_effective_date and pcsh.coverage_status = t2.coverage_status ; -- 65 milliseconds UPDATE public.final_employer_demographics_informations edi SET (policy_creation_date, updated_at) = (t2.min_coverage_effective_date, t2.updated_at) FROM ( SELECT a.representative_number, a.policy_number, MIN(a.coverage_effective_date) as min_coverage_effective_date, current_timestamp as updated_at FROM public.process_policy_coverage_status_histories a GROUP BY a.representative_number, a.policy_number ) t2 WHERE edi.policy_number = t2.policy_number; end; $BODY$ LANGUAGE plpgsql; }) end def down connection.execute(%q{ DROP FUNCTION public.proc_step_100(integer, date, date, date, date); }) end end
module Alf class Environment # # Specialization of Environment to work on files of a given folder. # # This kind of environment resolves datasets by simply looking at # recognized files in a specific folder. "Recognized" files are simply # those for which a Reader subclass has been previously registered. # This environment then serves reader instances. # class Folder < Environment # # (see Environment.recognizes?) # # Returns true if args contains onely a String which is an existing # folder. # def self.recognizes?(args) (args.size == 1) && args.first.is_a?(String) && File.directory?(args.first.to_s) end # # Creates an environment instance, wired to the specified folder. # # @param [String] folder path to the folder to use as dataset source # def initialize(folder) @folder = folder end # (see Environment#dataset) def dataset(name) if file = find_file(name) Reader.reader(file, self) else raise NoSuchDatasetError, "No such dataset #{name} (#{@folder})" end end protected def find_file(name) # TODO: refactor this, because it allows getting out of the folder if File.exists?(name.to_s) name.to_s elsif File.exists?(explicit = File.join(@folder, name.to_s)) && File.file?(explicit) explicit else Dir[File.join(@folder, "#{name}.*")].find do |f| File.file?(f) end end end Environment.register(:folder, self) end # class Folder end # class Environment end # module Alf
Given(/^open page ([^"]*)$/) do |url| DRIVER.get(url) end When(/^create screenshot$/) do screenshot end And(/^input to search line "([^"]*)"$/) do |text| DRIVER.find_element(:css, '.gLFyf.gsfi').send_keys(text) end And(/^push a keyboard "([^"]*)"$/) do |key| DRIVER.action.send_keys(elementVisible, :return).perform if key == 'ENTER' end Then(/^click button "([^"]*)"$/) do |arg| DRIVER.find_element(:css, '[name="btnK"]').click end Then(/^block searched is visible$/) do expect(DRIVER.find_element(:id, 'search').displayed?).to be true end Given(/^set timeout (\d+)$/) do |seconds| DRIVER.manage.timeouts.implicit_wait = seconds end
When(/^I make a request after logging in$/) do User.create!(email: 'bob@example.com', password: 'secret') page.driver.post "/api/authenticate", { email: 'bob@example.com', password: 'secret' } @last_response = page.driver.get "/api/jobs" end When(/^I make a request without logging in$/) do @last_response = page.driver.get "/api/jobs" end Then(/^I should receive an ok response$/) do ValidateResponse.with(@last_response) .expect_status(:ok) end Then(/^I should receive an unauthorized response$/) do ValidateResponse.with(@last_response) .expect_status(:unauthorized) end
# frozen_string_literal: true Factory.define(:product) do |f| f.name { fake(:commerce, :product_name) } f.price { fake(:commerce, :price).to_d } f.quantity_in_stock { fake(:number, :within, range: 1..10) } end
And(/^I fill in item mass edit fields:$/) do |table| table.raw.each do |label, value| field = label.gsub(' ', '_').underscore check "mass_action_allow_blank_#{field}" fill_in "mass_action_#{field}", with: value end end
class ChangeVisitorTeamIdToBeStringInGames < ActiveRecord::Migration[6.0] def change change_column :games, :visitor_team_id, :string end end
class AddUuidToFaxAccounts < ActiveRecord::Migration def change add_column :fax_accounts, :uuid, :string end end
module Report module Timelog class TaskTimelogGeneralInfo def data *args task_id = args.first timelogs = ::Timelog.eager_load(:user).where("task_id = ? AND stopped_at IS NOT NULL", task_id) count = timelogs.count total_time = 0 total_time = timelogs.collect { |t| t.stopped_at - t.started_at }.inject(:+) total_users = timelogs.group_by {|t| t.user_id}.count [total_users, count, total_time] end end end end
Rails.application.routes.draw do devise_for :users, skip: [:registrations] # defaults to dashboard root :to => redirect('/singleview') # view routes get '/singleview' => 'singleview#index' resources :pieces do collection do get :archived end post 'restore' end resources :clients do collection do get :archived end post 'restore' end resources :users do collection do get :archived end post 'restore' end end
# Pling Plang Plong # # Write a program that converts a number to a string per the following rules: # # If the number contains 3 as a factor, output 'Pling'. If the number contains 5 as a factor, output 'Plang'. If the number contains 7 as a factor, output 'Plong'. # # If the number does not contain 3, 5, or 7 as a factor, simply return the string representation of the number itself. # # E.g. # # The number 28 is divisible by 7, so... # # # => "Plong" # The number 1755 is divisible by 3 and 5, so... # # # => "PlingPlang" # The number 34 is not divisible by 3,5 or 7, so... # # # => "34" # THE REAL ANSWER #make a function and define it. same as javascript puts "Please enter a number" input = gets.chomp def raindrops ( number ) # make an empty string str = "" # divisible by 3 add and answer PlingPlang # if number % 3 == 0 # str += "Pling" # end # if you are doing something simple you can write everything on one line # once it gets longer it's too unreadable str += "Pling" if number % 3 == 0 str += "Plang" if number % 5 == 0 str += "Plong" if number % 7 == 0 # implicit return. gives us the last line in the answer # p str # p number return str unless str.empty? number end #raindrop # puts "#{ input }" puts raindrops input # # MY ANSWER # puts "Welcome to Pling Plang Plong" # # puts "Please enter a number" # number = gets.to_i # # string_number = number.to_s # # #make your empty variable to store in # puts "" # sound = gets.chomp # # # if number % 3 == 0 # sound "Pling " # puts sound # end # if number % 5 == 0 # sound "Plang " # puts sound # end # if number % 7 == 0 # sound "Plong " # puts sound # else # puts "Is this a string? #{ string_number }" # end # ANSWER NUMBER 1 # if number % 3 == 0 && number % 5 == 0 && number % 7 == 0 # puts "Pling Plang plong" # elsif number % 7 == 0 && number % 5 == 0 # puts "Plong Plang" # elsif number % 7 == 0 && number % 3 == 0 # puts "Pling Plong" # elsif number % 5 == 0 && number % 3 == 0 # puts "Pling Plang" # elsif number % 7 == 0 # puts "Plong" # elsif number % 5 == 0 # puts "Plang" # elsif number % 3 == 0 # puts "Pling" # else # puts "Is this a string? #{ string_number } " # end # # # # if number % 3 == 0 # # puts "Pling" # # elsif number % 5 == 0 # # puts "Plang" # # elsif number % 7 == 0 # # puts "Plong" # else # puts "#{ number }" # end
class Director extend Creation::ClassMethods include Creation::InstanceMethods attr_accessor :name attr_reader :movies @@all = [] def initialize(name) @name = name @movies = [] @@all << self end def add_movie(movie) if !@movies.include?(movie) @movies << movie end if !movie.directors.include?(self) movie.directors << self end end def self.all @@all end end
class GigsController < ApplicationController def index @gigs = Gig.asc(:created_at) end end
# Strings like 'yes' and 'true' and '1' are true; other stuff is false class String def to_bool if to_i.zero? %w[yes y true on].any? {|s| s == downcase} else true # strings like "1" end end end # 0 is false; other number true class Integer # rubocop: disable Lint/UnifiedInteger def to_bool nonzero? end end # nil is false class NilClass def to_bool false end end # true is true class TrueClass def to_bool true end end # false is false class FalseClass def to_bool false end end
# lib/vagrant-yml/plugin.rb require "vagrant" module VagrantPlugins module VagrantJson class Plugin < Vagrant.plugin('2') name 'VagrantJson' description "The `json` command gives you a starting point for json configurations" config(:json) do require_relative "config/json" Config::Json end command("json") do require File.expand_path("../command/root", __FILE__) Command::Root end end # end Plugin end # => end VagrantYml end # => end
require 'test_helper' class UUIDTest < ActiveSupport::TestCase # test that all models the have a uuid column included the HasUuid module def test_has_uuid_with_database Rails.application.eager_load! ApplicationRecord.descendants.each do |model| table_uuid_column_exists = model.column_names.include?("uuid") model_include_has_uuid = model.included_modules.include?(HasUuid) error_message = "table #{model.table_name} #{table_uuid_column_exists ? 'has' : "doesn't have"} uuid column," \ "but model #{model_include_has_uuid ? 'includes' : "doesn't include"} HasUuid module" assert_equal( table_uuid_column_exists, model_include_has_uuid, error_message ) end end def test_on_create_initialize_uuid Rails.application.eager_load! ApplicationRecord.descendants.select { |c| c.included_modules.include? HasUuid }.map do |model| factory_name = model.name.underscore.to_sym record = FactoryBot.build(factory_name) assert_nil record.uuid record.save! assert_not_nil record.uuid end end end
require_dependency "account_controller" module PluginStronger module AccountController # Maximum number of failed attempts before locking MAX_FAILED_ATTEMPTS = 5 LOCKED_FOR_MINUTES = 20 # Patch #invalid_credentials to add a brute force attack counter # # The counter increments each time the user logs in with a bad password. When # the counter reaches the max failed attemps limit, it locks the account. def invalid_credentials if user = User.active.find_by_login(params[:username].to_s) #increment brute-force counter set_brute_force_counter(user, get_brute_force_counter(user) + 1) #lock the user immediately if detecting a brute force attack if brute_forcing?(user) set_brute_force_lock_time(user, Time.now + LOCKED_FOR_MINUTES.minutes) user.update_attribute(:lock_comment, "Locked at #{Time.now} after #{MAX_FAILED_ATTEMPTS} erroneous password") user.lock! end end # original action super flash.now[:error] = l(:notice_account_invalid_credentials_or_locked) unless Rails.env == 'test' end def account_locked(user, redirect_path=signin_path) if get_brute_force_lock_time(user)&.past? # reactivate user when lock time is past user.update_attribute(:lock_comment, nil) user.activate! set_brute_force_lock_time(user, nil) successful_authentication(user) else flash[:error] = l(:notice_account_invalid_credentials_or_locked) redirect_to redirect_path end end # Patch #successful_authentication to reset brute force attack counter # # On successful authentication, brute_force_counter should be reset to 0 so # that user won't have problems the next time he mistakenly fills his # password. def successful_authentication(user) set_brute_force_counter(user, 0) super end private def brute_forcing?(user) user.pref[:brute_force_counter].to_i >= MAX_FAILED_ATTEMPTS end def set_brute_force_counter(user, value) pref = user.pref pref[:brute_force_counter] = value pref.save end def get_brute_force_counter(user) user.pref[:brute_force_counter].to_i end def set_brute_force_lock_time(user, time) pref = user.pref pref[:brute_force_lock_time] = time pref.save end def get_brute_force_lock_time(user) user.pref[:brute_force_lock_time] end end end AccountController.prepend PluginStronger::AccountController