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
38058db5890d94a23e58e07cfc762d8f86229ef8
1,323
# encoding: utf-8 require 'spec_helper' describe 'ButtonAction', 'when submitting' do include FormtasticSpecHelper before do @output_buffer = '' mock_everything concat(semantic_form_for(@new_post) do |builder| concat(builder.action(:submit, :as => :button)) end) end it 'should render a submit type of button' do output_buffer.should have_tag('button[@type="submit"].btn') end end describe 'ButtonAction', 'when resetting' do include FormtasticSpecHelper before do @output_buffer = '' mock_everything concat(semantic_form_for(@new_post) do |builder| concat(builder.action(:reset, :as => :button)) end) end it 'should render a reset type of button' do output_buffer.should have_tag('button[@type="reset"].btn', :text => "Reset Post") end it 'should not render a value attribute' do output_buffer.should_not have_tag('button[@value].btn') end end describe 'InputAction', 'when cancelling' do include FormtasticSpecHelper before do @output_buffer = '' mock_everything end it 'should raise an error' do lambda { concat(semantic_form_for(@new_post) do |builder| concat(builder.action(:cancel, :as => :button)) end) }.should raise_error(Formtastic::UnsupportedMethodForAction) end end
20.671875
85
0.69161
f8bdd5920bc9143b6739fa38b0b5decc1e492d8a
877
cask "itsycal" do if MacOS.version <= :el_capitan version "0.10.16" sha256 "dbf1b104c7a3a2ca3ead9879145cb0557955c29d53f35a92b42f48e68122957c" elsif MacOS.version <= :high_sierra version "0.11.17" sha256 "fda1ba5611deaf4d5b834118b3af37ea9c5d08d1f8c813d04e7dd0552a270e11" appcast "https://itsycal.s3.amazonaws.com/itsycal.xml" else version "0.12.4" sha256 "ce787786ac7631417f2fa9911773233733942031a979a939f0fb2d6f4824a29f" appcast "https://itsycal.s3.amazonaws.com/itsycal.xml" end # itsycal.s3.amazonaws.com/ was verified as official when first introduced to the cask url "https://itsycal.s3.amazonaws.com/Itsycal-#{version}.zip" name "Itsycal" desc "Menu bar calendar" homepage "https://www.mowglii.com/itsycal/" auto_updates true app "Itsycal.app" zap trash: "~/Library/Preferences/com.mowglii.ItsycalApp.plist" end
32.481481
88
0.758267
7a83d7f20a33660151badb4ca01ad2774b4be9aa
4,052
#!/usr/bin/env rspec require 'spec_helper' # We use this as a reasonable way to obtain all the support infrastructure. [:user, :group].each do |type_for_this_round| provider_class = Puppet::Type.type(type_for_this_round).provider(:directoryservice) describe provider_class do before do @resource = stub("resource") @provider = provider_class.new(@resource) end it "[#6009] should handle nested arrays of members" do current = ["foo", "bar", "baz"] desired = ["foo", ["quux"], "qorp"] group = 'example' @resource.stubs(:[]).with(:name).returns(group) @resource.stubs(:[]).with(:auth_membership).returns(true) @provider.instance_variable_set(:@property_value_cache_hash, { :members => current }) %w{bar baz}.each do |del| @provider.expects(:execute).once. with([:dseditgroup, '-o', 'edit', '-n', '.', '-d', del, group]) end %w{quux qorp}.each do |add| @provider.expects(:execute).once. with([:dseditgroup, '-o', 'edit', '-n', '.', '-a', add, group]) end expect { @provider.set(:members, desired) }.should_not raise_error end end end describe 'DirectoryService.single_report' do it 'should fail on OS X < 10.4' do Puppet::Provider::NameService::DirectoryService.stubs(:get_macosx_version_major).returns("10.3") lambda { Puppet::Provider::NameService::DirectoryService.single_report('resource_name') }.should raise_error(RuntimeError, "Puppet does not support OS X versions < 10.4") end it 'should use url data on 10.4' do Puppet::Provider::NameService::DirectoryService.stubs(:get_macosx_version_major).returns("10.4") Puppet::Provider::NameService::DirectoryService.stubs(:get_ds_path).returns('Users') Puppet::Provider::NameService::DirectoryService.stubs(:list_all_present).returns( ['root', 'user1', 'user2', 'resource_name'] ) Puppet::Provider::NameService::DirectoryService.stubs(:generate_attribute_hash) Puppet::Provider::NameService::DirectoryService.stubs(:execute) Puppet::Provider::NameService::DirectoryService.expects(:parse_dscl_url_data) Puppet::Provider::NameService::DirectoryService.single_report('resource_name') end it 'should use plist data on > 10.4' do Puppet::Provider::NameService::DirectoryService.stubs(:get_macosx_version_major).returns("10.5") Puppet::Provider::NameService::DirectoryService.stubs(:get_ds_path).returns('Users') Puppet::Provider::NameService::DirectoryService.stubs(:list_all_present).returns( ['root', 'user1', 'user2', 'resource_name'] ) Puppet::Provider::NameService::DirectoryService.stubs(:generate_attribute_hash) Puppet::Provider::NameService::DirectoryService.stubs(:execute) Puppet::Provider::NameService::DirectoryService.expects(:parse_dscl_plist_data) Puppet::Provider::NameService::DirectoryService.single_report('resource_name') end end describe 'DirectoryService.get_exec_preamble' do it 'should fail on OS X < 10.4' do Puppet::Provider::NameService::DirectoryService.stubs(:get_macosx_version_major).returns("10.3") lambda { Puppet::Provider::NameService::DirectoryService.get_exec_preamble('-list') }.should raise_error(RuntimeError, "Puppet does not support OS X versions < 10.4") end it 'should use url data on 10.4' do Puppet::Provider::NameService::DirectoryService.stubs(:get_macosx_version_major).returns("10.4") Puppet::Provider::NameService::DirectoryService.stubs(:get_ds_path).returns('Users') Puppet::Provider::NameService::DirectoryService.get_exec_preamble('-list').should include("-url") end it 'should use plist data on > 10.4' do Puppet::Provider::NameService::DirectoryService.stubs(:get_macosx_version_major).returns("10.5") Puppet::Provider::NameService::DirectoryService.stubs(:get_ds_path).returns('Users') Puppet::Provider::NameService::DirectoryService.get_exec_preamble('-list').should include("-plist") end end
41.346939
103
0.708292
4af263a667669b2f1fb4924872b5f1a9af9dc835
728
require 'rails_helper' RSpec.describe 'parties/index', vcr: true do before do assign(:people, []) assign(:parties, [double(:party, name: 'Conservative', graph_id: 'jF43Jxoc')]) assign(:letters, 'A') controller.params = { letter: 'a' } render end context 'header' do it 'will render the correct header' do expect(rendered).to match(/Current and former parties and groups/) end end context 'partials' do it 'will render pugin/components/_navigation-letter' do expect(response).to render_template(partial: 'pugin/components/_navigation-letter') end it 'will render _party_list' do expect(response).to render_template(partial: '_party_list') end end end
26
89
0.684066
e8e0cf4344f97e81878aa20255d83ed49c8a3ebc
1,117
Pod::Spec.new do |s| s.name = 'RedPacketAliAuthUI' s.version = '2.0.1' s.summary = 'RedPacketAliAuthUI' s.description = <<-DESC * RedPacketAliAuthUI. * Redpacket * Alipay * 支付宝支付 * 红包SDK * 收红包直接到支付宝账户 DESC s.homepage = 'http://yunzhanghu.com' s.license = { :type => 'MIT' , :file => "LICENSE" } s.author = { 'Mr.Yang' => '[email protected]' } s.source = { :git => 'https://github.com/YunzhanghuOpen/cocoapods-redpacket-ui.git', :tag => "#{s.version}" } s.platform = :ios, '7.0' s.requires_arc = true s.xcconfig = {'OTHER_LDFLAGS' => '-ObjC'} s.source_files = 'RedPacketAliAuthUI/**/*.{h,m}' s.resources = ['resources/*.bundle'] s.frameworks = 'AudioToolbox' s.documentation_url = 'https://docs.yunzhanghu.com/integration/ios.html' #红包SDKAPI层依赖 # s.dependency 'RedpacketAliAuthAPILib' #支付宝SDK依赖 s.dependency 'RPAlipayLib' end
33.848485
121
0.521038
21365d91ae6723174626fac75689e678d2519c6d
262
require 'rails_helper' RSpec.describe "Api::V1::Follows", type: :request do describe "GET /api/v1/follows" do it "works! (now write some real specs)" do get api_v1_follows_index_path expect(response).to have_http_status(200) end end end
23.818182
52
0.70229
6a80e3061bb003b477af19bcb2010e685c57fc5d
2,939
class UsersController < ApplicationController before_filter :skip_first_page, only: :new before_filter :handle_ip, only: :create before_filter :fetch_user, only: :show def new @bodyId = 'home' @is_mobile = mobile_device? @user = User.new respond_to do |format| format.html # new.html.erb end end def create ref_code = cookies[:h_ref] email = params[:user][:email] first_name = params[:user][:first_name] @user = User.new(email: email, first_name: first_name) @user.referrer = User.find_by_referral_code(ref_code) if ref_code if @user.save @user.update_attributes(:referrer_id => @user.id) if ref_code.blank? cookies[:h_email] = { value: @user.email } redirect_to user_path(@user.referral_code), notice: "Please check your email for the referral unique link" else if email.blank? logger.info("Error saving user with email, email is empty") flash[:error] = "Please enter email" else errors = "" errors += flatten_errors(@user.errors) if [email protected]? flash[:error] = errors logger.info("Error saving user with email, #{email}") end redirect_to root_path end end def refer @bodyId = 'refer' @is_mobile = mobile_device? @user = User.find_by_email(cookies[:h_email]) respond_to do |format| if @user.nil? format.html { redirect_to root_path, alert: 'Something went wrong!' } else format.html # refer.html.erb end end end def policy end def redirect redirect_to root_path, status: 404 end def show if @user.blank? redirect_to root_path, alert: 'Your referral code is does not match!' else render "refer" end end private def skip_first_page return if Rails.application.config.ended email = cookies[:h_email] if email && User.find_by_email(email) redirect_to '/refer-a-friend' else cookies.delete :h_email end end def fetch_user @user = User.find_by(referral_code: params[:id]) end def handle_ip # Prevent someone from gaming the site by referring themselves. # Presumably, users are doing this from the same device so block # their ip after their ip appears three times in the database. address = request.env['HTTP_X_FORWARDED_FOR'] return if address.nil? current_ip = IpAddress.find_by_address(address) if current_ip.nil? current_ip = IpAddress.create(address: address, count: 1) elsif current_ip.count > 2 logger.info('IP address has already appeared three times in our records. Redirecting user back to landing page.') flash[:error] = "Your IP address has reached the max entries. Your IP address has been blocked by the system." return redirect_to root_path else current_ip.count += 1 current_ip.save end end end
26.241071
116
0.664171
4a2bb881f0d2ce0a1231a9c8d299d22ac663fd98
353
RSpec.describe 'Class 8 Exercise 2' do let(:exercise2) do load File.expand_path('../../../lib/class8/exercise2.rb', __FILE__) end it 'follows the execution and displays a short message' do message = <<END Executing the method method_param is dinner Executing the block END expect { exercise2 }.to output(message).to_stdout end end
22.0625
71
0.719547
ab9ac525f67f289bcc37c6b6409103978792c408
1,867
# // 02/22/2012 # // 02/23/2012 # // Icy Engine Iliks $simport.r 'iei/magic_learn', '1.0.0', 'IEI Magic Learn' module IEI module MagicLearn module Mixins ; end end end module IEI::MagicLearn::Mixins::Battler def pre_init_iei super @magiclearn = {} end def init_iei super #init_magiclearn end def post_init_iei super # // Something else .x . init_magiclearn end # // def init_magiclearn @magiclearn = {} @skills.each { |id| @magiclearn[id] = 100 } end # // 02/23/2012 attr_reader :magiclearn def get_magiclearn(id) @magiclearn[id] || 0 end def get_magiclearn_r(id) get_magiclearn(id) / 100.0 end def change_magiclearn(id, n) @magiclearn[id] = n.clamp(0, 100) #puts "#{$data_skills[id].name} - #{@magiclearn[id]} / 100" magiclearn_learn_skill(id) end def inc_magiclearn(id, n) change_magiclearn(id, 0) unless @magiclearn.has_key?(id) change_magiclearn(id, @magiclearn[id] + n) end def dec_magiclearn(id, n) inc_magiclearn(id, -n) end def magiclearn_run_checks @magiclearn.keys.each{ |k| magiclearn_learn_skill(k) } end def magiclearn_learn_skill(skill_id) magiclearn_learn_skill!(skill_id) if magiclearn?(skill_id) end def magiclearn_learn_skill!(skill_id) @magiclearn[skill_id] = 100 ; learn_skill(skill_id) end def magiclearn?(id) return false if skill_learn?($data_skills[id]) # // . x . Might replace this return false unless @magiclearn.has_key?(id) return @magiclearn[id] >= 100 end # // 02/25/2012 def magiclearn_rate(item) 1 end def can_magiclearn?(item) return false if item.id < 20 return true end def use_item(item) super(item) if ExDatabase.skill?(item) && can_magiclearn?(item) inc_magiclearn(item.id,magiclearn_rate(item)) end end end
19.447917
80
0.664167
e979ff1a9cd593f0bebad497e0a6fb328eef5d9f
3,261
require 'spec_helper' describe Heartcheck::Checks::Firewall do let(:service_opts) { { port: 443, host: 'lala.com' } } let(:instance_default) { described_class.new.tap { |c| c.add_service service_opts } } describe '#services' do subject { described_class.new } it 'returns array of FirewallService' do subject.add_service(service_opts) expect(subject.services.first).to be_a(Heartcheck::Services::Firewall) end end describe '#uri_info' do context 'when multiple services are being checked' do before do subject.add_service(url: 'http://url1.com') subject.add_service(url: 'https://url2.com') subject.add_service(url: 'http://url3.com') end it 'returs a list os URI hashes' do result = subject.uri_info expect(result).to eq([{host: 'url1.com', port: 80, scheme: 'http'}, {host: 'url2.com', port: 443, scheme: 'https'}, {host: 'url3.com', port: 80, scheme: 'http'}]) end end end describe '#validate' do subject { instance_default } context 'without proxy' do context 'with success' do it 'calls Net::Telnet with valid params' do expect(Net::Telnet).to receive(:new).with('Port' => 443, 'Host' => 'lala.com', 'Timeout' => 2) subject.validate end end context 'with success' do before { allow(Net::Telnet).to receive(:new).and_raise(Timeout::Error.new) } it 'adds error message' do subject.validate expect(subject.instance_variable_get(:@errors)).to eq(['connection refused on: lala.com:443']) end it 'calls block when given' do subject = described_class.new.tap do |c| c.add_service(service_opts) c.on_error { |errors, service| errors << "Custom error message in port #{service.port}" } end subject.validate expect(subject.instance_variable_get(:@errors)).to eq(['Custom error message in port 443']) end end end context 'with proxy' do subject { described_class.new.tap { |c| c.add_service(port: 443, host: 'lala.com', proxy: 'http://uriproxy.com.br:8888') } } it 'calls Net::Telnet with valid params of proxy' do expect(Net::Telnet).to receive(:new).with('Port' => 8888, 'Host' => 'uriproxy.com.br', 'Timeout' => 2).ordered.and_return('proxy') expect(Net::Telnet).to receive(:new).with('Port' => 443, 'Host' => 'lala.com', 'Timeout' => 2, 'Proxy' => 'proxy').ordered subject.validate end context 'connection refused' do it 'avoid to adds errors array' do expect(Net::Telnet).to receive(:new).and_raise Errno::ECONNREFUSED.new subject.validate expect(subject.instance_variable_get(:@errors)).to be_empty end end context 'timeout' do it 'adds timeout to errors array' do expect(Net::Telnet).to receive(:new).and_raise Timeout::Error.new subject.validate expect(subject.instance_variable_get(:@errors)).to eq(['connection refused on: lala.com:443 via proxy: uriproxy.com.br:8888']) end end end end end
33.96875
138
0.609322
7aa0e7286bb4987b4e97efb783a6dcd56d1c83fb
3,152
# frozen_string_literal: true Capybara.add_selector(:disclosure) do def aria_or_real_button XPath.self(:button) | (XPath.attr(:role) == "button") end xpath do |name, **| button = aria_or_real_button & XPath.string.n.is(name.to_s) aria = XPath.descendant[XPath.attr(:id) == XPath.anywhere[button][XPath.attr(:"aria-expanded")].attr(:"aria-controls")] details = XPath.descendant(:details)[XPath.child(:summary)[XPath.string.n.is(name.to_s)]] aria + details end expression_filter(:expanded, :boolean) do |xpath, expanded| open = expanded ? XPath.attr(:open) : !XPath.attr(:open) button = XPath.anywhere[aria_or_real_button][XPath.attr(:"aria-expanded") == expanded.to_s] xpath[open | (button.attr(:"aria-controls") == XPath.attr(:id))] end describe_expression_filters do |expanded: nil, **| next if expanded.nil? expanded ? " expanded" : " closed" end end # Specifically selects the disclosure button # # find(:disclosure_button, "name").click Capybara.add_selector(:disclosure_button) do xpath do |name, **| XPath.descendant[[ (XPath.self(:button) | (XPath.attr(:role) == "button")), XPath.attr(:"aria-expanded"), XPath.string.n.is(name.to_s) ].reduce(:&)] + XPath.descendant(:summary)[XPath.string.n.is(name.to_s)] end expression_filter(:expanded, :boolean) do |xpath, expanded| open = expanded ? XPath.parent.attr(:open) : !XPath.parent.attr(:open) xpath[(XPath.attr(:"aria-expanded") == expanded.to_s) | open] end describe_expression_filters do |expanded: nil, **| next if expanded.nil? expanded ? " expanded" : " closed" end end module CapybaraAccessibleSelectors module Actions # Toggle a disclosure open or closed # # @param [String] locator The text of the button # @option options [Boolean] expand Set true to open, false to close, or nil to toggle # # @return [Capybara::Node::Element] The element clicked def toggle_disclosure(name = nil, expand: nil, **find_options) button = _locate_disclosure_button(name, **find_options) if expand.nil? button.click elsif button.tag_name == "summary" button.click if button.find(:xpath, "..")[:open] == expand elsif button[:"aria-expanded"] != (expand ? "true" : "false") button.click end end private def _locate_disclosure_button(name, **find_options) if is_a?(Capybara::Node::Element) && name.nil? return self if matches_selector?(:disclosure_button, wait: false) return find(:element, :summary, **find_options) if tag_name == "details" if matches_selector?(:disclosure, wait: false) return find(:xpath, XPath.anywhere[XPath.attr(:"aria-controls") == self[:id]], **find_options) end end find(:disclosure_button, name, **find_options) end end module Session # Limit supplied block to within a disclosure # # @param [String] Name Fieldset label # @param [Hash] options Finder options def within_disclosure(name, **options, &block) within(:disclosure, name, **options, &block) end end end
33.178947
123
0.665609
28806a88d1b31bd4e1090265b1fae048172dd26e
1,137
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## module MetasploitModule CachedSize = 1471264 include Msf::Payload::Single include Msf::Sessions::MeterpreterOptions include Msf::Sessions::MettleConfig def initialize(info = {}) super( update_info( info, 'Name' => 'Linux Meterpreter, Reverse HTTP 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_MIPSLE, 'License' => MSF_LICENSE, 'Handler' => Msf::Handler::ReverseHttp, 'Session' => Msf::Sessions::Meterpreter_mipsle_Linux ) ) end def generate opts = { scheme: 'http', stageless: true } MetasploitPayloads::Mettle.new('mipsel-linux-muslsf', generate_config(opts)).to_binary :exec end end
26.44186
96
0.596306
4a6106f583d4b6018a9750026521c2aa96120ef4
144
class Test array_testing = [1, 2, 3, 4, 5, 6] array_testing.each {|x| puts x} def hello_method (*_string_test) puts 'Hello' end end
18
36
0.645833
28ab38bc9f104a267e4c2334a16a5f9930fd47f4
173
class CreateEventUsers < ActiveRecord::Migration[5.1] def change create_table :event_users do |t| t.integer :event_id t.integer :user_id end end end
19.222222
53
0.687861
18e7203dab07fd73e97d6c2bb77a3803e9c951ba
3,134
module NestedLayoutTags include Radiant::Taggable class TagError < StandardError; end desc %{ Renders the contents of the tag inside of a "parent" layout, which is selected via the +name+ attribute. The contents of this tag are placed at a corresponding <r:content_for_layout/> tag within the parent layout. This tag is intended to be used within your layouts, and should only appear once per layout. *Usage:* <r:inside_layout name="master"> <div id="main-column"> <r:content_for_layout/> </div> </r:inside_layout> } tag 'inside_layout' do |tag| if name = tag.attr['name'] # Prepare the stacks tag.globals.nested_layouts_content_stack ||= [] tag.globals.nested_layouts_layout_stack ||= [] # Remember the original layout to support the +layout+ tag tag.globals.page_original_layout ||= tag.globals.page.layout # Remember the original layout # Find the layout name.strip! if layout = Layout.find_by_name(name) # Track this layout on the stack tag.globals.nested_layouts_layout_stack << name # Save contents of inside_layout for later insertion tag.globals.nested_layouts_content_stack << tag.expand # Set the page layout that Radiant should use for rendering, which is different than the actual # page's layout when layouts are nested. The final/highest +inside_layout+ tag will set or # overwrite this value for the last time. tag.globals.page.layout = layout tag.globals.page.render else raise TagError.new(%{Error (nested_layouts): Parent layout "#{name.strip}" not found for "inside_layout" tag}) end else raise TagError.new(%{Error (nested_layouts): "inside_layout" tag must contain a "name" attribute}) end end desc %{ Allows nested layouts to target this layout. The contents of <r:inside_layout> tag blocks in another layout will have their contents inserted at the location given by this tag (if they target this layout). This tag also behaves like a standard <r:content/> tag if this layout is specified directly by a page. This tag is intended to be used inside layouts. *Usage:* <html> <body> <r:content_for_layout/> </body> </html> } tag 'content_for_layout' do |tag| tag.globals.nested_layouts_content_stack ||= [] # return the saved content if any, or mimic a default +<r:content/>+ tag (render the body part) tag.globals.nested_layouts_content_stack.pop || tag.globals.page.render_snippet(tag.locals.page.part('body')) end desc %{ Return the layout name of the current page. *Usage:* <html> <body id="<r:layout/>" My body tag has an id corresponding to the layout I use. Sweet! </body> </html> } tag 'layout' do |tag| if layout = tag.globals.page_original_layout layout.name else if layout = tag.globals.page.layout layout.name else '' end end end end
31.979592
118
0.655073
612bbaa08cf110969053e8e94df7eab9206b952e
850
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'emd/version' require 'emd/post_message' Gem::Specification.new do |spec| spec.name = "emd" spec.version = Emd::VERSION spec.authors = ["Bryan Lim"] spec.email = ["[email protected]"] spec.summary = %q{Embedded markdown template for Ruby on Rails} spec.description = %q{mbedded markdown template for Ruby on Rails} spec.homepage = "" spec.license = "MIT" spec.require_paths = ["lib"] spec.post_install_message = Log::MESSAGE spec.files = Dir["{app,config,lib}/**/*", "LICENSE.txt", "README.md"] spec.add_runtime_dependency 'redcarpet' spec.add_development_dependency "bundler", "~> 1.11" spec.add_development_dependency "rake", "~> 10.0" end
36.956522
79
0.661176
bb4f391420a7cf7b7505eaf8f23e46850bf2d190
459
module DataSources class SniffersFactory < AbstractFactory # TODO handle file openning in other place. Handle file not exists and so on def records_set_builder DataSources::SniffersRecordsSetBuilder.new( routes_file: File.join(location, 'routes.csv'), node_times_file: File.join(location, 'node_times.csv'), sequences_file: File.join(location, 'sequences.csv'), passphrase: passphrase ) end end end
32.785714
80
0.705882
d5752d520793caf2065aebdc3f62d8207ce165c1
1,160
require 'dragonfly' module Refinery class Resource < Refinery::Core::BaseModel ::Refinery::Resources::Dragonfly.setup! include Resources::Validators resource_accessor :file validates :file, :presence => true validates_with FileSizeValidator delegate :ext, :size, :mime_type, :url, :to => :file # used for searching def type_of_content mime_type.split("/").join(" ") end # Returns a titleized version of the filename # my_file.pdf returns My File def title CGI::unescape(file_name.to_s).gsub(/\.\w+$/, '').titleize end class << self # How many resources per page should be displayed? def per_page(dialog = false) dialog ? Resources.pages_per_dialog : Resources.pages_per_admin_index end def create_resources(params) resources = [] unless params.present? and params[:file].is_a?(Array) resources << create(params) else params[:file].each do |resource| resources << create({:file => resource}.merge(params.except(:file))) end end resources end end end end
23.673469
80
0.627586
f8e791baefa17f0821055448fe3013886e11000e
4,460
class Ffmpeg < Formula desc "Play, record, convert, and stream audio and video" homepage "https://ffmpeg.org/" url "https://ffmpeg.org/releases/ffmpeg-4.4.1.tar.xz" sha256 "eadbad9e9ab30b25f5520fbfde99fae4a92a1ae3c0257a8d68569a4651e30e02" # None of these parts are used by default, you have to explicitly pass `--enable-gpl` # to configure to activate them. In this case, FFmpeg's license changes to GPL v2+. license "GPL-2.0-or-later" revision 3 head "https://github.com/FFmpeg/FFmpeg.git" livecheck do url "https://ffmpeg.org/download.html" regex(/href=.*?ffmpeg[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do sha256 arm64_monterey: "3f0fd439dab73037bf1577aeef75fe61693a8c7d231db15355685aa27d998503" sha256 arm64_big_sur: "595897c60fd28be047977306a35e53fc6f6f29b021af7b0ee542719bf892eca4" sha256 monterey: "d86a545fd61b459c1adafcec61bf1803f8f632fe527a88682af4fb89c37056fd" sha256 big_sur: "b3e866d21b8a51653e294e08c8be65e5095894f52f6cb6b914025992191c1c50" sha256 catalina: "ea2431a650ae91eb8ea197d7e1d8e82f50d5dfdaad08a0da7c067609e8b1922f" sha256 x86_64_linux: "a91fa175c2f2a47c9afd240bf2cf97064b14647077be5804da159b6a4244fe62" end depends_on "nasm" => :build depends_on "pkg-config" => :build depends_on "aom" depends_on "dav1d" depends_on "fontconfig" depends_on "freetype" depends_on "frei0r" depends_on "gnutls" depends_on "lame" depends_on "libass" depends_on "libbluray" depends_on "librist" depends_on "libsoxr" depends_on "libvidstab" depends_on "libvmaf" depends_on "libvorbis" depends_on "libvpx" depends_on "opencore-amr" depends_on "openjpeg" depends_on "opus" depends_on "rav1e" depends_on "rubberband" depends_on "sdl2" depends_on "snappy" depends_on "speex" depends_on "srt" depends_on "tesseract" depends_on "theora" depends_on "webp" depends_on "x264" depends_on "x265" depends_on "xvid" depends_on "xz" depends_on "zeromq" depends_on "zimg" uses_from_macos "bzip2" uses_from_macos "libxml2" uses_from_macos "zlib" on_linux do depends_on "libxv" end def install args = %W[ --prefix=#{prefix} --enable-shared --enable-pthreads --enable-version3 --cc=#{ENV.cc} --host-cflags=#{ENV.cflags} --host-ldflags=#{ENV.ldflags} --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libbluray --enable-libdav1d --enable-libmp3lame --enable-libopus --enable-librav1e --enable-librist --enable-librubberband --enable-libsnappy --enable-libsrt --enable-libtesseract --enable-libtheora --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libspeex --enable-libsoxr --enable-libzmq --enable-libzimg --disable-libjack --disable-indev=jack ] # libavresample has been deprecated and removed but some non-updated formulae are still linked to it # Remove in the next release args << "--enable-avresample" unless build.head? # Needs corefoundation, coremedia, corevideo args << "--enable-videotoolbox" if OS.mac? # Replace hardcoded default VMAF model path %w[doc/filters.texi libavfilter/vf_libvmaf.c].each do |f| inreplace f, "/usr/local/share/model", HOMEBREW_PREFIX/"share/libvmaf/model" # Since libvmaf v2.0.0, `.pkl` model files have been deprecated in favor of `.json` model files. inreplace f, "vmaf_v0.6.1.pkl", "vmaf_v0.6.1.json" end system "./configure", *args system "make", "install" # Build and install additional FFmpeg tools system "make", "alltools" bin.install Dir["tools/*"].select { |f| File.executable? f } # Fix for Non-executables that were installed to bin/ mv bin/"python", pkgshare/"python", force: true end test do # Create an example mp4 file mp4out = testpath/"video.mp4" system bin/"ffmpeg", "-filter_complex", "testsrc=rate=1:duration=1", mp4out assert_predicate mp4out, :exist? end end
29.536424
104
0.686099
91e38ed345bec5d78706a6bd4aa6c124c6479080
580
# Used by Prioritizer to adjust item quantities # see prioritizer_spec for use cases module Spree module Stock class Adjuster attr_accessor :variant, :need, :status def initialize(variant, quantity, status) @variant = variant @need = quantity @status = status end def adjust(item) if item.quantity >= need item.quantity = need @need = 0 elsif item.quantity < need @need -= item.quantity end end def fulfilled? @need == 0 end end end end
20
47
0.574138
260f16c3873629c0b11b8a51491a81b34678f287
1,417
class Hugo < Formula desc "Configurable static site generator" homepage "https://gohugo.io/" url "https://github.com/spf13/hugo/archive/v0.19.tar.gz" sha256 "f2d1926b226b4a5d64c4880538eb1bb47c84dd886152660d72c69269f7c5cf6f" head "https://github.com/spf13/hugo.git" bottle do cellar :any_skip_relocation sha256 "61d99bd31e79a83c1bd66db042293c9ffef6e504cb7fecc8f77b257675c4964c" => :sierra sha256 "bcf37ee1d81061a195007952ddc7741b71f3c3b3aefe772852336c1584f6a397" => :el_capitan sha256 "9fd791588839ca46721e78d918d8061d6ea99e810cf56f78fe35db94ef383816" => :yosemite end depends_on "go" => :build depends_on "govendor" => :build def install ENV["GOPATH"] = buildpath (buildpath/"src/github.com/spf13/hugo").install buildpath.children cd "src/github.com/spf13/hugo" do system "govendor", "sync" system "go", "build", "-o", bin/"hugo", "main.go" # Build bash completion system bin/"hugo", "gen", "autocomplete", "--completionfile=hugo.sh" bash_completion.install "hugo.sh" # Build man pages; target dir man/ is hardcoded :( (Pathname.pwd/"man").mkpath system bin/"hugo", "gen", "man" man1.install Dir["man/*.1"] prefix.install_metafiles end end test do site = testpath/"hops-yeast-malt-water" system "#{bin}/hugo", "new", "site", site assert File.exist?("#{site}/config.toml") end end
32.204545
92
0.697248
26a22792bac0fad6e4d766158833144c79a3d378
39
module Badger VERSION = "0.15.0" end
9.75
20
0.666667
215ce161def7f82d1dd0d373c4a7e390aabe3490
1,531
require 'spec_helper' describe Atrium::BrowseLevel do Given(:facet_name) { 'My Facet Name' } subject { Atrium::BrowseLevel.new(solr_facet_name: facet_name) } it_behaves_like "query_param_mixin" it { should belong_to :exhibit } it { should be_accessible :label } it { should be_accessible :level_number } it { should validate_presence_of :atrium_exhibit_id } it { should be_accessible :solr_facet_name } it { should validate_presence_of :solr_facet_name } it { should respond_to :selected } it { should respond_to :selected= } context '#values' do Then { subject.values.should be_kind_of Enumerable } end describe '#to_s' do Given(:comparison_string) { 'Hello'} When { subject.solr_facet_name = comparison_string } Then { subject.to_s.should == comparison_string } end describe '#label' do Given(:expected_label) { 'Hello World'} context 'override' do When{ subject.label = expected_label } Then{ subject.label.should == expected_label } end context 'lookup from configuration' do Given(:configured_expected_label) { 'Good-Bye World'} Given(:config) { double_config = double('Config') double_config.should_receive(:label_for_facet). with(facet_name).and_return(configured_expected_label) double_config } When{ subject.label = nil } Then { Atrium.should_receive(:config).and_return(config) subject.label.should == configured_expected_label } end end end
26.859649
66
0.693011
087b8cb5684bad1c1861ba19c9535d53f264e6ad
996
class CreateServiceProviders < ActiveRecord::Migration[4.2] def change create_table :service_providers do |t| t.string "issuer", null: false t.string "friendly_name" t.text "description" t.text "metadata_url" t.text "acs_url" t.text "assertion_consumer_logout_service_url" t.text "cert" t.text "logo" t.string "fingerprint" t.string "signature" t.string "block_encryption", default: 'aes256-cbc', null: false t.text "sp_initiated_login_url" t.text "return_to_sp_url" t.string "agency" t.json "attribute_bundle" t.string "redirect_uri" t.datetime "created_at" t.datetime "updated_at" t.boolean "active", default: false, null: false t.boolean "approved", default: false, null: false end add_index :service_providers, ["issuer"], name: "index_service_providers_on_issuer", unique: true, using: :btree end end
33.2
116
0.631526
381ee2305ab97f86142acc7c20ddf24de22dba42
289
class CompaniesProjects < ActiveRecord::Migration def self.up create_table :companies_projects, :force => true, :id => false do |t| t.belongs_to :company t.belongs_to :project t.timestamps end end def self.down drop_table :companies_projects end end
20.642857
73
0.688581
797f5d6697d0f3331314a511e3c0ad5f968a7278
752
# frozen_string_literal: true require 'spec_helper' RSpec.describe AppSec::Dast::Scans::ConsistencyWorker do let(:worker) { described_class.new } describe '#perform' do let_it_be(:project) { create(:project) } let_it_be(:pipeline) { create(:ci_pipeline, project: project) } let_it_be(:profile) { create(:dast_profile, project: project) } let(:job_args) { [pipeline.id, profile.id] } it 'ensures cross database association is created', :aggregate_failures do expect { worker.perform(*job_args) }.to change { Dast::ProfilesPipeline.count }.by(1) expect(Dast::ProfilesPipeline.where(ci_pipeline_id: pipeline.id, dast_profile_id: profile.id)).to exist end it_behaves_like 'an idempotent worker' end end
31.333333
109
0.720745
28b8cd0f69a0c6f2f96b23b5632b47aeca3766c1
3,124
require 'rack' require 'base64' # Takes an ApiGateway event and converts it to an Rack env that can be used for # rack.call(env). module Jets::Controller::Rack class Env def initialize(event, context, options={}) @event, @context, @options = event, context, options end def convert options = {} options = add_top_level(options) options = add_http_headers(options) path = @event['path'] || '/' # always set by API Gateway but might not be when testing shim, so setting it to make testing easier env = Rack::MockRequest.env_for(path, options) if @options[:adapter] env['adapter.event'] = @event env['adapter.context'] = @context end env end private def add_top_level(options) map = { 'CONTENT_TYPE' => content_type, 'QUERY_STRING' => query_string, 'REMOTE_ADDR' => headers['X-Forwarded-For'], 'REMOTE_HOST' => headers['Host'], 'REQUEST_METHOD' => @event['httpMethod'] || 'GET', # useful to default to GET when testing with Lambda console 'REQUEST_PATH' => @event['path'], 'REQUEST_URI' => request_uri, 'SCRIPT_NAME' => "", 'SERVER_NAME' => headers['Host'], 'SERVER_PORT' => headers['X-Forwarded-Port'], 'SERVER_PROTOCOL' => "HTTP/1.1", # unsure if this should be set 'SERVER_SOFTWARE' => "WEBrick/1.3.1 (Ruby/2.2.2/2015-04-13)", } map['CONTENT_LENGTH'] = content_length if content_length # Even if not set, Rack always assigns an StringIO to "rack.input" map['rack.input'] = StringIO.new(body) if body options.merge(map) end def content_type headers['content-type'] || Jets::Controller::DEFAULT_CONTENT_TYPE end def content_length bytesize = body.bytesize.to_s if body headers['Content-Length'] || bytesize end # Decoding base64 from API Gateaway if necessary # Rack will be none the wiser def body if @event['isBase64Encoded'] Base64.decode64(@event['body']) else @event['body'] end end def add_http_headers(options) headers.each do |k,v| # content-type => HTTP_CONTENT_TYPE key = k.gsub('-','_').upcase key = "HTTP_#{key}" options[key] = v end options end def request_uri # IE: "http://localhost:8888/posts/tung/edit?foo=bar" proto = headers['X-Forwarded-Proto'] host = headers['Host'] port = headers['X-Forwarded-Port'] # Add port if needed if proto == 'https' && port != '443' or proto == 'http' && port != '80' host = "#{host}:#{port}" end path = @event['path'] qs = "?#{query_string}" unless query_string.empty? "#{proto}://#{host}#{path}#{qs}" end def query_string qs_params = @event["queryStringParameters"] || {} # always set with API Gateway but when testing node shim might not be hash = Jets::Mega::HashConverter.encode(qs_params) hash.to_query end def headers @event['headers'] || {} end end end
29.196262
136
0.598912
6a1fa61f3c60c85b1a28c4bc01c0405fb5856abe
163
require 'rails_helper' RSpec.describe "Providers", type: :request do describe "GET /index" do pending "add some examples (or delete) #{__FILE__}" end end
20.375
55
0.711656
1cf28c2b3ca5dc6bc6fc6cffb0a5748d30b3f8e3
6,163
# frozen_string_literal: true require 'lib/params' require 'view/tiles' require_relative '../game_class_loader' module View class TilesPage < Tiles include GameClassLoader needs :route ROUTE_FORMAT = %r{/tiles/([^/?]*)(?:/([^?]+))?}.freeze TILE_IDS = [ Engine::Tile::WHITE.keys, Engine::Tile::YELLOW.keys, Engine::Tile::GREEN.keys, Engine::Tile::BROWN.keys, Engine::Tile::GRAY.keys, Engine::Tile::RED.keys, ].reduce(&:+) def render match = @route.match(ROUTE_FORMAT) dest = match[1] hexes_or_tiles = match[2] layout = (Lib::Params['l'] || 'flat').to_sym # parse URL params 'r' and 'n'; but don't apply them to /tiles/all, are # you trying to kill your browser? @rotations = case (r = Lib::Params['r']) when nil [0] when 'all' Engine::Tile::ALL_EDGES else # apparently separating rotations in URL with '+' works by passing ' ' # to split here r.split(' ').map(&:to_i) end @location_name = Lib::Params['n'] # all common hexes/tiles if dest == 'all' h('div#tiles', [ h('div#all_tiles', [ h(:h2, 'Generic Map Hexes and Common Track Tiles'), *TILE_IDS.flat_map { |t| render_tile_blocks(t, layout: layout) }, ]), ]) elsif dest == 'custom' location_name = Lib::Params['n'] color = Lib::Params['c'] || 'yellow' tile = Engine::Tile.from_code( 'custom', color, hexes_or_tiles, location_name: location_name ) rendered = render_tile_blocks('custom', layout: layout, tile: tile) h('div#tiles', rendered) # hexes/tiles from a specific game elsif hexes_or_tiles rendered = if hexes_or_tiles == 'all' game_titles = dest.split('+') game_titles.flat_map do |title| next [] unless (game_class = load_game_class(title)) map_hexes_and_tile_manifest_for(game_class) end else game_title = dest hex_or_tile_ids = hexes_or_tiles.split('+') hex_or_tile_ids.flat_map { |id| render_individual_tile_from_game(game_title, id) } end h('div#tiles', rendered) # common tile(s) else tile_ids_with_rotation = dest.split('+') rendered = tile_ids_with_rotation.flat_map do |tile_id_with_rotation| id, rotation = tile_id_with_rotation.split('-') rotations = rotation ? [rotation.to_i] : @rotations render_tile_blocks( id, layout: layout, scale: 3.0, rotations: rotations, location_name: @location_name, ) end h('div#tiles', rendered) end end def render_individual_tile_from_game(game_title, hex_or_tile_id) game_class = load_game_class(game_title) return [] unless game_class players = game_class::PLAYER_RANGE.max.times.map { |n| "Player #{n + 1}" } game = game_class.new(players) id, rotation = hex_or_tile_id.split('-') rotations = rotation ? [rotation.to_i] : @rotations # TODO?: handle case with big map and uses X for game-specific tiles # (i.e., "X1" is the name of a tile *and* a hex) tile, name, hex_coordinates = if game.class::TILES.include?(id) t = game.tile_by_id("#{id}-0") [t, t.name, nil] else t = game.hex_by_id(id).tile [t, id, id] end h(:div, [ h(:h2, game_class.title.to_s), *render_tile_blocks( name, layout: game.class::LAYOUT, tile: tile, location_name: tile.location_name || @location_name, scale: 3.0, rotations: rotations, hex_coordinates: hex_coordinates, ), ]) end def map_hexes_and_tile_manifest_for(game_class) players = game_class::PLAYER_RANGE.max.times.map { |n| "Player #{n + 1}" } game = game_class.new(players) # map_tiles: hash; key is hex ID, value is the Tile there map_tiles = game.hexes.map { |h| [h.name, h.tile] }.to_h # get mapping of tile -> all hex coordinates using that tile tile_to_coords = {} map_tiles.each do |coord, tile| tile_key = tile_to_coords.keys.find do |k| [ k.name == tile.name, k.location_name == tile.location_name, k.blockers == tile.blockers, k.cities.map(&:reservations) == tile.cities.map(&:reservations), ].all? end if tile_key.nil? tile_to_coords[tile] = [coord] else tile_to_coords[tile_key] << coord end end # truncate "names" (list of hexes with this tile) map_hexes = tile_to_coords.map do |tile, coords| name = coords.join(',') name = "#{name.slice(0, 10)}..." if name.size > 13 tile.name = name tile end rendered_map_hexes = map_hexes.sort.flat_map do |tile| render_tile_blocks( tile.name, layout: game.layout, tile: tile, location_name: tile.location_name, hex_coordinates: tile.name, ) end rendered_tiles = game.tiles.sort.group_by(&:name).flat_map do |name, tiles_| render_tile_blocks( name, layout: game.layout, tile: tiles_.first, num: tiles_.size, rotations: @rotations, location_name: @location_name, ) end h("div#hexes_and_tiles_#{game_class.title}", [ h(:h2, game_class.title.to_s), h("div#map_hexes_#{game_class.title}", [ h(:h3, "#{game_class.title} Map Hexes"), *rendered_map_hexes, ]), h("div#game_tiles_#{game_class.title}", [ h(:h3, "#{game_class.title} Tile Manifest"), *rendered_tiles, ]), ]) end end end
29.488038
94
0.55103
28475a576e2e0709db4f6de0de712bbfb7a5becf
465
class GenerateMonthlyTsvs < GenerateTsvs def perform super self.class.set(wait_until: beginning_of_next_month).perform_later TsvRelease.where(path: release_path).first_or_create end private def release_path @dir_name ||= Date.today.beginning_of_month.strftime('%d-%b-%Y') end def beginning_of_next_month Date.today .beginning_of_month .next_month .midnight end def filename_prefix release_path end end
19.375
69
0.729032
0311ab261f74564dbc0346c500abb212395a1aed
1,855
module Fog module Network class AzureRM # Real class for Express Route Circuit Peering Request class Real def get_express_route_circuit_peering(resource_group_name, peering_name, circuit_name) msg = "Getting Express Route Circuit Peering #{peering_name} from Resource Group #{resource_group_name}." Fog::Logger.debug msg begin circuit_peering = @network_client.express_route_circuit_peerings.get(resource_group_name, circuit_name, peering_name) rescue MsRestAzure::AzureOperationError => e raise_azure_exception(e, msg) end circuit_peering end end # Mock class for Express Route Circuit Peering Request class Mock def get_express_route_circuit_peering(*) { 'name' => 'peering_name', 'id' => '/subscriptions/########-####-####-####-############/resourceGroups/resource_group_name/providers/Microsoft.Network/expressRouteCircuits/circuit_name/peerings/peering_name', 'etag' => '', 'properties' => { 'provisioningState' => 'Succeeded', 'peeringType' => 'MicrosoftPeering', 'peerASN' => '', 'primaryPeerAddressPrefix' => '', 'secondaryPeerAddressPrefix' => '', 'primaryAzurePort' => 22, 'secondaryAzurePort' => 21, 'state' => 'Enabled', 'sharedKey' => '', 'vlanId' => 100, 'microsoftPeeringConfig' => { 'advertisedpublicprefixes' => %w(prefix1 prefix2), 'advertisedPublicPrefixState' => 'ValidationNeeded', 'customerAsn' => '', 'routingRegistryName' => '' } } } end end end end end
37.857143
193
0.558491
ac7acbd85aec825a13a818291fff4764bff3afda
47
module PgMantenimiento VERSION = '0.1.0' end
11.75
22
0.723404
87b56653d35b31eba0b2149321018f5ad0d4354f
1,316
class Export::AllActivityTotals attr_reader :totals def initialize(activity:, report: nil) @activity = activity @scoped_to_report = report @totals = nil end def call apply_base_scope apply_report_scope unless @scoped_to_report.nil? apply_select apply_grouping apply_ordering apply_sum_totals totals end private def apply_base_scope @totals = Transaction .joins("LEFT OUTER JOIN adjustment_details ON adjustment_details.adjustment_id = transactions.id") .where(parent_activity_id: @activity.id) end def apply_report_scope @totals = @totals .where(report_id: Report.historically_up_to(@scoped_to_report).pluck(:id)) end def apply_select @totals = @totals .select( :financial_quarter, :financial_year, :parent_activity_id, :value, :type, "adjustment_details.adjustment_type" ) end def apply_grouping @totals = @totals.group( :parent_activity_id, :financial_quarter, :financial_year, :type, "adjustment_details.adjustment_type" ) end def apply_ordering @totals = @totals.order(:parent_activity_id, :financial_quarter, :financial_year) end def apply_sum_totals @totals = @totals.sum(:value) end end
20.5625
104
0.680851
3814c1785758b34eb8b2914f34ff740ee897f007
793
# http://ow.ly/url/shorten-url -- not out yet # http://api.bit.ly/shorten?version=2.0.1&login=shurl&apiKey=R_a08944fe85b63e4e35dd04d78d180611&longUrl= require 'net/http' module Shurl class Shortener def initialize @@mini = [] @@shorteners = %w{http://is.gd/api.php?longurl= http://tinyarro.ws/api-create.php?url= http://idek.net/shorten/?idek-api=true&idek-ref=your_app&idek-anchor=anchortag&idek-url= http://chilp.it/api.php?url= } end def shorten(url) @@shorteners.each do |u| @@mini << Net::HTTP.get_response(URI.parse(u+urle(url))).body end @@mini.sort_by { |url| url.length } [0] end private def url_encode(url) URI.encode(url) end alias_method :urle, :url_encode end end
27.344828
104
0.629256
33d1fea6c756605a7e7d7448034bd0e6784c8a9b
218
require File.expand_path('../support/helpers', __FILE__) describe 'line::default' do include Helpers::Line # Example spec tests can be found at http://git.io/Fahwsw it 'runs no tests by default' do end end
18.166667
59
0.715596
339f4e0fc0835ebe10c5c0486119731ca77644e9
457
class CreateLivepeerEvents < ActiveRecord::Migration[5.2] def change create_table :livepeer_events do |t| t.belongs_to :round t.string :type t.datetime :timestamp t.string :transcoder_address t.jsonb :data, default: {} t.timestamps end add_index :livepeer_events, :type add_index :livepeer_events, :transcoder_address add_foreign_key :livepeer_events, :livepeer_rounds, column: :round_id end end
26.882353
73
0.706783
6a7ba2d83ca925ceece92b7f5de1f315a6d97d9f
1,644
# coding: utf-8 require "rails_helper" describe UsersHelper, :type => :helper do describe "user_avatar_width_for_size" do it "should calculate avatar width correctly" do expect(helper.user_avatar_width_for_size(:normal)).to eq(48) expect(helper.user_avatar_width_for_size(:small)).to eq(16) expect(helper.user_avatar_width_for_size(:large)).to eq(64) expect(helper.user_avatar_width_for_size(:big)).to eq(120) expect(helper.user_avatar_width_for_size(233)).to eq(233) end end describe "user_name_tag" do it "should result right html in normal" do user = Factory(:user) expect(helper.user_name_tag(user)).to eq(link_to(user.login, user_path(user.login), 'data-name' => user.name)) end it "should result right html with string param and downcase url" do login = "Monster" expect(helper.user_name_tag(login)).to eq(link_to(login, user_path(login.downcase), 'data-name' => login)) end it "should result empty with nil param" do expect(helper.user_name_tag(nil)).to eq("匿名") end end describe "user personal website" do let(:user) { Factory(:user, :website => 'http://example.com') } subject { helper.render_user_personal_website(user) } it { is_expected.to eq(link_to(user.website, user.website, :target => "_blank", :class => "url", :rel => "nofollow")) } context "url without protocal" do before { user.update_attribute(:website, 'example.com') } it { is_expected.to eq(link_to("http://" + user.website, "http://" + user.website, :class => "url", :target => "_blank", :rel => "nofollow")) } end end end
37.363636
149
0.680657
b9a860a6f40742166eed5917613822faad415e2a
4,931
# -*- encoding: utf-8 -*- require_relative '../spec_helper' require_relative '../../app' describe Razor::Command::SetNodeIPMICredentials do include Razor::Test::Commands let(:app) { Razor::App } let(:node) { Fabricate(:node).save } let(:command_hash) { { "name" => node.name } } before :each do header 'content-type', 'application/json' authorize 'fred', 'dead' end it_behaves_like "a command" it "should report 'no such node' if the name isn't found" do command 'set-node-ipmi-credentials', {:name => 'bananaman'} last_response.status.should == 404 end it "should update the node data correctly" do node.ipmi_hostname.should be_nil node.ipmi_username.should be_nil node.ipmi_password.should be_nil update = { 'ipmi-hostname' => Faker::Internet.ip_v4_address, 'ipmi-username' => Faker::Internet.user_name, 'ipmi-password' => Faker::Internet.password[0..19] } command 'set-node-ipmi-credentials', {:name => node.name}.merge(update) last_response.status.should == 202 node.reload # refresh from the database, plz node.ipmi_hostname.should == update['ipmi-hostname'] node.ipmi_username.should == update['ipmi-username'] node.ipmi_password.should == update['ipmi-password'] end end describe Razor::Command::RebootNode do include Razor::Test::Commands include TorqueBox::Injectors let(:app) { Razor::App } let(:node) { Fabricate(:node_with_ipmi).save } let(:queue) { fetch('/queues/razor/sequel-instance-messages') } let(:command_hash) { { "name" => node.name } } before :each do header 'content-type', 'application/json' authorize 'fred', 'dead' end it_behaves_like "a command" it "should work" do command 'reboot-node', {'name' => node.name} last_response.status.should == 202 end context "RBAC" do around :each do |spec| Tempfile.open('shiro.ini') do |config| config.print <<EOT [main] [users] can=can,reboot none=none [roles] reboot=commands:reboot-node:* EOT config.flush Razor.config['auth.config'] = config.path # ...and, thankfully, all our cleanup happens auto-magically. spec.call end end it "should reject an unauthenticated request" do command 'reboot-node', {'name' => node.name} last_response.status.should == 401 end it "should reject all reboot requests with no reboot rights" do authorize 'none', 'none' command 'reboot-node', {'name' => node.name} last_response.status.should == 403 end it "should accept a reboot request with reboot rights" do authorize 'can', 'can' command 'reboot-node', {'name' => node.name} last_response.status.should == 202 end end it "should 404 if the node does not exist" do command 'reboot-node', {'name' => node.name + '-plus'} last_response.status.should == 404 end it "should 422 if the node has no IPMI credentials" do node.set(:ipmi_hostname => nil).save command 'reboot-node', {'name' => node.name} last_response.status.should == 422 end it "should publish the `reboot!` message" do expect { command 'reboot-node', {'name' => node.name} last_response.status.should == 202 }.to have_published({ 'class' => node.class.name, 'instance' => node.pk_hash, 'message' => 'reboot!', 'arguments' => [] }).on(queue) end end describe Razor::Command::SetNodeDesiredPowerState do include Razor::Test::Commands let(:app) { Razor::App } let(:node) { Fabricate(:node_with_ipmi).save } let(:command_hash) { { "name" => node.name } } before :each do header 'content-type', 'application/json' authorize 'fred', 'dead' end it_behaves_like "a command" it "should 404 if the node does not exist" do command 'set-node-desired-power-state', {name: node.name + '-really'} last_response.status.should == 404 end it "should accept null for 'ignored'" do command 'set-node-desired-power-state', {name: node.name, to: nil} last_response.status.should == 202 last_response.json.should == {'result' => "set desired power state to ignored (null)"} end it "should accept 'on'" do command 'set-node-desired-power-state', {name: node.name, to: 'on'} last_response.status.should == 202 last_response.json.should == {'result' => "set desired power state to on"} end it "should accept 'off'" do command 'set-node-desired-power-state', {name: node.name, to: 'off'} last_response.status.should == 202 last_response.json.should == {'result' => "set desired power state to off"} end ([0, 1, true, false] + %w{true false up down yes no 1 0}).each do |bad| it "should reject #{bad.inspect}" do command 'set-node-desired-power-state', {name: node.name, to: bad} last_response.status.should == 422 end end end
28.836257
90
0.650578
b92a92a3e2179abdcee1d545d81c8a81544bebc6
5,838
# 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::Redis::Mgmt::V2017_02_01 # # A service client - single point of access to the REST API. # class RedisManagementClient < MsRestAzure::AzureServiceClient include MsRestAzure include MsRestAzure::Serialization # @return [String] the base URI of the service. attr_accessor :base_url # @return Credentials needed for the client to connect to Azure. attr_reader :credentials # @return [String] Gets subscription credentials which uniquely identify # the Microsoft Azure subscription. The subscription ID forms part of the # URI for every service call. attr_accessor :subscription_id # @return [String] Client Api Version. attr_reader :api_version # @return [String] The preferred language for the response. attr_accessor :accept_language # @return [Integer] The retry timeout in seconds for Long Running # Operations. Default value is 30. attr_accessor :long_running_operation_retry_timeout # @return [Boolean] Whether a unique x-ms-client-request-id should be # generated. When set to true a unique x-ms-client-request-id value is # generated and included in each request. Default is true. attr_accessor :generate_client_request_id # @return [Operations] operations attr_reader :operations # @return [Redis] redis attr_reader :redis # @return [FirewallRules] firewall_rules attr_reader :firewall_rules # @return [PatchSchedules] patch_schedules attr_reader :patch_schedules # @return [RedisLinkedServerOperations] redis_linked_server_operations attr_reader :redis_linked_server_operations # # Creates initializes a new instance of the RedisManagementClient class. # @param credentials [MsRest::ServiceClientCredentials] credentials to authorize HTTP requests made by the service client. # @param base_url [String] the base URI of the service. # @param options [Array] filters to be applied to the HTTP requests. # def initialize(credentials = nil, base_url = nil, options = nil) super(credentials, options) @base_url = base_url || 'https://management.azure.com' fail ArgumentError, 'invalid type of credentials input parameter' unless credentials.is_a?(MsRest::ServiceClientCredentials) unless credentials.nil? @credentials = credentials @operations = Operations.new(self) @redis = Redis.new(self) @firewall_rules = FirewallRules.new(self) @patch_schedules = PatchSchedules.new(self) @redis_linked_server_operations = RedisLinkedServerOperations.new(self) @api_version = '2017-02-01' @accept_language = 'en-US' @long_running_operation_retry_timeout = 30 @generate_client_request_id = true add_telemetry end # # Makes a request and returns the body of the response. # @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete. # @param path [String] the path, relative to {base_url}. # @param options [Hash{String=>String}] specifying any request options like :body. # @return [Hash{String=>String}] containing the body of the response. # Example: # # request_content = "{'location':'westus','tags':{'tag1':'val1','tag2':'val2'}}" # path = "/path" # options = { # body: request_content, # query_params: {'api-version' => '2016-02-01'} # } # result = @client.make_request(:put, path, options) # def make_request(method, path, options = {}) result = make_request_with_http_info(method, path, options) result.body unless result.nil? end # # Makes a request and returns the operation response. # @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete. # @param path [String] the path, relative to {base_url}. # @param options [Hash{String=>String}] specifying any request options like :body. # @return [MsRestAzure::AzureOperationResponse] Operation response containing the request, response and status. # def make_request_with_http_info(method, path, options = {}) result = make_request_async(method, path, options).value! result.body = result.response.body.to_s.empty? ? nil : JSON.load(result.response.body) result end # # Makes a request asynchronously. # @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete. # @param path [String] the path, relative to {base_url}. # @param options [Hash{String=>String}] specifying any request options like :body. # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def make_request_async(method, path, options = {}) fail ArgumentError, 'method is nil' if method.nil? fail ArgumentError, 'path is nil' if path.nil? request_url = options[:base_url] || @base_url if(!options[:headers].nil? && !options[:headers]['Content-Type'].nil?) @request_headers['Content-Type'] = options[:headers]['Content-Type'] end request_headers = @request_headers request_headers.merge!({'accept-language' => @accept_language}) unless @accept_language.nil? options.merge!({headers: request_headers.merge(options[:headers] || {})}) options.merge!({credentials: @credentials}) unless @credentials.nil? super(request_url, method, path, options) end private # # Adds telemetry information. # def add_telemetry sdk_information = 'azure_mgmt_redis' sdk_information = "#{sdk_information}/0.17.3" add_user_agent_information(sdk_information) end end end
38.92
154
0.698013
ff1d28c326a6ceda86f95e2a60a7ec822292cd2b
6,749
#! /usr/bin/env ruby require 'yaml' require 'erb' require 'attack_api' class AtomicRedTeam ATTACK_API = Attack.new ATOMICS_DIRECTORY = "#{File.dirname(File.dirname(__FILE__))}/atomics" # TODO- should these all be relative URLs? ROOT_GITHUB_URL = "https://github.com/redcanaryco/atomic-red-team" # # Returns a list of paths that contain Atomic Tests # def atomic_test_paths Dir["#{ATOMICS_DIRECTORY}/t*/t*.yaml"].sort end # # Returns a list of Atomic Tests in Atomic Red Team (as Hashes from source YAML) # def atomic_tests @atomic_tests ||= atomic_test_paths.collect do |path| atomic_yaml = YAML.load(File.read path) atomic_yaml['atomic_yaml_path'] = path atomic_yaml end end # # Returns the individual Atomic Tests for a given identifer, passed as either a string (T1234) or an ATT&CK technique object # def atomic_tests_for_technique(technique_or_technique_identifier) technique_identifier = if technique_or_technique_identifier.is_a? Hash ATTACK_API.technique_identifier_for_technique technique_or_technique_identifier else technique_or_technique_identifier end atomic_tests.find do |atomic_yaml| atomic_yaml.fetch('attack_technique').downcase == technique_identifier.downcase end.to_h.fetch('atomic_tests', []) end # # Returns a Markdown formatted Github link to a technique. This will be to the edit page for # techniques that already have one or more Atomic Red Team tests, or the create page for # techniques that have no existing tests. # def github_link_to_technique(technique, include_identifier=false) technique_identifier = ATTACK_API.technique_identifier_for_technique(technique).downcase link_display = "#{"#{technique_identifier.upcase} " if include_identifier}#{technique['name']}" if File.exists? "#{ATOMICS_DIRECTORY}/#{technique_identifier}/#{technique_identifier}.md" # we have a file for this technique, so link to it's Markdown file "[#{link_display}](#{ROOT_GITHUB_URL}/tree/master/atomics/#{technique_identifier}/#{technique_identifier}.md)" else # we don't have a file for this technique, so link to an edit page "[#{link_display}](#{ROOT_GITHUB_URL}/new/master/atomics/#{technique_identifier}?#{technique_identifier}.md)" end end def validate_atomic_yaml!(yaml) raise("YAML file has no elements") if yaml.nil? raise('`attack_technique` element is required') unless yaml.has_key?('attack_technique') raise('`attack_technique` element must be an array') unless yaml['attack_technique'].is_a?(String) raise('`display_name` element is required') unless yaml.has_key?('display_name') raise('`display_name` element must be an array') unless yaml['display_name'].is_a?(String) raise('`atomic_tests` element is required') unless yaml.has_key?('atomic_tests') raise('`atomic_tests` element must be an array') unless yaml['atomic_tests'].is_a?(Array) raise('`atomic_tests` element is empty - you have no tests') unless yaml['atomic_tests'].count > 0 yaml['atomic_tests'].each_with_index do |atomic, i| raise("`atomic_tests[#{i}].name` element is required") unless atomic.has_key?('name') raise("`atomic_tests[#{i}].name` element must be a string") unless atomic['name'].is_a?(String) raise("`atomic_tests[#{i}].description` element is required") unless atomic.has_key?('description') raise("`atomic_tests[#{i}].description` element must be a string") unless atomic['description'].is_a?(String) raise("`atomic_tests[#{i}].supported_platforms` element is required") unless atomic.has_key?('supported_platforms') raise("`atomic_tests[#{i}].supported_platforms` element must be an Array (was a #{atomic['supported_platforms'].class.name})") unless atomic['supported_platforms'].is_a?(Array) valid_supported_platforms = ['windows', 'centos', 'ubuntu', 'macos', 'linux'] atomic['supported_platforms'].each do |platform| if !valid_supported_platforms.include?(platform) raise("`atomic_tests[#{i}].supported_platforms` '#{platform}' must be one of #{valid_supported_platforms.join(', ')}") end end (atomic['input_arguments'] || {}).each_with_index do |arg_kvp, iai| arg_name, arg = arg_kvp raise("`atomic_tests[#{i}].input_arguments[#{iai}].description` element is required") unless arg.has_key?('description') raise("`atomic_tests[#{i}].input_arguments[#{iai}].description` element must be a string") unless arg['description'].is_a?(String) raise("`atomic_tests[#{i}].input_arguments[#{iai}].type` element is required") unless arg.has_key?('type') raise("`atomic_tests[#{i}].input_arguments[#{iai}].type` element must be a string") unless arg['type'].is_a?(String) raise("`atomic_tests[#{i}].input_arguments[#{iai}].type` element must be lowercased and underscored (was #{arg['type']})") unless arg['type'] =~ /[a-z_]+/ # TODO: determine if we think default values are required for EVERY input argument # raise("`atomic_tests[#{i}].input_arguments[#{iai}].default` element is required") unless arg.has_key?('default') # raise("`atomic_tests[#{i}].input_arguments[#{iai}].default` element must be a string (was a #{arg['default'].class.name})") unless arg['default'].is_a?(String) end raise("`atomic_tests[#{i}].executor` element is required") unless atomic.has_key?('executor') executor = atomic['executor'] raise("`atomic_tests[#{i}].executor.name` element is required") unless executor.has_key?('name') raise("`atomic_tests[#{i}].executor.name` element must be a string") unless executor['name'].is_a?(String) raise("`atomic_tests[#{i}].executor.name` element must be lowercased and underscored (was #{executor['name']})") unless executor['name'] =~ /[a-z_]+/ valid_executor_types = ['command_prompt', 'sh', 'bash', 'powershell', 'manual'] case executor['name'] when 'manual' raise("`atomic_tests[#{i}].executor.steps` element is required") unless executor.has_key?('steps') raise("`atomic_tests[#{i}].executor.steps` element must be a string") unless executor['steps'].is_a?(String) when 'command_prompt', 'sh', 'bash', 'powershell' raise("`atomic_tests[#{i}].executor.command` element is required") unless executor.has_key?('command') raise("`atomic_tests[#{i}].executor.command` element must be a string") unless executor['command'].is_a?(String) else raise("`atomic_tests[#{i}].executor.name` '#{executor['name']}' must be one of #{valid_executor_types.join(', ')}") end end end end
51.915385
182
0.696548
285311e88e7bb64b7d668670bcef748143c802be
648
# rubocop:disable Metrics/LineLength # == Schema Information # # Table name: group_permissions # # id :integer not null, primary key # permission :integer not null # created_at :datetime not null # updated_at :datetime not null # group_member_id :integer not null, indexed # # Indexes # # index_group_permissions_on_group_member_id (group_member_id) # # Foreign Keys # # fk_rails_f60693a634 (group_member_id => group_members.id) # # rubocop:enable Metrics/LineLength FactoryBot.define do factory :group_permission do group_member permission { 1 } end end
23.142857
64
0.67284
5d001537aa1b04f78d4ceea975964dab5985d3a5
5,692
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2016, Google Inc. All Rights Reserved. # # License:: 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. # # Common utilities used by the Authorized Buyers Ad Exchange Buyer API Samples. require 'optparse' require 'google/apis/adexchangebuyer2_v2beta1' require 'google/apis/options' require 'googleauth/service_account' ADEXCHANGEBUYER_V2BETA1 = "v2beta1" DEFAULT_VERSION = ADEXCHANGEBUYER_V2BETA1 SUPPORTED_VERSIONS = [ADEXCHANGEBUYER_V2BETA1] # The JSON key file for your Service Account found in the Google Developers # Console. KEY_FILE = 'path_to_key' # Path to JSON file containing your private key. # The maximum number of results to be returned in a page for any list response. MAX_PAGE_SIZE = 50 # Handles authentication and initializes the client. def get_service(version=DEFAULT_VERSION) if !SUPPORTED_VERSIONS.include? version raise ArgumentError, ( 'Unsupported version of Ad Exchange Buyer II API specified!' ) end Google::Apis::ClientOptions.default.application_name = "Ruby Ad Exchange Buyer II samples: #{$0}" Google::Apis::ClientOptions.default.application_version = "1.0.0" if version == ADEXCHANGEBUYER_V2BETA1 service = Google::Apis::Adexchangebuyer2V2beta1::AdExchangeBuyerIIService.new end auth_options = { :json_key_io => File.open(KEY_FILE, "r"), :scope => "https://www.googleapis.com/auth/adexchange.buyer" } authorization = Google::Auth::ServiceAccountCredentials.make_creds( options=auth_options) service.authorization = authorization service.authorization.fetch_access_token! return service end # An option to be passed into the example via a command-line argument. class Option # The long alias for the option; typically one or more words delimited by # underscores. Do not use "--help", as this is reserved for displaying help # information. attr_accessor :long_alias # The type used for type coercion. attr_accessor :type # The text displayed for the option if the user passes the "-h" or "--help" # options to display help information for the sample. attr_accessor :help_text # The short alias for the option; a single character. Do not use "-h", as # this is reserved for displaying help information. attr_accessor :short_alias # An optional array of values to be used to validate a user-specified value # against. attr_accessor :valid_values # The default value to use if the option is not specified as a command-line # argument. attr_accessor :default_value # A boolean indicating whether it is required that the user configure the # option. attr_accessor :required def initialize(long_alias, help_template, type: String, short_alias: nil, valid_values: nil, required: false, default_value: nil) @long_alias = long_alias if valid_values.nil? @help_text = help_template elsif !valid_values.kind_of?(Array) raise ArgumentError, 'The valid_values argument must be an Array.' else @valid_values = [] valid_values.each do |valid_value| @valid_values << valid_value.upcase end @help_text = ( help_template + " This can be set to: %s." % @valid_values.inspect ) end @type = type @short_alias = short_alias @default_value = default_value @required = required end def get_option_parser_args() args = [] if !short_alias.nil? args << '-%s %s' % [@short_alias, @long_alias.upcase] end args << '--%s %s' % [@long_alias, @long_alias.upcase] args << @type args << @help_text return args end end # Parses arguments for the given Options. class Parser def initialize(options) @parsed_args = {} @options = options @opt_parser = OptionParser.new do |opts| options.each do |option| opts.on(*option.get_option_parser_args()) do |x| unless option.valid_values.nil? if option.kind_of(Array) x.each do |value| check_valid_value(option.valid_values, value) end else check_valid_value(option.valid_values, x) end end @parsed_args[option.long_alias] = x end end end end def check_valid_value(valid_values, value) unless valid_values.include?(value.upcase) raise 'Invalid value "%s". Valid values are: %s' % [value, valid_values.inspect] end end def parse(args) @opt_parser.parse!(args) @options.each do |option| if !@parsed_args.include? option.long_alias @parsed_args[option.long_alias] = option.default_value end if option.required and @parsed_args[option.long_alias].nil? raise ('You need to set "%s", it is a required field. Set it by ' + 'passing "--%s %s" as a command line argument or giving the ' + 'corresponding option a default value.') % [option.long_alias, option.long_alias, option.long_alias.upcase] end end return @parsed_args end end
29.801047
79
0.685524
f8a5c6cf3e766eeec1458c83d2ae1c7fabbc60fd
1,496
require "spec_helper" RSpec.describe "ElasticsearchDeletionTest" do it "removes a document from the index" do commit_document( "government_test", { "link" => "/an-example-page", }, ) delete "/government_test/documents/%2Fan-example-page" expect_document_missing_in_rummager(id: "/an-example-page", index: "government_test") end it "removes a document from the index queued" do commit_document( "government_test", { "link" => "/an-example-page", }, ) delete "/government_test/documents/%2Fan-example-page" expect(last_response.status).to eq(202) end it "removes document with url" do commit_document( "government_test", { "link" => "http://example.com/", }, ) delete "/government_test/documents/edition/http:%2F%2Fexample.com%2F" expect_document_missing_in_rummager(id: "http://example.com/", index: "government_test") end it "deletes a best bet by type and id" do post "/metasearch_test/documents", { "_id" => "jobs_exact", "_type" => "best_bet", "link" => "/something", }.to_json commit_index("government_test") delete "/metasearch_test/documents/best_bet/jobs_exact" expect { client.get( index: "metasearch_test", type: "best_bet", id: "jobs_exact", ) }.to raise_error(Elasticsearch::Transport::Transport::Errors::NotFound) end end
23.375
92
0.619652
616c8aae4c8dcac3d518d212dee6344f85b1a3f3
68
module ApplicationHelper include PagesCore::ApplicationHelper end
17
38
0.867647
39df253f01c71ac7ef902cf44a765f6f336d0fee
57
module Annotate def self.version '2.7.3' end end
9.5
18
0.649123
39d4362e0e5bb4c80d347646e556b1322d1b4e7c
630
require 'test_helper' shared_examples describe 'Database Adapters' do let(:attributes) do { name: 'Ruby' } end after :each do Kind.delete_all end describe 'with duplicated record' do def setup Kind.mass_insert([attributes]) end it 'does not raises error if is duplicated and has the duplication handler on' do Kind.mass_insert([attributes], handle_duplication: true) end it 'raises error if is duplicated and does not have the duplication handler on' do assert_raises ActiveRecord::RecordNotUnique do Kind.mass_insert([attributes]) end end end end
21
86
0.696825
e9d2617d3e89a65acd4dc3f4f01811b49487b0cf
1,664
#!/usr/bin/env ruby class FastGame attr_reader :final_layout def initialize(initial) self.circle = Hash.new (initial.count - 1).times do |i| self.circle[initial[i]] = initial[i + 1] end self.current = initial[0] self.circle[initial[-1]] = self.current end def play(moves) lowest = self.circle.keys.min highest = self.circle.keys.max moves.times do |move| puts "Starting move #{move}..." if move % 1000000 == 0 moving_1 = self.circle[self.current] moving_2 = self.circle[moving_1] moving_3 = self.circle[moving_2] destination = self.current loop do destination = destination - 1 destination = highest if destination < lowest break unless destination == moving_1 || destination == moving_2 || destination == moving_3 end self.circle[self.current] = self.circle[moving_3] temp = self.circle[destination] self.circle[destination] = moving_1 self.circle[moving_3] = temp self.current = self.circle[self.current] end cur = 1 self.final_layout = Array.new loop do cur = self.circle[cur] break if cur == 1 self.final_layout << cur end end private attr_accessor :circle, :current attr_writer :final_layout end puts 'Part 1' initial = '156794823'.chars.map(&:to_i) game = FastGame.new(initial) game.play(100) puts " Final layout is #{game.final_layout.join}" puts puts 'Part 2' second_initial = initial + (10..1000000).to_a game = FastGame.new(second_initial) game.play(10000000) two_cups = game.final_layout[0..1] puts " Product of two cups is #{two_cups.reduce(&:*)}"
23.111111
98
0.656851
d5750826eaa078654d7e4a593adf50887a70427b
3,102
class Dspdfviewer < Formula desc "Dual-Screen PDF Viewer for latex-beamer" homepage "https://dspdfviewer.danny-edel.de/" url "https://github.com/dannyedel/dspdfviewer/archive/v1.15.1.tar.gz" sha256 "c5b6f8c93d732e65a27810286d49a4b1c6f777d725e26a207b14f6b792307b03" revision 8 head "https://github.com/dannyedel/dspdfviewer.git" bottle do sha256 "110de35c2516b74d0c6af47be2b1417f81a8805aae1a019b448e27e8dc03c362" => :catalina sha256 "f6063bf108432e891c5ec13665cde11d30498e99cf4d130236b78ea3a894c32c" => :mojave sha256 "93406709c843244b5c55b9f6167d67290899ac1aaa32bd32faa530fab66daae9" => :high_sierra sha256 "ec6ea81aaa5e037a27803b830a6bb8c7100b003a0095dec2dd3b1e217d1a6a30" => :sierra end depends_on "cmake" => :build depends_on "gobject-introspection" => :build depends_on "pkg-config" => :build depends_on "boost" depends_on "cairo" depends_on "fontconfig" depends_on "freetype" depends_on "gettext" depends_on "glib" depends_on "jpeg" depends_on "libpng" depends_on "libtiff" depends_on "openjpeg" depends_on "qt" resource "poppler" do url "https://poppler.freedesktop.org/poppler-0.65.0.tar.xz" sha256 "89c8cf73f83efda78c5a9bd37c28f4593ad0e8a51556dbe39ed81e1ae2dd8f07" end resource "font-data" do url "https://poppler.freedesktop.org/poppler-data-0.4.9.tar.gz" sha256 "1f9c7e7de9ecd0db6ab287349e31bf815ca108a5a175cf906a90163bdbe32012" end def install ENV.cxx11 resource("poppler").stage do system "cmake", ".", *std_cmake_args, "-DCMAKE_INSTALL_PREFIX=#{libexec}", "-DBUILD_GTK_TESTS=OFF", "-DENABLE_CMS=none", "-DENABLE_GLIB=ON", "-DENABLE_QT5=ON", "-DWITH_GObjectIntrospection=ON", "-DENABLE_XPDF_HEADERS=ON" system "make", "install" libpoppler = (libexec/"lib/libpoppler.dylib").readlink to_fix = ["#{libexec}/lib/libpoppler-cpp.dylib", "#{libexec}/lib/libpoppler-glib.dylib", "#{libexec}/lib/libpoppler-qt5.dylib", *Dir["#{libexec}/bin/*"]] to_fix.each do |f| macho = MachO.open(f) macho.change_dylib("@rpath/#{libpoppler}", "#{libexec}/lib/#{libpoppler}") macho.write! end resource("font-data").stage do system "make", "install", "prefix=#{libexec}" end end ENV.prepend_path "PKG_CONFIG_PATH", "#{libexec}/lib/pkgconfig" ENV.prepend "LDFLAGS", "-L#{libexec}/lib" mkdir "build" do system "cmake", "..", *std_cmake_args, "-DRunDualScreenTests=OFF", "-DUsePrerenderedPDF=ON", "-DUseQtFive=ON" system "make", "install" end libpoppler = (libexec/"lib/libpoppler-qt5.dylib").readlink macho = MachO.open(bin/"dspdfviewer") macho.change_dylib("@rpath/#{libpoppler}", "#{libexec}/lib/#{libpoppler}") macho.write! end test do system bin/"dspdfviewer", "--help" end end
34.087912
94
0.645712
1a3d14f04f5493129fa70d00fc9acec8d02052fe
3,664
# encoding: utf-8 # author: Dominik Richter # author: Christoph Hartmann require 'functional/helper' require 'jsonschema' require 'tmpdir' describe 'inspec check' do include FunctionalHelper describe 'inspec check with json formatter' do it 'can check a profile and produce valid JSON' do out = inspec('check ' + integration_test_path + ' --format json') out.exit_status.must_equal 0 JSON.parse(out.stdout) end end describe 'inspec check with special characters in path' do it 'can check a profile with special characters in its path' do out = inspec('check ' + File.join(profile_path, '{{special-path}}')) out.exit_status.must_equal 0 end end describe 'inspec check with skipping/failing a resource in FilterTable' do it 'can check a profile containing resource exceptions' do out = inspec('check ' + File.join(profile_path, 'profile-with-resource-exceptions')) out.exit_status.must_equal 0 end end describe 'inspec check with a profile containing only_if' do it 'ignores the `only_if`' do out = inspec('check ' + File.join(profile_path, 'only-if-os-nope')) out.exit_status.must_equal 0 end end describe 'inspec check with a aws profile' do it 'ignore train connection error' do out = inspec('check ' + File.join(examples_path, 'profile-aws')) out.exit_status.must_equal 0 end end describe 'inspec check with a azure profile' do it 'ignore train connection error' do out = inspec('check ' + File.join(examples_path, 'profile-azure')) out.exit_status.must_equal 0 end end describe 'inspec check with alternate cache dir' do it 'writes to the alternate cache dir' do Dir.mktmpdir do |tmpdir| cache_dir = File.join(tmpdir, "inspec_check_test_cache") File.exist?(cache_dir).must_equal false out = inspec('check ' + integration_test_path + ' --vendor-cache ' + cache_dir) out.exit_status.must_equal 0 File.exist?(cache_dir).must_equal true end end end describe 'inspec check for lockfile and dependencies' do it 'can check a profile where a lock file is not required' do out = inspec('check ' + File.join(profile_path, 'profile-lock-notrequired')) out.exit_status.must_equal 0 end it 'can check a profile where a lock file is required' do out = inspec('check ' + File.join(profile_path, 'profile-lock-required')) out.exit_status.must_equal 1 out.stdout.must_include 'profile needs to be vendored with `inspec vendor`.' end it 'can check a profile where lock file and inspec.yml are in synnc' do out = inspec('check ' + File.join(profile_path, 'profile-lock-insync')) out.exit_status.must_equal 0 end it 'can check a profile where lock file and inspec.yml are in not synnc' do out = inspec('check ' + File.join(profile_path, 'profile-lock-outofsync')) out.exit_status.must_equal 1 out.stdout.must_include 'inspec.yml and inspec.lock are out-of-sync. Please re-vendor with `inspec vendor`.' out.stdout.must_include 'Cannot find linux-baseline in lockfile. Please re-vendor with `inspec vendor`.' end end describe 'inspec check with invalid `include_controls` reference' do it 'raises an error matching /Cannot load \'invalid_name\'/' do invalid_profile = File.join(profile_path, 'invalid-include-controls') out = inspec('check ' + invalid_profile) out.exit_status.must_equal 1 out.stderr.must_match /Cannot load 'no_such_profile'/ out.stderr.must_match /not listed as a dependency/ end end end
35.230769
114
0.695688
01ad06b8d87dc8238b330a165782dbc62fdbf3a7
277
# frozen_string_literal: true require 'rails_helper' require 'models/step_shared_examples' RSpec.describe RimrockStep do subject { RimrockStep.new('rom', 'my/repo', 'repo_file.erb.sh') } let(:pipeline) { create(:pipeline) } it_behaves_like 'pipeline step builder' end
23.083333
67
0.754513
ab983e2fcb79b6e9dc6933a63b65a490f424f03c
6,378
# frozen_string_literal: true require "active_support/core_ext/class/attribute" module ActiveModel # == Active \Model \Error # # Represents one single error class Error CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict] MESSAGE_OPTIONS = [:message] class_attribute :i18n_customize_full_message, default: false def self.full_message(attribute, message, base_class) # :nodoc: return message if attribute == :base attribute = attribute.to_s if i18n_customize_full_message && base_class.respond_to?(:i18n_scope) attribute = attribute.remove(/\[\d+\]/) parts = attribute.split(".") attribute_name = parts.pop namespace = parts.join("/") unless parts.empty? attributes_scope = "#{base_class.i18n_scope}.errors.models" if namespace defaults = base_class.lookup_ancestors.map do |klass| [ :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.attributes.#{attribute_name}.format", :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.format", ] end else defaults = base_class.lookup_ancestors.map do |klass| [ :"#{attributes_scope}.#{klass.model_name.i18n_key}.attributes.#{attribute_name}.format", :"#{attributes_scope}.#{klass.model_name.i18n_key}.format", ] end end defaults.flatten! else defaults = [] end defaults << :"errors.format" defaults << "%{attribute} %{message}" attr_name = attribute.tr(".", "_").humanize attr_name = base_class.human_attribute_name(attribute, default: attr_name) I18n.t(defaults.shift, default: defaults, attribute: attr_name, message: message) end def self.generate_message(attribute, type, base, options) # :nodoc: type = options.delete(:message) if options[:message].is_a?(Symbol) value = (attribute != :base ? base.send(:read_attribute_for_validation, attribute) : nil) options = { model: base.model_name.human, attribute: base.class.human_attribute_name(attribute), value: value, object: base }.merge!(options) if base.class.respond_to?(:i18n_scope) i18n_scope = base.class.i18n_scope.to_s attribute = attribute.to_s.remove(/\[\d+\]/) defaults = base.class.lookup_ancestors.flat_map do |klass| [ :"#{i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}", :"#{i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ] end defaults << :"#{i18n_scope}.errors.messages.#{type}" catch(:exception) do translation = I18n.translate(defaults.first, **options.merge(default: defaults.drop(1), throw: true)) return translation unless translation.nil? end unless options[:message] else defaults = [] end defaults << :"errors.attributes.#{attribute}.#{type}" defaults << :"errors.messages.#{type}" key = defaults.shift defaults = options.delete(:message) if options[:message] options[:default] = defaults I18n.translate(key, **options) end def initialize(base, attribute, type = :invalid, **options) @base = base @attribute = attribute @raw_type = type @type = type || :invalid @options = options end def initialize_dup(other) # :nodoc: @attribute = @attribute.dup @raw_type = @raw_type.dup @type = @type.dup @options = @options.deep_dup end # The object which the error belongs to attr_reader :base # The attribute of +base+ which the error belongs to attr_reader :attribute # The type of error, defaults to `:invalid` unless specified attr_reader :type # The raw value provided as the second parameter when calling `errors#add` attr_reader :raw_type # The options provided when calling `errors#add` attr_reader :options # Returns the error message. # # error = ActiveModel::Error.new(person, :name, :too_short, count: 5) # error.message # # => "is too short (minimum is 5 characters)" def message case raw_type when Symbol self.class.generate_message(attribute, raw_type, @base, options.except(*CALLBACKS_OPTIONS)) else raw_type end end # Returns the error details. # # error = ActiveModel::Error.new(person, :name, :too_short, count: 5) # error.details # # => { error: :too_short, count: 5 } def details { error: raw_type }.merge(options.except(*CALLBACKS_OPTIONS + MESSAGE_OPTIONS)) end alias_method :detail, :details # Returns the full error message. # # error = ActiveModel::Error.new(person, :name, :too_short, count: 5) # error.full_message # # => "Name is too short (minimum is 5 characters)" def full_message self.class.full_message(attribute, message, @base.class) end # See if error matches provided +attribute+, +type+ and +options+. # # Omitted params are not checked for a match. def match?(attribute, type = nil, **options) if @attribute != attribute || (type && @type != type) return false end options.each do |key, value| if @options[key] != value return false end end true end # See if error matches provided +attribute+, +type+ and +options+ exactly. # # All params must be equal to Error's own attributes to be considered a # strict match. def strict_match?(attribute, type, **options) return false unless match?(attribute, type) options == @options.except(*CALLBACKS_OPTIONS + MESSAGE_OPTIONS) end def ==(other) # :nodoc: other.is_a?(self.class) && attributes_for_hash == other.attributes_for_hash end alias eql? == def hash # :nodoc: attributes_for_hash.hash end def inspect # :nodoc: "#<#{self.class.name} attribute=#{@attribute}, type=#{@type}, options=#{@options.inspect}>" end protected def attributes_for_hash [@base, @attribute, @raw_type, @options.except(*CALLBACKS_OPTIONS)] end end end
31.418719
115
0.625902
b9546362207c22ddfc0e0e746c731149ef4f8d94
1,327
## # $Id$ ## ## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # Framework web site for more information on licensing and terms of use. # http://metasploit.com/framework/ ## require 'msf/core' class Metasploit3 < Msf::Auxiliary include Msf::Auxiliary::Report include Msf::Exploit::Capture def initialize super( 'Name' => 'Simple Ethernet Frame Spoofer', 'Version' => '$Revision$', 'Description' => 'This module sends spoofed ethernet frames', 'Author' => 'hdm', 'License' => MSF_LICENSE, 'Actions' => [ [ 'Spoofer' ] ], 'DefaultAction' => 'Spoofer' ) end def run print_status("Opening the network interface...") open_pcap() r = Racket::Racket.new r.l2 = Racket::L2::Ethernet.new r.l2.ethertype = 0x0800 r.l2.src_mac = "00:41:41:41:41:41" r.l2.dst_mac = "00:42:42:42:42:42" r.l3 = Racket::L3::IPv4.new r.l3.src_ip = "41.41.41.41" r.l3.dst_ip = "42.42.42.42" r.l3.protocol = 17 r.l4 = Racket::L4::UDP.new r.l4.src_port = 0x41 r.l4.dst_port = 0x42 r.l4.payload = "SPOOOOOFED" r.l4.fix!(r.l3.src_ip, r.l3.dst_ip) 1.upto(10) do capture.inject(r.pack) end close_pcap() print_status("Finished sending") end end
20.734375
72
0.639789
2874e0a7d5104c96ee5e22b9c764ce326a0c19d3
2,129
require 'json' require_relative '../lib/karabiner.rb' TENKEY_MAPPING = { 'm'=> '1', 'comma'=> '2', 'period'=> '3', 'j'=> '4', 'k'=> '5', 'l'=> '6', 'u'=> '7', 'i'=> '8', 'o'=> '9', 'spacebar'=> '0' } ARITHMETIC_SYMBOLS_MAPPING = { 'semicolon' => 'keypad_plus', 'p' => 'keypad_hyphen', 'slash'=> 'keypad_equal_sign', '9' => 'keypad_slash', '0' => 'keypad_asterisk' } def main puts JSON.pretty_generate( title: 'CAPS 4 Tenkey', maintainers: %w[IvanShamatov], rules: [ tenkey_toggle, tenkey_mapping, arithmetic_symbols_mapping, ] ) end def tenkey_toggle { description: 'CAPS Tenkey: TenkeyMode on/off toggle', manipulators: [ # Turning on Tenkey mode { from: _from('caps_lock', [], ['any']), type: 'basic', to: _set_variable('tenkey_mode', 1), conditions: tenkey_mode_off }, # Turning off Tenkey mode { from: _from('caps_lock', [], ['any']), type: 'basic', to: _set_variable('tenkey_mode', 0), conditions: tenkey_mode_on } ] } end def tenkey_mapping { description: 'CAPS Tenkey: if TenkeyMode ON m,.jkluio' ' maps to 1234567890', manipulators: map_keys(TENKEY_MAPPING, conditions: tenkey_mode_on) } end def arithmetic_symbols_mapping { description: 'CAPS Tenkey: if TenkeyMode ON 90p;/ maps to /*-+=', manipulators: map_keys(ARITHMETIC_SYMBOLS_MAPPING, conditions: tenkey_mode_on) } end def _from(key_code, mandatory = [], optional = []) { key_code: key_code, modifiers: { mandatory: mandatory, optional: optional } } end def map_keys(mapping, conditions: []) mapping.map do |from_key, to_key| { type: 'basic', from: _from(from_key), to: { key_code: to_key }, conditions: conditions } end end def _set_variable(name, value) { set_variable: { name: name, value: value } } end def tenkey_mode_on [{ type: 'variable_if', name: 'tenkey_mode', value: 1 }] end def tenkey_mode_off [{ type: 'variable_if', name: 'tenkey_mode', value: 0 }] end main
19.712963
82
0.602161
016601eda2e4c98e2cbcd09e4a5632214642bf5d
341
cask "font-im-fell-dw-pica" do version :latest sha256 :no_check url "https://github.com/google/fonts/trunk/ofl/imfelldwpica", verified: "github.com/google/fonts/", using: :svn name "IM Fell DW Pica" homepage "https://fonts.google.com/specimen/IM+Fell+DW+Pica" font "IMFePIit28P.ttf" font "IMFePIrm28P.ttf" end
24.357143
63
0.68915
39bd88a95a2db8c240dbaee879c9c4c895687334
461
# frozen_string_literal: true require 'spec_helper' require 'vk/api/friends/responses/delete_all_requests_response' RSpec.describe Vk::API::Friends::Responses::DeleteAllRequestsResponse do subject(:model) { described_class } it { is_expected.to be < Dry::Struct } it { is_expected.to be < Vk::Schema::Response } describe 'attributes' do subject(:attributes) { model.instance_methods(false) } it { is_expected.to include :response } end end
28.8125
72
0.748373
87e57acbad6af77e95c5be666d71686124b83d7a
430
class CreateAppointment < ActiveRecord::Migration[5.1] def change create_table :physicians do |t| t.string :name t.timestamps end create_table :patients do |t| t.string :name t.timestamps end create_table :appointments do |t| t.belongs_to :physician, index: true t.belongs_to :patient, index: true t.datetime :appointment_date t.timestamps end end end
20.47619
54
0.651163
e24f14b83f9b93d9b1a915e1e1123aa2f46f560d
1,691
# frozen_string_literal: true RSpec.describe Material::Base, type: :material do subject { described_class } it { is_expected.to inherit_from Spicerack::AttributeObject } it { is_expected.to extend_module ActiveSupport::NumberHelper } it { is_expected.to include_module Conjunction::Junction } it { is_expected.to include_module Material::Components } it { is_expected.to include_module Material::Core } it { is_expected.to include_module Material::Display } it { is_expected.to include_module Material::Text } it { is_expected.to include_module Material::Site } it { is_expected.to include_module Material::Format } it { is_expected.to include_module Material::Attributes } it { is_expected.to have_material_component :list_item_style } describe ".for" do include_context "with an example material" it_behaves_like "a material lookup" do let(:base_class) { described_class } let(:example_class) { example_material_class } end end describe ".for_class" do include_context "with an example material" it_behaves_like "a material class lookup" do let(:base_class) { described_class } let(:example_class) { example_material_class } end end describe "#to_source_model" do include_context "with an example material" subject { example_material.to_source_model } let(:source_model) { double } before { allow(source).to receive(:to_model).and_return(source_model) } it { is_expected.to eq source_model } end describe "#to_model" do include_context "with an example material" subject { example_material.to_model } it { is_expected.to eq example_material } end end
28.183333
75
0.735659
ff6bc768446129a94c3f778113f90e59a2ea9a14
395
# frozen_string_literal: true require "bundler/setup" require "panolint" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
23.235294
66
0.756962
1a7be01c6d667b7f2993375932eb4eb0e602d07a
5,185
# # Be sure to run `pod spec lint QDXTFanqie.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see https://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |spec| # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # These will help people to find your library, and whilst it # can feel like a chore to fill in it's definitely to your advantage. The # summary should be tweet-length, and the description more in depth. # spec.name = "QDXTLast" spec.version = "1.0.0" spec.summary = "A short description of QDXTFanqie." # 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! spec.description = <<-DESC QDXTFanqie是一个iOS项目主键化管理工具 DESC spec.homepage = "https://github.com/xiaofanqie22/QDXTLast.git" # spec.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif" # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Licensing your code is important. See https://choosealicense.com for more info. # CocoaPods will detect a license file if there is a named LICENSE* # Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'. # #spec.license = "MIT (example)" spec.license = { :type => "MIT", :file => "LICENSE" } # ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Specify the authors of the library, with email addresses. Email addresses # of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also # accepts just a name if you'd rather not provide an email address. # # Specify a social_media_url where others can refer to, for example a twitter # profile URL. # spec.author = { "baipingdev" => "[email protected]" } # Or just: spec.author = "baipingdev" # spec.authors = { "baipingdev" => "[email protected]" } # spec.social_media_url = "https://twitter.com/baipingdev" # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # If this Pod runs only on iOS or OS X, then specify the platform and # the deployment target. You can optionally include the target after the platform. # spec.platform = :ios # spec.platform = :ios, "5.0" # When using multiple platforms # spec.ios.deployment_target = "5.0" # spec.osx.deployment_target = "10.7" # spec.watchos.deployment_target = "2.0" # spec.tvos.deployment_target = "9.0" # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Specify the location from where the source should be retrieved. # Supports git, hg, bzr, svn and HTTP. # spec.source = { :git => "https://github.com/xiaofanqie22/QDXTLast.git", :tag => spec.version } # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # CocoaPods is smart about how it includes source code. For source files # giving a folder will include any swift, h, m, mm, c & cpp files. # For header files it will include any header in the folder. # Not including the public_header_files will make all headers public. # spec.source_files = "QDXTCocoaPods/ygxtClass/ViewController.h" # spec.public_header_files = "ygxtClass/ygxtClass/ViewController.h" # ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # A list of resources included with the Pod. These are copied into the # target bundle with a build phase script. Anything else will be cleaned. # You can preserve files from being cleaned, please don't preserve # non-essential files like tests, examples and documentation. # # spec.resource = "icon.png" # spec.resources = "Resources/*.png" # spec.preserve_paths = "FilesToSave", "MoreFilesToSave" # ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Link your library with frameworks, or libraries. Libraries do not include # the lib prefix of their name. # # spec.framework = "SomeFramework" # spec.frameworks = "SomeFramework", "AnotherFramework" # spec.library = "iconv" # spec.libraries = "iconv", "xml2" # ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # If your library depends on compiler flags you can set them in the xcconfig hash # where they will only apply to your library. If you depend on other Podspecs # you can include multiple dependencies to ensure it works. spec.requires_arc = true # spec.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" } # spec.dependency "JSONKit", "~> 1.4" end
37.846715
102
0.605786
61cc5145ebdafc2a5db2e193f376d967b8bea773
350
require 'active_support/concern' module CamelizeKeys module ControllerExtension extend ActiveSupport::Concern included do before_filter do CamelizeKeys.underscore_keys params, deep: true end rescue_from CamelizeKeys::CollisionError do |e| render "public/400", :status => 400 end end end end
19.444444
55
0.691429
e8c2b8812cf7014ad81f3fb0538835b76d9bff38
1,047
# frozen_string_literal: true require_relative "error" require_relative "config" require_relative "credentials" require_relative "auth/client" module Firebase module Admin # An App holds configuration and state common to all Firebase services that are exposed from the SDK. class App attr_reader :project_id, :service_account_id, :credentials # Constructs a new App. # # @param [Credentials] credentials # Credentials for authenticating with Firebase. # @param [Config] config # Firebase configuration options. def initialize(credentials: nil, config: nil) @config = config || Config.from_env @credentials = credentials || Credentials.from_default @service_account_id = @config.service_account_id @project_id = @config.project_id || @credentials.project_id end # Gets the auth client for this App. # @return [Firebase::Admin::Auth::Client] def auth @auth_client ||= Auth::Client.new(self) end end end end
29.914286
105
0.684814
6154bffcb4a931da351917d382845b1035ccfcbd
342
module InformantRails class Model < Struct.new(:model) def name model.class.name end def errors model.errors.map do |field, error| InformantRails::FieldError.new(field.to_s, model[field], error) end end def as_json(*args) { name: name, errors: errors.map(&:as_json) } end end end
19
71
0.622807
d5c8b47cdb804c496b84bc92c2ef71d29801fae8
1,590
class EventsController < ApplicationController #presents new event form get '/events' do redirect_if_not_logged_in #helper method erb :'/events/new' #renders form for a new event end #creates a new event post '/events/new' do @user = current_user event = @user.events.create(:name => params[:name]) moment = event.moments.create(:name => params[:moments][:name]) redirect '/moments' #creates a new event then redirects to the moments page end #Dynamic routes example: #The HTTP request verb, GET matches the get method in our controller. The /events/1/edit path in the #HTTP request matches our path in this controller method. The 1 is an id parameter that's being passed #into the path, matching the controllers expectation for an id parameter to be passed in place of :id #presents a form to edit an event get '/events/:id/edit' do redirect_if_not_logged_in @event = Event.find_by_id(params[:id]) erb :'events/edit' end #updates/edits our existing event using the patch action patch '/events/:id' do @event = Event.find_by_id(params[:id]) @event.name = params[:name] @event.save redirect '/moments' end #presents the delete prompt to ensure you want to delete a specific event get '/events/:id/delete' do @event = Event.find_by_id(params[:id]) erb :'events/delete' end #deletes the event delete '/events/:id' do @event = Event.find_by_id(params[:id]) @event.destroy redirect '/moments' end end
31.176471
106
0.669182
385006b95c76ebf7cd30fc16611f92dc3a2bf7dd
725
Pod::Spec.new do |s| s.name = 'AWSTranscribe' s.version = '2.25.0' s.summary = 'Amazon Web Services SDK for iOS.' s.description = 'The AWS SDK for iOS provides a library, code samples, and documentation for developers to build connected mobile applications using AWS.' s.homepage = 'http://aws.amazon.com/mobile/sdk' s.license = 'Apache License, Version 2.0' s.author = { 'Amazon Web Services' => 'amazonwebservices' } s.platform = :ios, '9.0' s.source = { :git => 'https://github.com/aws-amplify/aws-sdk-ios.git', :tag => s.version} s.requires_arc = true s.dependency 'AWSCore', '2.25.0' s.source_files = 'AWSTranscribe/*.{h,m}' end
40.277778
157
0.617931
e2f1a2363bcc7aff22d5133ad701b53d2b33878f
4,296
require 'spec_helper' describe 'nexus::package', :type => :class do on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) do facts end let(:params) { { 'deploy_pro' => false, 'download_site' => 'http://download.sonatype.com/nexus/oss', 'nexus_root' => '/srv', 'nexus_home_dir' => 'nexus', 'nexus_user' => 'nexus', 'nexus_group' => 'nexus', 'nexus_work_dir' => '/srv/sonatype-work/nexus', 'nexus_work_dir_manage' => true, 'nexus_work_recurse' => true, 'nexus_type' => 'bundle', 'nexus_selinux_ignore_defaults' => true, # Assume a good revision as init.pp screens for us 'revision' => '01', 'version' => '2.11.2', 'download_folder' => '/srv', 'md5sum' => '', } } context 'with default values' do it { should contain_class('nexus::package') } it { should contain_wget__fetch('nexus-2.11.2-01-bundle.tar.gz').with( 'source' => 'http://download.sonatype.com/nexus/oss/nexus-2.11.2-01-bundle.tar.gz', 'destination' => '/srv/nexus-2.11.2-01-bundle.tar.gz', 'before' => 'Exec[nexus-untar]', 'source_hash' => '', ) } it { should contain_exec('nexus-untar').with( 'command' => 'tar zxf /srv/nexus-2.11.2-01-bundle.tar.gz --directory /srv', 'creates' => '/srv/nexus-2.11.2-01', 'path' => [ '/bin', '/usr/bin' ], ) } it { should contain_file('/srv/nexus-2.11.2-01').with( 'ensure' => 'directory', 'owner' => 'nexus', 'group' => 'nexus', 'recurse' => true, 'require' => 'Exec[nexus-untar]', ) } it { should contain_file('/srv/sonatype-work/nexus').with( 'ensure' => 'directory', 'owner' => 'nexus', 'group' => 'nexus', 'recurse' => true, 'require' => 'Exec[nexus-untar]', ) } it { should contain_file('/srv/nexus').with( 'ensure' => 'link', 'target' => '/srv/nexus-2.11.2-01', 'require' => 'Exec[nexus-untar]', ) } it 'should handle deploy_pro' do params.merge!( { 'deploy_pro' => true, 'download_site' => 'http://download.sonatype.com/nexus/professional-bundle' } ) should contain_wget__fetch('nexus-professional-2.11.2-01-bundle.tar.gz').with( 'source' => 'http://download.sonatype.com/nexus/professional-bundle/nexus-professional-2.11.2-01-bundle.tar.gz', 'destination' => '/srv/nexus-professional-2.11.2-01-bundle.tar.gz', ) should contain_exec('nexus-untar').with( 'command' => 'tar zxf /srv/nexus-professional-2.11.2-01-bundle.tar.gz --directory /srv', 'creates' => '/srv/nexus-professional-2.11.2-01', ) should contain_file('/srv/nexus-professional-2.11.2-01') should contain_file('/srv/nexus').with( 'target' => '/srv/nexus-professional-2.11.2-01', ) end it 'should working with md5sum' do params.merge!( { 'md5sum' => '1234567890' } ) should contain_wget__fetch('nexus-2.11.2-01-bundle.tar.gz').with( 'source' => 'http://download.sonatype.com/nexus/oss/nexus-2.11.2-01-bundle.tar.gz', 'destination' => '/srv/nexus-2.11.2-01-bundle.tar.gz', 'before' => 'Exec[nexus-untar]', 'source_hash' => '1234567890', ) should contain_exec('nexus-untar').with( 'command' => 'tar zxf /srv/nexus-2.11.2-01-bundle.tar.gz --directory /srv', 'creates' => '/srv/nexus-2.11.2-01', 'path' => [ '/bin', '/usr/bin' ], ) end end end end end # vim: sw=2 ts=2 sts=2 et :
35.8
124
0.474395
283221744384a9baac6ab515de47f11a6edea6a6
4,090
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = Uglifier.new(harmony: true) # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options) config.active_storage.service = :local # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "earthquake_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') config.serve_static_assets = true config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' config.assets.compile = true if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
41.313131
102
0.759413
08bf46b418e51b20c3db3fb34378dab9363a4b84
328
require 'steps/common_steps' steps_for :search_with_drivers do include CommonSteps step "I am on wikipedia.com" do visit('/') end step "I enter word :word" do |word| fill_in "searchInput", :with => word end step "I submit request" do find(".sprite-icons-search-icon", match: :first).click end end
17.263158
58
0.676829
012fdf1d02f606592f3435810a998f60d8e3cc3b
2,171
module SmartEnv EXPLICITLY_FALSE_VALUES = [0, "0", "false", "no"] def self.keys @keys ||= [] end def self.default_values @default_values ||= {} end def self.required_keys @required_keys ||= [] end def self.boolean_keys @boolean_keys ||= [] end def self.reset! @keys = nil @required_keys = nil @boolean_keys = nil @default_values = nil end def self.set key, opts={} self.add key, opts end def self.add key, opts={} key = key.to_s keys << key unless keys.include?(key) if opts.has_key?(:required) required_keys.delete key required_keys << key if opts[:required] end if opts.has_key?(:boolean) boolean_keys.delete key boolean_keys << key if opts[:boolean] end if opts.has_key?(:default) default_values[key] = opts[:default] end end def self.add_required key, opts={} self.add key, opts.update({required: true}) end def self.add_boolean key, opts={} self.add key, opts.update({boolean: true}) end def self.check! required_keys.each do |k| raise MissingKey.new("Missing mandatory ENV key `#{k}`") unless ENV.has_key?(k) end end def self.[] key self.fetch(key) end def self.boolean key, opts={} self.fetch key, opts.update({boolean: true}) end def self.fetch key, opts={} key = key.to_s unless keys.include?(key) logger.warn("Fetching unexpected ENV key `#{key}`") keys << key end default = nil default = opts[:default] if opts.has_key?(:default) default = yield if block_given? val = ENV.fetch(key, nil) || default || default_values[key] val = cast_boolean(val) if opts[:boolean] || boolean_keys.include?(key) val end @@default_logger = nil def self.default_logger @@default_logger ||= Logger.new($stdout) end def self.logger Rails.logger || default_logger end def self.cast_boolean value value = value.downcase if value.is_a?(String) return false if EXPLICITLY_FALSE_VALUES.include?(value) return value.present? if value.is_a?(String) !!value end class MissingKey < Exception end end
20.875
85
0.640258
ab37f9176f01aa319ec646c8823b1a39414e7069
2,333
# server-based syntax # ====================== # Defines a single server with a list of roles and multiple properties. # You can define all roles on a single server, or split them: server "35.182.156.156", user: "ubuntu", roles: %w{app db web} # server "example.com", user: "deploy", roles: %w{app web}, other_property: :other_value # server "db.example.com", user: "deploy", roles: %w{db} app = ENV['APP'] if app.nil? or app.empty? app = "AndreDeSantana" end set :application, app set :rails_env, "development" set :bundle_without, "production" set :deploy_to, "/home/ubuntu/apps/#{app}" set :linked_dirs, %w{tmp/pids tmp/sockets log} set :linked_files, %w{config/database.yml config/database_second.yml config/application.yml} # role-based syntax # ================== # Defines a role with one or multiple servers. The primary server in each # group is considered to be the first unless any hosts have the primary # property set. Specify the username and a domain or IP for the server. # Don't use `:all`, it's a meta role. role :app, %w{[email protected]} role :web, %w{[email protected]} role :db, %w{[email protected]} # Configuration # ============= # You can set any configuration variable like in config/deploy.rb # These variables are then only loaded and set in this stage. # For available Capistrano configuration variables see the documentation page. # http://capistranorb.com/documentation/getting-started/configuration/ # Feel free to add new variables to customise your setup. # Custom SSH Options # ================== # You may pass any option but keep in mind that net/ssh understands a # limited set of options, consult the Net::SSH documentation. # http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start # # Global options # -------------- # set :ssh_options, { # keys: %w(/home/rlisowski/.ssh/id_rsa), # forward_agent: false, # auth_methods: %w(password) # } # # The server-based syntax can be used to override options: # ------------------------------------ # server "example.com", # user: "user_name", # roles: %w{web app}, # ssh_options: { # user: "user_name", # overrides user setting above # keys: %w(/home/user_name/.ssh/id_rsa), # forward_agent: false, # auth_methods: %w(publickey password) # # password: "please use keys" # }
33.811594
92
0.675954
21ce7a28e1b2589c4d609a3b2003b9909a3cde04
917
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'undergrounder/version' Gem::Specification.new do |gem| gem.name = "undergrounder" gem.version = Undergrounder::VERSION gem.authors = ["Enzo Rivello"] gem.email = ["[email protected]"] gem.description = "Simple Implementation of a short path finder for the London Tube" gem.summary = "" gem.homepage = "https://github.com/enzor/undergrounder" gem.add_dependency "sinatra" gem.add_dependency "padrino" gem.add_development_dependency "rspec" gem.add_development_dependency "ruby-debug19" gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] end
36.68
88
0.670665
e24f878a50e3d53cb9f86d5eb391ce8954d2913e
7,091
require 'xcodeproj/project/object/helpers/groupable_helper' module Xcodeproj class Project module Object # This class represents a reference to a file in the file system. # class PBXFileReference < AbstractObject # @!group Attributes # @return [String] the name of the reference, often not present. # attribute :name, String # @return [String] the path to the file relative to the source tree # attribute :path, String # @return [String] the directory to which the path is relative. # # @note The accepted values are: # - `<absolute>` for absolute paths # - `<group>` for paths relative to the group # - `SOURCE_ROOT` for paths relative to the project # - `DEVELOPER_DIR` for paths relative to the developer # directory. # - `BUILT_PRODUCTS_DIR` for paths relative to the build # products directory. # - `SDKROOT` for paths relative to the SDK directory. # attribute :source_tree, String, 'SOURCE_ROOT' # @return [String] the file type (apparently) used for products # generated by Xcode (i.e. applications, libraries). # attribute :explicit_file_type, String # @return [String] the file type guessed by Xcode. # # @note This attribute is not present if there is an # `explicit_file_type`. # attribute :last_known_file_type, String # @return [String] whether this file should be indexed. It can # be either `0` or `1`. # # @note Apparently present only for products generated by Xcode with # a value of `0`. # attribute :include_in_index, String, '1' # @return [String] a string containing a number which represents the # encoding format of the file. # attribute :fileEncoding, String # @return [String] a string that specifies the UTI for the syntax # highlighting. # # @example # `xcode.lang.ruby` # attribute :xc_language_specification_identifier, String # @return [String] a string that specifies the UTI for the structure of # a plist file. # # @example # `com.apple.xcode.plist.structure-definition.iphone.info-plist` # attribute :plist_structure_definition_identifier, String # @return [String] Whether Xcode should use tabs for text alignment. # # @example # `1` # attribute :uses_tabs, String # @return [String] The width of the indent. # # @example # `2` # attribute :indent_width, String # @return [String] The width of the tabs. # # @example # `2` # attribute :tab_width, String # @return [String] Whether Xcode should wrap lines. # # @example # `1` # attribute :wraps_lines, String # @return [String] Apparently whether Xcode should add, if needed, a # new line feed before saving the file. # # @example # `0` # attribute :line_ending, String # @return [String] Comments associated with this file. # # @note This is apparently no longer used by Xcode. # attribute :comments, String attribute :refType, String, '0' #---------------------------------------------------------------------# public # @!group Helpers # @return [String] the name of the file taking into account the path if # needed. # def display_name name || (File.basename(path) if path) end # @return [PBXGroup, PBXProject] the parent of the file. # def parent GroupableHelper.parent(self) end # @return [Array<PBXGroup, PBXProject>] The list of the parents of the # reference. # def parents GroupableHelper.parents(self) end # @return [String] A representation of the reference hierarchy. # def hierarchy_path GroupableHelper.hierarchy_path(self) end # Moves the reference to a new parent. # # @param [PBXGroup] new_parent # The new parent. # # @return [void] # def move(new_parent) GroupableHelper.move(self, new_parent) end # @return [Pathname] the absolute path of the file resolving the # source tree. # def real_path GroupableHelper.real_path(self) end # Sets the source tree of the reference. # # @param [Symbol, String] source_tree # The source tree, either a string or a symbol. # # @return [void] # def set_source_tree(source_tree) GroupableHelper.set_source_tree(self, source_tree) end # Allows to set the path according to the source tree of the reference. # # @param [#to_s] the path for the reference. # # @return [void] # def set_path(path) if path GroupableHelper.set_path_with_source_tree(self, path, source_tree) else self.path = nil end end # @return [Array<PBXBuildFile>] the build files associated with the # current file reference. # def build_files referrers.select { |r| r.class == PBXBuildFile } end # Sets the last known file type according to the extension of the path. # # @return [void] # def set_last_known_file_type(type = nil) if type self.last_known_file_type = type elsif path extension = Pathname(path).extname[1..-1] self.last_known_file_type = Constants::FILE_TYPES_BY_EXTENSION[extension] end end # Sets the explicit file type according to the extension of the path, # and clears the last known file type. # # @return [void] # def set_explicit_file_type(type = nil) self.last_known_file_type = nil if type self.explicit_file_type = type elsif path extension = Pathname(path).extname[1..-1] self.explicit_file_type = Constants::FILE_TYPES_BY_EXTENSION[extension] end end # Checks whether the reference is a proxy. # # @return [Bool] always false for this ISA. # def proxy? false end #---------------------------------------------------------------------# end end end end
29.061475
85
0.53575
d538b49647c3df86ad0056687c0d6c7beab32153
2,616
require File.expand_path('spec_helper', File.dirname(__FILE__)) describe Sunspot::Batcher do it "includes Enumerable" do expect(described_class).to include Enumerable end describe "#each" do let(:current) { [:foo, :bar] } before { allow(subject).to receive(:current).and_return current } it "iterates over current" do yielded_values = [] subject.each do |value| yielded_values << value end expect(yielded_values).to eq current end end describe "adding to current batch" do it "#push pushes to current" do subject.push :foo expect(subject.current).to include :foo end it "#<< pushes to current" do subject.push :foo expect(subject.current).to include :foo end it "#concat concatinates on current batch" do subject << :foo subject.concat [:bar, :mix] is_expected.to include :foo, :bar, :mix end end describe "#current" do context "no current" do it "starts a new" do expect { subject.current }.to change(subject, :depth).by 1 end it "is empty by default" do expect(subject.current).to be_empty end end context "with a current" do before { subject.start_new } it "does not start a new" do expect { subject.current }.to_not change(subject, :depth) end it "returns the same as last time" do expect(subject.current).to eq subject.current end end end describe "#start_new" do it "creates a new batches" do expect { 2.times { subject.start_new } }.to change(subject, :depth).by 2 end it "changes current" do subject << :foo subject.start_new is_expected.not_to include :foo end end describe "#end_current" do context "no current batch" do it "fails" do expect { subject.end_current }.to raise_error Sunspot::Batcher::NoCurrentBatchError end end context "with current batch" do before { subject.start_new } it "changes current" do subject << :foo subject.end_current is_expected.not_to include :foo end it "returns current" do subject << :foo expect(subject.end_current).to include :foo end end end describe "#batching?" do it "is false when depth is 0" do expect(subject).to receive(:depth).and_return 0 is_expected.not_to be_batching end it "is true when depth is more than 0" do expect(subject).to receive(:depth).and_return 1 is_expected.to be_batching end end end
23.150442
91
0.630734
012a7ced7d01785da72aa9e325d08a3c853cfed1
1,674
require File.expand_path('../integration_test', __FILE__) module Propono class SlowQueueTest < IntegrationTest def test_slow_messages_are_received topic = "propono-tests-slow-queue-topic" slow_topic = "propono-tests-slow-queue-topic-slow" text = "This is my message #{DateTime.now} #{rand()}" slow_text = "This is my slow message #{DateTime.now} #{rand()}" flunks = [] message_received = false slow_message_received = false propono_client.drain_queue(topic) propono_client.drain_queue(slow_topic) propono_client.subscribe(topic) thread = Thread.new do begin propono_client.listen(topic) do |message, context| flunks << "Wrong message" unless (message == text || message == slow_text) message_received = true if message == text slow_message_received = true if message == slow_text thread.terminate if message_received && slow_message_received end rescue => e flunks << e.message ensure thread.terminate end end Thread.new do sleep(1) while !message_received sleep(1) while !slow_message_received sleep(5) # Make sure all the message deletion clear up in the thread has happened thread.terminate end sleep(1) # Make sure the listener has started propono_client.publish(slow_topic, slow_text) propono_client.publish(topic, text) flunks << "Test Timeout" unless wait_for_thread(thread, 60) flunk(flunks.join("\n")) unless flunks.empty? ensure thread.terminate if thread end end end
31.584906
89
0.650538
287447ccc8adabe5c8b31815fc74cd079cfb0fee
760
require 'rails/generators' require "rails/generators/active_record" class FriendlyIdMobilityGenerator < ::Rails::Generators::Base include ::Rails::Generators::Migration desc "Generates migration to add locale column to friendly_id_slugs table." source_root File.expand_path('../templates', __FILE__) def self.next_migration_number(dirname) ::ActiveRecord::Generators::Base.next_migration_number(dirname) end def create_migration_file template = "add_locale_to_friendly_id_slugs" migration_dir = File.expand_path("db/migrate") if self.class.migration_exists?(migration_dir, template) ::Kernel.warn "Migration already exists." else migration_template "migration.rb", "db/migrate/#{template}.rb" end end end
30.4
77
0.760526
bfb118c41601388c414190596fa75344174063ec
37,951
## # This file contains stuff stolen outright from: # # rtags.rb - # ruby-lex.rb - ruby lexcal analyzer # ruby-token.rb - ruby tokens # by Keiju ISHITSUKA (Nippon Rational Inc.) # require 'rdoc/ruby_token' require 'rdoc/ruby_lex' require 'rdoc/code_objects' require 'rdoc/tokenstream' require 'rdoc/markup/preprocess' require 'rdoc/parser' require 'rdoc/parser/ruby_tools' $TOKEN_DEBUG ||= nil ## # Extracts code elements from a source file returning a TopLevel object # containing the constituent file elements. # # This file is based on rtags # # RubyParser understands how to document: # * classes # * modules # * methods # * constants # * aliases # * private, public, protected # * private_class_function, public_class_function # * module_function # * attr, attr_reader, attr_writer, attr_accessor # * extra accessors given on the command line # * metaprogrammed methods # * require # * include # # == Method Arguments # #-- # NOTE: I don't think this works, needs tests, remove the paragraph following # this block when known to work # # The parser extracts the arguments from the method definition. You can # override this with a custom argument definition using the :args: directive: # # ## # # This method tries over and over until it is tired # # def go_go_go(thing_to_try, tries = 10) # :args: thing_to_try # puts thing_to_try # go_go_go thing_to_try, tries - 1 # end # # If you have a more-complex set of overrides you can use the :call-seq: # directive: #++ # # The parser extracts the arguments from the method definition. You can # override this with a custom argument definition using the :call-seq: # directive: # # ## # # This method can be called with a range or an offset and length # # # # :call-seq: # # my_method(Range) # # my_method(offset, length) # # def my_method(*args) # end # # The parser extracts +yield+ expressions from method bodies to gather the # yielded argument names. If your method manually calls a block instead of # yielding or you want to override the discovered argument names use # the :yields: directive: # # ## # # My method is awesome # # def my_method(&block) # :yields: happy, times # block.call 1, 2 # end # # == Metaprogrammed Methods # # To pick up a metaprogrammed method, the parser looks for a comment starting # with '##' before an identifier: # # ## # # This is a meta-programmed method! # # add_my_method :meta_method, :arg1, :arg2 # # The parser looks at the token after the identifier to determine the name, in # this example, :meta_method. If a name cannot be found, a warning is printed # and 'unknown is used. # # You can force the name of a method using the :method: directive: # # ## # # :method: woo_hoo! # # By default, meta-methods are instance methods. To indicate that a method is # a singleton method instead use the :singleton-method: directive: # # ## # # :singleton-method: # # You can also use the :singleton-method: directive with a name: # # ## # # :singleton-method: woo_hoo! # # Additionally you can mark a method as an attribute by # using :attr:, :attr_reader:, :attr_writer: or :attr_accessor:. Just like # for :method:, the name is optional. # # ## # # :attr_reader: my_attr_name # # == Hidden methods and attributes # # You can provide documentation for methods that don't appear using # the :method:, :singleton-method: and :attr: directives: # # ## # # :attr_writer: ghost_writer # # There is an attribute here, but you can't see it! # # ## # # :method: ghost_method # # There is a method here, but you can't see it! # # ## # # this is a comment for a regular method # # def regular_method() end # # Note that by default, the :method: directive will be ignored if there is a # standard rdocable item following it. class RDoc::Parser::Ruby < RDoc::Parser parse_files_matching(/\.rbw?$/) include RDoc::RubyToken include RDoc::TokenStream include RDoc::Parser::RubyTools ## # RDoc::NormalClass type NORMAL = "::" ## # RDoc::SingleClass type SINGLE = "<<" def initialize(top_level, file_name, content, options, stats) super @size = 0 @token_listeners = nil @scanner = RDoc::RubyLex.new content, @options @scanner.exception_on_syntax_error = false @prev_seek = nil reset end ## # Look for the first comment in a file that isn't a shebang line. def collect_first_comment skip_tkspace comment = '' first_line = true tk = get_tk while TkCOMMENT === tk if first_line and tk.text =~ /\A#!/ then skip_tkspace tk = get_tk elsif first_line and tk.text =~ /\A#\s*-\*-/ then first_line = false skip_tkspace tk = get_tk else first_line = false comment << tk.text << "\n" tk = get_tk if TkNL === tk then skip_tkspace false tk = get_tk end end end unget_tk tk comment end def error(msg) msg = make_message msg $stderr.puts msg exit false end ## # Look for a 'call-seq' in the comment, and override the normal parameter # stuff def extract_call_seq(comment, meth) if comment.sub!(/:?call-seq:(.*?)^\s*\#?\s*$/m, '') then seq = $1 seq.gsub!(/^\s*\#\s*/, '') meth.call_seq = seq end meth end def get_bool skip_tkspace tk = get_tk case tk when TkTRUE true when TkFALSE, TkNIL false else unget_tk tk true end end ## # Look for the name of a class of module (optionally with a leading :: or # with :: separated named) and return the ultimate name and container def get_class_or_module(container) skip_tkspace name_t = get_tk # class ::A -> A is in the top level case name_t when TkCOLON2, TkCOLON3 then # bug name_t = get_tk container = @top_level end skip_tkspace false while TkCOLON2 === peek_tk do prev_container = container container = container.find_module_named name_t.name unless container then container = prev_container.add_module RDoc::NormalModule, name_t.name end get_tk name_t = get_tk end skip_tkspace false return [container, name_t] end ## # Return a superclass, which can be either a constant of an expression def get_class_specification tk = get_tk return "self" if TkSELF === tk res = "" while TkCOLON2 === tk or TkCOLON3 === tk or TkCONSTANT === tk do res += tk.name tk = get_tk end unget_tk(tk) skip_tkspace false get_tkread # empty out read buffer tk = get_tk case tk when TkNL, TkCOMMENT, TkSEMICOLON then unget_tk(tk) return res end res += parse_call_parameters(tk) res end ## # Parse a constant, which might be qualified by one or more class or module # names def get_constant res = "" skip_tkspace false tk = get_tk while TkCOLON2 === tk or TkCOLON3 === tk or TkCONSTANT === tk do res += tk.name tk = get_tk end # if res.empty? # warn("Unexpected token #{tk} in constant") # end unget_tk(tk) res end ## # Get a constant that may be surrounded by parens def get_constant_with_optional_parens skip_tkspace false nest = 0 while TkLPAREN === (tk = peek_tk) or TkfLPAREN === tk do get_tk skip_tkspace nest += 1 end name = get_constant while nest > 0 skip_tkspace tk = get_tk nest -= 1 if TkRPAREN === tk end name end def get_symbol_or_name tk = get_tk case tk when TkSYMBOL then text = tk.text.sub(/^:/, '') if TkASSIGN === peek_tk then get_tk text << '=' end text when TkId, TkOp then tk.name when TkSTRING, TkDSTRING then tk.text else raise RDoc::Error, "Name or symbol expected (got #{tk})" end end ## # Look for directives in a normal comment block: # # # :stopdoc: # # Don't display comment from this point forward # # This routine modifies it's parameter def look_for_directives_in(context, comment) preprocess = RDoc::Markup::PreProcess.new @file_name, @options.rdoc_include preprocess.handle comment, context do |directive, param| case directive when 'enddoc' then throw :enddoc when 'main' then @options.main_page = param '' when 'method', 'singleton-method', 'attr', 'attr_accessor', 'attr_reader', 'attr_writer' then false # handled elsewhere when 'section' then context.set_current_section param, comment comment.replace '' break when 'startdoc' then context.start_doc context.force_documentation = true '' when 'stopdoc' then context.stop_doc '' when 'title' then @options.title = param '' end end remove_private_comments comment end ## # Adds useful info about the parser to +message+ def make_message message prefix = "#{@file_name}:" prefix << "#{@scanner.line_no}:#{@scanner.char_no}:" if @scanner "#{prefix} #{message}" end ## # Creates an RDoc::Attr for the name following +tk+, setting the comment to # +comment+. def parse_attr(context, single, tk, comment) args = parse_symbol_arg 1 if args.size > 0 name = args[0] rw = "R" skip_tkspace false tk = get_tk if TkCOMMA === tk then rw = "RW" if get_bool else unget_tk tk end att = RDoc::Attr.new get_tkread, name, rw, comment read_documentation_modifiers att, RDoc::ATTR_MODIFIERS if att.document_self context.add_attribute(att) end else warn("'attr' ignored - looks like a variable") end end ## # Creates an RDoc::Attr for each attribute listed after +tk+, setting the # comment for each to +comment+. def parse_attr_accessor(context, single, tk, comment) args = parse_symbol_arg read = get_tkread rw = "?" # TODO If nodoc is given, don't document any of them tmp = RDoc::CodeObject.new read_documentation_modifiers tmp, RDoc::ATTR_MODIFIERS return unless tmp.document_self case tk.name when "attr_reader" then rw = "R" when "attr_writer" then rw = "W" when "attr_accessor" then rw = "RW" else rw = '?' end for name in args att = RDoc::Attr.new get_tkread, name, rw, comment context.add_attribute att end end def parse_alias(context, single, tk, comment) skip_tkspace if TkLPAREN === peek_tk then get_tk skip_tkspace end new_name = get_symbol_or_name @scanner.instance_eval { @lex_state = EXPR_FNAME } skip_tkspace if TkCOMMA === peek_tk then get_tk skip_tkspace end begin old_name = get_symbol_or_name rescue RDoc::Error return end al = RDoc::Alias.new get_tkread, old_name, new_name, comment read_documentation_modifiers al, RDoc::ATTR_MODIFIERS context.add_alias al if al.document_self end def parse_call_parameters(tk) end_token = case tk when TkLPAREN, TkfLPAREN TkRPAREN when TkRPAREN return "" else TkNL end nest = 0 loop do case tk when TkSEMICOLON break when TkLPAREN, TkfLPAREN nest += 1 when end_token if end_token == TkRPAREN nest -= 1 break if @scanner.lex_state == EXPR_END and nest <= 0 else break unless @scanner.continue end when TkCOMMENT, TkASSIGN, TkOPASGN unget_tk(tk) break when nil then break end tk = get_tk end res = get_tkread.tr("\n", " ").strip res = "" if res == ";" res end def parse_class(container, single, tk, comment) container, name_t = get_class_or_module container case name_t when TkCONSTANT name = name_t.name superclass = "Object" if TkLT === peek_tk then get_tk skip_tkspace superclass = get_class_specification superclass = "<unknown>" if superclass.empty? end cls_type = single == SINGLE ? RDoc::SingleClass : RDoc::NormalClass cls = container.add_class cls_type, name, superclass read_documentation_modifiers cls, RDoc::CLASS_MODIFIERS cls.record_location @top_level cls.comment = comment @stats.add_class cls parse_statements cls when TkLSHFT case name = get_class_specification when "self", container.name parse_statements container, SINGLE when /\A[A-Z]/ other = RDoc::TopLevel.find_class_named name unless other then other = container.add_module RDoc::NormalModule, name other.record_location @top_level other.comment = comment end @stats.add_class other read_documentation_modifiers other, RDoc::CLASS_MODIFIERS parse_statements(other, SINGLE) end else warn("Expected class name or '<<'. Got #{name_t.class}: #{name_t.text.inspect}") end end def parse_constant(container, tk, comment) name = tk.name skip_tkspace false eq_tk = get_tk unless TkASSIGN === eq_tk then unget_tk eq_tk return end nest = 0 get_tkread tk = get_tk if TkGT === tk then unget_tk tk unget_tk eq_tk return end rhs_name = '' loop do case tk when TkSEMICOLON then break when TkLPAREN, TkfLPAREN, TkLBRACE, TkLBRACK, TkDO, TkIF, TkUNLESS, TkCASE then nest += 1 when TkRPAREN, TkRBRACE, TkRBRACK, TkEND then nest -= 1 when TkCOMMENT then if nest <= 0 && @scanner.lex_state == EXPR_END unget_tk tk break end when TkCONSTANT then rhs_name << tk.name if nest <= 0 and TkNL === peek_tk then mod = if rhs_name =~ /^::/ then RDoc::TopLevel.find_class_or_module rhs_name else container.find_module_named rhs_name end container.add_module_alias mod, name if mod get_tk # TkNL break end when TkNL then if nest <= 0 && (@scanner.lex_state == EXPR_END || [email protected]) then unget_tk tk break end when TkCOLON2, TkCOLON3 then rhs_name << '::' when nil then break end tk = get_tk end res = get_tkread.tr("\n", " ").strip res = "" if res == ";" con = RDoc::Constant.new name, res, comment read_documentation_modifiers con, RDoc::CONSTANT_MODIFIERS @stats.add_constant con container.add_constant con if con.document_self end ## # Generates an RDoc::Method or RDoc::Attr from +comment+ by looking for # :method: or :attr: directives in +comment+. def parse_comment(container, tk, comment) line_no = tk.line_no column = tk.char_no singleton = !!comment.sub!(/(^# +:?)(singleton-)(method:)/, '\1\3') # REFACTOR if comment.sub!(/^# +:?method: *(\S*).*?\n/i, '') then name = $1 unless $1.empty? meth = RDoc::GhostMethod.new get_tkread, name meth.singleton = singleton meth.start_collecting_tokens indent = TkSPACE.new nil, 1, 1 indent.set_text " " * column position_comment = TkCOMMENT.new nil, line_no, 1 position_comment.set_text "# File #{@top_level.absolute_name}, line #{line_no}" meth.add_tokens [position_comment, NEWLINE_TOKEN, indent] meth.params = '' extract_call_seq comment, meth return unless meth.name container.add_method meth if meth.document_self meth.comment = comment @stats.add_method meth elsif comment.sub!(/# +:?(attr(_reader|_writer|_accessor)?:) *(\S*).*?\n/i, '') then rw = case $1 when 'attr_reader' then 'R' when 'attr_writer' then 'W' else 'RW' end name = $3 unless $3.empty? att = RDoc::Attr.new get_tkread, name, rw, comment container.add_attribute att @stats.add_method att end end def parse_include(context, comment) loop do skip_tkspace_comment name = get_constant_with_optional_parens context.add_include RDoc::Include.new(name, comment) unless name.empty? return unless TkCOMMA === peek_tk get_tk end end ## # Parses a meta-programmed attribute and creates an RDoc::Attr. # # To create foo and bar attributes on class C with comment "My attributes": # # class C # # ## # # :attr: # # # # My attributes # # my_attr :foo, :bar # # end # # To create a foo attribute on class C with comment "My attribute": # # class C # # ## # # :attr: foo # # # # My attribute # # my_attr :foo, :bar # # end def parse_meta_attr(context, single, tk, comment) args = parse_symbol_arg read = get_tkread rw = "?" # If nodoc is given, don't document any of them tmp = RDoc::CodeObject.new read_documentation_modifiers tmp, RDoc::ATTR_MODIFIERS return unless tmp.document_self if comment.sub!(/^# +:?(attr(_reader|_writer|_accessor)?): *(\S*).*?\n/i, '') then rw = case $1 when 'attr_reader' then 'R' when 'attr_writer' then 'W' else 'RW' end name = $3 unless $3.empty? end if name then att = RDoc::Attr.new get_tkread, name, rw, comment context.add_attribute att else args.each do |attr_name| att = RDoc::Attr.new get_tkread, attr_name, rw, comment context.add_attribute att end end end ## # Parses a meta-programmed method def parse_meta_method(container, single, tk, comment) line_no = tk.line_no column = tk.char_no start_collecting_tokens add_token tk add_token_listener self skip_tkspace false singleton = !!comment.sub!(/(^# +:?)(singleton-)(method:)/, '\1\3') if comment.sub!(/^# +:?method: *(\S*).*?\n/i, '') then name = $1 unless $1.empty? end if name.nil? then name_t = get_tk case name_t when TkSYMBOL then name = name_t.text[1..-1] when TkSTRING then name = name_t.value[1..-2] when TkASSIGN then # ignore remove_token_listener self return else warn "unknown name token #{name_t.inspect} for meta-method '#{tk.name}'" name = 'unknown' end end meth = RDoc::MetaMethod.new get_tkread, name meth.singleton = singleton remove_token_listener self meth.start_collecting_tokens indent = TkSPACE.new nil, 1, 1 indent.set_text " " * column position_comment = TkCOMMENT.new nil, line_no, 1 position_comment.value = "# File #{@top_level.absolute_name}, line #{line_no}" meth.add_tokens [position_comment, NEWLINE_TOKEN, indent] meth.add_tokens @token_stream token_listener meth do meth.params = '' extract_call_seq comment, meth container.add_method meth if meth.document_self last_tk = tk while tk = get_tk do case tk when TkSEMICOLON then break when TkNL then break unless last_tk and TkCOMMA === last_tk when TkSPACE then # expression continues else last_tk = tk end end end meth.comment = comment @stats.add_method meth end ## # Parses a normal method defined by +def+ def parse_method(container, single, tk, comment) added_container = nil meth = nil name = nil line_no = tk.line_no column = tk.char_no start_collecting_tokens add_token tk token_listener self do @scanner.instance_eval do @lex_state = EXPR_FNAME end skip_tkspace false name_t = get_tk back_tk = skip_tkspace meth = nil added_container = false dot = get_tk if TkDOT === dot or TkCOLON2 === dot then @scanner.instance_eval do @lex_state = EXPR_FNAME end skip_tkspace name_t2 = get_tk case name_t when TkSELF, TkMOD then name = name_t2.name when TkCONSTANT then name = name_t2.name prev_container = container container = container.find_module_named(name_t.name) unless container then added_container = true obj = name_t.name.split("::").inject(Object) do |state, item| state.const_get(item) end rescue nil type = obj.class == Class ? RDoc::NormalClass : RDoc::NormalModule unless [Class, Module].include?(obj.class) then warn("Couldn't find #{name_t.name}. Assuming it's a module") end if type == RDoc::NormalClass then sclass = obj.superclass ? obj.superclass.name : nil container = prev_container.add_class type, name_t.name, sclass else container = prev_container.add_module type, name_t.name end container.record_location @top_level end when TkIDENTIFIER, TkIVAR then dummy = RDoc::Context.new dummy.parent = container skip_method dummy return else warn "unexpected method name token #{name_t.inspect}" # break skip_method container return end meth = RDoc::AnyMethod.new(get_tkread, name) meth.singleton = true else unget_tk dot back_tk.reverse_each do |token| unget_tk token end name = case name_t when TkSTAR, TkAMPER then name_t.text else unless name_t.respond_to? :name then warn "expected method name token, . or ::, got #{name_t.inspect}" skip_method container return end name_t.name end meth = RDoc::AnyMethod.new get_tkread, name meth.singleton = (single == SINGLE) end end meth.start_collecting_tokens indent = TkSPACE.new nil, 1, 1 indent.set_text " " * column token = TkCOMMENT.new nil, line_no, 1 token.set_text "# File #{@top_level.absolute_name}, line #{line_no}" meth.add_tokens [token, NEWLINE_TOKEN, indent] meth.add_tokens @token_stream token_listener meth do @scanner.instance_eval do @continue = false end parse_method_parameters meth if meth.document_self then container.add_method meth elsif added_container then container.document_self = false end # Having now read the method parameters and documentation modifiers, we # now know whether we have to rename #initialize to ::new if name == "initialize" && !meth.singleton then if meth.dont_rename_initialize then meth.visibility = :protected else meth.singleton = true meth.name = "new" meth.visibility = :public end end parse_statements container, single, meth end extract_call_seq comment, meth meth.comment = comment @stats.add_method meth end def parse_method_or_yield_parameters(method = nil, modifiers = RDoc::METHOD_MODIFIERS) skip_tkspace false tk = get_tk # Little hack going on here. In the statement # f = 2*(1+yield) # We see the RPAREN as the next token, so we need # to exit early. This still won't catch all cases # (such as "a = yield + 1" end_token = case tk when TkLPAREN, TkfLPAREN TkRPAREN when TkRPAREN return "" else TkNL end nest = 0 loop do case tk when TkSEMICOLON then break when TkLBRACE then nest += 1 when TkRBRACE then # we might have a.each {|i| yield i } unget_tk(tk) if nest.zero? nest -= 1 break if nest <= 0 when TkLPAREN, TkfLPAREN then nest += 1 when end_token then if end_token == TkRPAREN nest -= 1 break if @scanner.lex_state == EXPR_END and nest <= 0 else break unless @scanner.continue end when method && method.block_params.nil? && TkCOMMENT then unget_tk tk read_documentation_modifiers method, modifiers @read.pop when TkCOMMENT then @read.pop when nil then break end tk = get_tk end res = get_tkread.gsub(/\s+/, ' ').strip res = '' if res == ';' res end ## # Capture the method's parameters. Along the way, look for a comment # containing: # # # yields: .... # # and add this as the block_params for the method def parse_method_parameters(method) res = parse_method_or_yield_parameters method res = "(#{res})" unless res =~ /\A\(/ method.params = res unless method.params if method.block_params.nil? then skip_tkspace false read_documentation_modifiers method, RDoc::METHOD_MODIFIERS end end def parse_module(container, single, tk, comment) container, name_t = get_class_or_module container name = name_t.name mod = container.add_module RDoc::NormalModule, name mod.record_location @top_level read_documentation_modifiers mod, RDoc::CLASS_MODIFIERS parse_statements(mod) mod.comment = comment @stats.add_module mod end def parse_require(context, comment) skip_tkspace_comment tk = get_tk if TkLPAREN === tk then skip_tkspace_comment tk = get_tk end name = tk.text if TkSTRING === tk if name then context.add_require RDoc::Require.new(name, comment) else unget_tk tk end end ## # The core of the ruby parser. def parse_statements(container, single = NORMAL, current_method = nil, comment = '') nest = 1 save_visibility = container.visibility non_comment_seen = true while tk = get_tk do keep_comment = false non_comment_seen = true unless TkCOMMENT === tk case tk when TkNL then skip_tkspace tk = get_tk if TkCOMMENT === tk then if non_comment_seen then # Look for RDoc in a comment about to be thrown away parse_comment container, tk, comment unless comment.empty? comment = '' non_comment_seen = false end while TkCOMMENT === tk do comment << tk.text << "\n" tk = get_tk # this is the newline skip_tkspace false # leading spaces tk = get_tk end unless comment.empty? then look_for_directives_in container, comment if container.done_documenting then container.ongoing_visibility = save_visibility end end keep_comment = true else non_comment_seen = true end unget_tk tk keep_comment = true when TkCLASS then if container.document_children then parse_class container, single, tk, comment else nest += 1 end when TkMODULE then if container.document_children then parse_module container, single, tk, comment else nest += 1 end when TkDEF then if container.document_self then parse_method container, single, tk, comment else nest += 1 end when TkCONSTANT then if container.document_self then parse_constant container, tk, comment end when TkALIAS then if container.document_self and not current_method then parse_alias container, single, tk, comment end when TkYIELD then if current_method.nil? then warn "Warning: yield outside of method" if container.document_self else parse_yield container, single, tk, current_method end # Until and While can have a 'do', which shouldn't increase the nesting. # We can't solve the general case, but we can handle most occurrences by # ignoring a do at the end of a line. when TkUNTIL, TkWHILE then nest += 1 skip_optional_do_after_expression # 'for' is trickier when TkFOR then nest += 1 skip_for_variable skip_optional_do_after_expression when TkCASE, TkDO, TkIF, TkUNLESS, TkBEGIN then nest += 1 when TkIDENTIFIER then if nest == 1 and current_method.nil? then case tk.name when 'private', 'protected', 'public', 'private_class_method', 'public_class_method', 'module_function' then parse_visibility container, single, tk keep_comment = true when 'attr' then parse_attr container, single, tk, comment when /^attr_(reader|writer|accessor)$/ then parse_attr_accessor container, single, tk, comment when 'alias_method' then parse_alias container, single, tk, comment if container.document_self when 'require', 'include' then # ignore else if container.document_self and comment =~ /\A#\#$/ then case comment when /^# +:?attr(_reader|_writer|_accessor)?:/ then parse_meta_attr container, single, tk, comment else parse_meta_method container, single, tk, comment end end end end case tk.name when "require" then parse_require container, comment when "include" then parse_include container, comment end when TkEND then nest -= 1 if nest == 0 then read_documentation_modifiers container, RDoc::CLASS_MODIFIERS container.ongoing_visibility = save_visibility parse_comment container, tk, comment unless comment.empty? return end end comment = '' unless keep_comment begin get_tkread skip_tkspace false end while peek_tk == TkNL end end def parse_symbol_arg(no = nil) args = [] skip_tkspace_comment case tk = get_tk when TkLPAREN loop do skip_tkspace_comment if tk1 = parse_symbol_in_arg args.push tk1 break if no and args.size >= no end skip_tkspace_comment case tk2 = get_tk when TkRPAREN break when TkCOMMA else warn("unexpected token: '#{tk2.inspect}'") if $DEBUG_RDOC break end end else unget_tk tk if tk = parse_symbol_in_arg args.push tk return args if no and args.size >= no end loop do skip_tkspace false tk1 = get_tk unless TkCOMMA === tk1 then unget_tk tk1 break end skip_tkspace_comment if tk = parse_symbol_in_arg args.push tk break if no and args.size >= no end end end args end def parse_symbol_in_arg case tk = get_tk when TkSYMBOL tk.text.sub(/^:/, '') when TkSTRING eval @read[-1] else warn("Expected symbol or string, got #{tk.inspect}") if $DEBUG_RDOC nil end end def parse_top_level_statements(container) comment = collect_first_comment look_for_directives_in(container, comment) container.comment = comment unless comment.empty? parse_statements container, NORMAL, nil, comment end def parse_visibility(container, single, tk) singleton = (single == SINGLE) vis_type = tk.name vis = case vis_type when 'private' then :private when 'protected' then :protected when 'public' then :public when 'private_class_method' then singleton = true :private when 'public_class_method' then singleton = true :public when 'module_function' then singleton = true :public else raise RDoc::Error, "Invalid visibility: #{tk.name}" end skip_tkspace_comment false case peek_tk # Ryan Davis suggested the extension to ignore modifiers, because he # often writes # # protected unless $TESTING # when TkNL, TkUNLESS_MOD, TkIF_MOD, TkSEMICOLON then container.ongoing_visibility = vis else if vis_type == 'module_function' then args = parse_symbol_arg container.set_visibility_for args, :private, false module_functions = [] container.methods_matching args do |m| s_m = m.dup s_m.singleton = true if RDoc::AnyMethod === s_m s_m.visibility = :public module_functions << s_m end module_functions.each do |s_m| case s_m when RDoc::AnyMethod then container.add_method s_m when RDoc::Attr then container.add_attribute s_m end end else args = parse_symbol_arg container.set_visibility_for args, vis, singleton end end end def parse_yield(context, single, tk, method) return if method.block_params get_tkread @scanner.instance_eval { @continue = false } method.block_params = parse_method_or_yield_parameters end ## # Directives are modifier comments that can appear after class, module, or # method names. For example: # # def fred # :yields: a, b # # or: # # class MyClass # :nodoc: # # We return the directive name and any parameters as a two element array def read_directive(allowed) tk = get_tk result = nil if TkCOMMENT === tk then if tk.text =~ /\s*:?(\w+):\s*(.*)/ then directive = $1.downcase if allowed.include? directive then result = [directive, $2] end end else unget_tk tk end result end def read_documentation_modifiers(context, allow) dir = read_directive(allow) case dir[0] when "notnew", "not_new", "not-new" then context.dont_rename_initialize = true when "nodoc" then context.document_self = false if dir[1].downcase == "all" context.document_children = false end when "doc" then context.document_self = true context.force_documentation = true when "yield", "yields" then unless context.params.nil? context.params.sub!(/(,|)\s*&\w+/,'') # remove parameter &proc end context.block_params = dir[1] when "arg", "args" then context.params = dir[1] end if dir end def remove_private_comments(comment) comment.gsub!(/^#--\n.*?^#\+\+/m, '') comment.sub!(/^#--\n.*/m, '') end def scan reset catch :eof do catch :enddoc do begin parse_top_level_statements @top_level rescue StandardError => e bytes = '' 20.times do @scanner.ungetc end count = 0 60.times do |i| count = i byte = @scanner.getc break unless byte bytes << byte end count -= 20 count.times do @scanner.ungetc end $stderr.puts <<-EOF #{self.class} failure around line #{@scanner.line_no} of #{@file_name} EOF unless bytes.empty? then $stderr.puts $stderr.puts bytes.inspect end raise e end end end @top_level end ## # while, until, and for have an optional do def skip_optional_do_after_expression skip_tkspace false tk = get_tk case tk when TkLPAREN, TkfLPAREN then end_token = TkRPAREN else end_token = TkNL end b_nest = 0 nest = 0 @scanner.instance_eval { @continue = false } loop do case tk when TkSEMICOLON then break if b_nest.zero? when TkLPAREN, TkfLPAREN then nest += 1 when TkBEGIN then b_nest += 1 when TkEND then b_nest -= 1 when TkDO break if nest.zero? when end_token then if end_token == TkRPAREN nest -= 1 break if @scanner.lex_state == EXPR_END and nest.zero? else break unless @scanner.continue end when nil then break end tk = get_tk end skip_tkspace false get_tk if TkDO === peek_tk end ## # skip the var [in] part of a 'for' statement def skip_for_variable skip_tkspace false tk = get_tk skip_tkspace false tk = get_tk unget_tk(tk) unless TkIN === tk end def skip_method container meth = RDoc::AnyMethod.new "", "anon" parse_method_parameters meth parse_statements container, false, meth end ## # Skip spaces until a comment is found def skip_tkspace_comment(skip_nl = true) loop do skip_tkspace skip_nl return unless TkCOMMENT === peek_tk get_tk end end def warn(msg) return if @options.quiet msg = make_message msg $stderr.puts msg end end
23.719375
88
0.601908
260add96cfab3b99283a4ca7669b1708d47c0168
1,746
class SalesController < ApplicationController before_action :require_login, only: [:show, :new, :create, :update] def new redirect_to user_path(current_user) unless !current_user.is_manager? @sale = Sale.new @manager_products = Product.where('manager_id = ?', current_user.manager_id) end def create redirect_to user_path(current_user) unless !current_user.is_manager? @sale = Sale.new @sale.quantity = params[:sale][:quantity] @sale.product_id = params[:sale][:product_id] @sale.user_id = current_user.id if @sale.save render json: @sale, status: 201 else render json: { errors: @sale.errors } end end def show redirect_to user_path(current_user) unless current_user.sales.include?(Sale.find(params[:id])) && !current_user.is_manager? @user = User.find(params[:user_id]) @sale = Sale.find(params[:id]) @manager_products = Product.where('manager_id = ?', current_user.manager_id) end def data if current_user.sales.include?(Sale.find(params[:id])) && !current_user.is_manager? @sale = Sale.find(params[:id]) render json: @sale, status: 200 end end def update @sale = Sale.find(params[:id]) @sale.product_id = params[:sale][:product_id] @sale.quantity = params[:sale][:quantity] if @sale.save redirect_to user_path(current_user) else @user = User.find(params[:user_id]) render 'show' end end def destroy @sale = Sale.find(params[:id]) if current_user.id == params[:user_id].to_i @sale.destroy redirect_to user_path(current_user) else redirect_to user_path(current_user) end end def by_quantity @sales = Sale.display_by_quantity end end
26.861538
127
0.675258
1a52fe7bf685e34a7df97ce21c0ebaea1bbe18a2
547
class QuestionPageList @pages_url = 'http://toster.ru/my/feed_latest?page=' class << self attr_accessor :pages_url end def self.get_questions_ids(user_agent=nil, cookie=nil) page = Nokogiri::HTML(open("http://toster.ru/questions/latest", {'User-Agent' => user_agent||'', 'Cookie' => cookie||''})) (1..page.css('body > div > div.content.with_sidebar > div.main_content > div.left_column > div > div.questions_list.shortcuts_items > div:nth-child(1) > div.info > div.title > a')[0].attr('href')[/[0-9]+/].to_i).to_a end end
39.071429
220
0.678245
111faf7f8edaad2b582d38c4d2fd529cc81a4b11
1,952
# -*- coding: utf-8 -*- # #-- # Copyright (C) 2009-2016 Thomas Leitner <[email protected]> # # This file is part of kramdown which is licensed under the MIT. #++ # require 'kramdown/parser' module Kramdown module Parser # Used for parsing a document in Markdown format. # # This parser is based on the kramdown parser and removes the parser methods for the additional # non-Markdown features. However, since some things are handled differently by the kramdown # parser methods (like deciding when a list item contains just text), this parser differs from # real Markdown parsers in some respects. # # Note, though, that the parser basically fails just one of the Markdown test cases (some others # also fail but those failures are negligible). class Markdown < Kramdown # Array with all the parsing methods that should be removed from the standard kramdown parser. EXTENDED = [:codeblock_fenced, :table, :definition_list, :footnote_definition, :abbrev_definition, :block_math, :block_extensions, :footnote_marker, :smart_quotes, :inline_math, :span_extensions, :typographic_syms] def initialize(source, options) # :nodoc: super @block_parsers.delete_if {|i| EXTENDED.include?(i)} @span_parsers.delete_if {|i| EXTENDED.include?(i)} end # :stopdoc: BLOCK_BOUNDARY = /#{BLANK_LINE}|#{EOB_MARKER}|\Z/ LAZY_END = /#{BLANK_LINE}|#{EOB_MARKER}|^#{OPT_SPACE}#{LAZY_END_HTML_STOP}|^#{OPT_SPACE}#{LAZY_END_HTML_START}|\Z/ CODEBLOCK_MATCH = /(?:#{BLANK_LINE}?(?:#{INDENT}[ \t]*\S.*\n)+)*/ PARAGRAPH_END = LAZY_END IAL_RAND_CHARS = (('a'..'z').to_a + ('0'..'9').to_a) IAL_RAND_STRING = (1..20).collect {|a| IAL_RAND_CHARS[rand(IAL_RAND_CHARS.size)]}.join LIST_ITEM_IAL = /^\s*(#{IAL_RAND_STRING})?\s*\n/ IAL_SPAN_START = LIST_ITEM_IAL # :startdoc: end end end
34.245614
120
0.667008
bf7a94894b7930a5fc3398fd2d90c0c9a6490b09
831
class FontNotoSansMyanmarUi < Formula head "https://github.com/google/fonts/trunk/ofl/notosansmyanmarui", verified: "github.com/google/fonts/", using: :svn desc "Noto Sans Myanmar UI" homepage "https://fonts.google.com/specimen/Noto+Sans+Myanmar+UI" def install (share/"fonts").install "NotoSansMyanmarUI-Black.ttf" (share/"fonts").install "NotoSansMyanmarUI-Bold.ttf" (share/"fonts").install "NotoSansMyanmarUI-ExtraBold.ttf" (share/"fonts").install "NotoSansMyanmarUI-ExtraLight.ttf" (share/"fonts").install "NotoSansMyanmarUI-Light.ttf" (share/"fonts").install "NotoSansMyanmarUI-Medium.ttf" (share/"fonts").install "NotoSansMyanmarUI-Regular.ttf" (share/"fonts").install "NotoSansMyanmarUI-SemiBold.ttf" (share/"fonts").install "NotoSansMyanmarUI-Thin.ttf" end test do end end
43.736842
119
0.736462
1cb86e2ff6601c4fa146daa07aac2683c2862087
1,051
# encoding: utf-8 $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = "bootstrap_forms" s.version = "2.0.1" s.author = "Seth Vargo" s.email = "[email protected]" s.homepage = "https://github.com/sethvargo/bootstrap_forms" s.summary = %q{Bootstrap Forms makes Twitter's Bootstrap on Rails easy!} s.description = %q{Bootstrap Forms makes Twitter's Bootstrap on Rails easy to use by creating helpful form builders that minimize markup in your views.} s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_development_dependency "rspec-rails", "~> 2.10.1" s.add_development_dependency "capybara", "~> 1.1.0" s.add_development_dependency "rake" s.add_development_dependency "rails", "~> 3.2.0" s.add_development_dependency "guard-rspec" s.add_development_dependency "sqlite3" end
42.04
154
0.674596
aca0fe2e026f39f6f14109a656f430e65bbdcebb
3,773
class Weeet < ApplicationRecord belongs_to :user validates :user, presence: true validates :content, length: { maximum: 280 }, strict: true has_many :votes, dependent: :destroy before_create :add_evaluate_at # def publish! # self.is_published = true # self.save! # end def self.seed ActiveRecord::Base.transaction do users = User.seed user_count = users.count 24.times do |i| user = users[i % user_count] content = "This post is created by #{user.name}" user.weet! content: content end end end def self.fetch limit:, from:, is_guest: w = query(is_guest: is_guest).limit(limit) if from > 0 w = w.where('weeets.id < :t', t: from) end return w end def self.fetch_with id:, is_guest: return query(is_guest: is_guest).where('weeets.id': id).first end def self.query is_guest: w = Weeet.joins(:user) .order('weeets.created_at DESC') .select('weeets.id AS id', 'weeets.content AS weet_content', 'weeets.created_at AS weet_created_at', 'users.id AS weeter_id', 'users.name AS weeter_name', 'users.email AS weeter_email', 'weeets.evaluate_at AS weet_evaluate_at', 'weeets.is_evaluated AS weet_is_evaluated', 'weeets.is_published AS weet_is_published') if is_guest w = w.where('weeets.is_published' => true) end return w end def self.get_votes id:, user_id: votes = Vote.where(weeet_id: id) has_voted = (votes.where(user_id: user_id).count == 1) return { id: id, upvote_count: votes.where(voteup: true).count, downvote_count: votes.where(voteup: false).count, has_voted: votes.where(user_id: user_id).count == 1, voteup: has_voted ? votes.where(user_id: user_id).first.voteup : nil } end def vote up: true, by: if Time.now > self.evaluate_at raise RuntimeError, 'Voting period has ended' end Vote.create weeet_id: self.id, user_id: by, voteup: up end def self.mass_evaluate count = 0 Weeet.where(is_evaluated: false) .where('evaluate_at <= :t', t: Time.now).each do |weet| weet.evaluate! count = count + 1 end ap "#{count} Weets evaluated" end def evaluate! return if self.is_evaluated return if Time.now < self.evaluate_at votes = Vote.where(weeet_id: self.id) ups = votes.where(voteup: true) downs = votes.where(voteup: false) ActiveRecord::Base.transaction do self.is_evaluated = true if ups.count > downs.count self.is_published = true ups.each do |upvote| User.find(upvote.user_id).win! end downs.each do |downvote| User.find(downvote.user_id).lose! end else ups.each do |upvote| User.find(upvote.user_id).lose! end downs.each do |downvote| User.find(downvote.user_id).win! end end self.save! ActionCable.server.broadcast 'weeet_channel', { action: :weet_evaluated, id: self.id, val: self.is_published } Blockchain.publish weet: self, val: self.is_published end end private def add_evaluate_at evaluate_time = ENV['mode'] == 'fast' ? (Time.now + 1.minute) : (Time.now + 1.hour) self.evaluate_at = evaluate_time EvaluatorWorker.perform_at(evaluate_time, 'evaluate') EvaluatorWorker.perform_at(evaluate_time + 5.seconds, 'evaluate') end end
26.384615
87
0.588391
abf25f4c06ba68bc89e52484cadf40449a280c36
2,208
class User < ApplicationRecord attr_accessor :remember_token, :activation_token, :reset_token before_save :downcase_email before_create :create_activation_digest validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } has_secure_password validates :password, presence: true, length: { minimum: 6 }, allow_nil: true def User.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end def User.new_token SecureRandom.urlsafe_base64 end def remember self.remember_token = User.new_token self.update_attribute(:remember_digest, User.digest(remember_token)) end def forget self.update_attribute(:remember_digest, nil) end # トークンがダイジェストと一致したらtrueを返す def authenticated?(attribute, token) digest = send("#{attribute}_digest") return false if digest.nil? BCrypt::Password.new(digest).is_password?(token) end # アカウントを有効にする def activate update_attribute(:activated, true) update_attribute(:activated_at, Time.zone.now) end # 有効化用のメールを送信する def send_activation_email UserMailer.account_activation(self).deliver_now end # パスワード再設定の属性を設定する def create_reset_digest self.reset_token = User.new_token update_attribute(:reset_digest, User.digest(reset_token)) update_attribute(:reset_sent_at, Time.zone.now) end # パスワード再設定のメールを送信する def send_password_reset_email UserMailer.password_reset(self).deliver_now end # パスワード再設定の期限が切れている場合はtrueを返す def password_reset_expired? reset_sent_at < 2.hours.ago end private # メールアドレスをすべて小文字にする def downcase_email self.email = email.downcase end # 有効化トークンとダイジェストを作成および代入する def create_activation_digest self.activation_token = User.new_token self.activation_digest = User.digest(activation_token) end end
27.259259
76
0.703804
26ea11a1779c7b92810b561265eb1d7eded41a7c
1,974
require 'openssl' require 'tools_string' require 'padding' module AESCipher module_function def encryptECB(plaintext,key, padding: true) cipher = OpenSSL::Cipher::AES.new('128-ECB') cipher.encrypt cipher.key = key cipher.padding = 0 if not padding cipher.update(plaintext) + cipher.final end def decryptECB(ciphertext,key, padding: true) cipher = OpenSSL::Cipher::AES.new('128-ECB') cipher.decrypt cipher.key = key cipher.padding=0 if not padding cipher.update(ciphertext) + cipher.final end ## The point of challenge 10 is to implement CBC without using OpenSSl ## So, we have to do it by hand. def encryptCBC(plaintext, key, iv, padding: false) ## split the text into chunks of block size block_size = 16 blocks = plaintext.chars.each_slice(block_size).to_a.map{|v| v.join.to_s} ciphertext = String.new vector = iv blocks.each do |block| xor = block^vector vector = encryptECB(xor, key, padding: false) ciphertext += vector end ciphertext end def decryptCBC(ciphertext, key, iv, padding: false) ## split the text into chunks of block size block_size = 16 blocks = ciphertext.chars.each_slice(block_size).to_a.map{|v| v.join.to_s} plaintext = String.new vector = iv blocks.each do |block| decrypted_block = decryptECB(block, key, padding: false) plaintext += decrypted_block^vector vector = block end plaintext end def generateKey Random.new.bytes(16) end def encryption_oracle(plaintext) key = generateKey randombytes = Proc.new {Random.new.bytes(Random.new.rand(5..10))} plaintext = (randombytes.call + plaintext + randombytes.call) plaintext = Padding.addPKCS7(plaintext, 16) if Random.new.rand(0..1) == 0 return encryptECB(plaintext, key, padding: false), 'ECB' else iv = generateKey return encryptCBC(plaintext, key, iv, padding: false), 'CBC' end end end
24.073171
77
0.684904
625fc1ea3f80034ad3d090513ff390eb4af0bb2e
1,291
# frozen_string_literal: true # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! # [START gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_sync] require "google/cloud/gke_multi_cloud/v1" # Create a client object. The client can be reused for multiple calls. client = Google::Cloud::GkeMultiCloud::V1::AwsClusters::Client.new # Create a request. To set request fields, pass in keyword arguments. request = Google::Cloud::GkeMultiCloud::V1::GetAwsNodePoolRequest.new # Call the get_aws_node_pool method. result = client.get_aws_node_pool request # The returned object is of type Google::Cloud::GkeMultiCloud::V1::AwsNodePool. p result # [END gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_sync]
37.970588
79
0.788536
f876ee6dce27f5eb5f758c6e6e2660207b5024e0
460
# encoding: utf-8 module WorldLite c = Country.new c.name = 'Venezuela' c.key = 've' c.alpha3 = 'VEN' c.fifa = 'VEN' c.net = 've' c.continent_name = 'South America' c.un = true c.eu = false c.euro = false # Venezuela / South America # tags: south america, andean states, un, fifa, conmebol VE = c WORLD << VE WORLD_UN << VE WORLD_ISO << VE WORLD_FIFA << VE end # module WorldLite
13.939394
61
0.56087
bbb2ef8452c12814084591b35b4c41058d58b47c
2,641
## # $Id: php_eval.rb 5783 2008-10-23 02:43:21Z ramon $ ## ## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # Framework web site for more information on licensing and terms of use. # http://metasploit.com/projects/Framework/ ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote include Msf::Exploit::Remote::HttpClient def initialize(info = {}) super(update_info(info, 'Name' => 'OpenHelpDesk eval (previously unpublished)', 'Description' => %q{ OpenHelpDesk version 1.0.100 is vulnerable to a php code execution vulnerability due to improper use of eval(). The php.ini register_globals directive is *not* required to be on to exploit this vulnerability. There is no known public exploit for this vulnerability. }, 'Author' => [ 'LSO <[email protected]>' ], 'License' => BSD_LICENSE, 'Version' => '$Revision$', 'References' => [ 'URL' , 'http://sourceforge.net/projects/openhelpdesk' ], 'Privileged' => false, 'Platform' => ['php'], 'Arch' => ARCH_PHP, 'Payload' => { 'Space' => 4000, # max url length for some old # versions of apache according to # http://www.boutell.com/newfaq/misc/urllength.html 'DisableNops' => true, 'BadChars' => %q|'"`|, # quotes are escaped by PHP's magic_quotes_gpc in a default install 'Compat' => { 'ConnectionType' => 'find', }, 'Keys' => ['php'], }, 'Targets' => [ ['Automatic', { }], ], 'DefaultTarget' => 0 )) register_options( [ OptString.new('URIPATH', [ true, "The URI of ajax.php ", '/openhelpdesk/ajax.php']), ], self.class) end def check tester = rand_text_alpha(10) php_code = "echo('#{tester}');" response = eval_sploit(php_code) #print_status(response) if (response && response.body.match(tester).to_a.first) print_status("PHP code execution achieved; safe_mode or disable_functions might still prevent host compromise") checkcode = Exploit::CheckCode::Vulnerable else checkcode = Exploit::CheckCode::Safe end return checkcode end def exploit response = eval_sploit(payload.encoded) handler end def eval_sploit(php_code) uri = datastore['URIPATH'] + "?function=" + php_code + "//" response = send_request_raw({ 'uri' => uri },1) return response end end # milw0rm.com [2009-02-02]
29.344444
115
0.607724
1894b242a710233054c4fc4d4ee61c8a06d2222c
702
# frozen_string_literal: true module HelpScout class Attachment < HelpScout::Base class << self def create(conversation_id, thread_id, params) HelpScout.api.post( create_path(conversation_id, thread_id), HelpScout::Util.camelize_keys(params) ) true end private def base_path 'conversations/%<CONVERSATION_ID>/threads/%<THREAD_ID>/attachments' end def create_path(conversation_id, thread_id) replacements = { '%<CONVERSATION_ID>' => conversation_id, '%<THREAD_ID>' => thread_id } HelpScout::Util.parse_path(base_path, replacements) end end end end
22.645161
75
0.622507
08636473402e26c5a1316d7eb937bf644fa81e30
2,068
node["nginx"]["lua"]["packages"].each do |package_name| package package_name do action :install end end devel_kit_filename = ::File.basename(node['nginx']['lua']['url']) lua_nginx_module_filename = ::File.basename(node['nginx']['ngx_devel_kit']['url']) devel_kit_extract_path = "#{Chef::Config['file_cache_path']}/devel_kit/#{node['nginx']['ngx_devel_kit']['check_sum']}" lua_nginx_module_extract_path = "#{Chef::Config['file_cache_path']}/lua_module/#{node['nginx']['lua']['check_sum']}" devel_kit_src_filepath = "#{Chef::Config['file_cache_path']}/#{devel_kit_filename}" lua_nginx_module_src_filepath = "#{Chef::Config['file_cache_path']}/#{lua_nginx_module_filename}" remote_file devel_kit_src_filepath do source node['nginx']['ngx_devel_kit']['url'] checksum node['nginx']['ngx_devel_kit']['check_sum'] owner "root" group "root" mode 00644 end remote_file lua_nginx_module_src_filepath do source node['nginx']['lua']['url'] checksum node['nginx']['lua']['check_sum'] owner "root" group "root" mode 00644 end bash "extract_devel_kit" do cwd ::File.dirname(devel_kit_src_filepath) code <<-EOH mkdir -p #{devel_kit_extract_path} tar xzf #{devel_kit_filename} -C #{devel_kit_extract_path} mv #{devel_kit_extract_path}/*/* #{devel_kit_extract_path}/ EOH not_if { ::File.exists?(devel_kit_extract_path) } end bash "extract_lua_module" do cwd ::File.dirname(lua_nginx_module_src_filepath) code <<-EOH mkdir -p #{lua_nginx_module_extract_path} tar xzf #{lua_nginx_module_filename} -C #{lua_nginx_module_extract_path} mv #{lua_nginx_module_extract_path}/*/* #{lua_nginx_module_extract_path}/ EOH not_if { ::File.exists?(lua_nginx_module_extract_path) } end ENV['LUAJIT_LIB'] = node['nginx']['lua']['jit']['lib'] ENV['LUAJIT_INC'] = node['nginx']['lua']['jit']['inc'] node.run_state['nginx_configure_flags'] = node.run_state['nginx_configure_flags'] | ["--add-module=#{devel_kit_extract_path}", "--add-module=#{lua_nginx_module_extract_path}"]
32.3125
118
0.710348
261f726590f93ce34bc847a8200cd2dad72da70f
5,650
# frozen_string_literal: true require "helper" require "open-uri" class TestApplyCommand < BridgetownUnitTest unless ENV["GITHUB_ACTIONS"] context "the apply command" do setup do @cmd = Bridgetown::Commands::Apply.new File.delete("bridgetown.automation.rb") if File.exist?("bridgetown.automation.rb") @template = "" + <<-TEMPLATE say_status :urltest, "Works!" TEMPLATE allow(@template).to receive(:read).and_return(@template) end should "automatically run bridgetown.automation.rb" do output = capture_stdout do @cmd.apply_automation end assert_match "add bridgetown.automation.rb", output File.open("bridgetown.automation.rb", "w") do |f| f.puts "say_status :applytest, 'I am Bridgetown. Hear me roar!'" end output = capture_stdout do @cmd.apply_automation end File.delete("bridgetown.automation.rb") assert_match %r!applytest.*?Hear me roar\!!, output end should "run automations via relative file paths" do file = "test/fixtures/test_automation.rb" output = capture_stdout do @cmd.invoke(:apply_automation, [file]) end assert_match %r!fixture.*?Works\!!, output end should "run automations from URLs" do allow(URI).to receive(:open).and_return(@template) file = "http://randomdomain.com/12345.rb" output = capture_stdout do @cmd.invoke(:apply_automation, [file]) end assert_match %r!apply.*?http://randomdomain\.com/12345\.rb!, output assert_match %r!urltest.*?Works\!!, output end should "automatically add bridgetown.automation.rb to URL folder path" do allow(URI).to receive(:open).and_return(@template) file = "http://randomdomain.com/foo" output = capture_stdout do @cmd.invoke(:apply_automation, [file]) end assert_match %r!apply.*?http://randomdomain\.com/foo/bridgetown\.automation\.rb!, output end should "transform GitHub repo URLs automatically" do allow(URI).to receive(:open).and_return(@template) file = "https://github.com/bridgetownrb/bridgetown-automations" output = capture_stdout do @cmd.invoke(:apply_automation, [file]) end assert_match %r!apply.*?https://raw\.githubusercontent.com/bridgetownrb/bridgetown-automations/master/bridgetown\.automation\.rb!, output assert_match %r!urltest.*?Works\!!, output end should "transform GitHub repo URLs and respect branches" do allow(URI).to receive(:open).and_return(@template) # file url includes */tree/<branch>/* for a regular github url file = "https://github.com/bridgetownrb/bridgetown-automations/tree/my-tree" output = capture_stdout do @cmd.invoke(:apply_automation, [file]) end # when pulling raw content, */tree/<branch>/* transforms to */<branch>/* assert_match %r!apply.*?https://raw\.githubusercontent.com/bridgetownrb/bridgetown-automations/my-tree/bridgetown\.automation\.rb!, output assert_match %r!urltest.*?Works\!!, output end should "transform GitHub repo URLs and preserve directories named 'tree'" do allow(URI).to receive(:open).and_return(@template) file = "https://github.com/bridgetownrb/bridgetown-automations/tree/my-tree/tree" output = capture_stdout do @cmd.invoke(:apply_automation, [file]) end # when pulling raw content, */tree/<branch>/* transforms to */<branch>/* assert_match %r!apply.*?https://raw\.githubusercontent.com/bridgetownrb/bridgetown-automations/my-tree/tree/bridgetown\.automation\.rb!, output assert_match %r!urltest.*?Works\!!, output end should "transform GitHub repo URLs and not cause issues if the repo name is 'tree'" do allow(URI).to receive(:open).and_return(@template) file = "https://github.com/bridgetown/tree/tree/my-tree/tree" output = capture_stdout do @cmd.invoke(:apply_automation, [file]) end # when pulling raw content, */tree/<branch>/* transforms to */<branch>/* assert_match %r!apply.*?https://raw\.githubusercontent.com/bridgetown/tree/my-tree/tree/bridgetown\.automation\.rb!, output assert_match %r!urltest.*?Works\!!, output end should "transform GitHub file blob URLs" do allow(URI).to receive(:open).and_return(@template) # file url includes */tree/<branch>/* for a regular github url file = "https://github.com/bridgetownrb/bridgetown-automations/blob/branchname/folder/file.rb" output = capture_stdout do @cmd.invoke(:apply_automation, [file]) end # when pulling raw content, */tree/<branch>/* transforms to */<branch>/* assert_match %r!apply.*?https://raw\.githubusercontent.com/bridgetownrb/bridgetown-automations/branchname/folder/file.rb!, output assert_match %r!urltest.*?Works\!!, output end should "transform Gist URLs automatically" do allow(URI).to receive(:open).and_return(@template) file = "https://gist.github.com/jaredcwhite/963d40acab5f21b42152536ad6847575" output = capture_stdout do @cmd.invoke(:apply_automation, [file]) end assert_match %r!apply.*?https://gist\.githubusercontent.com/jaredcwhite/963d40acab5f21b42152536ad6847575/raw/bridgetown\.automation\.rb!, output assert_match %r!urltest.*?Works\!!, output end end end end
42.481203
152
0.655398
e9c5eb7543a33d54c5f86394bddc014b5e29ab23
159
class CreateNotifies < ActiveRecord::Migration[5.2] def change create_table :notifies do |t| t.string :email t.timestamps end end end
15.9
51
0.666667
21fbd611bb43a07c9180bcca6cda41184476aca3
2,128
require 'spec_helper' describe Member, :type => :model do it { is_expected.to have_many( :sponsorships ) } it { is_expected.to have_many( :bills ).through( :sponsorships ) } describe "information formatted for display" do before( :each ) do @member = FactoryBot.create( :member ) end it "should return last_name, first_name as name" do expect(@member.name).to eq("#{@member.last_name}, #{@member.first_name}") end it "should return first_name last_name as display_name" do expect(@member.display_name).to eq("#{@member.first_name} " + "#{@member.last_name}") end it "should return house and district as district_name" do expect(@member.district_name).to eq("#{@member.house}#{@member.district}") end end describe "party search scopes" do before( :each ) do FactoryBot.build( :member, :party => 'D' ) FactoryBot.build( :member, :party => 'R' ) end it "should return only democratic members" do expect(Member.democrats.all).to eq(Member.where( "party = ?", 'D' )) end it "should return only republican members" do expect(Member.republicans.all).to eq(Member.where( "party = ?", 'R' )) end it "should find members of a party" do expect(Member.find_by_party('D').all).to eq( Member.where( "party = ?", 'D' )) expect(Member.find_by_party('R').all).to eq( Member.where( "party = ?", 'R' )) end end describe "house search scopes" do before( :each ) do FactoryBot.build( :member, :house => 'H' ) FactoryBot.build( :member, :house => 'S' ) end it "should find only house members" do expect(Member.reps.all).to eq(Member.where( "house = ?", 'H' )) end it "should find only senate members" do expect(Member.senators.all).to eq(Member.where( "house = ?", 'S' )) end it "should find members of a house" do expect(Member.find_by_house( 'H' ).all).to eq( Member.where( "house = ?", 'H' )) expect(Member.find_by_house( 'S' ).all).to eq( Member.where( "house = ?", 'S' )) end end end
30.4
80
0.616071
79dcd569e0c0b81d2a1381adac325e2b7e3c25c5
5,106
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present? # Compress CSS using a preprocessor. config.assets.css_compressor = :purger # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = "http://assets.example.com" # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = "wss://example.com/cable" # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Include generic and useful information about system operation, but avoid logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). config.log_level = :info # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "ruby_itsm_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Don't log any deprecations. config.active_support.report_deprecations = false # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require "syslog/logger" # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new "app-name") if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Inserts middleware to perform automatic connection switching. # The `database_selector` hash is used to pass options to the DatabaseSelector # middleware. The `delay` is used to determine how long to wait after a write # to send a subsequent read to the primary. # # The `database_resolver` class is used by the middleware to determine which # database is appropriate to use based on the time delay. # # The `database_resolver_context` class is used by the middleware to set # timestamps for the last write to the primary. The resolver uses the context # class timestamps to determine how long to wait before reading from the # replica. # # By default Rails will store a last write timestamp in the session. The # DatabaseSelector middleware is designed as such you can define your own # strategy for connection switching and pass that into the middleware through # these configuration options. # config.active_record.database_selector = { delay: 2.seconds } # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end
44.4
114
0.763807
28ae3719ab545d4f3d5b600a38f33944bbb5a7d1
927
class Redpen < Formula desc "Proofreading tool to help writers of technical documentation" homepage "https://redpen.cc/" url "https://github.com/redpen-cc/redpen/releases/download/redpen-1.10.4/redpen-1.10.4.tar.gz" sha256 "6c3dc4a6a45828f9cc833ca7253fdb036179036631248288251cb9ac4520c39d" license "Apache-2.0" bottle :unneeded depends_on "openjdk" def install # Don't need Windows files. rm_f Dir["bin/*.bat"] libexec.install %w[conf lib sample-doc js] prefix.install "bin" bin.env_script_all_files libexec/"bin", JAVA_HOME: Formula["openjdk"].opt_prefix end test do path = "#{libexec}/sample-doc/en/sampledoc-en.txt" output = "#{bin}/redpen -l 20 -c #{libexec}/conf/redpen-conf-en.xml #{path}" match = /sampledoc-en.txt:1: ValidationError[SentcLgh]*/ assert_match match, shell_output(output).split("\n").find { |line| line.include?("sampledoc-en.txt") } end end
33.107143
106
0.710895
e902ef8bc4d76d4dfd4938211a15f8ad83477bbf
9,034
# :nodoc: class ServiceOptionAssignmentsController < ManageCmrController add_breadcrumb 'Service Option Assignments', :service_option_assignments_path def index; end def new authorize :service_option_assignment set_service_entries set_service_options end def create authorize :service_option_assignment payload = service_option_assignment_params.fetch('service_option_assignment_catalog_guid_toList', []).map do |catalog_item_guid| { 'CatalogItemGuid' => catalog_item_guid, 'ServiceEntryGuid' => service_option_assignment_params[:service_entry_guid], 'AppliesOnlyToGranules' => (service_option_assignment_params[:applies_only_to_granules] || false), 'ServiceOptionDefinitionGuid' => service_option_assignment_params[:service_option_definition_guid] } end response = echo_client.create_service_option_assignments(echo_provider_token, payload) if response.success? redirect_to service_option_assignments_path, flash: { success: 'Service Option Assignments successfully created' } else Rails.logger.error("Create Service Option Assignments Error: #{response.clean_inspect}") flash[:error] = response.error_message set_service_entries set_service_options render :new end end def update # Initialize the assignments array for the view @assignments = [] assignments_response = echo_client.get_service_option_assignments_by_service(echo_provider_token, service_option_assignment_params['service_entries_toList']) if assignments_response.success? service_option_associations = Array.wrap(assignments_response.parsed_body(parser: 'libxml').fetch('Item', [])) # Collect all of the guids/ids we'll need to lookup in order to populate the table in the view collection_ids = service_option_associations.map { |a| a['CatalogItemGuid'] }.compact service_entry_guids = service_option_associations.map { |a| a['ServiceEntryGuid'] }.compact service_option_guids = service_option_associations.map { |a| a['ServiceOptionDefinitionGuid'] }.compact # Retrieve all collections associated with the requested service implementations assignment_collections_response = cmr_client.get_collections_by_post({ concept_id: collection_ids, page_size: collection_ids.count }, token) assignment_collections = if collection_ids.any? && assignment_collections_response.success? assignment_collections_response.body['items'] || [] else Rails.logger.error("Retrieve Collections to Update Service Option Assignments Error: #{assignment_collections_response.clean_inspect}") if assignment_collections_response.error? [] end # Retrieve all service entries associated with the requested service implementations assignment_service_entries_response = echo_client.get_service_entries(echo_provider_token, service_entry_guids) assignment_service_entries = if service_entry_guids.any? && assignment_service_entries_response.success? Array.wrap(assignment_service_entries_response.parsed_body(parser: 'libxml')['Item']) else Rails.logger.error("#{request.uuid} - ServiceOptionAssignmentsController#update - Retrieve Service Entries to Update Service Option Assignments Error: #{assignment_service_entries_response.clean_inspect}") if assignment_service_entries_response.error? flash[:error] = I18n.t("controllers.service_option_assignments.update.get_service_entries.flash.timeout_error", request: request.uuid) if assignment_service_entries_response.timeout_error? [] end # Retrieve all service options associated with the requested service implementations assignment_service_options_response = get_service_option_list(echo_provider_token, service_option_guids) assignment_service_options = Array.wrap(assignment_service_options_response.fetch('Result', [])) # Use the data collected above (which we did in bulk to avoid multiple calls to ECHO) to # add new keys containing full objects to the assignments array that we use to populate # the table within the view service_option_associations.each do |association| # Look for the collection by concept-id. If no collection is found we will ignore this association collection = assignment_collections.find { |c| c.fetch('meta', {}).fetch('concept-id', nil) == association['CatalogItemGuid'] } # Ignore associations where the collection no longer exists if collection.nil? Rails.logger.debug "Collection with concept-id `#{association['CatalogItemGuid']}` not found in #{assignment_collections.map { |c| c.fetch('meta', {}).fetch('concept-id', nil) }}" next end # Ignore associations where the service entry no longer exists service_entry = assignment_service_entries.find { |c| c['Guid'] == association['ServiceEntryGuid'] } if service_entry.nil? Rails.logger.debug "Service Entry with guid `#{association['ServiceEntryGuid']}` not found in #{assignment_service_entries.map { |s| s['Guid'] }}" next end # Ignore associations where the service option no longer exists service_option = assignment_service_options.find { |c| c['Guid'] == association['ServiceOptionDefinitionGuid'] } if service_option.nil? Rails.logger.debug "Service Option with guid `#{association['ServiceOptionDefinitionGuid']}` not found in #{assignment_service_options.map { |s| s['Guid'] }}" next end # Merge fully qualified objects in with the association object guids and # push the record to the instance variable @assignments << { 'CatalogItem' => collection, 'ServiceEntry' => service_entry, 'ServiceOption' => service_option }.merge(association) end else Rails.logger.error("#{request.uuid} - ServiceOptionAssignmentsController#update - Retrieve Service Options Assignments to Update Error: #{assignments_response.clean_inspect}") flash[:error] = I18n.t("controllers.service_option_assignments.update.get_service_option_assignments.flash.timeout_error", request: request.uuid) if assignments_response.timeout_error? end render action: :edit end def destroy authorize :service_option_assignment response = echo_client.remove_service_option_assignments(echo_provider_token, service_option_assignment_params.fetch('service_option_assignment', [])) if response.success? redirect_to service_option_assignments_path, flash: { success: 'Successfully deleted the selected service option assignments.' } else Rails.logger.error("#{request.uuid} - ServiceOptionAssignmentsController#destroy - Delete Service Option Assignments Error: #{response.clean_inspect}") redirect_to service_option_assignments_path, flash: { error: response.error_message } end end private # params used in controller: # In create: # :service_entry_guid, # :service_option_definition_guid, # :applies_only_to_granules, # :service_option_assignment_catalog_guid_toList # In update: # :service_entries_toList # In destroy: # :service_option_assignment def service_option_assignment_params params.permit(:service_entry_guid, :service_option_definition_guid, :applies_only_to_granules, service_option_assignment_catalog_guid_toList: [], service_entries_toList: [], service_option_assignment: []) end def set_service_entries @service_entries = begin get_service_implementations_with_datasets.map { |option| [option['Name'], option['Guid']] } rescue [] end end def set_service_options service_option_response = echo_client.get_service_options_names(echo_provider_token) @service_options = if service_option_response.success? # Retreive the service options and sort by name, ignoring case Array.wrap(service_option_response.parsed_body(parser: 'libxml').fetch('Item', [])).sort_by { |option| option.fetch('Name', '').downcase }.map { |option| [option['Name'], option['Guid']] } else Rails.logger.error("#{request.uuid} - ServiceOptionAssignmentsController#set_service_options - Retrieve Service Options Error: #{service_option_response.clean_inspect}") flash[:error] = I18n.t("controllers.service_option_assignments.set_service_options.flash.timeout_error", request: request.uuid) if service_option_response.timeout_error? [] end end end
51.622857
288
0.709763
2816572d96e11cfb5356ac86a00923b9bbcd5685
70
# frozen_string_literal: true module Logster VERSION = "2.7.1" end
11.666667
29
0.728571
38d4f7a06d091906e469666ac7b01105502d2a1f
9,252
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20141229081622) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "authorizations", force: true do |t| t.string "provider" t.string "uid" t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "token" t.string "secret" t.datetime "token_expires" t.string "temp_token" end add_index "authorizations", ["user_id"], name: "index_authorizations_on_user_id", using: :btree create_table "categories", force: true do |t| t.string "title" t.string "color" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "comments", force: true do |t| t.text "body" t.integer "user_id" t.integer "commentable_id" t.string "commentable_type" t.datetime "created_at" t.datetime "updated_at" end add_index "comments", ["commentable_id", "commentable_type"], name: "index_comments_on_commentable_id_and_commentable_type", using: :btree add_index "comments", ["user_id"], name: "index_comments_on_user_id", using: :btree create_table "event_curations", force: true do |t| t.integer "user_id" t.integer "event_id" t.datetime "created_at" t.datetime "updated_at" end add_index "event_curations", ["event_id"], name: "index_event_curations_on_event_id", using: :btree add_index "event_curations", ["user_id"], name: "index_event_curations_on_user_id", using: :btree create_table "events", force: true do |t| t.string "name" t.text "description" t.text "schedule_yaml" t.string "url" t.string "twitter" t.datetime "created_at" t.datetime "updated_at" t.boolean "full_day", default: false t.string "twitter_hashtag" t.integer "category_id" t.integer "venue_id" t.string "venue_info" t.integer "picture_id" t.integer "region_id" end add_index "events", ["category_id"], name: "index_events_on_category_id", using: :btree add_index "events", ["picture_id"], name: "index_events_on_picture_id", using: :btree add_index "events", ["region_id"], name: "index_events_on_region_id", using: :btree add_index "events", ["venue_id"], name: "index_events_on_venue_id", using: :btree create_table "pictures", force: true do |t| t.string "title" t.text "description" t.string "box_image" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "radar_entries", force: true do |t| t.integer "radar_setting_id" t.string "entry_id" t.datetime "entry_date" t.string "state" t.text "content" t.text "previous_confirmed_content" t.string "entry_type" end create_table "radar_settings", force: true do |t| t.integer "event_id" t.string "url" t.string "radar_type" t.datetime "last_processed" t.string "last_result" end create_table "region_organizers", force: true do |t| t.integer "region_id" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end add_index "region_organizers", ["region_id"], name: "index_region_organizers_on_region_id", using: :btree add_index "region_organizers", ["user_id"], name: "index_region_organizers_on_user_id", using: :btree create_table "regions", force: true do |t| t.string "name" t.string "slug" t.float "latitude" t.float "longitude" t.float "perimeter", default: 20.0 t.datetime "created_at" t.datetime "updated_at" t.boolean "active" end add_index "regions", ["slug"], name: "index_regions_on_slug", using: :btree create_table "single_event_external_users", force: true do |t| t.integer "single_event_id" t.string "email" t.string "name" t.datetime "created_at" t.datetime "updated_at" t.string "session_token" end add_index "single_event_external_users", ["single_event_id"], name: "index_single_event_external_users_on_single_event_id", using: :btree create_table "single_events", force: true do |t| t.string "name" t.text "description" t.integer "event_id" t.datetime "created_at" t.datetime "updated_at" t.datetime "occurrence" t.string "url" t.integer "duration" t.boolean "full_day" t.string "twitter_hashtag" t.boolean "based_on_rule", default: false t.integer "category_id" t.integer "venue_id" t.string "venue_info" t.integer "picture_id" t.string "twitter" t.boolean "use_venue_info_of_event", default: true t.integer "region_id" end add_index "single_events", ["category_id"], name: "index_single_events_on_category_id", using: :btree add_index "single_events", ["event_id"], name: "index_single_events_on_event_id", using: :btree add_index "single_events", ["picture_id"], name: "index_single_events_on_picture_id", using: :btree add_index "single_events", ["region_id"], name: "index_single_events_on_region_id", using: :btree add_index "single_events", ["venue_id"], name: "index_single_events_on_venue_id", using: :btree create_table "single_events_users", id: false, force: true do |t| t.integer "user_id" t.integer "single_event_id" end add_index "single_events_users", ["single_event_id"], name: "index_single_events_users_on_single_event_id", using: :btree add_index "single_events_users", ["user_id"], name: "index_single_events_users_on_user_id", using: :btree create_table "suggestions", force: true do |t| t.text "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "email_address" end create_table "taggings", force: true do |t| t.integer "tag_id" t.integer "taggable_id" t.string "taggable_type" t.integer "tagger_id" t.string "tagger_type" t.string "context" t.datetime "created_at" end add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true, using: :btree add_index "taggings", ["tagger_id", "tagger_type"], name: "index_taggings_on_tagger_id_and_tagger_type", using: :btree create_table "tags", force: true do |t| t.string "name" t.integer "category_id" t.integer "taggings_count", default: 0 end add_index "tags", ["category_id"], name: "index_tags_on_category_id", using: :btree add_index "tags", ["name"], name: "index_tags_on_name", unique: true, using: :btree create_table "users", force: true do |t| t.string "email" t.string "encrypted_password" t.string "reset_password_token" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0 t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at" t.datetime "updated_at" t.boolean "admin", default: false t.string "nickname", default: "", null: false t.text "description" t.string "github" t.string "twitter" t.string "homepage" t.string "guid" t.boolean "allow_ignore_view" t.datetime "reset_password_sent_at" t.string "image_url" t.string "team" t.string "name" t.integer "current_region_id", default: 2 t.string "gravatar_email" end add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree add_index "users", ["nickname"], name: "index_users_on_nickname", unique: true, using: :btree add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree create_table "venues", force: true do |t| t.string "location" t.string "street" t.string "zipcode" t.string "city" t.string "country" t.float "latitude" t.float "longitude" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "url" t.integer "region_id", default: 2 end add_index "venues", ["latitude", "longitude"], name: "index_venues_on_latitude_and_longitude", using: :btree add_index "venues", ["region_id"], name: "index_venues_on_region_id", using: :btree end
35.860465
156
0.684825
f7f02644f89eaeb1b26d183f0601220f5d20e206
1,237
#!/usr/bin/env ruby # $Id: test-tracelines.rb 51 2008-01-26 10:18:26Z rockyb $ require 'test/unit' require 'fileutils' require 'tempfile' # require 'rubygems' # require 'ruby-debug'; Debugger.init SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__ # Test TestLineNumbers module class TestLineNumbers1 < Test::Unit::TestCase @@TEST_DIR = File.expand_path(File.dirname(__FILE__)) @@TOP_SRC_DIR = File.join(@@TEST_DIR, '..', 'lib') require File.join(@@TOP_SRC_DIR, 'tracelines.rb') @@rcov_file = File.join(@@TEST_DIR, 'rcov-bug.rb') File.open(@@rcov_file, 'r') {|fp| first_line = fp.readline[1..-2] @@rcov_lnums = eval(first_line, binding, __FILE__, __LINE__) } def test_for_file rcov_lines = TraceLineNumbers.lnums_for_file(@@rcov_file) assert_equal(@@rcov_lnums, rcov_lines) end def test_for_string string = "# Some rcov bugs.\nz = \"\nNow is the time\n\"\n\nz =~ \n /\n 5\n /ix\n" rcov_lines = TraceLineNumbers.lnums_for_str(string) assert_equal([2, 9], rcov_lines) end def test_for_string_array load(@@rcov_file, 0) rcov_lines = TraceLineNumbers.lnums_for_str_array(SCRIPT_LINES__[@@rcov_file]) assert_equal(@@rcov_lnums, rcov_lines) end end
29.452381
99
0.692805
6203738876ab0a57ce85db9a9efeafcc3128bcf1
3,892
module D3Timer class Timer @@frame = nil #is an animation frame pending? @@timeout = nil # is a timeout pending? @@interval = nil # are any timers active? @@pokeDelay = 1 #how frequently we check for clock skew , 1sec = 1000ms @@clockLast = nil @@clockNow = nil @@clockSkew = 0 @@clock = Time @@taskTail = nil @@taskHead = nil attr_accessor :_call, :_time, :_next def initialize @_call = @_time = @_next = nil end def self.now @@clockNow || @@clockNow = (@@clock.now().to_f * 1000).to_i + @@clockSkew end def self.timer(delay = 0, time = now, &block) t = Timer.new t.restart(delay, time, &block) t end def self.timer_flush self.now @@frame = @@frame.to_i + 1 #Pretend we’ve set an alarm, if we haven’t already. t = @@taskHead while (t) e = @@clockNow.to_i - t._time if e >= 0 t._call.call(e) t = t._next end end @@frame = nil end def restart(delay = 0, time = self.class.now, &block) raise TypeError.new "callback is not given or callback is not a block" if !block_given? time = time + delay if (!@_next && @@taskTail != self) if (@@taskTail) @@taskTail._next = self else @@taskHead = self @@taskTail = self end end @_call = block @_time = time timer_sleep end def stop if (@_call) @_call = nil @_time = Float::INFINITY @@frame = nil timer_sleep(@_time) end end private def set_timeout(delay = 0.017, &block) @@timeout = Thread.new do sleep delay yield end end def clear_timeout(thread) Thread.kill(thread) nil end def set_interval(time_interval, &block) @@interval = Thread.new do loop do sleep time_interval yield end end end def clear_interval(thread) clear_timeout(thread) end def wake @@clockNow = (@@clockLast = (@@clock.now().to_f * 1000).to_i) + @@clockSkew @@frame = @@timeout = nil begin self.class.timer_flush rescue #handle the error here ensure @@frame = nil nap @@clockNow = nil end end def poke now = (@@clock.now().to_f * 1000).to_i delay = now - @@clockLast if (delay > @@pokeDelay) @@clockSkew -= delay @@lockLast = now end end def nap t1 = @@taskHead t0 = t2 = nil time = Float::INFINITY while (t1) if (t1._call) time = t1._time if time > t1._time t0 = t1 t1 = t1._next else t2 = t1._next t1._next = nil t1 = t0 ? t0._next = t2 : @@taskHead = t2 end end @@taskTail = t0 timer_sleep(time) end def timer_sleep(time = 0) return if @@frame @@timeout = clear_timeout(@@timeout) if @@timeout delay = time - @@clockNow.to_i; # Strictly less than if we recomputed clockNow. if (delay > 24) set_timeout(time - (@@clock.now().to_f * 1000).to_i - @@clockSkew){ wake } if time < Float::INFINITY @@timeout.join if @@timeout @@interval = clear_interval(@@interval) if @@interval else if (!@@interval) @@clockLast = (@@clock.now().to_f * 1000).to_i call_interval_and_timeout @@interval.join @@timeout.join if @@timeout else @@frame = 1 set_timeout{ wake } @@timeout.join end end end def call_interval_and_timeout set_interval(@@pokeDelay){ poke } @@frame = 1 set_timeout{ wake } end def clear_now @@clockNow = nil end end end
22.760234
108
0.527749
ac5a87b2d75bbe3d92ffee10425a98a5757680f4
1,144
# Copyright (c) 2013 Solano Labs All Rights Reserved require 'socket' module NoLockFirefox class PortPool HOST = "127.0.0.1" START_PORT = 24576 def initialize(path=nil) @path_ports = path @path_ports ||= "/tmp/webdriver-firefox.ports.json" @random = Random.new end def find_free_port probed = nil tid = ENV.fetch('TDDIUM_TID', 0).to_i range = 256*tid index = @random.rand(256) limit = START_PORT+256*(tid+1) timeout = Time.now+90 while Time.now < timeout do port = START_PORT+range+index while port < limit do probed = probe_port(port) if probed then probed.close return port end port += 1 Kernel.sleep(0.1) end end raise "unable to find open port in reasonable time" end def probe_port(port) begin s = TCPServer.new(HOST, port) s.close_on_exec = true # ChildProcess.close_on_exec s return s rescue SocketError, Errno::EADDRINUSE => e return nil end end end end
20.8
57
0.570804
d5b31e4b94397df5cc12b9b867aeab1ab4a74886
846
class QuestionsController < ApplicationController before_filter :authenticate_user! before_action :set_question, only: [:show, :edit, :update, :destroy] respond_to :html def index @questions = Question.all respond_with(@questions) end def show respond_with(@question) end def new @question = Question.new respond_with(@question) end def edit end def create @question = Question.new(question_params) @question.save respond_with(@question) end def update @question.update(question_params) respond_with(@question) end def destroy @question.destroy respond_with(@question) end private def set_question @question = Question.find(params[:id]) end def question_params params.require(:question).permit(:title, :description) end end
17.265306
70
0.692671