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
bfeb5a2d097c2c13aa753cd0090b8f05f306522b
5,955
class Admin::UsersController < Admin::ApplicationController before_action :user, except: [:index, :new, :create] def index @users = User.order_name_asc.filter(params[:filter]) @users = @users.search_with_secondary_emails(params[:search_query]) if params[:search_query].present? @users = @users.sort_by_attribute(@sort = params[:sort]) @users = @users.page(params[:page]) end def show end def projects @personal_projects = user.personal_projects @joined_projects = user.projects.joined(@user) end def keys @keys = user.keys.order_id_desc end def new @user = User.new end def edit user end def impersonate if can?(user, :log_in) session[:impersonator_id] = current_user.id warden.set_user(user, scope: :user) Gitlab::AppLogger.info("User #{current_user.username} has started impersonating #{user.username}") flash[:alert] = "You are now impersonating #{user.username}" redirect_to root_path else flash[:alert] = if user.blocked? "You cannot impersonate a blocked user" elsif user.internal? "You cannot impersonate an internal user" else "You cannot impersonate a user who cannot log in" end redirect_to admin_user_path(user) end end def block if update_user { |user| user.block } redirect_back_or_admin_user(notice: "Successfully blocked") else redirect_back_or_admin_user(alert: "Error occurred. User was not blocked") end end def unblock if user.ldap_blocked? redirect_back_or_admin_user(alert: "This user cannot be unlocked manually from GitLab") elsif update_user { |user| user.activate } redirect_back_or_admin_user(notice: "Successfully unblocked") else redirect_back_or_admin_user(alert: "Error occurred. User was not unblocked") end end def unlock if update_user { |user| user.unlock_access! } redirect_back_or_admin_user(alert: "Successfully unlocked") else redirect_back_or_admin_user(alert: "Error occurred. User was not unlocked") end end def confirm if update_user { |user| user.confirm } redirect_back_or_admin_user(notice: "Successfully confirmed") else redirect_back_or_admin_user(alert: "Error occurred. User was not confirmed") end end def disable_two_factor update_user { |user| user.disable_two_factor! } redirect_to admin_user_path(user), notice: 'Two-factor Authentication has been disabled for this user' end def create opts = { reset_password: true, skip_confirmation: true } @user = Users::CreateService.new(current_user, user_params.merge(opts)).execute respond_to do |format| if @user.persisted? format.html { redirect_to [:admin, @user], notice: 'User was successfully created.' } format.json { render json: @user, status: :created, location: @user } else format.html { render "new" } format.json { render json: @user.errors, status: :unprocessable_entity } end end end def update user_params_with_pass = user_params.dup if params[:user][:password].present? password_params = { password: params[:user][:password], password_confirmation: params[:user][:password_confirmation] } password_params[:password_expires_at] = Time.now unless changing_own_password? user_params_with_pass.merge!(password_params) end respond_to do |format| result = Users::UpdateService.new(current_user, user_params_with_pass.merge(user: user)).execute do |user| user.skip_reconfirmation! end if result[:status] == :success format.html { redirect_to [:admin, user], notice: 'User was successfully updated.' } format.json { head :ok } else # restore username to keep form action url. user.username = params[:id] format.html { render "edit" } format.json { render json: [result[:message]], status: result[:status] } end end end def destroy user.delete_async(deleted_by: current_user, params: params.permit(:hard_delete)) respond_to do |format| format.html { redirect_to admin_users_path, status: 302, notice: "The user is being deleted." } format.json { head :ok } end end def remove_email email = user.emails.find(params[:email_id]) success = Emails::DestroyService.new(current_user, user: user).execute(email) respond_to do |format| if success format.html { redirect_back_or_admin_user(notice: 'Successfully removed email.') } format.json { head :ok } else format.html { redirect_back_or_admin_user(alert: 'There was an error removing the e-mail.') } format.json { render json: 'There was an error removing the e-mail.', status: 400 } end end end protected def changing_own_password? user == current_user end def user @user ||= User.find_by!(username: params[:id]) end def redirect_back_or_admin_user(options = {}) redirect_back_or_default(default: default_route, options: options) end def default_route [:admin, @user] end def user_params params.require(:user).permit(user_params_ce) end def user_params_ce [ :access_level, :avatar, :bio, :can_create_group, :color_scheme_id, :email, :extern_uid, :external, :force_random_password, :hide_no_password, :hide_no_ssh_key, :key_id, :linkedin, :name, :password_expires_at, :projects_limit, :provider, :remember_me, :skype, :theme_id, :twitter, :username, :website_url ] end def update_user(&block) result = Users::UpdateService.new(current_user, user: user).execute(&block) result[:status] == :success end end
26.23348
112
0.665155
bf8bcea89246c245918b3f4d6ff75a74a2642b30
71
# frozen_string_literal: true module Parser VERSION = '2.7.1.4' end
11.833333
29
0.71831
1d592d22be6b7bed1214507d78e988a8b187b9af
5,461
# -------------------------------------------------------------------------- # # Copyright 2010-2014, C12G Labs S.L. # # # # 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. # #--------------------------------------------------------------------------- # class Log class << self # This class handles logging for each service and for the service server # Log.info("SERVER", "It works"), it will be written in the main log # Log.info("LCM", "Service 3 started", 3), it will be written in a # specific log for service number 3 LOG_COMP = "LOG" DEBUG_LEVEL = [ Logger::ERROR, # 0 Logger::WARN, # 1 Logger::INFO, # 2 Logger::DEBUG # 3 ] #LOG_LOCATION = '/var/log/one' @log_level = Logger::DEBUG # Mon Feb 27 06:02:30 2012 [Clo] [E]: Error message example MSG_FORMAT = %{%s [%s]: [%s] %s\n} # Mon Feb 27 06:02:30 2012 DATE_FORMAT = "%a %b %d %H:%M:%S %Y" # Message to be used in CloudLogger CLOUD_LOGGER_MSG = %{[%s] %s} # Sets the server logger # @param [CloudLogger::CloudLogger, Logger] logger def logger=(logger) @@logger = logger end # Sets the log level # @param [Integer] log_level (0:ERROR, 1:WARN, 2:INFO, 3:DEBUG) def level=(log_level) @@log_level = DEBUG_LEVEL[log_level] end # Writes a info message to the log. If a service_id is specified the # message will be written to the service log, otherwise the server log # will be used. # @param [String] component # @param [String] message # @param [String] service_id # # @example # Mon Feb 27 06:02:30 2012 [<component>] [I]: <message> def info(component, message, service_id=nil) if service_id add(Logger::INFO, component, message, service_id) else @@logger.info(CLOUD_LOGGER_MSG % [component, message]) end end # Writes a debug message to the log. If a service_id is specified the # message will be written to the service log, otherwise the server log # will be used. # @param [String] component # @param [String] message # @param [String] service_id # # @example # Mon Feb 27 06:02:30 2012 [<component>] [D]: <message> def debug(component, message, service_id=nil) if service_id add(Logger::DEBUG, component, message, service_id) else @@logger.debug(CLOUD_LOGGER_MSG % [component, message]) end end # Writes a error message to the log. If a service_id is specified the # message will be written to the service log, otherwise the server log # will be used. # @param [String] component # @param [String] message # @param [String] service_id # # @example # Mon Feb 27 06:02:30 2012 [<component>] [E]: <message> def error(component, message, service_id=nil) if service_id add(Logger::ERROR, component, message, service_id) else @@logger.error(CLOUD_LOGGER_MSG % [component, message]) end end # Writes a warn message to the log. If a service_id is specified the # message will be written to the service log, otherwise the server log # will be used. # @param [String] component # @param [String] message # @param [String] service_id # # @example # Mon Feb 27 06:02:30 2012 [<component>] [W]: <message> def warn(component, message, service_id=nil) if service_id add(Logger::WARN, component, message, service_id) else @@logger.warn(CLOUD_LOGGER_MSG % [component, message]) end end private def add(severity, component, message, service_id) if severity < @@log_level return true end begin msg = MSG_FORMAT % [ Time.now.strftime(DATE_FORMAT), Logger::SEV_LABEL[severity][0..0], component, message ] open("#{LOG_LOCATION}/oneflow/#{service_id}.log", 'a') do |f| f << msg end rescue Errno::ENOENT => e FileUtils.mkdir("#{LOG_LOCATION}/oneflow/") open("#{LOG_LOCATION}/oneflow/#{service_id}.log", 'a') do |f| f << msg end rescue => e message = "Could not log into #{LOG_LOCATION}/oneflow/#{service_id}.log: #{e.message}" error LOG_COMP, message end end end end
34.783439
98
0.537264
084f1a7eb25eb51d064d427176fe3facd69ef951
2,819
class Test::Unit::TestCase def create_table(table_name, &block) connection = ActiveRecord::Base.connection begin connection.execute("DROP TABLE IF EXISTS #{table_name}") connection.create_table(table_name, &block) @created_tables ||= [] @created_tables << table_name connection rescue Exception => e connection.execute("DROP TABLE IF EXISTS #{table_name}") raise e end end def define_constant(class_name, base, &block) class_name = class_name.to_s.camelize klass = Class.new(base) Object.const_set(class_name, klass) klass.class_eval(&block) if block_given? @defined_constants ||= [] @defined_constants << class_name klass end def define_model_class(class_name, &block) define_constant(class_name, ActiveRecord::Base, &block) end def define_model(name, columns = {}, &block) class_name = name.to_s.pluralize.classify table_name = class_name.tableize create_table(table_name) do |table| columns.each do |name, type| table.column name, type end end define_model_class(class_name, &block) end def define_controller(class_name, &block) class_name = class_name.to_s class_name << 'Controller' unless class_name =~ /Controller$/ define_constant(class_name, ActionController::Base, &block) end def define_routes(&block) @replaced_routes = ActionController::Routing::Routes new_routes = ActionController::Routing::RouteSet.new silence_warnings do ActionController::Routing.const_set('Routes', new_routes) end new_routes.draw(&block) end def build_response(&block) klass = define_controller('Examples') block ||= lambda { render :nothing => true } klass.class_eval { define_method(:example, &block) } define_routes do |map| map.connect 'examples', :controller => 'examples', :action => 'example' end @controller = klass.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new get :example @controller end def teardown_with_models if @defined_constants @defined_constants.each do |class_name| Object.send(:remove_const, class_name) end end if @created_tables @created_tables.each do |table_name| ActiveRecord::Base. connection. execute("DROP TABLE IF EXISTS #{table_name}") end end if @replaced_routes ActionController::Routing::Routes.clear! silence_warnings do ActionController::Routing.const_set('Routes', @replaced_routes) end @replaced_routes.reload! end teardown_without_models end alias_method :teardown_without_models, :teardown alias_method :teardown, :teardown_with_models end
26.345794
77
0.686414
7a7d8817b58ecb2f51d1f3c842804228d430f6b9
3,490
require_relative "../test_helper" module SmartAnswer class CheckboxQuestionTest < ActiveSupport::TestCase context "specifying options" do should "be able to specify options, and retreive them in the order specified" do q = Question::Checkbox.new(nil, :something) do option :red option "blue" option :green option "blue-green" option :reddy_brown end assert_equal %w[red blue green blue-green reddy_brown], q.option_keys end should "be able to specify options with block" do q = Question::Checkbox.new(nil, :something) do options { %w[x y z] } end assert_equal %w[x y z], q.options_block.call end should "not be able to use reserved 'none' option" do assert_raise InvalidNode do Question::Checkbox.new(nil, :something) { option :none } end end should "not be able to use options with non URL safe characters" do assert_raise InvalidNode do Question::Checkbox.new(nil, :something) { option "a space" } end assert_raise InvalidNode do Question::Checkbox.new(nil, :something) { option "a,comma" } end end end context "setup" do should "resolve the options keys from the option block" do q = Question::Checkbox.new(nil, :example) do options { %i[x y] } end q.setup(nil) assert_equal %i[x y], q.option_keys end should "not clear options keys if option block is nil" do q = Question::Checkbox.new(nil, :example) do option :a option :b end q.setup(nil) assert_equal %w[a b], q.option_keys end end context "parsing response" do setup do @question = Question::Checkbox.new(nil, :something) do option :red option :blue option :green end end context "with an array" do should "return the responses as a sorted comma-separated string" do assert_equal "green,red", @question.parse_input(%w[red green]) end should "raise an error if given a non-existing response" do assert_raise InvalidResponse do @question.parse_input %w[blue orange] end end end context "with a comma separated string" do should "return the responses as a sorted comma-separated string" do assert_equal "green,red", @question.parse_input("red,green") end should "raise an error if given a non-existing response" do assert_raise InvalidResponse do @question.parse_input "blue,orange" end end end context "handling the special none case" do should "return none when passed nil" do assert_equal "none", @question.parse_input(nil) end should "return none when passed special value 'none'" do assert_equal "none", @question.parse_input("none") end end context "with an explicitly set 'none' option" do setup do @question.none_option end should "enable the none option" do assert @question.none_option? end should "raise if the response is blank" do assert_raise InvalidResponse do @question.parse_input(nil) end end end end end end
27.698413
86
0.595702
61f3749be208ac5dbec9cc35f042f44e79b3ec9a
239
FactoryGirl.define do factory :profile, class: Profile do first_name { Faker::Name.first_name } last_name { Faker::Name.last_name } date_of_birth { Faker::Date.between(30.years.ago, 10.years.ago) } user end end
26.555556
69
0.677824
e9a0d636645802c74af638b5ead48730019a8633
534
Gem.loaded_specs['nyauth'].dependencies.each do |d| begin require d.name.gsub('-', '/') rescue LoadError require d.name end end module Nyauth class Engine < ::Rails::Engine isolate_namespace Nyauth config.generators do |g| g.test_framework :rspec, fixture: false g.fixture_replacement :factory_girl, dir: 'spec/factories' g.assets false g.helper false end initializer 'nyauth.add_middleware' do |app| app.middleware.use Nyauth::Middleware end end end
21.36
64
0.662921
e2a863fdb1cc53d361c83e304ba9ce7732b232e8
761
#################################### # ACTIONS # #################################### When 'I navigate to home page' do HomePage.open end When 'I force making screenshot and saving source page' do HomePage.on do Capybara::Screenshot.screenshot_and_save_page end end #################################### # CHECKS # #################################### Then 'I should see screenshot in log directory' do screenshot = File.join(File.dirname(__FILE__), '../../log/screenshot.png') expect(File).to be_exist(screenshot) end Then 'I should see source page in log directory' do source_page = File.join(File.dirname(__FILE__), '../../log/screenshot.html') expect(File).to be_exist(source_page) end
29.269231
78
0.545335
1ac4c37c779b45c43bbc1e831abc0cf87cc57c31
343
require 'revs' require_jar 'log4j', 'log4j' java_import 'com.eventswarm.powerset.NewSetAction' class AddSet include Log4JLogger include NewSetAction def initialize(&block) @handler = block end def execute(trigger, set, key) logger.debug "Calling NewSetAction for key #{key}" @handler.call trigger, set, key end end
18.052632
54
0.725948
33dd6bcb17ec2c991f70f18414fa598fdbd57387
699
# frozen_string_literal: true require 'application_system_test_case' class Notification::AnswersTest < ApplicationSystemTestCase setup do @notice_text = 'komagataさんから回答がありました。' end test "recieve a notification when I got my question's answer" do visit_with_auth "/questions/#{questions(:question2).id}", 'komagata' within('.thread-comment-form__form') do fill_in('answer[description]', with: 'reduceも使ってみては?') end click_button 'コメントする' wait_for_vuejs logout visit_with_auth '/', 'sotugyou' open_notification assert_equal @notice_text, notification_message logout visit_with_auth '/', 'komagata' refute_text @notice_text end end
24.964286
72
0.729614
bb494e8aa6a5a77957d40bbf4228c7e1587034a0
1,279
require_relative 'service' module AdyenOfficial class Checkout < Service DEFAULT_VERSION = 49 def initialize(client, version = DEFAULT_VERSION) service = 'Checkout' method_names = [ :payment_methods, :payment_session ] super(client, version, service, method_names) end # This method can't be dynamically defined because # it needs to be both a method and a class # to enable payments() and payments.detail(), # which is accomplished via an argument length checker # and the CheckoutDetail class below def payments(*args) case args.size when 0 AdyenOfficial::CheckoutDetail.new(@client, @version) when 1 action = 'payments' @client.call_adyen_api(@service, action, args[0], @version) end end end class CheckoutDetail < Service def initialize(client, version = DEFAULT_VERSION) @service = 'Checkout' @client = client @version = version end def details(request) action = "payments/details" @client.call_adyen_api(@service, action, request, @version) end def result(request) action = "payments/result" @client.call_adyen_api(@service, action, request, @version) end end end
25.078431
67
0.653636
0383cddd5aa42a1b1e7fd145cba32918e68878a2
313
class FixLengthOfTextFields < ActiveRecord::Migration[5.2] def change change_column :casino_proxy_tickets, :service, :text, :limit => nil change_column :casino_service_tickets, :service, :text, :limit => nil change_column :casino_ticket_granting_tickets, :user_agent, :text, :limit => nil end end
39.125
84
0.750799
019e43bfd70accb2bd1647874986481607b5bb10
112
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'define_private' require 'minitest/autorun'
22.4
58
0.758929
18f63fdf7ae88efb9ddfe49ae6b9804afdd13d31
248
require "openxml/drawingml/properties/paragraph_properties" module OpenXml module DrawingML module Properties class Level9ParagraphProperties < ParagraphProperties namespace :a tag :lvl9pPr end end end end
17.714286
59
0.717742
1ad701e784000dce5c7deaadb1588076a201b1a9
113
class AddWikititleIndexToPages < ActiveRecord::Migration def change add_index :pages, :wikititle end end
18.833333
56
0.778761
6227075306ef3dab0754f8a5a0a5e006718851b9
551
# frozen_string_literal: true module AsciiDetector class PatternMatcher attr_reader :frame, :pattern def initialize(frame, pattern) @pattern = pattern @frame = frame @matched = 0 end def call frame.each_with_index { |item, row, col| match(item, pattern[row][col]) } matched_percent end private def matched_percent (@matched.to_f / frame.area) * 100 end def match(field_item, pattern_item) return if field_item != pattern_item @matched += 1 end end end
17.774194
79
0.637024
f8da774764b0a2fad09a0a160a24d13392130ec7
707
# frozen_string_literal: true unless Rails.env.test? require 'flamegraph' require 'rack-mini-profiler' Rack::MiniProfilerRails.initialize!(Rails.application) Rack::MiniProfiler.config.position = 'right' Rack::MiniProfiler.config.skip_schema_queries = true # set MemoryStore Rack::MiniProfiler.config.storage = Rack::MiniProfiler::MemoryStore # set RedisStore and overide MemoryStore in production if Rails.env.production? && ENV.key?('REDIS_SERVER_URL') uri = URI.parse(ENV['REDIS_SERVER_URL']) Rack::MiniProfiler.config.storage_options = { :host => uri.host, :port => uri.port, :password => uri.password } Rack::MiniProfiler.config.storage = Rack::MiniProfiler::RedisStore end end
35.35
113
0.759547
5d4eba3789ecf13577147bbfd2d4e1180cf71ac0
645
module Telegram module Bot module Types class Poll < Base attribute :id, String attribute :question, String attribute :options, Array[PollOption] attribute :total_voter_count, Integer attribute :is_closed, Boolean attribute :is_anonymous, Boolean attribute :type, String attribute :allows_multiple_answers, Boolean attribute :correct_option_id, Integer attribute :explanation, String attribute :explanation_entities, Array[MessageEntity] attribute :open_period, Integer attribute :close_date, Integer end end end end
29.318182
61
0.671318
abc261c528c40add19fb0a68d10e993e3f5afa3d
1,833
#! /usr/bin/env ruby require 'spec_helper' describe Puppet::Type.type(:compellent_volume) do let :resource do described_class.new( :name => 'Test_Volume_spec', :ensure => 'present', :boot => false, :volumefolder => '', :purge => 'yes', :size => '2g', :notes => 'Test Space Notes', :replayprofile => 'Sample', :storageprofile => 'Low Priority' ) end it "should have name as its keyattribute" do described_class.key_attributes.should == [:name] end describe "when validating attributes" do [:name].each do |param| it "should hava a #{param} parameter" do described_class.attrtype(param).should == :param end end end describe "when validating values" do describe "for name" do it "should allow a valid mapping name where ensure is present" do described_class.new(:name => 'Test_Volume_spec', :ensure => 'present')[:name].should == 'Test_Volume_Test' end it "should allow a valid mapping name where ensure is absent" do described_class.new(:name => 'Test_Volume_spec', :ensure => 'absent')[:name].should == 'Test_Volume_Test' end end describe "for ensure" do it "should allow present" do described_class.new(:name => 'Test_Volume_spec', :ensure => 'present')[:ensure].should == :present end it "should allow absent" do described_class.new(:name => 'Test_Volume_spec', :ensure => 'absent')[:ensure].should == :absent end it "should not allow something else" do expect { described_class.new(:name => 'newvolThree', :ensure => 'foo') }.to raise_error Puppet::Error, /Invalid value/ end end end end
30.04918
127
0.591926
385067b9660cf56830c24cc56026a4af1a924649
45
module SwannViewTool VERSION = "0.1.0" end
11.25
20
0.711111
e2a8b4d4e379e0a31e566844fb129c7f32571a81
1,184
module ActiveSupport # This module provides an internal implementation to track descendants # which is faster than iterating through ObjectSpace. module DescendantsTracker @@direct_descendants = Hash.new { |h, k| h[k] = [] } def self.direct_descendants(klass) @@direct_descendants[klass] end def self.descendants(klass) @@direct_descendants[klass].inject([]) do |descendants, _klass| descendants << _klass descendants.concat _klass.descendants end end def self.clear if defined? ActiveSupport::Dependencies @@direct_descendants.each do |klass, descendants| if ActiveSupport::Dependencies.autoloaded?(klass) @@direct_descendants.delete(klass) else descendants.reject! { |v| ActiveSupport::Dependencies.autoloaded?(v) } end end else @@direct_descendants.clear end end def inherited(base) self.direct_descendants << base super end def direct_descendants DescendantsTracker.direct_descendants(self) end def descendants DescendantsTracker.descendants(self) end end end
25.73913
82
0.662162
91f6f33ef27dbfb464e323cecd257c601909ba43
443
module MetrcService module Plant class Harvest < Base def call # allow for harvest of nursery crops - generates clones return success! if barcodes.empty? success! end private def transaction @transaction ||= get_transaction(:harvest_batch) end def seeding_unit_id @seeding_unit_id ||= @attributes.dig(:options, :seeding_unit_id) end end end end
19.26087
72
0.625282
263d3e46a2a85db82f5c6e0d36d96dc483f20acc
61
FactoryGirl.define do factory :sentence do end end
8.714286
22
0.688525
01a6d3377e8224b52f2805a148367cec22012158
1,942
# This file is automatically generated by puppet-swagger-generator and # any manual changes are likely to be clobbered when the files # are regenerated. require_relative '../../puppet_x/puppetlabs/swagger/fuzzy_compare' Puppet::Type.newtype(:kubernetes_node_affinity) do @doc = "Node affinity is a group of node affinity scheduling rules." ensurable apply_to_all newparam(:name, namevar: true) do desc 'Name of the node_affinity.' end newproperty(:required_during_scheduling_ignored_during_execution) do desc "If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to an update), the system may or may not try to eventually evict the pod from its node." def insync?(is) PuppetX::Puppetlabs::Swagger::Utils::fuzzy_compare(is, should) end end newproperty(:preferred_during_scheduling_ignored_during_execution, :array_matching => :all) do desc "The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding 'weight' to the sum if the node matches the corresponding matchExpressions; the node(s) with the highest sum are the most preferred." def insync?(is) PuppetX::Puppetlabs::Swagger::Utils::fuzzy_compare(is, should) end end end
39.632653
621
0.717302
e2097768d0a36043dc685bc32e543dc6f13228ee
1,267
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'google/apis/iam_v1/service.rb' require 'google/apis/iam_v1/classes.rb' require 'google/apis/iam_v1/representations.rb' module Google module Apis # Identity and Access Management (IAM) API # # Manages identity and access control for Google Cloud Platform resources, # including the creation of service accounts, which you can use to authenticate # to Google and make API calls. # # @see https://cloud.google.com/iam/ module IamV1 VERSION = 'V1' REVISION = '20201112' # View and manage your data across Google Cloud Platform services AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform' end end end
34.243243
83
0.732439
9146bd12c58e15d6d943e009a72a23a1df4a0ce5
415
module Api module V1 class MakeAMoveController < ApplicationController def make_a_move if(params.has_key?(:board)) current_board = params[:board] move = MakeAMoveHelper.generate_a_move(current_board) updated_board = MakeAMoveHelper.update_board(current_board) render json: { 'move': move, 'board': updated_board } end end end end end
25.9375
69
0.653012
01af73ec33f6a2177a5b87fb06c3a19e366bbbf9
103
require 'fog/openstack/requests/volume/accept_transfer' require 'fog/openstack/requests/volume_v1/real'
51.5
55
0.854369
e84fcefd35b05bb53e4e8e88ba39d9ae62294212
96
# frozen_string_literal: true json.partial! 'technologies/technology', technology: @technology
24
64
0.8125
87cd5c231b7bebb06d745caa6e50044409a9bbf4
126
module Shrine class Base < ActiveRecord::Base self.abstract_class = true establish_connection SHRINE_DB end end
15.75
34
0.746032
d5007117c633fcb9f8e33bff9d111de61d90e326
836
require 'test_helper' class StaticPagesControllerTest < ActionDispatch::IntegrationTest def setup @base_title = "Ruby on Rails Tutorial Sample App" end test "should get root" do get root_url assert_response :success end test "should get home" do get root_path assert_response :success # assert_select "title", "Home | #{@base_title}" assert_select "title", "#{@base_title}" end test "should get help" do get help_path assert_response :success assert_select "title", "Help | #{@base_title}" end test "should get about" do get about_path assert_response :success assert_select "title", "About | #{@base_title}" end test "should get contact" do get contact_path assert_response :success assert_select "title", "Contact | #{@base_title}" end end
22
65
0.688995
26aeb44e5fe1685c93fa21ed4500bdf621f34f83
226
# frozen_string_literal: true module Computer module OperatingSystems module Linux class ServiceManagementThrowdown < Base CATEGORIES = %w(Systemd SystemV(init) Upstart).freeze end end end end
18.833333
61
0.712389
11146cdc9354dbd20388899f607a743840395a65
57
module MatchPro class General < Hashie::Mash end end
11.4
30
0.736842
286d9a2b2af2a2feffffbab6d790d30c6b08d243
304
class CreateSettings < ActiveRecord::Migration[6.0] def change create_table :settings do |t| t.string :name, null: false t.string :description t.string :level, null: false, default: 'site' t.boolean :locked, null: false, default: true t.timestamps end end end
21.714286
51
0.651316
ed327a7dd000f985356b3157655e739c6fd8af70
1,899
class GitHooks < Formula desc "Manage project, user, and global Git hooks" homepage "https://github.com/icefox/git-hooks" url "https://github.com/icefox/git-hooks/archive/1.00.0.tar.gz" sha256 "8197ca1de975ff1f795a2b9cfcac1a6f7ee24276750c757eecf3bcb49b74808e" head "https://github.com/icefox/git-hooks.git" bottle do sha256 cellar: :any_skip_relocation, catalina: "d33514436cb623e468314418876fe1e7bb8c31ee64fdcd3c9a297f26a7e7ae42" sha256 cellar: :any_skip_relocation, mojave: "a66bf94650a35829721b07c4f6a497154c9e667917ea8c28418b870c0de15697" sha256 cellar: :any_skip_relocation, high_sierra: "710495206af282348fa5e311f825bdbbcb7a891345ff467468908e16b3dbc090" sha256 cellar: :any_skip_relocation, sierra: "aaceeb7b390f71c45e3c1db15c23ab664a06bfc34de1c629a2b2f5b29e1bdec2" sha256 cellar: :any_skip_relocation, el_capitan: "bdfffb820e5a7574169b91113ed59c578ebe88bcea8c890166a33fb9af17c0ce" sha256 cellar: :any_skip_relocation, yosemite: "d4c5fba7f1b80e8e68762356a2f64ac216bf4e9f3151cf2f236c92a9524b97ed" sha256 cellar: :any_skip_relocation, mavericks: "ace6acaff04ef09795d26e6034bf411a89c9f348287dd95f756c82068cea123d" sha256 cellar: :any_skip_relocation, x86_64_linux: "d752497286961e018f332e0e0be3a342473645c553c3542b72d1debe9f0054f8" end # The icefox/git-hooks repository has been deleted and it doesn't appear to # have moved to an alternative location. There is a rewrite in Go by a # different author which someone may want to work into a new formula as a # replacement: https://github.com/git-hooks/git-hooks deprecate! date: "2020-06-25", because: :repo_removed def install bin.install "git-hooks" (etc/"git-hooks").install "contrib" end test do system "git", "init" output = shell_output("git hooks").strip assert_match "Listing User, Project, and Global hooks", output end end
52.75
121
0.790943
ffe294ba4e3e370e7f3dbd60888078216d03ec07
2,199
class CommitsController < ApplicationController before_action :set_commit, only: [:show, :edit, :update, :destroy] # GET /commits # GET /commits.json def index Commit.load(search_params) if search_params.present? @commits = Commit.all.page params[:page] end # GET /commits/1 # GET /commits/1.json def show end # GET /commits/new def new @commit = Commit.new end # GET /commits/1/edit def edit end # POST /commits # POST /commits.json def create @commit = Commit.new(commit_params) respond_to do |format| if @commit.save format.html { redirect_to @commit, notice: 'Commit was successfully created.' } format.json { render :show, status: :created, location: @commit } else format.html { render :new } format.json { render json: @commit.errors, status: :unprocessable_entity } end end end # PATCH/PUT /commits/1 # PATCH/PUT /commits/1.json def update respond_to do |format| if @commit.update(commit_params) format.html { redirect_to @commit, notice: 'Commit was successfully updated.' } format.json { render :show, status: :ok, location: @commit } else format.html { render :edit } format.json { render json: @commit.errors, status: :unprocessable_entity } end end end # DELETE /commits/1 # DELETE /commits/1.json def destroy @commit.destroy respond_to do |format| format.js format.html { redirect_to commits_url } end end def destroy_multiple Commit.where(:id => params[:commit_ids]).delete_all respond_to do |format| format.js format.html { redirect_to commits_url } end end private # Use callbacks to share common setup or constraints between actions. def set_commit @commit = Commit.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def commit_params params.require(:commit).permit(:commiter_name, :commiter_email, :message, :commit_url, :profile_url, :commit_date) end def search_params params.permit(:owner, :repo, :author_email) end end
25.275862
120
0.6603
87df08ffc9c77b248dd8a4c970e4e2670a091f99
1,617
require "rails_helper" RSpec.describe Api::OrderDetail do subject { Api::OrderDetail.new(order_detail) } let(:expected_hash) { { account: account_hash, ordered_for: ordered_for_hash } } let(:order) { double(Order, user: ordered_for) } let(:order_detail) { double(OrderDetail, account: account, order: order, order_number: "12-3") } let(:ordered_for) { build(:user, id: 2) } describe "#to_h" do context "when the order_detail has an account" do let(:account) { double(Account, id: 1, owner: account_user) } let(:account_owner) { build(:user, id: 1) } let(:account_user) { double(AccountUser, user: account_owner) } it "generates the expected hash" do expect(subject.to_h).to match a_hash_including( order_number: "12-3", ordered_for: { id: ordered_for.id, name: ordered_for.name, username: ordered_for.username, email: ordered_for.email, }, account: { id: account.id, owner: { id: account_owner.id, name: account_owner.name, username: account_owner.username, email: account_owner.email, }, }, ) end end context "when the order_detail has no account" do let(:account) { nil } let(:account_hash) { nil } it "generates the expected hash" do expect(subject.to_h).to match a_hash_including( order_number: "12-3", ordered_for: an_instance_of(Hash), account: nil, ) end end end end
29.944444
98
0.588126
f87222e7f959bc825a11e03d43b7fc0a2f59d9a9
476
cask 'eclipse-platform' do version '4.6-201606061100' sha256 'd8c0b7b970581bbfab047375c0bf44243f5f4e528e950be2313e275451d684b6' url "http://www.eclipse.org/downloads/download.php?file=/eclipse/downloads/drops#{version.to_i}/R-#{version}/eclipse-SDK-#{version.sub(%r{-.*}, '')}-macosx-cocoa-x86_64.tar.gz&r=1" name 'Eclipse SDK' homepage 'https://eclipse.org' license :eclipse depends_on macos: '>= :leopard' depends_on arch: :x86_64 app 'Eclipse.app' end
31.733333
182
0.735294
7a5dd2519da7e7d170b0339d62a69a09bd416390
5,712
describe :string_concat, :shared => true do it "concatenates the given argument to self and returns self" do str = 'hello ' str.send(@method, 'world').should equal(str) str.should == "hello world" end it "converts the given argument to a String using to_str" do obj = mock('world!') obj.should_receive(:to_str).and_return("world!") a = 'hello '.send(@method, obj) a.should == 'hello world!' end it "raises a TypeError if the given argument can't be converted to a String" do lambda { 'hello '.send(@method, []) }.should raise_error(TypeError) lambda { 'hello '.send(@method, mock('x')) }.should raise_error(TypeError) end it "raises a RuntimeError when self is frozen" do a = "hello" a.freeze lambda { a.send(@method, "") }.should raise_error(RuntimeError) lambda { a.send(@method, "test") }.should raise_error(RuntimeError) end it "works when given a subclass instance" do a = "hello" a.send(@method, StringSpecs::MyString.new(" world")) a.should == "hello world" end it "taints self if other is tainted" do "x".send(@method, "".taint).tainted?.should == true "x".send(@method, "y".taint).tainted?.should == true end it "untrusts self if other is untrusted" do "x".send(@method, "".untrust).untrusted?.should == true "x".send(@method, "y".untrust).untrusted?.should == true end describe "with Integer" do it "concatencates the argument interpreted as a codepoint" do b = "".send(@method, 33) b.should == "!" b.encode!(Encoding::UTF_8) b.send(@method, 0x203D) b.should == "!\u203D" end # #5855 it "returns a ASCII-8BIT string if self is US-ASCII and the argument is between 128-255 (inclusive)" do a = ("".encode(Encoding::US_ASCII).send(@method, 128)) a.encoding.should == Encoding::ASCII_8BIT a.should == 128.chr a = ("".encode(Encoding::US_ASCII).send(@method, 255)) a.encoding.should == Encoding::ASCII_8BIT a.should == 255.chr end it "raises RangeError if the argument is an invalid codepoint for self's encoding" do lambda { "".encode(Encoding::US_ASCII).send(@method, 256) }.should raise_error(RangeError) lambda { "".encode(Encoding::EUC_JP).send(@method, 0x81) }.should raise_error(RangeError) end it "raises RangeError if the argument is negative" do lambda { "".send(@method, -200) }.should raise_error(RangeError) lambda { "".send(@method, -bignum_value) }.should raise_error(RangeError) end it "doesn't call to_int on its argument" do x = mock('x') x.should_not_receive(:to_int) lambda { "".send(@method, x) }.should raise_error(TypeError) end it "raises a RuntimeError when self is frozen" do a = "hello" a.freeze lambda { a.send(@method, 0) }.should raise_error(RuntimeError) lambda { a.send(@method, 33) }.should raise_error(RuntimeError) end end end describe :string_concat_encoding, :shared => true do describe "when self is in an ASCII-incompatible encoding incompatible with the argument's encoding" do it "uses self's encoding if both are empty" do "".encode("UTF-16LE").send(@method, "").encoding.should == Encoding::UTF_16LE end it "uses self's encoding if the argument is empty" do "x".encode("UTF-16LE").send(@method, "").encoding.should == Encoding::UTF_16LE end it "uses the argument's encoding if self is empty" do "".encode("UTF-16LE").send(@method, "x".encode("UTF-8")).encoding.should == Encoding::UTF_8 end it "raises Encoding::CompatibilityError if neither are empty" do lambda { "x".encode("UTF-16LE").send(@method, "y".encode("UTF-8")) }.should raise_error(Encoding::CompatibilityError) end end describe "when the argument is in an ASCII-incompatible encoding incompatible with self's encoding" do it "uses self's encoding if both are empty" do "".encode("UTF-8").send(@method, "".encode("UTF-16LE")).encoding.should == Encoding::UTF_8 end it "uses self's encoding if the argument is empty" do "x".encode("UTF-8").send(@method, "".encode("UTF-16LE")).encoding.should == Encoding::UTF_8 end it "uses the argument's encoding if self is empty" do "".encode("UTF-8").send(@method, "x".encode("UTF-16LE")).encoding.should == Encoding::UTF_16LE end it "raises Encoding::CompatibilityError if neither are empty" do lambda { "x".encode("UTF-8").send(@method, "y".encode("UTF-16LE")) }.should raise_error(Encoding::CompatibilityError) end end describe "when self and the argument are in different ASCII-compatible encodings" do it "uses self's encoding if both are ASCII-only" do "abc".encode("UTF-8").send(@method, "123".encode("SHIFT_JIS")).encoding.should == Encoding::UTF_8 end it "uses self's encoding if the argument is ASCII-only" do "\u00E9".encode("UTF-8").send(@method, "123".encode("ISO-8859-1")).encoding.should == Encoding::UTF_8 end it "uses the argument's encoding if self is ASCII-only" do "abc".encode("UTF-8").send(@method, "\u00E9".encode("ISO-8859-1")).encoding.should == Encoding::ISO_8859_1 end it "raises Encoding::CompatibilityError if neither are ASCII-only" do lambda { "\u00E9".encode("UTF-8").send(@method, "\u00E9".encode("ISO-8859-1")) }.should raise_error(Encoding::CompatibilityError) end end describe "when self is ASCII-8BIT and argument is US-ASCII" do it "uses ASCII-8BIT encoding" do "abc".encode("ASCII-8BIT").send(@method, "123".encode("US-ASCII")).encoding.should == Encoding::ASCII_8BIT end end end
37.333333
135
0.658613
4ac6961eadcb35a51e4192e78ef1ed8adece7ce2
1,922
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2019_09_01 module Models # # Result of on demand test probe. # class ApplicationGatewayBackendHealthOnDemand include MsRestAzure # @return [ApplicationGatewayBackendAddressPool] Reference of an # ApplicationGatewayBackendAddressPool resource. attr_accessor :backend_address_pool # @return [ApplicationGatewayBackendHealthHttpSettings] Application # gateway BackendHealthHttp settings. attr_accessor :backend_health_http_settings # # Mapper for ApplicationGatewayBackendHealthOnDemand class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ApplicationGatewayBackendHealthOnDemand', type: { name: 'Composite', class_name: 'ApplicationGatewayBackendHealthOnDemand', model_properties: { backend_address_pool: { client_side_validation: true, required: false, serialized_name: 'backendAddressPool', type: { name: 'Composite', class_name: 'ApplicationGatewayBackendAddressPool' } }, backend_health_http_settings: { client_side_validation: true, required: false, serialized_name: 'backendHealthHttpSettings', type: { name: 'Composite', class_name: 'ApplicationGatewayBackendHealthHttpSettings' } } } } } end end end end
31
78
0.604579
6adfa19ec3eba95f10b0ada5f56b2b451a1f9e34
2,319
# Issues to be mindful of when using this function # It is coupled to the border styling # All whitespace is discarded # Rows containing entirely dashes and/or plusses will be interpretted as the # beginning of a new row def parse_text_table(text_table) cells = parse_cells(text_table) output_rows = [[]] cells.each do |cell| if cell == "\n" output_rows.append([]) else output_rows.last.append(cell) end end grouped_rows = [] output_rows.each do |row| if is_a_row_delimeter?(row) grouped_rows.append([]) else grouped_rows.last.append(row) end end real_rows = [] grouped_rows.each do |group| real_rows.append([]) group.each do |row| row.each_with_index do |cell, index| real_rows.last[index] = "" if real_rows.last[index].nil? real_rows.last[index] += cell end real_rows.last.map! do |cell| cell.gsub(/\s/, "") end end end real_rows end def parse_cells(text_table) cell_delimeters = /\||\+/ text_table.split(cell_delimeters).compact_blank end def is_a_row_delimeter?(row) contains_only_dashes = /^\-+$/ row.join.match?(contains_only_dashes) end RSpec::Matchers.define :have_cell_containing do |text| match do |table_output| cells = get_row_and_column_cells_in_output(table_output) cells.any? { |cell| cell&.match?(text) } end def get_row_and_column_cells_in_output(table_output) text_table = parse_text_table(table_output) if @at_row && @at_column [text_table[@at_row][@at_column]] elsif @at_row text_table[@at_row] elsif @at_column text_table.map { |row| row[@at_column] } end end chain :at_row do |row| @at_row = row end chain :at_column do |column| @at_column = column end failure_message do |table_output| <<~EOMESSAGE expected to find: #{text} To be in row #{@at_row || '(any)'} and column #{@at_column || '(any)'}: #{get_row_and_column_cells_in_output(table_output)} EOMESSAGE end failure_message_when_negated do |table_output| <<~EOMESSAGE expected not to find: #{text} To be in row #{@at_row || '(any)'} and column #{@at_column || '(any)'}: #{get_row_and_column_cells_in_output(table_output)} EOMESSAGE end end
21.877358
77
0.661492
03986d313808eee9c768f3a52cea3b77dbc8b0d7
282
module Admin::DynamicTemplatesHelper def preview_of_dt(dt) case dt.content_type when "html" content_tag(:div, dt.content.html_safe, :class => 'content-preview') when "text" content_tag(:pre, dt.content, :class => 'content-preview') end end end
21.692308
74
0.663121
213e02d141ef0bacddff74e7c9d56c5a2e80b4b7
565
# generated by 'rake generate' require 'cocoa/bindings/NSObject' module Cocoa class CAMediaTimingFunction < Cocoa::NSObject attach_singular_method :functionWithControlPoints, :args=>4, :names=>[], :types=>["f", "f", "f", "f"], :retval=>"@" attach_singular_method :functionWithName, :args=>1, :names=>[], :types=>["@"], :retval=>"@" attach_method :getControlPointAtIndex, :args=>2, :names=>[:values], :types=>["Q", "^f"], :retval=>"v" attach_method :initWithControlPoints, :args=>4, :names=>[], :types=>["f", "f", "f", "f"], :retval=>"@" end end
51.363636
119
0.640708
79f56febb7cdbe5ca1baa7e036f3c54fccf0c6d5
627
# frozen_string_literal: true RSpec.describe Hyrax::MessengerService do describe '#deliver' do let(:sender) { create(:user) } let(:recipients) { create(:user) } let(:body) { 'Quite an excellent message' } let(:subject) { 'IMPORTANT' } let(:other_arg) { 'Did I make it?' } it 'invokes Hyrax::MessengerService to deliver the message' do expect(sender).to receive(:send_message).with(recipients, body, subject, other_arg) expect(StreamNotificationsJob).to receive(:perform_later).with(recipients) described_class.deliver(sender, recipients, body, subject, other_arg) end end end
36.882353
89
0.701754
03511afe7a75c979521d2cf926123df00afe726e
1,398
describe Api::V1::AuthorizationScopeSerializer do subject do serializer_class.new(model, options).to_json end let(:serializer_class) { Api::V1::AuthorizationScopeSerializer } let(:options) { {root: false} } context "for expense account" do let(:model) { build_stubbed :expense_account, name: "Materials" } it { is_expected.to be_json_eql(model.id).at_path("id") } it { is_expected.to be_json_eql("Materials".to_json).at_path("name") } it { is_expected.to be_json_eql("Expense".to_json).at_path("type") } end context "for vendor" do let(:model) { build_stubbed :vendor, name: "Another Co." } it { is_expected.to be_json_eql(model.id).at_path("id") } it { is_expected.to be_json_eql("Another Co.".to_json).at_path("name") } it { is_expected.to be_json_eql("Vendor".to_json).at_path("type") } end context "for QuickBooks class" do let(:model) { build_stubbed :qb_class, name: "HQ" } it { is_expected.to be_json_eql(model.id).at_path("id") } it { is_expected.to be_json_eql("HQ".to_json).at_path("name") } it { is_expected.to be_json_eql("QBClass".to_json).at_path("type") } end it "inherits from CoreSerializer defined in its namespace" do expected_superclass = serializer_class.name.gsub(/::\w+\Z/, "::CoreSerializer").constantize expect(serializer_class.ancestors).to include(expected_superclass) end end
34.95
95
0.703863
e8f8dd592d369ce9a42cc711cafad6b9767a4057
695
# frozen_string_literal: true # Take a signed permanent reference for a variant and turn it into an expiring service URL for download. # Note: These URLs are publicly accessible. If you need to enforce access protection beyond the # security-through-obscurity factor of the signed blob and variation reference, you'll need to implement your own # authenticated redirection controller. class ActiveStorage::VariantsController < ActionController::Base include ActiveStorage::SetBlob def show expires_in ActiveStorage::Blob.service.url_expires_in redirect_to ActiveStorage::Variant.new(@blob, params[:variation_key]).processed.service_url(disposition: params[:disposition]) end end
46.333333
130
0.808633
5d4f031cab9802c250fe95aad67778d6931aff6e
188
require_dependency 'support/application_record' module Support module Cms class Nav < ApplicationRecord self.table_name = 'extranet.cms_navs' audited end end end
15.666667
47
0.723404
f8a9ece0c4914d55ddc73082f7ac5c5487b4d6b2
181
RSpec.describe BabyCare do it "has a version number" do expect(BabyCare::VERSION).not_to be nil end it "does something useful" do expect(false).to eq(true) end end
18.1
43
0.701657
acf1e42c7a95ffc436bee4fc7888466d18fbcde7
3,298
# frozen_string_literal: true require 'hocon' require 'bolt/error' module BoltServer class BaseConfig def config_keys %w[host port ssl-cert ssl-key ssl-ca-cert ssl-cipher-suites loglevel logfile allowlist projects-dir] end def env_keys %w[ssl-cert ssl-key ssl-ca-cert loglevel] end def defaults { 'host' => '127.0.0.1', 'loglevel' => 'warn', 'ssl-cipher-suites' => %w[ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-RSA-AES256-GCM-SHA384 ECDHE-ECDSA-CHACHA20-POLY1305 ECDHE-RSA-CHACHA20-POLY1305 ECDHE-ECDSA-AES128-GCM-SHA256 ECDHE-RSA-AES128-GCM-SHA256 ECDHE-ECDSA-AES256-SHA384 ECDHE-RSA-AES256-SHA384 ECDHE-ECDSA-AES128-SHA256 ECDHE-RSA-AES128-SHA256] } end def ssl_keys %w[ssl-cert ssl-key ssl-ca-cert] end def required_keys ssl_keys end def service_name raise "Method service_name must be defined in the service class" end def initialize(config = nil) @data = defaults @data = @data.merge(config.select { |key, _| config_keys.include?(key) }) if config @config_path = nil end def load_file_config(path) @config_path = path begin # This lets us get the actual config values without needing to # know the service name parsed_hocon = Hocon.load(path)[service_name] rescue Hocon::ConfigError => e raise "Hocon data in '#{path}' failed to load.\n Error: '#{e.message}'" rescue Errno::EACCES raise "Your user doesn't have permission to read #{path}" end raise "Could not find service config at #{path}" if parsed_hocon.nil? parsed_hocon = parsed_hocon.select { |key, _| config_keys.include?(key) } @data = @data.merge(parsed_hocon) end def load_env_config raise "load_env_config should be defined in the service class" end def natural?(num) num.is_a?(Integer) && num.positive? end def validate required_keys.each do |k| # Handled nested config if k.is_a?(Array) next unless @data.dig(*k).nil? else next unless @data[k].nil? end raise Bolt::ValidationError, "You must configure #{k} in #{@config_path}" end unless natural?(@data['port']) raise Bolt::ValidationError, "Configured 'port' must be a valid integer greater than 0" end ssl_keys.each do |sk| unless File.file?(@data[sk]) && File.readable?(@data[sk]) raise Bolt::ValidationError, "Configured #{sk} must be a valid filepath" end end unless @data['ssl-cipher-suites'].is_a?(Array) raise Bolt::ValidationError, "Configured 'ssl-cipher-suites' must be an array of cipher suite names" end unless @data['allowlist'].nil? || @data['allowlist'].is_a?(Array) raise Bolt::ValidationError, "Configured 'allowlist' must be an array of names" end end def [](key) @data[key] end end end
29.711712
108
0.578836
f83da1277466e5b5760d00cfb4c26107fc647bb9
285
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA1990e do let(:instance) { FactoryBot.build(:va1990e) } it_should_behave_like 'saved_claim' validate_inclusion(:form_id, '22-1990E') end
23.75
56
0.796491
ab3de2178a8ff687437a16c59f39ef3160487eb9
3,329
require 'active_support' require 'active_support/testing/autorun' require 'platform_agent' class BasecampAgent < PlatformAgent def ios_app? match? /BC3 iOS/ end def android_app? match? /BC3 Android/ end def mac_app? match?(/Electron/) && match?(/basecamp3/) && match?(/Macintosh/) end def windows_app? match?(/Electron/) && match?(/basecamp3/) && match?(/Windows/) end end class PlatformAgentTest < ActiveSupport::TestCase WINDOWS_PHONE = 'Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 520) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537' CHROME_DESKTOP = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' CHROME_ANDROID = 'Mozilla/5.0 (Linux; Android 4.4; Nexus 5 Build/_BuildID_) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36' SAFARI_IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B410 Safari/600.1.4' SAFARI_IPAD = 'Mozilla/5.0 (iPad; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B410 Safari/600.1.4' BASECAMP_MAC = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) basecamp3/1.0.2 Chrome/47.0.2526.110 Electron/0.36.7 Safari/537.36' BASECAMP_WINDOWS = 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) basecamp3/1.0.2 Chrome/49.0.2623.75 Electron/0.36.7 Safari/537.36' BASECAMP_IPAD = 'BC3 iOS/3.0.1 (build 13; iPad Air 2); iOS 9.3' BASECAMP_IPHONE = 'BC3 iOS/3.0.1 (build 13; iPhone 6S); iOS 9.3' BASECAMP_ANDROID = 'BC3 Android/3.0.1 (build 13; Galaxy S3); Marshmallow' test "chrome is via web" do assert_equal "web", platform(CHROME_DESKTOP) end test "safari iOS is via phone" do assert_equal "phone", platform(SAFARI_IPHONE) end test "safari iPad is via tablet" do assert_equal "tablet", platform(SAFARI_IPAD) end test "basecamp iPhone is via iPhone app" do assert_equal "iPhone app", platform(BASECAMP_IPHONE) end test "basecamp iPad is via iPad app" do assert_equal "iPad app", platform(BASECAMP_IPAD) end test "basecamp Android is via Android app" do assert_equal "Android app", platform(BASECAMP_ANDROID) end test "basecamp Mac is via Mac app" do assert_equal "Mac app", platform(BASECAMP_MAC) end test "basecamp Windows is via Windows app" do assert_equal "Windows app", platform(BASECAMP_WINDOWS) end test "blank user agent is via missing" do assert_equal "missing", platform(nil) end test "other phones are via phone" do assert_equal "phone", platform(WINDOWS_PHONE) end test "non-native app android detection" do assert android_phone?(CHROME_ANDROID), "CHROME_ANDROID should be android phone" assert_not android_phone?(SAFARI_IPHONE), "SAFARI_IPHONE should not be android phone" assert_not android_phone?(BASECAMP_ANDROID), "BC3_ANDROID should not be android phone" end private def platform(agent) BasecampAgent.new(agent).to_s end def android_phone?(agent) BasecampAgent.new(agent).android_phone? end end
36.184783
226
0.717333
61317376931b1714dd00ae0677e63f560e458872
826
Pod::Spec.new do |s| s.name = "TBCacaoIOS" s.version = "0.0.2" s.summary = "Small and simple dependency injection framework for iOS" s.description = <<-DESC TBCacaoIOS is a small and simple dependency injection framework for Objective-C. It is the iOS version of TBCacao for OS X. DESC s.homepage = "https://github.com/qvacua/tbcacao" s.license = { :type => 'Apache License, Version 2.0', :file => 'LICENSE' } s.author = { "Tae Won Ha" => "[email protected]" } s.platform = :ios, '7.0' s.source = { :git => "https://github.com/qvacua/tbcacao.git", :tag => "v0.0.2-3" } s.source_files = 'TBCacao', 'TBCacao/**/*.{h,m}', 'TBCacaoIOS', 'TBCacaoIOS/**/*.{h,m}' s.exclude_files = 'TBCacaoTests' s.requires_arc = true end
39.333333
142
0.585956
abaf3c1cda7256d6c903355a5af96833204c8c81
172
class CreateUsers < ActiveRecord::Migration[5.1] def change create_table :users do |t| t.string :name t.string :uid t.timestamps end end end
15.636364
48
0.633721
917fadbd7e095452e9a00c68096e81d580487613
1,285
# -*- encoding: utf-8 -*- # stub: jekyll-theme-dinky 0.1.0 ruby lib Gem::Specification.new do |s| s.name = "jekyll-theme-dinky".freeze s.version = "0.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Diana Mounter".freeze, "GitHub, Inc.".freeze] s.date = "2017-08-14" s.email = ["[email protected]".freeze] s.homepage = "https://github.com/pages-themes/dinky".freeze s.licenses = ["CC0-1.0".freeze] s.rubygems_version = "2.6.14.1".freeze s.summary = "Dinky is a Jekyll theme for GitHub Pages".freeze s.installed_by_version = "2.6.14.1" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<jekyll>.freeze, ["~> 3.5"]) s.add_runtime_dependency(%q<jekyll-seo-tag>.freeze, ["~> 2.0"]) else s.add_dependency(%q<jekyll>.freeze, ["~> 3.5"]) s.add_dependency(%q<jekyll-seo-tag>.freeze, ["~> 2.0"]) end else s.add_dependency(%q<jekyll>.freeze, ["~> 3.5"]) s.add_dependency(%q<jekyll-seo-tag>.freeze, ["~> 2.0"]) end end
36.714286
112
0.661479
6a9dbc1ec36b20ae78efbaf5063988530aaafab2
5,132
# frozen_string_literal: true require 'psych/helper' module Psych module Visitors class TestYAMLTree < TestCase class TestDelegatorClass < Delegator def initialize(obj); super; @obj = obj; end def __setobj__(obj); @obj = obj; end def __getobj__; @obj if defined?(@obj); end end class TestSimpleDelegatorClass < SimpleDelegator end def setup super @v = Visitors::YAMLTree.create end def test_tree_can_be_called_twice @v.start @v << Object.new t = @v.tree assert_equal t, @v.tree end def test_yaml_tree_can_take_an_emitter io = StringIO.new e = Psych::Emitter.new io v = Visitors::YAMLTree.create({}, e) v.start v << "hello world" v.finish assert_match "hello world", io.string end def test_binary_formatting gif = "GIF89a\f\x00\f\x00\x84\x00\x00\xFF\xFF\xF7\xF5\xF5\xEE\xE9\xE9\xE5fff\x00\x00\x00\xE7\xE7\xE7^^^\xF3\xF3\xED\x8E\x8E\x8E\xE0\xE0\xE0\x9F\x9F\x9F\x93\x93\x93\xA7\xA7\xA7\x9E\x9E\x9Eiiiccc\xA3\xA3\xA3\x84\x84\x84\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9!\xFE\x0EMade with GIMP\x00,\x00\x00\x00\x00\f\x00\f\x00\x00\x05, \x8E\x810\x9E\xE3@\x14\xE8i\x10\xC4\xD1\x8A\b\x1C\xCF\x80M$z\xEF\xFF0\x85p\xB8\xB01f\r\e\xCE\x01\xC3\x01\x1E\x10' \x82\n\x01\x00;".b @v << gif scalar = @v.tree.children.first.children.first assert_equal Psych::Nodes::Scalar::LITERAL, scalar.style end def test_object_has_no_class yaml = Psych.dump(Object.new) assert(Psych.dump(Object.new) !~ /Object/, yaml) end def test_struct_const foo = Struct.new("Foo", :bar) assert_cycle foo.new('bar') Struct.instance_eval { remove_const(:Foo) } end A = Struct.new(:foo) def test_struct assert_cycle A.new('bar') end def test_struct_anon s = Struct.new(:foo).new('bar') obj = Psych.unsafe_load(Psych.dump(s)) assert_equal s.foo, obj.foo end def test_override_method s = Struct.new(:method).new('override') obj = Psych.unsafe_load(Psych.dump(s)) assert_equal s.method, obj.method end def test_exception ex = Exception.new 'foo' loaded = Psych.unsafe_load(Psych.dump(ex)) assert_equal ex.message, loaded.message assert_equal ex.class, loaded.class end def test_regexp assert_cycle(/foo/) assert_cycle(/foo/i) assert_cycle(/foo/mx) end def test_time t = Time.now assert_equal t, Psych.unsafe_load(Psych.dump(t)) end def test_date date = Date.strptime('2002-12-14', '%Y-%m-%d') assert_cycle date end def test_rational assert_cycle Rational(1,2) end def test_complex assert_cycle Complex(1,2) end def test_scalar assert_cycle 'foo' assert_cycle ':foo' assert_cycle '' assert_cycle ':' end def test_boolean assert_cycle true assert_cycle 'true' assert_cycle false assert_cycle 'false' end def test_range_inclusive assert_cycle 1..2 end def test_range_exclusive assert_cycle 1...2 end def test_anon_class assert_raise(TypeError) do @v.accept Class.new end assert_raise(TypeError) do Psych.dump(Class.new) end end def test_hash assert_cycle('a' => 'b') end def test_list assert_cycle(%w{ a b }) assert_cycle([1, 2.2]) end def test_symbol assert_cycle :foo end def test_int assert_cycle 1 assert_cycle(-1) assert_cycle '1' assert_cycle '-1' end def test_float assert_cycle 1.2 assert_cycle '1.2' assert Psych.load(Psych.dump(0.0 / 0.0)).nan? assert_equal 1, Psych.load(Psych.dump(1 / 0.0)).infinite? assert_equal(-1, Psych.load(Psych.dump(-1 / 0.0)).infinite?) end def test_string assert_match(/'017'/, Psych.dump({'a' => '017'})) assert_match(/'019'/, Psych.dump({'a' => '019'})) assert_match(/'01818'/, Psych.dump({'a' => '01818'})) end # http://yaml.org/type/null.html def test_nil assert_cycle nil assert_nil Psych.load('null') assert_nil Psych.load('Null') assert_nil Psych.load('NULL') assert_nil Psych.load('~') assert_equal({'foo' => nil}, Psych.load('foo: ')) assert_cycle 'null' assert_cycle 'nUll' assert_cycle '~' end def test_delegator assert_cycle(TestDelegatorClass.new([1, 2, 3])) end def test_simple_delegator assert_cycle(TestSimpleDelegatorClass.new([1, 2, 3])) end end end end
25.919192
592
0.589049
f80731ccee515a3d0840ba91d52cd687a66aa75f
324
module Rasti module Web class ViewContext attr_reader :request, :response def initialize(request, response) @request = request @response = response end def render(template, locals={}, &block) Template.render template, self, locals, &block end end end end
18
54
0.617284
bb913d8a0ee195fbc7c166c6a57010d75af8c4dc
835
cask "macpass" do version "0.7.12" sha256 "acde7f51fd0b6529553e1e4ad4a7cbc137096bd355987bb5f4fb869f578f33be" # github.com/MacPass/MacPass/ was verified as official when first introduced to the cask url "https://github.com/MacPass/MacPass/releases/download/#{version}/MacPass-#{version}.zip" appcast "https://github.com/MacPass/MacPass/releases.atom" name "MacPass" homepage "https://macpass.github.io/" auto_updates true depends_on macos: ">= :yosemite" app "MacPass.app" zap delete: [ "~/Library/Application Support/MacPass", "~/Library/Caches/com.hicknhacksoftware.MacPass", "~/Library/Cookies/com.hicknhacksoftware.MacPass.binarycookies", "~/Library/Preferences/com.hicknhacksoftware.MacPass.plist", "~/Library/Saved Application State/com.hicknhacksoftware.MacPass.savedState", ] end
34.791667
94
0.752096
26dd91944fbe8afd8cafb75f08164c569283e93b
253
# frozen_string_literal: true class AlterReplyKeyOnEmailLogs < ActiveRecord::Migration[5.2] def up change_column :email_logs, :reply_key, 'uuid USING reply_key::uuid' end def down change_column :email_logs, :reply_key, :string end end
21.083333
71
0.750988
621f14c4d069cb3fd7d504471a1842f194c34363
2,023
# frozen_string_literal: true require 'rails_helper' require "#{Rails.root}/spec/shared_contexts/eligibilities/magi_medicaid_application_data.rb" RSpec.describe ::MitcService::CallMagiInTheCloud do include Dry::Monads[:result, :do] include_context 'setup magi_medicaid application with two applicants' let(:mitc_request_payload) do mm_app = ::AcaEntities::MagiMedicaid::Operations::InitializeApplication.new.call(magi_medicaid_application).success ::AcaEntities::MagiMedicaid::Operations::Mitc::GenerateRequestPayload.new.call(mm_app).success end let(:event) { Success(double) } let(:obj) {MitcService::CallMagiInTheCloud.new} context 'with valid response from MitC service' do before do allow(MitcService::CallMagiInTheCloud).to receive(:new).and_return(obj) allow(obj).to receive(:build_event).and_return(event) allow(event.success).to receive(:publish).and_return(true) @result = subject.call(mitc_request_payload) end it 'should return success with valid mitc response' do expect(@result).to be_success end it 'should return success with a message' do expect(@result.success).to eq("Successfully sent request payload to mitc") end end # context 'with bad response from MitC service' do # let(:connection_params) do # { # protocol: :http, # publish_operation_name: '/determinations/eval' # } # end # let(:connection) { # manager = EventSource::ConnectionManager.instance # manager.find_connection(connection_params) # } # before do # connection.disconnect # @result = subject.call(mitc_request_payload) # end # it 'should return failure' do # expect(@result).to be_failure # end # it 'should return failure with a message' do # msg = "Error getting a response from MitC for magi_medicaid_application with hbx_id: #{magi_medicaid_application[:hbx_id]}" # expect(@result.failure).to eq(msg) # end # end end
32.111111
131
0.705388
217d55b5e861a48fa72766d3200c9cfd796a77f0
1,131
require 'faraday' module Smsc # Custom error class for rescuing from all Smsc errors class Error < StandardError; end # Main class for client errors class ClientError < Error; end # Raised when Smsc return error with status code 1, 7 class BadRequest < ClientError; end # Raised when Smsc return error with status code 2 class Unauthorized < ClientError; end # Raised when Smsc return error with status code 4, 9 class TooManyRequests < ClientError; end # Raised when Smsc return error with status code 3 class PaymentRequired < ClientError; end # Raised when Smsc return error with status code 6 class Forbidden < ClientError; end # Main class for server errors class ServerError < Error; end # Raised when Smsc returns the HTTP status code 500 class InternalServerError < ServerError; end # Raised when Smsc returns the HTTP status code 502 class BadGateway < ServerError; end # Raised when Smsc returns the HTTP status code 503 class ServiceUnavailable < ServerError; end # Raised when Smsc returns the HTTP status code 504 class GatewayTimeout < ServerError; end end
28.275
56
0.753316
f84a1a8ba346d8800e4c539f9992542604c7db7c
253
module ApplicationHelper # Returns the full title on a per-page basis. def full_title(page_title = '') base_title = "Budget Tracking App" if page_title.empty? base_title else page_title + " | " + base_title end end end
21.083333
47
0.660079
4a64e64c55484564c3af20af11bbec381ee6cd37
952
class SessionsController < ApplicationController def create @user = User.find_by(username: params[:userDetails][:username]) if @user && @user.authenticate(params[:userDetails][:password]) render json: @user, status: 200 else render json: {message: "Unable to login with that username and password combination"}, status: 400 end end def signup @user = User.find_by(username: params[:userDetails][:username]) @user2 = User.find_by(email: params[:userDetails][:email]) if @user || @user2 render json: {message: "That username or email is already in use"}, status: 400 else user = User.new(user_params) if user.save render json: user, status: 200 else render json: {message: "Something went wrong, please try again"}, status: 400 end end end private def user_params params.require(:userDetails).permit(:username, :password, :email) end end
28.848485
104
0.668067
91a2d94dde8b2cde957e0f698fcebc191112f418
80
class TopicSerializer include FastJsonapi::ObjectSerializer attributes end
16
39
0.8375
1a6eea73c5656105e8bdcecf87cb582f63902cee
1,236
# frozen_string_literal: true require 'forwardable' require 'multi_json' require 'rubycent/version' require 'rubycent/client' require 'rubycent/request' require 'rubycent/error' require 'rubycent/errors/network_error' require 'rubycent/errors/request_error' require 'rubycent/errors/response_error' # Rubycent # # Entry point and configuration definition # module Rubycent class << self extend Forwardable def_delegators :api_client, :scheme, :host, :port, :secret, :api_key def_delegators :api_client, :scheme=, :host=, :port=, :secret=, :api_key= def_delegators :api_client, :timeout=, :open_timeout= def_delegators :api_client, :publish, :broadcast, :unsubscribe, :disconnect, :presence, :presence_stats, :history, :channels, :info, :issue_user_token, :issue_channel_token attr_writer :logger, :request_adapter def logger @logger ||= begin Logger.new($stdout).tap { |log| log.level = Logger::INFO } end end def request_adapter @request_adapter ||= Faraday.default_adapter end def api_client @api_client ||= Rubycent::Client.new end end end
23.320755
77
0.661812
21c5df060c38c1e973bfa41e0d90510f7806f239
22,500
require "open3" require "optparse" require "shellwords" module RBS class CLI class LibraryOptions attr_accessor :core_root attr_reader :repos attr_reader :libs attr_reader :dirs def initialize() @core_root = EnvironmentLoader::DEFAULT_CORE_ROOT @repos = [] @libs = [] @dirs = [] end def loader repository = Repository.new(no_stdlib: core_root.nil?) repos.each do |repo| repository.add(Pathname(repo)) end loader = EnvironmentLoader.new(core_root: core_root, repository: repository) dirs.each do |dir| loader.add(path: Pathname(dir)) end libs.each do |lib| name, version = lib.split(/:/, 2) next unless name loader.add(library: name, version: version) end loader end def setup_library_options(opts) opts.on("-r LIBRARY", "Load RBS files of the library") do |lib| libs << lib end opts.on("-I DIR", "Load RBS files from the directory") do |dir| dirs << dir end opts.on("--no-stdlib", "Skip loading standard library signatures") do self.core_root = nil end opts.on("--repo DIR", "Add RBS repository") do |dir| repos << dir end opts end end attr_reader :stdout attr_reader :stderr def initialize(stdout:, stderr:) @stdout = stdout @stderr = stderr end COMMANDS = [:ast, :list, :ancestors, :methods, :method, :validate, :constant, :paths, :prototype, :vendor, :parse, :test] def parse_logging_options(opts) opts.on("--log-level LEVEL", "Specify log level (defaults to `warn`)") do |level| RBS.logger_level = level end opts.on("--log-output OUTPUT", "Specify the file to output log (defaults to stderr)") do |output| io = File.open(output, "a") or raise RBS.logger_output = io end opts end def has_parser? defined?(RubyVM::AbstractSyntaxTree) end def run(args) options = LibraryOptions.new opts = OptionParser.new opts.banner = <<~USAGE Usage: rbs [options...] [command...] Available commands: #{COMMANDS.join(", ")}, version, help. Options: USAGE options.setup_library_options(opts) parse_logging_options(opts) opts.version = RBS::VERSION opts.order!(args) command = args.shift&.to_sym case command when :version stdout.puts opts.ver when *COMMANDS __send__ :"run_#{command}", args, options else stdout.puts opts.help end end def run_ast(args, options) OptionParser.new do |opts| opts.banner = <<EOB Usage: rbs ast [patterns...] Print JSON AST of loaded environment. You can specify patterns to filter declarations with the file names. Examples: $ rbs ast $ rbs ast 'basic_object.rbs' $ rbs -I ./sig ast ./sig $ rbs -I ./sig ast '*/models/*.rbs' EOB end.order!(args) patterns = args.map do |arg| path = Pathname(arg) if path.exist? # Pathname means a directory or a file path else # String means a `fnmatch` pattern arg end end loader = options.loader() env = Environment.from_loader(loader).resolve_type_names decls = env.declarations.select do |decl| loc = decl.location or raise # @type var name: String name = loc.buffer.name patterns.empty? || patterns.any? do |pat| case pat when Pathname Pathname(name).ascend.any? {|p| p == pat } when String name.end_with?(pat) || File.fnmatch(pat, name, File::FNM_EXTGLOB) end end end stdout.print JSON.generate(decls) stdout.flush end def run_list(args, options) # @type var list: Set[:class | :module | :interface] list = Set[] OptionParser.new do |opts| opts.banner = <<EOB Usage: rbs list [options...] List classes, modules, and interfaces. Examples: $ rbs list $ rbs list --class --module --interface Options: EOB opts.on("--class", "List classes") { list << :class } opts.on("--module", "List modules") { list << :module } opts.on("--interface", "List interfaces") { list << :interface } end.order!(args) list.merge(_ = [:class, :module, :interface]) if list.empty? loader = options.loader() env = Environment.from_loader(loader).resolve_type_names if list.include?(:class) || list.include?(:module) env.class_decls.each do |name, entry| case entry when Environment::ModuleEntry if list.include?(:module) stdout.puts "#{name} (module)" end when Environment::ClassEntry if list.include?(:class) stdout.puts "#{name} (class)" end end end end if list.include?(:interface) env.interface_decls.each do |name, entry| stdout.puts "#{name} (interface)" end end end def run_ancestors(args, options) # @type var kind: :instance | :singleton kind = :instance OptionParser.new do |opts| opts.banner = <<EOU Usage: rbs ancestors [options...] [type_name] Show ancestors of the given class or module. Examples: $ rbs ancestors --instance String $ rbs ancestors --singleton Array Options: EOU opts.on("--instance", "Ancestors of instance of the given type_name (default)") { kind = :instance } opts.on("--singleton", "Ancestors of singleton of the given type_name") { kind = :singleton } end.order!(args) loader = options.loader() env = Environment.from_loader(loader).resolve_type_names builder = DefinitionBuilder::AncestorBuilder.new(env: env) type_name = TypeName(args[0]).absolute! if env.class_decls.key?(type_name) ancestors = case kind when :instance builder.instance_ancestors(type_name) when :singleton builder.singleton_ancestors(type_name) else raise end ancestors.ancestors.each do |ancestor| case ancestor when Definition::Ancestor::Singleton stdout.puts "singleton(#{ancestor.name})" when Definition::Ancestor::Instance if ancestor.args.empty? stdout.puts ancestor.name.to_s else stdout.puts "#{ancestor.name}[#{ancestor.args.join(", ")}]" end end end else stdout.puts "Cannot find class: #{type_name}" end end def run_methods(args, options) # @type var kind: :instance | :singleton kind = :instance inherit = true OptionParser.new do |opts| opts.banner = <<EOU Usage: rbs methods [options...] [type_name] Show methods defined in the class or module. Examples: $ rbs methods --instance Kernel $ rbs methods --singleton --no-inherit String Options: EOU opts.on("--instance", "Show instance methods (default)") { kind = :instance } opts.on("--singleton", "Show singleton methods") { kind = :singleton } opts.on("--[no-]inherit", "Show methods defined in super class and mixed modules too") {|v| inherit = v } end.order!(args) unless args.size == 1 stdout.puts "Expected one argument." return end loader = options.loader() env = Environment.from_loader(loader).resolve_type_names builder = DefinitionBuilder.new(env: env) type_name = TypeName(args[0]).absolute! if env.class_decls.key?(type_name) definition = case kind when :instance builder.build_instance(type_name) when :singleton builder.build_singleton(type_name) else raise end definition.methods.keys.sort.each do |name| method = definition.methods[name] if inherit || method.implemented_in == type_name stdout.puts "#{name} (#{method.accessibility})" end end else stdout.puts "Cannot find class: #{type_name}" end end def run_method(args, options) # @type var kind: :instance | :singleton kind = :instance OptionParser.new do |opts| opts.banner = <<EOU Usage: rbs method [options...] [type_name] [method_name] Show the information of the method specified by type_name and method_name. Examples: $ rbs method --instance Kernel puts $ rbs method --singleton String try_convert Options: EOU opts.on("--instance", "Show an instance method (default)") { kind = :instance } opts.on("--singleton", "Show a singleton method") { kind = :singleton } end.order!(args) unless args.size == 2 stdout.puts "Expected two arguments, but given #{args.size}." return end loader = options.loader() env = Environment.from_loader(loader).resolve_type_names builder = DefinitionBuilder.new(env: env) type_name = TypeName(args[0]).absolute! method_name = args[1].to_sym unless env.class_decls.key?(type_name) stdout.puts "Cannot find class: #{type_name}" return end definition = case kind when :instance builder.build_instance(type_name) when :singleton builder.build_singleton(type_name) else raise end method = definition.methods[method_name] unless method stdout.puts "Cannot find method: #{method_name}" return end stdout.puts "#{type_name}#{kind == :instance ? "#" : "."}#{method_name}" stdout.puts " defined_in: #{method.defined_in}" stdout.puts " implementation: #{method.implemented_in}" stdout.puts " accessibility: #{method.accessibility}" stdout.puts " types:" separator = " " for type in method.method_types stdout.puts " #{separator} #{type}" separator = "|" end end def run_validate(args, options) OptionParser.new do |opts| opts.banner = <<EOU Usage: rbs validate Validate RBS files. It ensures the type names in RBS files are present and the type applications have correct arity. Examples: $ rbs validate EOU opts.on("--silent") do require "stringio" @stdout = StringIO.new end end.parse!(args) loader = options.loader() env = Environment.from_loader(loader).resolve_type_names builder = DefinitionBuilder.new(env: env) validator = Validator.new(env: env, resolver: TypeNameResolver.from_env(env)) env.class_decls.each_key do |name| stdout.puts "Validating class/module definition: `#{name}`..." builder.build_instance(name).each_type do |type| validator.validate_type type, context: [Namespace.root] end builder.build_singleton(name).each_type do |type| validator.validate_type type, context: [Namespace.root] end end env.interface_decls.each_key do |name| stdout.puts "Validating interface: `#{name}`..." builder.build_interface(name).each_type do |type| validator.validate_type type, context: [Namespace.root] end end env.constant_decls.each do |name, const| stdout.puts "Validating constant: `#{name}`..." validator.validate_type const.decl.type, context: const.context builder.ensure_namespace!(name.namespace, location: const.decl.location) end env.global_decls.each do |name, global| stdout.puts "Validating global: `#{name}`..." validator.validate_type global.decl.type, context: [Namespace.root] end env.alias_decls.each do |name, decl| stdout.puts "Validating alias: `#{name}`..." builder.expand_alias(name).tap do |type| validator.validate_type type, context: [Namespace.root] end end end def run_constant(args, options) # @type var context: String? context = nil OptionParser.new do |opts| opts.banner = <<EOU Usage: rbs constant [options...] [name] Resolve constant based on RBS. Examples: $ rbs constant ::Object $ rbs constant UTF_8 $ rbs constant --context=::Encoding UTF_8 Options: EOU opts.on("--context CONTEXT", "Name of the module where the constant resolution starts") {|c| context = c } end.order!(args) unless args.size == 1 stdout.puts "Expected one argument." return end loader = options.loader() env = Environment.from_loader(loader).resolve_type_names builder = DefinitionBuilder.new(env: env) table = ConstantTable.new(builder: builder) namespace = context ? Namespace.parse(context).absolute! : Namespace.root stdout.puts "Context: #{namespace}" name = Namespace.parse(args[0]).to_type_name stdout.puts "Constant name: #{name}" constant = table.resolve_constant_reference(name, context: namespace.ascend.to_a) if constant stdout.puts " => #{constant.name}: #{constant.type}" else stdout.puts " => [no constant]" end end def run_paths(args, options) OptionParser.new do |opts| opts.banner = <<EOU Usage: rbs paths Show paths to directories where the RBS files are loaded from. Examples: $ rbs paths $ rbs -r set paths EOU end.parse!(args) loader = options.loader() kind_of = -> (path) { # @type var path: Pathname case when path.file? "file" when path.directory? "dir" when !path.exist? "absent" else "unknown" end } loader.each_dir do |source, dir| case source when :core stdout.puts "#{dir} (#{kind_of[dir]}, core)" when Pathname stdout.puts "#{dir} (#{kind_of[dir]})" when EnvironmentLoader::Library stdout.puts "#{dir} (#{kind_of[dir]}, library, name=#{source.name})" end end end def run_prototype(args, options) format = args.shift case format when "rbi", "rb" decls = run_prototype_file(format, args) when "runtime" require_libs = [] relative_libs = [] merge = false owners_included = [] OptionParser.new do |opts| opts.banner = <<EOU Usage: rbs prototype runtime [options...] [pattern...] Generate RBS prototype based on runtime introspection. It loads Ruby code specified in [options] and generates RBS prototypes for classes matches to [pattern]. Examples: $ rbs prototype runtime String $ rbs prototype runtime --require set Set $ rbs prototype runtime -R lib/rbs RBS::* Options: EOU opts.on("-r", "--require LIB", "Load library using `require`") do |lib| require_libs << lib end opts.on("-R", "--require-relative LIB", "Load library using `require_relative`") do |lib| relative_libs << lib end opts.on("--merge", "Merge generated prototype RBS with existing RBS") do merge = true end opts.on("--method-owner CLASS", "Generate method prototypes if the owner of the method is [CLASS]") do |klass| owners_included << klass end end.parse!(args) loader = options.loader() env = Environment.from_loader(loader).resolve_type_names require_libs.each do |lib| require(lib) end relative_libs.each do |lib| eval("require_relative(lib)", binding, "rbs") end decls = Prototype::Runtime.new(patterns: args, env: env, merge: merge, owners_included: owners_included).decls else stdout.puts <<EOU Usage: rbs prototype [generator...] [args...] Generate prototype of RBS files. Supported generators are rb, rbi, runtime. Examples: $ rbs prototype rb foo.rb $ rbs prototype rbi foo.rbi $ rbs prototype runtime String EOU exit 1 end if decls writer = Writer.new(out: stdout) writer.write decls else exit 1 end end def run_prototype_file(format, args) availability = unless has_parser? "\n** This command does not work on this interpreter (#{RUBY_ENGINE}) **\n" end opts = OptionParser.new opts.banner = <<EOU Usage: rbs prototype #{format} [files...] #{availability} Generate RBS prototype from source code. It parses specified Ruby code and and generates RBS prototypes. It only works on MRI because it parses Ruby code with `RubyVM::AbstractSyntaxTree`. Examples: $ rbs prototype rb lib/foo.rb $ rbs prototype rbi sorbet/rbi/foo.rbi EOU opts.parse!(args) unless has_parser? stdout.puts "Not supported on this interpreter (#{RUBY_ENGINE})." exit 1 end if args.empty? stdout.puts opts return nil end parser = case format when "rbi" Prototype::RBI.new() when "rb" Prototype::RB.new() end args.each do |file| parser.parse Pathname(file).read end parser.decls end def run_vendor(args, options) clean = false vendor_dir = Pathname("vendor/sigs") OptionParser.new do |opts| opts.banner = <<-EOB Usage: rbs vendor [options...] [gems...] Vendor signatures in the project directory. This command ignores the RBS loading global options, `-r` and `-I`. Examples: $ rbs vendor $ rbs vendor --vendor-dir=sig $ rbs vendor --no-stdlib Options: EOB opts.on("--[no-]clean", "Clean vendor directory (default: no)") do |v| clean = v end opts.on("--vendor-dir [DIR]", "Specify the directory for vendored signatures (default: vendor/sigs)") do |path| vendor_dir = Pathname(path) end end.parse!(args) stdout.puts "Vendoring signatures to #{vendor_dir}..." loader = options.loader() args.each do |gem| name, version = gem.split(/:/, 2) next unless name stdout.puts " Loading library: #{name}, version=#{version}..." loader.add(library: name, version: version) end vendorer = Vendorer.new(vendor_dir: vendor_dir, loader: loader) if clean stdout.puts " Deleting #{vendor_dir}..." vendorer.clean! end stdout.puts " Copying RBS files..." vendorer.copy! end def run_parse(args, options) OptionParser.new do |opts| opts.banner = <<-EOB Usage: rbs parse [files...] Parse given RBS files and print syntax errors. Examples: $ rbs parse sig/app/models.rbs sig/app/controllers.rbs EOB end.parse!(args) loader = options.loader() syntax_error = false args.each do |path| path = Pathname(path) loader.each_file(path, skip_hidden: false, immediate: true) do |file_path| Parser.parse_signature(file_path.read) rescue RBS::Parser::SyntaxError => ex loc = ex.error_value.location stdout.puts "#{file_path}:#{loc.start_line}:#{loc.start_column}: parse error on value: (#{ex.token_str})" syntax_error = true rescue RBS::Parser::SemanticsError => ex loc = ex.location stdout.puts "#{file_path}:#{loc.start_line}:#{loc.start_column}: #{ex.original_message}" syntax_error = true end end exit 1 if syntax_error end def test_opt options opts = [] opts.push(*options.repos.map {|dir| "--repo #{Shellwords.escape(dir)}"}) opts.push(*options.dirs.map {|dir| "-I #{Shellwords.escape(dir)}"}) opts.push(*options.libs.map {|lib| "-r#{Shellwords.escape(lib)}"}) opts.empty? ? nil : opts.join(" ") end def run_test(args, options) # @type var unchecked_classes: Array[String] unchecked_classes = [] # @type var targets: Array[String] targets = [] # @type var sample_size: String? sample_size = nil # @type var double_suite: String? double_suite = nil (opts = OptionParser.new do |opts| opts.banner = <<EOB Usage: rbs [rbs options...] test [test options...] COMMAND Examples: $ rbs test rake test $ rbs --log-level=debug test --target SomeModule::* rspec $ rbs test --target SomeModule::* --target AnotherModule::* --target SomeClass rake test Options: EOB opts.on("--target TARGET", "Sets the runtime test target") do |target| targets << target end opts.on("--sample-size SAMPLE_SIZE", "Sets the sample size") do |size| sample_size = size end opts.on("--unchecked-class UNCHECKED_CLASS", "Sets the class that would not be checked") do |unchecked_class| unchecked_classes << unchecked_class end opts.on("--double-suite DOUBLE_SUITE", "Sets the double suite in use (currently supported: rspec | minitest)") do |suite| double_suite = suite end end).order!(args) if args.length.zero? stdout.puts opts.help exit 1 end # @type var env_hash: Hash[String, String?] env_hash = { 'RUBYOPT' => "#{ENV['RUBYOPT']} -rrbs/test/setup", 'RBS_TEST_OPT' => test_opt(options), 'RBS_TEST_LOGLEVEL' => RBS.logger_level, 'RBS_TEST_SAMPLE_SIZE' => sample_size, 'RBS_TEST_DOUBLE_SUITE' => double_suite, 'RBS_TEST_UNCHECKED_CLASSES' => (unchecked_classes.join(',') unless unchecked_classes.empty?), 'RBS_TEST_TARGET' => (targets.join(',') unless targets.empty?) } # @type var out: String # @type var err: String out, err, status = Open3.capture3(env_hash, *args) stdout.print(out) stderr.print(err) status end end end
27.141134
129
0.594622
01bb04b92d7010d5d40423dfcd11f857d5da8425
945
class UsersController < ApplicationController get '/signup' do erb :"/users/signup" end post '/signup' do @user = User.create(:username => params[:username], :email => params[:email], :password => params[:password]) if @user.valid? redirect '/login' else erb :"/users/signup" end end get '/login' do erb :"/users/login" end post '/login' do if params[:username].empty? || params[:password].empty? flash[:notice] = "Please enter Username and Password!" redirect 'login' else login(params[:username], params[:password]) redirect '/categories' end end get "/failure" do erb :"/users/failure" end get '/logout' do logout! redirect "/" end get '/index' do @users = User.all erb :'/users/index' end end
21.477273
117
0.522751
d54ee6aaa91d0de31cecbc2dd925205933611c4f
2,497
require "test_helper" require "fileutils" require "time" context "The file-based backend" do setup do @soup = Soup.new(Soup::Backends::FileBackend.new(@base_path)) end should "parse attributes from lines starting with colon" do write_snip "snip", %{ Here is the content of the snip :name: thing :render_as: Markdown :multi_line_attribute: | stuff things :blah: yes } snip = @soup["snip"] assert_equal "Here is the content\nof the snip", snip.content assert_equal "thing", snip.name end should "write a snip in the simple format" do @soup << {:content => "Here is the content", :name => "dave"} assert_equal %{Here is the content\n\n:name: dave\n}, File.read(path_for("dave")) end should "not require snip attributes to give content" do write_snip "test", "snip content" assert_equal "snip content", @soup["test"].content end should "take updated_at and created_at from file timestamps if not supplied" do @soup << {:name => "snip", :content => "whatever"} time = Time.parse("2010-11-04 14:56") File.utime(time, time, path_for("snip")) end should "take name from filename if not supplied" do write_snip "blahface", "The snip content" assert_equal "blahface", @soup["blahface"].name end should "take updated_at and created_at from file timestamps if not supplied" do @soup << {:name => "snip", :content => "whatever"} time = Time.parse("2010-11-04 14:56") File.utime(time, time, path_for("snip")) snip = @soup["snip"] assert_equal time, snip.updated_at assert_equal time, snip.created_at end should "take created_at from attributes if supplied" do created_at = Time.parse("2010-11-04 14:56") @soup << {:name => "snip", :content => "whatever", :created_at => created_at} snip = @soup["snip"] assert_equal created_at.to_i, snip.created_at.to_i end should "set the extension attribute if one is present" do File.open(File.join(@base_path, "test_snip.snip.markdown"), "w") { |f| f.write "This is the content" } snip = @soup["test_snip"] assert_equal "markdown", snip.extension end should "not ignore directories" do FileUtils.mkdir(File.join(@base_path, "test")) write_snip("test", "content") assert_equal "content", @soup["test"].content end def path_for(name) File.join(@base_path, name + ".snip") end def write_snip(name, content) File.open(path_for(name), "w") { |f| f.write content.strip } end end
28.701149
106
0.674009
91443edefcd86c7d1109c27280af70f355608c28
1,437
# encoding: utf-8 describe ROM::Cassandra::Migrations::Migration do let(:migration) { described_class.new session } let(:session) { double :session, call: nil, freeze: nil } describe "#session" do subject { migration.session } it { is_expected.to eql session } end # describe #session describe "#up" do subject { migration.up } it { is_expected.to be_nil } end # describe #up describe "#down" do subject { migration.down } it { is_expected.to be_nil } end # describe #down describe "#call" do subject { migration.call query } let(:query) { double :query, to_s: :foo } it "is delegated to #session" do expect(session).to receive(:call).with(:foo) subject end end # describe #call describe "#keyspace" do subject { migration.keyspace(:foo) } it "starts building query" do query = subject.create.if_not_exists.to_s expect(query).to eql "CREATE KEYSPACE IF NOT EXISTS foo;" end end # describe #keyspace describe ".inherited" do subject { Class.new described_class } it "hides helpers" do expect(subject.private_instance_methods) .to include(:call, :keyspace, :up, :down) end it "keeps parent class' helpers unchanged" do expect { subject }.not_to change { described_class.new(session).methods } end end # describe .inherited end # describe ROM::Cassandra::Migrations::Migration
23.95
79
0.662491
4a70e6156f389933fc96b378b355ba93fd6cf628
116
class AddAdminToUsers < ActiveRecord::Migration[5.2] def change add_column :users, :admin, :integer end end
19.333333
52
0.732759
26773aedeca72ecbc8eec939d29851f658ea0b3f
1,485
#-- copyright # OpenProject is a project management system. # Copyright (C) 2012-2015 the OpenProject Foundation (OPF) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2013 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See doc/COPYRIGHT.rdoc for more details. #++ ## # A placeholder module which contains OpenProject hooks module OpenProject module Hooks; end end # actual hooks are added with the following require statemens require 'open_project/hooks/view_account_login_auth_provider' require 'open_project/hooks/view_account_login_bottom'
39.078947
91
0.777104
61db57cd9f8bdfb42b6dbdc5c8b554f4f6f1d0f9
127
require 'rails_helper' RSpec.describe MusicUser, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
21.166667
56
0.748031
39d22b449006e476a5584667f28c71a5e7d51c7d
2,968
# This file is copied to spec/ when you run 'rails generate rspec:install' require 'spec_helper' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../config/environment', __dir__) # Prevent database truncation if the environment is production abort("The Rails environment is running in production mode!") if Rails.env.production? require 'rspec/rails' # Add additional requires below this line. Rails is not loaded until this point! require 'database_cleaner/active_record' require 'factory_bot_rails' require 'faker' # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. # # The following line is provided for convenience purposes. It has the downside # of increasing the boot-up time by auto-requiring all files in the support # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. # Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } # Checks for pending migrations and applies them before tests are run. # If you are not using ActiveRecord, you can remove these lines. begin ActiveRecord::Migration.maintain_test_schema! rescue ActiveRecord::PendingMigrationError => e puts e.to_s.strip exit 1 end RSpec.configure do |config| # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # You can uncomment this line to turn off ActiveRecord support entirely. # config.use_active_record = false # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, type: :controller do # # ... # end # # The different available types are documented in the features, such as in # https://relishapp.com/rspec/rspec-rails/docs config.infer_spec_type_from_file_location! # Filter lines from Rails gems in backtraces. config.filter_rails_from_backtrace! # arbitrary gems may also be filtered via: # config.filter_gems_from_backtrace("gem name") end
43.647059
86
0.75438
bb1a3456a5bf737958eac3be430292abba5660e4
1,621
# frozen_string_literal: true require File.dirname(__FILE__) + '/spec_helper' RSpec.describe "YARD::Handlers::Ruby::#{LEGACY_PARSER ? "Legacy::" : ""}VisibilityHandler" do before(:all) { parse_file :visibility_handler_001, __FILE__ } it "is able to set visibility to public" do expect(Registry.at("Testing#pub").visibility).to eq :public expect(Registry.at("Testing#pub2").visibility).to eq :public end it "is able to set visibility to private" do expect(Registry.at("Testing#priv").visibility).to eq :private end it "is able to set visibility to protected" do expect(Registry.at("Testing#prot").visibility).to eq :protected end it "supports parameters and only set visibility on those methods" do expect(Registry.at('Testing#notpriv').visibility).to eq :protected expect(Registry.at('Testing#notpriv2').visibility).to eq :protected expect(Registry.at('Testing#notpriv?').visibility).to eq :protected end it "only accepts strings and symbols" do expect(Registry.at('Testing#name')).to be nil expect(Registry.at('Testing#argument')).to be nil expect(Registry.at('Testing#method_call')).to be nil end it "handles constants passed in as symbols" do expect(Registry.at('Testing#Foo').visibility).to eq :private end it "does not register classes with visibility" do expect(Registry.at('Testing::Bar').visibility).to eq :public expect(Registry.at('Testing::Baz').visibility).to eq :public end it "can decorate a method definition" do expect(Registry.at('Testing#decpriv').visibility).to eq :private end unless LEGACY_PARSER end
36.022222
93
0.726712
f790c50dc317b7b07024411a1d2fcb2b29fc71af
945
require_relative '../bodies/body.rb' require_relative '../bodies/fixture.rb' class Contact attr_reader :obj_1 attr_reader :obj_2 attr_accessor :first #boolean for first contact or not def initialize(obj_1, obj_2) raise ArgumentError.new("Objects passed to contact must be of the same type!") unless (obj_1.class == obj_2.class) if (!(obj_1.is_a? Fixture) && !(obj_1.is_a? Body)) raise ArgumentError.new("Objects passed to contact must be fixtures or bodies!") end @obj_1 = obj_1 @obj_2 = obj_2 @first = true #contact is always first when initially created end #check if a physics object is part of this collision def contains?(obj) if (!(obj.is_a? Fixture) && !(obj.is_a? Body)) raise ArgumentError.new("Only fixtures or bodies can be checked againt a contact!") end (obj.eql? @obj_1) || (obj.eql? @obj_2) end end
35
122
0.646561
331c9c0a42a70016bfc0b4de83dd40151134c2d3
179
# name - string # archive_number - string # archived_at - datetime class ArchivalTableName < ActiveRecord::Base self.table_name = "legacy" archival_record end
16.272727
44
0.698324
1d23b3f7815e1339fd60922365d6ee128b8d0a00
8,815
# encoding: utf-8 require_relative '../spec_helper' include Warden::Test::Helpers include Carto::Factories::Visualizations def login(user) login_as(user, scope: user.username) host! "#{user.username}.localhost.lan" end def follow_redirects(limit = 10) while response.redirect? && (limit -= 1) > 0 follow_redirect! end end describe "UserState" do before(:all) do @feature_flag = FactoryGirl.create(:feature_flag, name: 'no_free_tier', restricted: false) @locked_user = FactoryGirl.create(:locked_user) @map, @table, @table_visualization, @visualization = create_full_builder_vis(@locked_user) @visualization.create_mapcap! @non_locked_user = FactoryGirl.create(:valid_user) @dashboard_endpoints = ['/dashboard', '/dashboard/tables', '/dashboard/datasets', '/dashboard/visualizations', '/dashboard/maps'].freeze @public_user_endpoints = ['/me'].freeze @user_endpoints = ['/account', '/profile'].freeze @tables_endpoints = ["/tables/#{@table.id}", "/tables/#{@table.id}/public", "/tables/#{@table.id}/embed_map"].freeze @viz_endpoints = ["/viz/#{@visualization.id}/public", "/viz/#{@visualization.id}/embed_map", "/viz/#{@visualization.id}/public_map", "/builder/#{@visualization.id}", "/builder/#{@visualization.id}/embed"].freeze @public_api_endpoints = ["/api/v1/viz", "/api/v1/viz/#{@visualization.id}", "/api/v2/viz/#{@visualization.id}/viz", "/api/v3/me", "/api/v3/viz/#{@visualization.id}/viz"].freeze @private_api_endpoints = ["/api/v1/tables/#{@table.id}", "/api/v1/tables/#{@table.id}/columns", "/api/v1/imports", "/api/v1/users/#{@locked_user.id}/layers", "/api/v1/synchronizations", "/api/v1/geocodings", "/api/v1/users/#{@locked_user.id}"] @headers = {} @api_headers = { 'CONTENT_TYPE' => 'application/json', :format => "json" } end after(:all) do @locked_user.destroy @non_locked_user.destroy end describe '#locked user' do it 'owner accessing their resources' do login(@locked_user) @dashboard_endpoints.each do |endpoint| get endpoint, {}, @headers response.status.should == 302 follow_redirect! request.path.should == '/lockout' response.status.should == 200 end @user_endpoints.each do |endpoint| get endpoint, {}, @headers response.status.should == 302 follow_redirect! request.path.should == '/lockout' response.status.should == 200 end @public_user_endpoints.each do |endpoint| get endpoint, {}, @headers response.status.should == 302 follow_redirect! request.path.should == '/lockout' response.status.should == 200 end @tables_endpoints.each do |endpoint| get endpoint, {}, @headers response.status.should == 302 follow_redirect! request.path.should == '/lockout' response.status.should == 200 end @viz_endpoints.each do |endpoint| get endpoint, {}, @headers response.status.should == 302 follow_redirect! request.path.should == '/lockout' response.status.should == 200 end @private_api_endpoints.each do |endpoint| get "#{endpoint}?api_key=#{@locked_user.api_key}", {}, @api_headers request.path == endpoint response.status.should == 404 end @public_api_endpoints.each do |endpoint| get endpoint, {}, @api_headers request.path == endpoint response.status.should == 404 end end it 'user accessing a locked user resources' do login(@non_locked_user) host! "#{@locked_user.username}.localhost.lan" @user_endpoints.each do |endpoint| get endpoint, {}, @headers response.status.should == 404 end @public_user_endpoints.each do |endpoint| get endpoint, {}, @headers response.status.should == 404 end @tables_endpoints.each do |endpoint| get endpoint, {}, @headers response.status.should == 404 end @viz_endpoints.each do |endpoint| get endpoint, {}, @headers response.status.should == 404 end @public_api_endpoints.each do |endpoint| get endpoint, {}, @api_headers request.path == endpoint response.status.should == 404 end end it 'non-logged user accessing a locked user resources' do host! "#{@locked_user.username}.localhost.lan" @public_user_endpoints.each do |endpoint| get endpoint, {}, @headers response.status.should == 404 end @tables_endpoints.each do |endpoint| get endpoint, {}, @headers response.status.should == 404 end @viz_endpoints.each do |endpoint| get endpoint, {}, @headers response.status.should == 404 end @public_api_endpoints.each do |endpoint| get endpoint, {}, @api_headers request.path == endpoint response.status.should == 404 end end end describe '#non locked user' do before(:all) do @locked_user.state = 'active' @locked_user.save end after(:all) do @locked_user.state = 'locked' @locked_user.save end it 'owner accessing their resources' do login(@locked_user) host! "#{@locked_user.username}.localhost.lan" @dashboard_endpoints.each do |endpoint| get endpoint, {}, @headers follow_redirects request.path.should_not == '/lockout' response.status.should == 200 end @user_endpoints.each do |endpoint| get endpoint, {}, @headers follow_redirects request.path.should_not == '/lockout' response.status.should == 200 end @public_user_endpoints.each do |endpoint| get endpoint, {}, @headers follow_redirects request.path.should_not == '/lockout' response.status.should == 200 end @tables_endpoints.each do |endpoint| get endpoint, {}, @headers follow_redirects request.path.should_not == '/lockout' response.status.should == 200 end @viz_endpoints.each do |endpoint| get endpoint, {}, @headers follow_redirects request.path.should_not == '/lockout' response.status.should == 200 end @private_api_endpoints.each do |endpoint| get "#{endpoint}?api_key=#{@locked_user.api_key}", {}, @api_headers request.path == endpoint response.status.should == 200 end @public_api_endpoints.each do |endpoint| get endpoint, {}, @api_headers request.path == endpoint response.status.should == 200 end end it 'non locked user accessing a locked user resources' do login(@non_locked_user) @user_endpoints.each do |endpoint| host! "#{@locked_user.username}.localhost.lan" get endpoint, {}, @headers follow_redirects response.status.should == 200 end @public_user_endpoints.each do |endpoint| host! "#{@locked_user.username}.localhost.lan" get endpoint, {}, @headers follow_redirects response.status.should == 200 end @tables_endpoints.each do |endpoint| host! "#{@locked_user.username}.localhost.lan" get endpoint, {}, @headers follow_redirects response.status.should == 200 end @viz_endpoints.each do |endpoint| host! "#{@locked_user.username}.localhost.lan" get endpoint, {}, @headers follow_redirects response.status.should == 200 end @public_api_endpoints.each do |endpoint| get endpoint, {}, @api_headers request.path == endpoint response.status.should == 200 end end it 'non-logged user accessing a locked user resources' do host! "#{@locked_user.username}.localhost.lan" @public_user_endpoints.each do |endpoint| get endpoint, {}, @headers follow_redirects response.status.should == 200 end @tables_endpoints.each do |endpoint| get endpoint, {}, @headers follow_redirects response.status.should == 200 end @viz_endpoints.each do |endpoint| get endpoint, {}, @headers follow_redirects response.status.should == 200 end @public_api_endpoints.each do |endpoint| get endpoint, {}, @api_headers request.path == endpoint response.status.should == 200 end end end end
34.433594
114
0.607714
26f48ef585146185ec9a016b6e5105805d98647e
3,675
require "language/perl" class Kpcli < Formula include Language::Perl::Shebang desc "Command-line interface to KeePass database files" homepage "https://kpcli.sourceforge.io/" url "https://downloads.sourceforge.net/project/kpcli/kpcli-3.4.pl" sha256 "403e5d73cc4685722a5e4207c5fcbdad8e30475434cfba151c095e13a2658668" bottle do cellar :any sha256 "efd9da40a0733bc1da58ab3ba12149743cc4bf034b1e91bb4cc00d09e8532552" => :catalina sha256 "416401e644f180dc05d3da14486c1c281e860752d5e525888bfaa2ea34d83e5e" => :mojave sha256 "40f4fe9bf01d09f432bb55c4d1f4c52d3a8466e2b62b0793b65c20ef4bd3ee4d" => :high_sierra end depends_on "readline" uses_from_macos "perl" resource "File::KeePass" do url "https://cpan.metacpan.org/authors/id/R/RH/RHANDOM/File-KeePass-2.03.tar.gz" sha256 "c30c688027a52ff4f58cd69d6d8ef35472a7cf106d4ce94eb73a796ba7c7ffa7" end resource "Crypt::Rijndael" do url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/Crypt-Rijndael-1.14.tar.gz" sha256 "6451c3dffe8703523be2bb08d1adca97e77df2a8a4dd46944d18a99330b7850e" end resource "Sort::Naturally" do url "https://cpan.metacpan.org/authors/id/B/BI/BINGOS/Sort-Naturally-1.03.tar.gz" sha256 "eaab1c5c87575a7826089304ab1f8ffa7f18e6cd8b3937623e998e865ec1e746" end resource "Term::ShellUI" do url "https://cpan.metacpan.org/authors/id/B/BR/BRONSON/Term-ShellUI-0.92.tar.gz" sha256 "3279c01c76227335eeff09032a40f4b02b285151b3576c04cacd15be05942bdb" end resource "Term::Readline::Gnu" do url "https://cpan.metacpan.org/authors/id/H/HA/HAYASHI/Term-ReadLine-Gnu-1.36.tar.gz" sha256 "9a08f7a4013c9b865541c10dbba1210779eb9128b961250b746d26702bab6925" end resource "Data::Password" do url "https://cpan.metacpan.org/authors/id/R/RA/RAZINF/Data-Password-1.12.tar.gz" sha256 "830cde81741ff384385412e16faba55745a54a7cc019dd23d7ed4f05d551a961" end resource "Clipboard" do url "https://cpan.metacpan.org/authors/id/S/SH/SHLOMIF/Clipboard-0.22.tar.gz" sha256 "9fdb4dfc2e9bc2f3990b5b71649094dfe83aa12172c5a1809cf7e8b3be295ca7" end resource "Mac::Pasteboard" do url "https://cpan.metacpan.org/authors/id/W/WY/WYANT/Mac-Pasteboard-0.011.tar.gz" sha256 "bd8c4510b1e805c43e4b55155c0beaf002b649fe30b6a7841ff05e7399ba02a9" end resource "Capture::Tiny" do url "https://cpan.metacpan.org/authors/id/D/DA/DAGOLDEN/Capture-Tiny-0.48.tar.gz" sha256 "6c23113e87bad393308c90a207013e505f659274736638d8c79bac9c67cc3e19" end def install ENV.prepend_create_path "PERL5LIB", libexec/"lib/perl5" ENV.prepend_path "PERL5LIB", libexec/"lib" resources = [ "File::KeePass", "Crypt::Rijndael", "Sort::Naturally", "Term::ShellUI", "Data::Password", "Clipboard", "Mac::Pasteboard", "Capture::Tiny", ] resources.each do |r| resource(r).stage do system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}" system "make", "install" end end resource("Term::Readline::Gnu").stage do # Prevent the Makefile to try and build universal binaries ENV.refurbish_args system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}", "--includedir=#{Formula["readline"].opt_include}", "--libdir=#{Formula["readline"].opt_lib}" system "make", "install" end rewrite_shebang detected_perl_shebang, "kpcli-#{version}.pl" libexec.install "kpcli-#{version}.pl" => "kpcli" chmod 0755, libexec/"kpcli" (bin/"kpcli").write_env_script("#{libexec}/kpcli", :PERL5LIB => ENV["PERL5LIB"]) end test do system bin/"kpcli", "--help" end end
33.715596
93
0.722721
ab9a0c778d239b118a72229dfeb3c26cef74c6ab
6,678
# frozen_string_literal: true require "rails_helper" RSpec.describe DelegatesController, type: :controller do let(:delegate) { FactoryBot.create :staff_profile } let(:valid_attributes) { { delegate_id: delegate.id } } let(:invalid_attributes) { { delegate_id: "blah" } } let(:valid_session) { {} } let(:user) { FactoryBot.create :user } let(:staff_profile) { FactoryBot.create :staff_profile, user: user } before do staff_profile sign_in user end describe "GET #index" do it "returns a success response" do sally_smith = FactoryBot.create :staff_profile, given_name: "Sally", surname: "Smith" jane_doe = FactoryBot.create :staff_profile, given_name: "Jane", surname: "Doe" delegate = FactoryBot.create :delegate, delegator: staff_profile, delegate: sally_smith delegate2 = FactoryBot.create :delegate, delegator: staff_profile, delegate: jane_doe FactoryBot.create :delegate get :index, params: {}, session: valid_session expect(response).to be_successful expect(assigns[:delegates]).to eq [delegate2, delegate] end end describe "GET #assume" do it "returns a success response" do delegate = FactoryBot.create :delegate, delegate: staff_profile get :assume, params: { id: delegate.to_param }, session: valid_session expect(response).to redirect_to(my_requests_path) expect(session["approvals_delegate"]).to eq delegate.id.to_s expect(flash[:success]).to eq "You are now acting on behalf of #{delegate.delegator}" end context "invalid delegate id" do it "returns a redirect response" do get :assume, params: { id: 1234 }, session: valid_session expect(response).to redirect_to(my_requests_path) expect(session["approvals_delegate"]).to be_blank expect(flash[:error]).to eq "Invalid delegation attempt!" end end context "assume another's delegate " do it "returns a redirect response" do delegate = FactoryBot.create :delegate get :assume, params: { id: delegate.to_param }, session: valid_session expect(response).to redirect_to(my_requests_path) expect(response.headers["APPROVALS-DELEGATE"]).not_to eq delegate.to_s expect(flash[:error]).to eq "Invalid delegation attempt!" end end context "when you are being delegate" do it "does not allow you to assume a delegation" do delegate = FactoryBot.create :delegate, delegate: staff_profile delegate2 = FactoryBot.create :delegate, delegate: delegate.delegator valid_session["approvals_delegate"] = delegate.id.to_s get :assume, params: { id: delegate2.to_param }, session: valid_session expect(response).to redirect_to(my_requests_path) expect(response.headers["APPROVALS-DELEGATE"]).not_to eq delegate.to_s expect(flash[:error]).to eq "You can not modify delegations as a delegate" end end end describe "GET #cancel_delegation" do it "returns a success response" do delegate = FactoryBot.create :delegate, delegate: staff_profile valid_session["approvals_delegate"] = delegate.id.to_s get :cancel, session: valid_session expect(response).to redirect_to(my_requests_path) expect(session["approvals_delegate"]).to be_blank expect(flash[:success]).to eq "You are now acting on your own behalf" end end describe "GET #to_assume" do it "returns a success response" do sally_smith = FactoryBot.create :staff_profile, given_name: "Sally", surname: "Smith" jane_doe = FactoryBot.create :staff_profile, given_name: "Jane", surname: "Doe" delegate = FactoryBot.create :delegate, delegate: staff_profile, delegator: sally_smith delegate2 = FactoryBot.create :delegate, delegate: staff_profile, delegator: jane_doe FactoryBot.create :delegate get :to_assume, params: {}, session: valid_session expect(response).to be_successful expect(assigns[:delegators]).to eq [delegate2, delegate] end end describe "POST #create" do context "with valid params" do it "creates a new Delegate" do expect do post :create, params: { delegate: valid_attributes }, session: valid_session end.to change(Delegate, :count).by(1) end it "redirects to the delegates list" do post :create, params: { delegate: valid_attributes }, session: valid_session expect(response).to redirect_to(delegates_url) end end context "with invalid params" do it "renders the new form" do post :create, params: { delegate: invalid_attributes }, session: valid_session expect(response).to be_successful end end context "when you are being delegate" do it "does not allow you to create a delegation" do delegate = FactoryBot.create :delegate, delegate: staff_profile valid_session["approvals_delegate"] = delegate.id.to_s post :create, params: { delegate: valid_attributes }, session: valid_session expect(response).to redirect_to(my_requests_path) expect(response.headers["APPROVALS-DELEGATE"]).not_to eq delegate.to_s expect(flash[:error]).to eq "You can not modify delegations as a delegate" end end end describe "DELETE #destroy" do it "destroys the requested delegate" do delegate = FactoryBot.create :delegate, delegator: staff_profile expect do delete :destroy, params: { id: delegate.to_param }, session: valid_session end.to change(Delegate, :count).by(-1) end it "redirects to the delegates list" do delegate = FactoryBot.create :delegate, delegator: staff_profile delete :destroy, params: { id: delegate.to_param }, session: valid_session expect(response).to redirect_to(delegates_url) end it "errors on bad delegate" do delete :destroy, params: { id: 123 }, session: valid_session expect(response).to redirect_to(delegates_url) end it "does not allow you to assume a delegation" do delegate = FactoryBot.create :delegate, delegate: staff_profile delegate2 = FactoryBot.create :delegate, delegate: delegate.delegator valid_session["approvals_delegate"] = delegate.id.to_s expect do delete :destroy, params: { id: delegate2.to_param }, session: valid_session end.to change(Delegate, :count).by(0) expect(response).to redirect_to(my_requests_path) expect(response.headers["APPROVALS-DELEGATE"]).not_to eq delegate.to_s expect(flash[:error]).to eq "You can not modify delegations as a delegate" end end end
40.969325
93
0.697215
08254ce1f20aa69854917a6a224c73a7dcd7e3fa
3,510
#! /usr/bin/env ruby require 'spec_helper' require 'yaml' require 'puppet/provider/vcenter' require 'rbvmomi' provider_path = Pathname.new(__FILE__).parent.parent.parent.parent describe Puppet::Type.type(:esx_mem).provider(:esx_mem) do integration_yml = File.join(provider_path, '/fixtures/integration/integration.yml') esx_mem_yml = YAML.load_file(integration_yml) esxconfiguremem = esx_mem_yml['esxconfiguremem'] transport_yml = File.join(provider_path, '/fixtures/integration/transport.yml') transport_yaml = YAML.load_file(transport_yml) transport_node = transport_yaml['transport'] let(:esx_configure_mem) do @catalog = Puppet::Resource::Catalog.new transport = Puppet::Type.type(:transport).new({ :name => transport_node['name'], :username => transport_node['username'], :password => transport_node['password'], :server => transport_node['server'], :options => transport_node['options'], }) @catalog.add_resource(transport) Puppet::Type.type(:esx_mem).new( :name => esxconfiguremem['host'], :configure_mem => esxconfiguremem['configure_mem'], :storage_groupip => esxconfiguremem['storage_groupip'], :vnics_ipaddress => esxconfiguremem['vnics_ipaddress'], :iscsi_vswitch => esxconfiguremem['iscsi_vswitch'], :iscsi_netmask => esxconfiguremem['iscsi_netmask'], :vnics => esxconfiguremem['vnics'], :iscsi_chapuser => esxconfiguremem['iscsi_chapuser'], :iscsi_chapsecret => esxconfiguremem['iscsi_chapsecret'], :disable_hw_iscsi => esxconfiguremem['disable_hw_iscsi'], :host_username => esxconfiguremem['host_username'], :host_password => esxconfiguremem['host_password'], :script_executable_path => esxconfiguremem['script_executable_path'], :setup_script_filepath => esxconfiguremem['setup_script_filepath'], :transport => transport, :catalog => @catalog ) end esxinstallmem = esx_mem_yml['esxinstallmem'] let :esx_install_mem do @catalog = Puppet::Resource::Catalog.new transport = Puppet::Type.type(:transport).new({ :name => transport_node['name'], :username => transport_node['username'], :password => transport_node['password'], :server => transport_node['server'], :options => transport_node['options'], }) @catalog.add_resource(transport) Puppet::Type.type(:esx_mem).new( :name => esxinstallmem['host'], :install_mem => esxinstallmem['install_mem'], :host_username => esxinstallmem['host_username'], :host_password => esxinstallmem['host_password'], :script_executable_path => esxinstallmem['script_executable_path'], :setup_script_filepath => esxinstallmem['setup_script_filepath'], :transport => transport, :catalog => @catalog ) end describe "when configuring mem on esx host" do it "should be able to configure mem on esx host" do esx_configure_mem.provider.configure_mem='test' end end describe "when installing mem on esx host" do it "should be able to install mem on esx host" do if (esx_install_mem.provider.install_mem == 'false') esx_install_mem.provider.install_mem='test' end end end end
39.438202
87
0.645014
214c985d58755496e18b63cffb795b2e8c00f85a
319
###################### # Topology template file ########## ['topology.properties'].each do |file| template "#{node['mso_config_path']}#{file}" do source "mso-topology-config/#{file}" owner "jboss" group "jboss" mode "0744" variables( :var => node["mso-config"]["topology"] ) end end
21.266667
49
0.548589
f7c32f952fd992cfd478a6a376b0d49907ed84ca
1,379
class CrossHatchHeuristic def initialize(puzzle_cell_intelligence) @candidates = puzzle_cell_intelligence end def execute(puzzle, cell) find_naked_singles(cell, puzzle) find_hidden_singles(cell, puzzle) end private def find_naked_singles(cell, puzzle) candidates = @candidates.cell(puzzle, cell) puzzle.set(cell, candidates[0]) if candidates.length == 1 merge_candidates(candidates, puzzle, cell) end def find_hidden_singles(cell, puzzle) candidate_counts = Hash[(1..9).to_a.map { |key| [key, []] }] candidate_counts = @candidates .grid(puzzle, cell) .reduce(candidate_counts) do |counts, (location, candidates)| puzzle.set(location, candidates[0]) if candidates.length == 1 candidates.each { |value| counts[value].push(location) } if candidates.length > 1 counts end candidate_counts.each do |candidate, cells| next unless cells.length == 1 puzzle.set(cells[0], candidate) end @candidates .grid(puzzle, cell) .each do |location, candidates| merge_candidates(candidates, puzzle, location) end end def merge_candidates(new, puzzle, cell) old = puzzle.candidates(cell) return puzzle.candidates(cell, new) if old.empty? (old - new).each { |candidate| old.delete(candidate) } puzzle.candidates(cell, old) end end
28.142857
89
0.683829
e91c0113004d8d779025aef2358cf3fa72ec6dd8
4,821
module Runners module Ruby class InstallGemsFailure < UserError; end def install_gems(default_specs, constraints:, optionals: [], &block) original_default_specs = default_specs.dup user_specs = config_gems LockfileLoader.new(root_dir: root_dir, shell: shell).ensure_lockfile do |lockfile| default_specs = default_specs(default_specs, constraints, lockfile) optionals = optional_specs(optionals, lockfile) user_specs = user_specs(user_specs, lockfile) end use_local = (user_specs + optionals).empty? && original_default_specs == default_specs specs = merge_specs(default_specs, user_specs.empty? ? optionals : user_specs) Tmpdir.mktmpdir do |path| installer = GemInstaller.new(shell: shell, home: path, config_path_name: config.path_name, specs: specs, trace_writer: trace_writer, constraints: constraints, use_local: use_local) installer.install!(&block) end end private def default_specs(specs, constraints, lockfile) specs.map do |spec| if lockfile.spec_exists?(spec) if lockfile.satisfied_by?(spec, constraints) spec.override_by_lockfile(lockfile) else locked_version = lockfile.locked_version!(spec) add_warning <<~MESSAGE `#{spec.name} #{spec.requirement}` will be installed instead of `#{locked_version}` in your `Gemfile.lock`. Because `#{locked_version}` does not satisfy our constraints `#{constraints.fetch(spec.name)}`. If you want to use a different version of `#{spec.name}`, please do either: - Update your `Gemfile.lock` to satisfy the constraint - Set the `#{config_field_path(:dependencies)}` option in your `#{config.path_name}` MESSAGE spec end else spec end end end private def optional_specs(specs, lockfile) specs.select { |spec| lockfile.spec_exists?(spec) } .map { |spec| spec.override_by_lockfile(lockfile) } end private def user_specs(specs, lockfile) specs.map do |spec| if spec.requirement.none? spec.override_by_lockfile(lockfile) else spec end end end def show_runtime_versions capture3! "ruby", "-v" capture3! "gem", "-v" capture3! "bundle", "-v" super end def ruby_analyzer_command(*args) Command.new("bundle", ["exec", analyzer_bin, *args]) end def analyzer_version @analyzer_version ||= extract_version! ruby_analyzer_command.to_a end def default_gem_specs(*gem_names) # @see https://guides.rubygems.org/command-reference/#gem-list stdout, = capture3! "gem", "list", "--quiet", "--exact", *gem_names gem_names.map do |name| # NOTE: A format example: `rubocop (0.75.1, 0.75.0)` version = /#{Regexp.escape(name)} \((.+)\)/.match(stdout)&.captures&.first if version GemInstaller::Spec.new(name, requirement: version.split(/,\s*/)) else raise "Not found installed gem #{name.inspect}" end end end def gem_info(gem_name) @gem_info ||= {} info = @gem_info[gem_name] unless info info, _ = capture3! "gem", "info", "--both", "--exact", "--quiet", gem_name @gem_info[gem_name] = info end info end private def config_gems (config_linter[:dependencies] || config_linter[:gems] || []).map do |item| gem = case item when Hash item when String { name: item.to_s, version: nil, source: nil, git: nil } else raise item.inspect end GemInstaller::Spec.new( gem.fetch(:name), requirement: Array(gem[:version]), source: GemInstaller::Source.new(uri: gem[:source], git: gem[:git]), ) end end def merge_specs(defaults, users) defaults_hash = defaults.to_h { |spec| [spec.name, spec] } users_hash = users.to_h { |spec| [spec.name, spec] } specs = [] specs += defaults_hash.map do |name, spec| user_spec = users_hash[name] if user_spec GemInstaller::Spec.new(name, requirement: user_spec.requirement, source: user_spec.source) else spec end end specs += users_hash.filter_map do |name, spec| spec unless defaults_hash.include?(name) end specs end end end
31.509804
121
0.577681
11533ab780119a51f47e18993351cfd84f65f97f
1,828
# # Cookbook Name:: universe_ubuntu # Recipe:: essentials # # Copyright (c) 2017 The Authors, All Rights Reserved. include_recipe 'apt::default' apt_repository 'add golang latest repo' do uri 'ppa:ubuntu-lxc/lxd-stable' only_if { node['platform_version'] == '14.04' } end ruby_block 'Allow non root users start the GUI' do block do file = Chef::Util::FileEdit.new '/etc/X11/Xwrapper.config' file.search_file_replace_line(/^allowed_users=console/, 'allowed_users=anybody') file.write_file end only_if { node['platform_version'] == '14.04' } end packages = %w(golang libjpeg-turbo8-dev make tmux htop chromium-browser git cmake zlib1g-dev libjpeg-dev xvfb libav-tools xorg-dev python-opengl libboost-all-dev libsdl2-dev swig tilda terminator) packages.each { |item| package item } execute 'Customize the Unity Launcher favorite apps' do command 'dbus-launch gsettings set com.canonical.Unity.Launcher favorites '\ "\"['application://tilda.desktop', 'application://terminator.desktop', "\ "'application://debian-xterm.desktop', 'application://remmina.desktop', "\ "'application://chromium-browser.desktop', 'application://firefox.desktop', "\ "'application://org.gnome.Nautilus.desktop', 'application://org.gnome.Software.desktop', "\ "'application://unity-control-center.desktop', 'unity://running-apps', "\ "'unity://expo-icon', 'unity://devices']\"" end execute 'Set default terminal emulator' do command 'dbus-launch gsettings set org.gnome.desktop.default-applications.terminal '\ "exec '/usr/bin/tilda'" end
30.466667
95
0.624726
037a710e180b83e69ddb1ee45b4feabd75af2c90
68
# frozen_string_literal: true module Split VERSION = "4.0.1" end
11.333333
29
0.720588
4ab83b1326548528a00be5b2d5d203fb9a738f12
128
module Workspace::EmployeesHelper def full_name(employee) "#{employee.first_name} #{employee.last_name}" end end
14.222222
52
0.710938
1c73325e1cf66c517d29eee951db91963c8bb493
802
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "msgpack" s.version = "0.4.6" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["FURUHASHI Sadayuki"] s.date = "2011-08-08" s.email = "[email protected]" s.extensions = ["ext/extconf.rb"] s.files = ["ext/extconf.rb"] s.homepage = "http://msgpack.org/" s.rdoc_options = ["ext"] s.require_paths = ["lib"] s.rubyforge_project = "msgpack" s.rubygems_version = "1.8.21" s.summary = "MessagePack, a binary-based efficient data interchange format." if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
27.655172
105
0.667082
114b7cb3066a34f774da5b1c40b4c977f25fb8c8
2,107
class AwscliAT1 < Formula include Language::Python::Virtualenv desc "Official Amazon AWS command-line interface" homepage "https://aws.amazon.com/cli/" # awscli should only be updated every 10 releases on multiples of 10 url "https://github.com/aws/aws-cli/archive/1.19.90.tar.gz" sha256 "041a0c58dc8065284d9400c2e1f4e68440df5e1628436deb7a935b455a9a4a05" license "Apache-2.0" livecheck do url :stable regex(/^v?(1(?:\.\d+)+)$/i) end bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "72c45fc7e2f69c1c3cc7981df7957bd0dc9e8b1bfd0cf38d1c6128ce181254d7" sha256 cellar: :any_skip_relocation, big_sur: "12ee40b046c8f257eba6759e40ff7b7eda0848f97d1ec35280c53243c1313b83" sha256 cellar: :any_skip_relocation, catalina: "d432d1e2e07f21a4fbf6fc5b6ae4e8b4abffb93bd99abb75472b12bfb9137644" sha256 cellar: :any_skip_relocation, mojave: "76422b9dc324e6c6bb6915c4adc415dea9cdff0ff98f459c37fd0e180742d5e2" end keg_only :versioned_formula # Some AWS APIs require TLS1.2, which system Python doesn't have before High # Sierra depends_on "[email protected]" uses_from_macos "groff" def install venv = virtualenv_create(libexec, "python3") system libexec/"bin/pip", "install", "-v", "--no-binary", ":all:", "--ignore-installed", buildpath system libexec/"bin/pip", "uninstall", "-y", "awscli" venv.pip_install_and_link buildpath pkgshare.install "awscli/examples" rm Dir["#{bin}/{aws.cmd,aws_bash_completer,aws_zsh_completer.sh}"] bash_completion.install "bin/aws_bash_completer" zsh_completion.install "bin/aws_zsh_completer.sh" (zsh_completion/"_aws").write <<~EOS #compdef aws _aws () { local e e=$(dirname ${funcsourcetrace[1]%:*})/aws_zsh_completer.sh if [[ -f $e ]]; then source $e; fi } EOS end def caveats <<~EOS The "examples" directory has been installed to: #{HOMEBREW_PREFIX}/share/awscli/examples EOS end test do assert_match "topics", shell_output("#{bin}/aws help") end end
33.444444
122
0.705268
61b06b4df5bf78b04a9f7fe4557098c6b7c54526
1,891
# CLI controller class CLI def call Scraper.scrape_colleges if @colleges == nil welcome end def welcome input = nil while input != "exit" puts "Welcome, to see a list of colleges and universities in the state of Illinois type 'list', or type 'exit' to exit the program:" input = gets.strip.downcase if input == "list" list_colleges menu elsif input == "exit" goodbye exit else puts "Not sure what you meant, please type 'list' or 'exit'.." end end end def list_colleges puts "Colleges and universities in the state of Illinois:" College.all.each_with_index do |college, i| puts "#{i + 1}. #{college.name}" end end def menu input = nil while input != "exit" puts "Please enter the number of the institution that you would like more information on, type 'list' to list the institutions again, or type 'exit':" input = gets.strip.downcase if input.to_i > 0 && input.to_i <= Colleges.all.length #Checked if it was too small, but need to check if it is too big the_college = College.all[input.to_i - 1] the_college.details ||= Scraper.scrape_college_detail(the_college) puts "#{the_college.name} - #{the_college.location}" puts "Type: #{the_college.details[:type]}" puts "Size: #{the_college.details[:size]}" puts "Profit-status: #{the_college.details[:profit_status]}" puts "Degrees Offered: #{the_college.details[:degrees_offered]}" elsif input == "list" list_colleges elsif input == "exit" goodbye exit else puts "Not sure what you meant, please type 'list' or 'exit'.." end end end def goodbye puts "Come back anytime to learn more about the colleges and universities in the state of Illinois!" end end
29.546875
156
0.634585
9146373dde33f440c9c1b428cac274300a401ea9
485
# frozen_string_literal: true require 'test_helper' class Memberships::SwitchControllerTest < ActionController::TestCase setup do @membership = send 'public.memberships', :franco_default login end test 'should create' do post :create, params: { membership_id: @membership } assert_redirected_to root_url assert_equal @membership.account.tenant_name, session[:tenant_name] assert_equal @membership.user.auth_token, cookies.encrypted[:token] end end
24.25
71
0.760825
21f479026a8b0e47135efcd322b975ce7664865b
886
module MouseHole::Helpers def rss( io ) feed = Builder::XmlMarkup.new( :target => io, :indent => 2 ) feed.instruct! :xml, :version => "1.0", :encoding => "UTF-8" feed.rss( 'xmlns:admin' => 'http://webns.net/mvcb/', 'xmlns:sy' => 'http://purl.org/rss/1.0/modules/syndication/', 'xmlns:dc' => 'http://purl.org/dc/elements/1.1/', 'xmlns:rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'version' => '2.0' ) do |rss| rss.channel do |c| # channel stuffs c.dc :language, "en-us" c.dc :creator, "MouseHole #{ MouseHole::VERSION }" c.dc :date, Time.now.utc.strftime( "%Y-%m-%dT%H:%M:%S+00:00" ) c.admin :generatorAgent, "rdf:resource" => "http://builder.rubyforge.org/" c.sy :updatePeriod, "hourly" c.sy :updateFrequency, 1 yield c end end end end
35.44
82
0.547404
1d0427ddae57ad94025ff4eb478f77224c89fe38
2,453
module HealthSeven::V2_5 class Rxg < ::HealthSeven::Segment # Give Sub-ID Counter attribute :give_sub_id_counter, Nm, position: "RXG.1", require: true # Dispense Sub-ID Counter attribute :dispense_sub_id_counter, Nm, position: "RXG.2" # Quantity/Timing attribute :quantity_timing, Tq, position: "RXG.3" # Give Code attribute :give_code, Ce, position: "RXG.4", require: true # Give Amount - Minimum attribute :give_amount_minimum, Nm, position: "RXG.5", require: true # Give Amount - Maximum attribute :give_amount_maximum, Nm, position: "RXG.6" # Give Units attribute :give_units, Ce, position: "RXG.7", require: true # Give Dosage Form attribute :give_dosage_form, Ce, position: "RXG.8" # Administration Notes attribute :administration_notes, Array[Ce], position: "RXG.9", multiple: true # Substitution Status attribute :substitution_status, Id, position: "RXG.10" # Dispense-to Location attribute :dispense_to_location, La2, position: "RXG.11" # Needs Human Review attribute :needs_human_review, Id, position: "RXG.12" # Pharmacy/Treatment Supplier's Special Administration Instructions attribute :pharmacy_treatment_supplier_s_special_administration_instructions, Array[Ce], position: "RXG.13", multiple: true # Give Per (Time Unit) attribute :give_per_time_unit, St, position: "RXG.14" # Give Rate Amount attribute :give_rate_amount, St, position: "RXG.15" # Give Rate Units attribute :give_rate_units, Ce, position: "RXG.16" # Give Strength attribute :give_strength, Nm, position: "RXG.17" # Give Strength Units attribute :give_strength_units, Ce, position: "RXG.18" # Substance Lot Number attribute :substance_lot_numbers, Array[St], position: "RXG.19", multiple: true # Substance Expiration Date attribute :substance_expiration_dates, Array[Ts], position: "RXG.20", multiple: true # Substance Manufacturer Name attribute :substance_manufacturer_names, Array[Ce], position: "RXG.21", multiple: true # Indication attribute :indications, Array[Ce], position: "RXG.22", multiple: true # Give Drug Strength Volume attribute :give_drug_strength_volume, Nm, position: "RXG.23" # Give Drug Strength Volume Units attribute :give_drug_strength_volume_units, Cwe, position: "RXG.24" # Give Barcode Identifier attribute :give_barcode_identifier, Cwe, position: "RXG.25" # Pharmacy Order Type attribute :pharmacy_order_type, Id, position: "RXG.26" end end
43.803571
125
0.747248
e2b928b9121e296a23dbd7e073ee06115f9db804
1,427
# frozen_string_literal: true module Node class Command class Serve < ShopifyCli::SubCommand prerequisite_task ensure_project_type: :node prerequisite_task :ensure_env, :ensure_dev_store options do |parser, flags| parser.on("--host=HOST") do |h| flags[:host] = h.gsub('"', "") end end def call(*) project = ShopifyCli::Project.current url = options.flags[:host] || ShopifyCli::Tunnel.start(@ctx) @ctx.abort(@ctx.message("node.serve.error.host_must_be_https")) if url.match(/^https/i).nil? project.env.update(@ctx, :host, url) ShopifyCli::Tasks::UpdateDashboardURLS.call( @ctx, url: url, callback_url: "/auth/callback", ) if project.env.shop project_url = "#{project.env.host}/auth?shop=#{project.env.shop}" @ctx.puts("\n" + @ctx.message("node.serve.open_info", project_url) + "\n") end CLI::UI::Frame.open(@ctx.message("node.serve.running_server")) do env = project.env.to_h env["PORT"] = ShopifyCli::Tunnel::PORT.to_s @ctx.system("npm run dev", env: env) end end def self.help ShopifyCli::Context.message("node.serve.help", ShopifyCli::TOOL_NAME) end def self.extended_help ShopifyCli::Context.message("node.serve.extended_help") end end end end
30.361702
100
0.599159
ed31740d22b4b56fbf0730d267bc8ed44ee23cf6
216
class CreateSites < ActiveRecord::Migration def change create_table :sites do |t| t.string :url t.string :name t.string :username t.string :logo_url t.timestamps end end end
18
43
0.634259
e8356070f131858150e710001eb95c44fb620ed4
624
require "spec_helper" MetricFu.lib_require { "templates/report" } describe MetricFu::Templates::Report do # TODO: This test only shows how the code works and that it doesn't blow up. # Perhaps it should test something more specific? it "Reads in a source file, and produces an annotated HTML report" do lines = { "2" => [{ type: :reek, description: "Bad Param Names" }] } source_file = File.join(MetricFu.root_dir, "spec", "dummy", "lib", "bad_encoding.rb") report = MetricFu::Templates::Report.new(source_file, lines) expect { rendered_report = report.render }.not_to raise_error end end
39
89
0.703526
b967174ddfd9b857af3fb6b30720a1c91256164d
152
# frozen_string_literal: true class AddUserToEntries < ActiveRecord::Migration[4.2] def change add_column :entries, :user_id, :integer end end
19
53
0.756579
7af47c35013036b04a40a2d0eabc9f5d1b17a338
977
module WechatAuthorize class << self attr_accessor :config def configure puts "= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = init configure" yield self.config ||= Config.new end def weixin_redis return nil if config.nil? @redis ||= config.redis end def key_expired config.key_expired || 100 end # 可选配置: RestClient timeout, etc. # key 必须是符号 # 如果出现 RestClient::SSLCertificateNotVerified Exception: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed # 这个错,除了改 verify_ssl: true,请参考:http://www.extendi.it/blog/2015/5/23/47-sslv3-read-server-certificate-b-certificate-verify-failed def rest_client_options if config.nil? return {timeout: 5, open_timeout: 5, verify_ssl: true} end config.rest_client_options end end class Config attr_accessor :redis, :rest_client_options, :key_expired end end
26.405405
155
0.646878
5d73fafd425e41fbb955b7bad98bf6645d9999c2
703
# frozen_string_literal: true require_relative 'test_helper' class TestFakerSimpsons < Test::Unit::TestCase def setup Faker::Config.locale = nil end def test_characters 10.times { assert Faker::Simpsons.character.match(/[\w]+/) } end def test_locations 10.times { assert Faker::Simpsons.location.match(/[\w]+/) } end def test_quote 10.times { assert Faker::Simpsons.quote.match(/[\w]+/) } end def test_locales [nil, 'en', 'de'].each do |_locale_name| Faker::Config.locale = 'de' assert Faker::Simpsons.character.is_a? String assert Faker::Simpsons.location .is_a? String assert Faker::Simpsons.quote .is_a? String end end end
22.677419
64
0.672831
bf731e11d57dfc67b8df17227a68994509beba65
8,213
# frozen_string_literal: true require 'test_helper' module Vedeu module DSL describe Wordwrap do let(:described) { Vedeu::DSL::Wordwrap } let(:instance) { described.new(text, options) } let(:text) { '' } let(:mode) { :default } let(:_name) {} let(:width) { 30 } let(:options) { { ellipsis: '...', mode: mode, name: _name, width: width, } } let(:text_line) { "Krypton (from Greek: κρυπτός kryptos 'the hidden one')." } let(:text_block) { "Krypton (from Greek: κρυπτός kryptos 'the hidden one') is a " \ "chemical element with symbol Kr and atomic number 36. It is a " \ 'member of group 18 (noble gases) elements.' } let(:text_newlines) { "Krypton is a colorless, odorless, tasteless noble gas.\n" \ "It occurs in trace amounts in the atmosphere.\n" \ "It is isolated by fractionally distilling liquefied air.\n" \ "Krypton is often used with other rare gases in fluorescent lamps.\n" } let(:text_blanklines) { "Krypton (from Greek: κρυπτός kryptos 'the hidden one').\n\n" \ "It is a chemical element with symbol Kr and atomic number 36.\n" \ "It is a member of group 18 (noble gases) elements.\n\n" \ '-- Wikipedia' } let(:text_line_objects) { [ Vedeu::Views::Line.new(value: [ Vedeu::Views::Stream.new( value: 'Krypton is a colorless, odorless, tasteless noble gas.' )]), Vedeu::Views::Line.new(value: [ Vedeu::Views::Stream.new( value: 'It occurs in trace amounts in the atmosphere.' )]), Vedeu::Views::Line.new(value: [ Vedeu::Views::Stream.new( value: 'It is isolated by fractionally distilling liquefied air.' )]), Vedeu::Views::Line.new(value: [ Vedeu::Views::Stream.new( value: 'Krypton is often used with other rare gases in ' \ 'fluorescent lamps.' )]) ] } describe '#initialize' do it { instance.must_be_instance_of(described) } it { instance.instance_variable_get('@text').must_equal(text) } it { instance.instance_variable_get('@options').must_equal(options) } end describe '#content' do it { instance.must_respond_to(:content) } end describe '#prune' do let(:text) { text_line } subject { instance.prune } context 'when the text is <= the pruning width' do let(:width) { 80 } it { subject.must_be_instance_of(String) } it { subject.must_equal( "Krypton (from Greek: κρυπτός kryptos 'the hidden one')." ) } end context 'when the text is > the pruning width' do context 'with a single line of text' do it { subject.must_equal('Krypton (from Greek: κρυπτός...') } end context 'with a text block' do let(:text) { text_block } it { subject.must_equal('Krypton (from Greek: κρυπτός...') } end context 'with a text block containing newlines' do let(:text) { text_newlines } it { subject.must_equal([ 'Krypton is a colorless, odor...', 'It occurs in trace amounts i...', 'It is isolated by fractional...', 'Krypton is often used with o...' ]) } end context 'with a text block containing newlines and blank lines' do let(:text) { text_blanklines } it { subject.must_equal([ 'Krypton (from Greek: κρυπτός...', '', 'It is a chemical element wit...', 'It is a member of group 18 (...', '', '-- Wikipedia...' ]) } end end end describe '#wrap' do subject { instance.wrap } context 'with a single line of text' do let(:text) { text_line } it { subject.must_equal([ 'Krypton (from Greek: κρυπτός', "kryptos 'the hidden one')." ]) } end context 'with a text block' do let(:text) { text_block } it { subject.must_equal([ 'Krypton (from Greek: κρυπτός', "kryptos 'the hidden one') is", 'a chemical element with', 'symbol Kr and atomic number', '36. It is a member of group', '18 (noble gases) elements.' ]) } end context 'with a text block containing newlines' do let(:text) { text_newlines } it { subject.must_equal([ 'Krypton is a colorless,', 'odorless, tasteless noble', 'gas.', 'It occurs in trace amounts', 'in the atmosphere.', 'It is isolated by', 'fractionally distilling', 'liquefied air.', 'Krypton is often used with', 'other rare gases in', 'fluorescent lamps.' ]) } end context 'with a text block containing newlines and blank lines' do let(:text) { text_blanklines } it { subject.must_equal([ 'Krypton (from Greek: κρυπτός', "kryptos 'the hidden one').", '', 'It is a chemical element', 'with symbol Kr and atomic', 'number 36.', 'It is a member of group 18', '(noble gases) elements.', '', '-- Wikipedia' ]) } end end describe '.for' do subject { described.for(text, options) } it { subject.must_be_instance_of(Vedeu::Views::Lines) } context 'with a single line of text' do let(:text) { text_line } it { subject.size.must_equal(1) } end context 'with a text block' do let(:text) { text_block } it { subject.size.must_equal(1) } end context 'with a text block containing newlines' do let(:text) { text_newlines } it { subject.size.must_equal(4) } end context 'with a text block containing newlines and blank lines' do let(:text) { text_blanklines } it { subject.size.must_equal(6) } end context 'when mode: :prune' do let(:mode) { :prune } context 'with a single line of text' do let(:text) { text_line } it { subject.size.must_equal(1) } end context 'with a text block' do let(:text) { text_block } it { subject.size.must_equal(1) } end context 'with a text block containing newlines' do let(:text) { text_newlines } it { subject.size.must_equal(4) } end context 'with a text block containing newlines and blank lines' do let(:text) { text_blanklines } it { subject.size.must_equal(6) } end end context 'when mode: :wrap' do let(:mode) { :wrap } context 'with a single line of text' do let(:text) { text_line } it { subject.size.must_equal(2) } end context 'with a text block' do let(:text) { text_block } it { subject.size.must_equal(6) } end context 'with a text block containing newlines' do let(:text) { text_newlines } it { subject.size.must_equal(11) } end context 'with a text block containing newlines and blank lines' do let(:text) { text_blanklines } it { subject.size.must_equal(10) } end end end end # Wordwrap end # DSL end # Vedeu
28.517361
79
0.505905
4af18b77677e0c5a37be96b7c05def4ec74fd758
212
class ApplicationController < ActionController::Base protect_from_forgery prepend: true, with: :exception def ensure_admin redirect_to projects_path if !current_user || !current_user.is_admin? end end
26.5
73
0.79717
28ac752f55029b1615ecc5e9c1022a18109623a6
6,922
# frozen_string_literal: true module Emails module MergeRequests def new_merge_request_email(recipient_id, merge_request_id, reason = nil) setup_merge_request_mail(merge_request_id, recipient_id, present: true) mail_new_thread(@merge_request, merge_request_thread_options(@merge_request.author_id, recipient_id, reason)) end def new_mention_in_merge_request_email(recipient_id, merge_request_id, updated_by_user_id, reason = nil) setup_merge_request_mail(merge_request_id, recipient_id, present: true) mail_answer_thread(@merge_request, merge_request_thread_options(updated_by_user_id, recipient_id, reason)) end def push_to_merge_request_email(recipient_id, merge_request_id, updated_by_user_id, reason = nil, new_commits: [], existing_commits: []) setup_merge_request_mail(merge_request_id, recipient_id) @new_commits = new_commits @existing_commits = existing_commits @updated_by_user = User.find(updated_by_user_id) mail_answer_thread(@merge_request, merge_request_thread_options(updated_by_user_id, recipient_id, reason)) end # rubocop: disable CodeReuse/ActiveRecord def reassigned_merge_request_email(recipient_id, merge_request_id, previous_assignee_ids, updated_by_user_id, reason = nil) setup_merge_request_mail(merge_request_id, recipient_id) @previous_assignees = [] @previous_assignees = User.where(id: previous_assignee_ids) if previous_assignee_ids.any? mail_answer_thread(@merge_request, merge_request_thread_options(updated_by_user_id, recipient_id, reason)) end # rubocop: enable CodeReuse/ActiveRecord # rubocop: disable CodeReuse/ActiveRecord def changed_reviewer_of_merge_request_email(recipient_id, merge_request_id, previous_reviewer_ids, updated_by_user_id, reason = nil) setup_merge_request_mail(merge_request_id, recipient_id) @previous_reviewers = [] @previous_reviewers = User.where(id: previous_reviewer_ids) if previous_reviewer_ids.any? mail_answer_thread(@merge_request, merge_request_thread_options(updated_by_user_id, recipient_id, reason)) end # rubocop: enable CodeReuse/ActiveRecord def relabeled_merge_request_email(recipient_id, merge_request_id, label_names, updated_by_user_id, reason = nil) setup_merge_request_mail(merge_request_id, recipient_id) @label_names = label_names @labels_url = project_labels_url(@project) mail_answer_thread(@merge_request, merge_request_thread_options(updated_by_user_id, recipient_id, reason)) end def removed_milestone_merge_request_email(recipient_id, merge_request_id, updated_by_user_id, reason = nil) setup_merge_request_mail(merge_request_id, recipient_id) mail_answer_thread(@merge_request, merge_request_thread_options(updated_by_user_id, recipient_id, reason)) end def changed_milestone_merge_request_email(recipient_id, merge_request_id, milestone, updated_by_user_id, reason = nil) setup_merge_request_mail(merge_request_id, recipient_id) @milestone = milestone @milestone_url = milestone_url(@milestone) mail_answer_thread(@merge_request, merge_request_thread_options(updated_by_user_id, recipient_id, reason).merge({ template_name: 'changed_milestone_email' })) end def closed_merge_request_email(recipient_id, merge_request_id, updated_by_user_id, reason: nil, closed_via: nil) setup_merge_request_mail(merge_request_id, recipient_id) @updated_by = User.find(updated_by_user_id) mail_answer_thread(@merge_request, merge_request_thread_options(updated_by_user_id, recipient_id, reason)) end def merged_merge_request_email(recipient_id, merge_request_id, updated_by_user_id, reason: nil, closed_via: nil) setup_merge_request_mail(merge_request_id, recipient_id) mail_answer_thread(@merge_request, merge_request_thread_options(updated_by_user_id, recipient_id, reason)) end def merge_request_status_email(recipient_id, merge_request_id, status, updated_by_user_id, reason = nil) setup_merge_request_mail(merge_request_id, recipient_id) @mr_status = status @updated_by = User.find(updated_by_user_id) mail_answer_thread(@merge_request, merge_request_thread_options(updated_by_user_id, recipient_id, reason)) end def merge_request_unmergeable_email(recipient_id, merge_request_id, reason = nil) setup_merge_request_mail(merge_request_id, recipient_id) mail_answer_thread(@merge_request, merge_request_thread_options(@merge_request.author_id, recipient_id, reason)) end def resolved_all_discussions_email(recipient_id, merge_request_id, resolved_by_user_id, reason = nil) setup_merge_request_mail(merge_request_id, recipient_id) @resolved_by = User.find(resolved_by_user_id) mail_answer_thread(@merge_request, merge_request_thread_options(resolved_by_user_id, recipient_id, reason)) end def merge_when_pipeline_succeeds_email(recipient_id, merge_request_id, mwps_set_by_user_id, reason = nil) setup_merge_request_mail(merge_request_id, recipient_id) @mwps_set_by = ::User.find(mwps_set_by_user_id) mail_answer_thread(@merge_request, merge_request_thread_options(mwps_set_by_user_id, recipient_id, reason)) end def merge_requests_csv_email(user, project, csv_data, export_status) @project = project @count = export_status.fetch(:rows_expected) @written_count = export_status.fetch(:rows_written) @truncated = export_status.fetch(:truncated) filename = "#{project.full_path.parameterize}_merge_requests_#{Date.current.iso8601}.csv" attachments[filename] = { content: csv_data, mime_type: 'text/csv' } mail(to: user.notification_email_for(@project.group), subject: subject("Exported merge requests")) do |format| format.html { render layout: 'mailer' } format.text { render layout: 'mailer' } end end private def setup_merge_request_mail(merge_request_id, recipient_id, present: false) @merge_request = MergeRequest.find(merge_request_id) @project = @merge_request.project @target_url = project_merge_request_url(@project, @merge_request) if present recipient = User.find(recipient_id) @mr_presenter = @merge_request.present(current_user: recipient) end @sent_notification = SentNotification.record(@merge_request, recipient_id, reply_key) end def merge_request_thread_options(sender_id, recipient_id, reason = nil) { from: sender(sender_id), to: User.find(recipient_id).notification_email_for(@project.group), subject: subject("#{@merge_request.title} (#{@merge_request.to_reference})"), 'X-GitLab-NotificationReason' => reason } end end end Emails::MergeRequests.prepend_if_ee('EE::Emails::MergeRequests')
44.948052
140
0.775065
1c235c1d2fdd26725173cafe7667adf2eb9c03f7
1,794
# typed: true # frozen_string_literal: true require "thor" require_relative 'cli/helper' require_relative "cli/bump" require_relative "cli/config" require_relative "cli/lsp" require_relative "cli/coverage" require_relative "cli/run" module Spoom module Cli class Main < Thor extend T::Sig include Helper class_option :color, desc: "Use colors", type: :boolean, default: true class_option :path, desc: "Run spoom in a specific path", type: :string, default: ".", aliases: :p map T.unsafe(%w[--version -v] => :__print_version) desc "bump", "bump Sorbet sigils from `false` to `true` when no errors" subcommand "bump", Spoom::Cli::Bump desc "config", "manage Sorbet config" subcommand "config", Spoom::Cli::Config desc "coverage", "collect metrics related to Sorbet coverage" subcommand "coverage", Spoom::Cli::Coverage desc "lsp", "send LSP requests to Sorbet" subcommand "lsp", Spoom::Cli::LSP desc "tc", "run Sorbet and parses its output" subcommand "tc", Spoom::Cli::Run desc "files", "list all the files typechecked by Sorbet" def files in_sorbet_project! path = exec_path config = Spoom::Sorbet::Config.parse_file(sorbet_config) files = Spoom::Sorbet.srb_files(config, path: path) say("Files matching `#{sorbet_config}`:") if files.empty? say(" NONE") else tree = FileTree.new(files, strip_prefix: path) tree.print(colors: options[:color], indent_level: 2) end end desc "--version", "show version" def __print_version puts "Spoom v#{Spoom::VERSION}" end # Utils def self.exit_on_failure? true end end end end
26
104
0.632664