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
7aad76c5571589443709ff1176f642b49f028a61
341
require 'delegate' require 'hay/message' module Baler class Message class Encoder class MsgPack < DelegateClass(Hay::Message) def initialize(message) @message = message super end def payload @payload ||= @message.payload.to_msgpack end end end end end
16.238095
50
0.58651
edf9103b51397f5b7114724b96be36954df449ee
903
Detour::Application.routes.draw do |map| # map.resources :products, :member => { :detailed => :get } resources :products do get :detailed, :on => :member end # map.resources :forums, :collection => { :sortable => :get, :sort => :put } do |forums| # forums.resources :topics # end resources :forums do collection do get :sortable put :sort end resources :topics end # map.root :controller => "home", :action => "index" root :to => "home#index" # map.about "/about", :controller => "info", :action => "about" match "/about(.:format)" => "info#about", :as => :about match "/:year(/:month(/:day))" => "info#about", :constraints => { :year => /\d{4}/, :month => /\d{2}/, :day => /\d{2}/ } constraints :host => /localhost/ do match "/secret" => "info#about" end match "/hello" => proc { |env| [200, {}, "Hello Rack!"] } end
28.21875
122
0.563677
f84e366a88ef90d0e1e9f1f901f5af5cf387890e
793
Pod::Spec.new do |s| s.name = "BarcodeScanner" s.summary = "Simple and beautiful barcode scanner." s.version = "5.0.0" s.homepage = "https://github.com/hyperoslo/BarcodeScanner" s.license = 'MIT' s.author = { "Hyper Interaktiv AS" => "[email protected]" } s.source = { :git => "https://github.com/hyperoslo/BarcodeScanner.git", :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/hyperoslo' s.platform = :ios, '11.0' s.requires_arc = true s.source_files = 'Sources/**/*' s.resource_bundles = { 'BarcodeScanner' => ['Images/*.{png}'], 'Localization' => ['Localization/*.lproj/Localizable.strings'] } s.frameworks = 'UIKit', 'AVFoundation' s.swift_version = '5.0' end
31.72
68
0.587642
036f85e2b0ad1b419d9bc88a243756b78445d0f9
1,472
require "test_helper" class UsersLoginTest < ActionDispatch::IntegrationTest def setup @user = users(:michael) end test "login with valid email/invalid password" do get login_path assert_template 'session/new' post login_path, params: { session: { email: @user.email, password: "invalid" } } assert_not is_logged_in? assert_template 'session/new' assert_not flash.empty? get root_path assert flash.empty? end test "login with valid information followed by logout" do get login_path post login_path, params: { session: { email: @user.email, password: 'password' }} assert is_logged_in? assert_redirected_to @user follow_redirect! assert_template 'users/show' assert_select "a[href=?]", login_path, count: 0 assert_select "a[href=?]", logout_path assert_select "a[href=?]", user_path(@user) delete logout_path assert_not is_logged_in? assert_redirected_to root_url delete logout_path follow_redirect! assert_select "a[href=?]", login_path assert_select "a[href=?]", logout_path, count: 0 assert_select "a[href=?]", user_path(@user), count: 0 end test "login with remembering" do log_in_as(@user, remember_me: '1') assert_not cookies[:remember_token].blank? end test "login without remembering" do log_in_as(@user, remember_me: '1') log_in_as(@user, remember_me: '0') assert cookies[:remember_token].blank? end end
28.307692
88
0.697011
2884a311349bbd5823e3d852d401fc9e47d72d41
122
class AddVersionToInstances < ActiveRecord::Migration def change add_column :instances, :version, :string end end
20.333333
53
0.770492
ff2b4d777b141e2cc7e808e9d6bc89cf8c4ee570
803
class SessionsController < ApplicationController include SessionsHelper def create user = User.find_by(email: params[:session][:email].downcase) if user && user.authenticate(params[:session][:password]) log_in user params[:session][:remember_me] == '1' ? remember_user(user) : forget_user(user) flash= {:info => "欢迎回来: #{user.name} :)"} if user.first == false render "users/edit" else if !user.admin redirect_to root_url, :flash => flash else redirect_to root_url, :flash => flash end end else flash= {:danger => '账号或密码错误'} redirect_to sessions_login_path, :flash => flash end end def new end def destroy log_out if logged_in? redirect_to root_url end end
22.942857
85
0.616438
1c4ffc7b8cc8af163e474960e8c9a7c40e37b53e
8,954
# encoding: utf-8 require 'common/validation_error_tools' =begin = CalendarDAO - Goggles framework vers.: 4.00.570 - author: Leega DAO class containing the structure for calendar rendering. =end class CalendarDAO < Draper::Decorator class MeetingSessionDAO # These must be initialized on creation: attr_reader :id, :session_order, :scheduled_date, :warm_up_time, :begin_time, :events_list, :linked_pool #, :swimming_pool, # These can be edited later on: attr_accessor :date_span, :pool_span #-- ------------------------------------------------------------------------- #++ # Creates a new instance. # def initialize( meeting_session, date_span = 1, pool_span = 1 ) unless meeting_session && meeting_session.instance_of?( MeetingSession ) raise ArgumentError.new("CalendarDAO sessions needs a valid meeting session") end @id = meeting_session.id @session_order = meeting_session.session_order @scheduled_date = meeting_session.get_scheduled_date @warm_up_time = meeting_session.get_warm_up_time @begin_time = meeting_session.get_begin_time #@events_list = meeting_session.get_short_events @events_list = meeting_session.meeting_events.map{ |event| event.event_type.i18n_compact }.join( ", " ) #@swimming_pool = meeting_session.swimming_pool @linked_pool = meeting_session.swimming_pool.decorate.get_linked_name( :get_city_and_attributes ) @date_span = date_span @pool_span = pool_span end # Compatibility methods # def get_scheduled_date @scheduled_date end def get_warm_up_time @warm_up_time end def get_begin_time @begin_time end def get_short_events @events_list end end class MeetingDAO # These must be initialized on creation: attr_reader :id, :description, :header_date, :is_confirmed, :are_results_acquired, :has_start_list, :has_invitation, :season_id, :linked_name, :season_type_code, :reservation_button, :month, :can_manage, :team_affiliation_id, :is_user_starred, :is_team_starred, :is_current, :meeting_sessions #-- ------------------------------------------------------------------------- #++ # Creates a new instance. # def initialize( meeting, current_user = nil, can_manage = false, team_affiliation_id = nil, is_user_tagged = false, is_team_tagged = false ) unless meeting && meeting.instance_of?( Meeting ) raise ArgumentError.new("CalendarDAO meetings needs a valid meeting") end @id = meeting.id @description = meeting.get_full_name @header_date = meeting.header_date @is_confirmed = meeting.is_confirmed @are_results_acquired = meeting.are_results_acquired @has_start_list = meeting.has_start_list @season_id = meeting.season_id @can_manage = can_manage @team_affiliation_id = team_affiliation_id @season_type_code = meeting.season.season_type.code @has_invitation = (meeting.invitation != nil) decorated_meeting = meeting.decorate @linked_name = decorated_meeting.get_linked_name( :get_full_name ) #@reservation_button = current_user != nil ? decorated_meeting.manage_reservation_button_tm( current_user, can_manage ) : '' @reservation_button = current_user != nil ? decorated_meeting.manage_reservation_button( current_user ) : '' #@is_user_starred = current_user != nil ? meeting.tags_by_user_list.include?( "u#{ current_user.id }" ) : false #@is_team_starred = @team_affiliation_id != nil ? meeting.tags_by_team_list.include?( "ta#{ @team_affiliation_id }" ) : false @is_user_starred = is_user_tagged @is_team_starred = is_team_tagged @is_current = (@header_date >= Date.today() - 6 && @header_date <= Date.today() + 6) @month = month_name( @header_date ) @meeting_sessions = [] previous_date = nil previous_pool = nil date_span = 0 pool_span = 0 # Collect meeting sessions (sessions already ordered by default) meeting.meeting_sessions.each do |meeting_session| # Manage col span for session scheduled date if meeting_session.get_scheduled_date != previous_date previous_date = meeting_session.get_scheduled_date date_span = 1 else date_span = 0 end # Manage col span for swimming pool if meeting_session.swimming_pool != previous_pool previous_pool = meeting_session.swimming_pool pool_span = 1 else pool_span = 0 end @meeting_sessions << MeetingSessionDAO.new( meeting_session, date_span, pool_span ) end # Calculates column spans calculate_span end # Determinates the col span forose fields that could be present many times # and should not be shown in calendar views # def calculate_span date_span_count = 0 pool_span_count = 0 @meeting_sessions.reverse.each do |meeting_session_dao| date_span_count += 1 pool_span_count += 1 if meeting_session_dao.date_span > 0 meeting_session_dao.date_span = date_span_count date_span_count = 0 end if meeting_session_dao.pool_span > 0 meeting_session_dao.pool_span = pool_span_count pool_span_count = 0 end end end # Retrieve the month name def month_name( header_date ) month_names = {1=>'Gennaio', 2=>'Febbraio', 3=>'Marzo', 4=>'Aprile', 5=>'Maggio', 6=>'Giugno', 7=>'Luglio', 8=>'Agosto', 9=>'Settembre', 10=>'Ottobre', 11=>'Novembre', 12=>'Dicembre'} header_date && month_names[header_date.month] ? month_names[header_date.month] + ' ' + header_date.year.to_s : 'Da definire' end end # These must be initialized on creation: attr_reader :meeting_count, :months, :first_current, :seasons #-- ------------------------------------------------------------------------- #++ # These can be edited later on: #attr_accessor #-- ------------------------------------------------------------------------- #++ # Creates a new instance. # def initialize( current_user = nil ) @meetings = [] @meeting_count = 0 @paginated = false @months = [] @first_current = 0 @seasons = Hash.new end def meetings @paginated = false @meetings end def get_meetings @paginated = false @meetings end def get_paginated_meetings( page = 1 ) @paginated = true Kaminari.paginate_array(@meetings).page( page ) # TODO # @months should be calculated within the page end def paginated? @paginated end def show_months_header? months = @months.size months > 1 && @meeting_count > 6 && @meeting_count > months end def show_months_index? months = @months.size !@paginated && months > 1 && months < 20 && @meeting_count > 6 && @meeting_count > months end def show_season? @seasons.size > 1 end def column_to_be_shown show_season? ? 7 : 6 end # Adds a meetingDAO to the meeting colelction of calendar DAO def add_meeting( meeting, current_user = nil, can_manage = false, team_affiliation_id = nil, is_user_tagged = false, is_team_tagged = false ) if meeting && meeting.instance_of?( Meeting ) meetingDAO = MeetingDAO.new( meeting, current_user, can_manage, team_affiliation_id, is_user_tagged, is_team_tagged ) @meetings << meetingDAO @meeting_count += 1 @months << meetingDAO.month if [email protected]?( meetingDAO.month ) @first_current = @meeting_count if meetingDAO.is_current && @first_current == 0 @seasons[meetingDAO.season_type_code] = get_logo_for_season_type( meetingDAO.season_type_code ) if [email protected]?( meetingDAO.season_type_code ) end @meeting_count end # Returns an image_tag for this meeting, according to the associated season type. # Returns an empty string when not defined. # def get_logo_for_season_type( season_type_code ) if season_type_code =~ /CSI/i h.image_tag( 'logo_csi.png', size: '20x16' ) elsif season_type_code =~ /FIN/i h.image_tag( 'logo_fin.png', size: '40x16' ) elsif season_type_code =~ /UISP/i h.image_tag( 'logo_uisp.png', size: '40x16' ) else season_type_code end end #-- ------------------------------------------------------------------------- #++ end
34.438462
190
0.617154
01848b0ff280fb2bb17071ae7486de51106f2157
8,255
=begin #Ory Kratos API #Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the administative API port you should use something like Nginx, Ory Oathkeeper, or any other technology capable of authorizing incoming requests. The version of the OpenAPI document: v0.7.6-alpha.7 Contact: [email protected] Generated by: https://openapi-generator.tech OpenAPI Generator version: 5.2.1 =end require 'date' require 'time' module OryKratosClient class AdminCreateSelfServiceRecoveryLinkBody # Link Expires In The recovery link will expire at that point in time. Defaults to the configuration value of `selfservice.flows.recovery.request_lifespan`. attr_accessor :expires_in attr_accessor :identity_id # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'expires_in' => :'expires_in', :'identity_id' => :'identity_id' } end # Returns all the JSON keys this model knows about def self.acceptable_attributes attribute_map.values end # Attribute type mapping. def self.openapi_types { :'expires_in' => :'String', :'identity_id' => :'String' } end # List of attributes with nullable: true def self.openapi_nullable Set.new([ ]) end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) if (!attributes.is_a?(Hash)) fail ArgumentError, "The input argument (attributes) must be a hash in `OryKratosClient::AdminCreateSelfServiceRecoveryLinkBody` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `OryKratosClient::AdminCreateSelfServiceRecoveryLinkBody`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect end h[k.to_sym] = v } if attributes.key?(:'expires_in') self.expires_in = attributes[:'expires_in'] end if attributes.key?(:'identity_id') self.identity_id = attributes[:'identity_id'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new pattern = Regexp.new(/^[0-9]+(ns|us|ms|s|m|h)$/) if !@expires_in.nil? && @expires_in !~ pattern invalid_properties.push("invalid value for \"expires_in\", must conform to the pattern #{pattern}.") end if @identity_id.nil? invalid_properties.push('invalid value for "identity_id", identity_id cannot be nil.') end invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return false if !@expires_in.nil? && @expires_in !~ Regexp.new(/^[0-9]+(ns|us|ms|s|m|h)$/) return false if @identity_id.nil? true end # Custom attribute writer method with validation # @param [Object] expires_in Value to be assigned def expires_in=(expires_in) pattern = Regexp.new(/^[0-9]+(ns|us|ms|s|m|h)$/) if !expires_in.nil? && expires_in !~ pattern fail ArgumentError, "invalid value for \"expires_in\", must conform to the pattern #{pattern}." end @expires_in = expires_in end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && expires_in == o.expires_in && identity_id == o.identity_id end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Integer] Hash code def hash [expires_in, identity_id].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) self.send("#{key}=", nil) elsif type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :Time Time.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model # models (e.g. Pet) or oneOf klass = OryKratosClient.const_get(type) klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) if value.nil? is_nullable = self.class.openapi_nullable.include?(attr) next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) end hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
32.888446
429
0.642883
5dda797ce10de45f45454704e6f725947d7088f5
1,041
# encoding: UTF-8 require 'coffee-script' module Spontaneous::Rack class JS JS_EXTENSION = /\.js$/o def initialize(app, options = {}) @roots = options[:root] @app = app end def call(env) try_coffeescript(env[S::PATH_INFO]) or @app.call(env) end def try_coffeescript(request_path) return nil unless request_path =~ JS_EXTENSION try_paths = @roots.map { |root| File.join(root, request_path) } # if the css file itself exists then we want to use that return nil if try_paths.detect { |file| ::File.exists?(file) } try_paths.each do |path| template = template_path(path) return render_coffeescript(template) if File.exists?(template) end nil end def render_coffeescript(template) script = CoffeeScript.compile(File.read(template)) [200, {'Content-type' => 'application/javascript;charset=utf-8'}, StringIO.new(script)] end def template_path(path) path.gsub(JS_EXTENSION, ".coffee") end end end
24.785714
93
0.649376
ab4560b915cc2ffbcc041ba0bdd79610300bb576
3,457
class User < ApplicationRecord has_many :microposts, dependent: :destroy has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy has_many :following, through: :active_relationships, source: :followed has_many :followers, through: :passive_relationships, source: :follower attr_accessor :remember_token, :activation_token, :reset_token attr_accessor :remember_token, :activation_token before_save :downcase_email before_create :create_activation_digest validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } has_secure_password validates :password, presence: true, length: { minimum: 6 }, allow_nil: true def User.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end # ランダムなトークンを返す def User.new_token SecureRandom.urlsafe_base64 end # 永続セッションのためにユーザーをデータベースに記憶する def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(remember_token)) end # トークンがダイジェストと一致したらtrueを返す def authenticated?(attribute, token) digest = send("#{attribute}_digest") return false if digest.nil? BCrypt::Password.new(digest).is_password?(token) end # ユーザーのログイン情報を破棄する def forget update_attribute(:remember_digest, nil) end # アカウントを有効にする def activate update_attribute(:activated, true) update_attribute(:activated_at, Time.zone.now) end # 有効化用のメールを送信する def send_activation_email UserMailer.account_activation(self).deliver_now end # パスワード再設定の属性を設定する def create_reset_digest self.reset_token = User.new_token update_attribute(:reset_digest, User.digest(reset_token)) update_attribute(:reset_sent_at, Time.zone.now) end # パスワード再設定のメールを送信する def send_password_reset_email UserMailer.password_reset(self).deliver_now end # パスワード再設定の期限が切れている場合はtrueを返す def password_reset_expired? reset_sent_at < 2.hours.ago end # ユーザーのステータスフィードを返す def feed following_ids = "SELECT followed_id FROM relationships WHERE follower_id = :user_id" Micropost.where("user_id IN (#{following_ids}) OR user_id = :user_id", user_id: id) end # ユーザーをフォローする def follow(other_user) following << other_user end # ユーザーをフォロー解除する def unfollow(other_user) active_relationships.find_by(followed_id: other_user.id).destroy end # 現在のユーザーがフォローしてたらtrueを返す def following?(other_user) following.include?(other_user) end private # メールアドレスをすべて小文字にする def downcase_email self.email = email.downcase end # 有効化トークンとダイジェストを作成および代入する def create_activation_digest self.activation_token = User.new_token self.activation_digest = User.digest(activation_token) end end
29.547009
88
0.67978
acd0e1c7875ac42dbf4550be876e5f3ec3262cd0
328
require 'fact_store' class Ruleset def initialize(*rules) @rules = rules end def apply(factset) transaction = FactStore::Transaction.new rules.each do |rule| rule.apply(factset).each do |entry| transaction << entry factset += entry.facts end end transaction end end
14.26087
44
0.631098
edd7212991ed6fc5faedbcdf100e2adb352438e6
8,926
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Mosel < RegexLexer tag 'mosel' filenames '*.mos' title "Mosel" desc "An optimization language used by Fico's Xpress." # https://www.fico.com/en/products/fico-xpress-optimization-suite filenames '*.mos' mimetypes 'text/x-mosel' def self.detect?(text) return true if text =~ /^\s*(model|package)\s+/ end id = /[a-zA-Z_][a-zA-Z0-9_]*/ ############################################################################################################################ # General language lements ############################################################################################################################ core_keywords = %w( and array as boolean break case count counter declarations div do dynamic elif else end evaluation exit false forall forward from function if imports in include initialisations initializations integer inter is_binary is_continuous is_free is_integer is_partint is_semcont is_semint is_sos1 is_sos2 linctr list max min mod model mpvar next not of options or package parameters procedure public prod range real record repeat requirements set string sum then to true union until uses version while with ) core_functions = %w( abs arctan assert bitflip bitneg bitset bitshift bittest bitval ceil cos create currentdate currenttime cuthead cuttail delcell exists exit exp exportprob fclose fflush finalize findfirst findlast floor fopen fselect fskipline getact getcoeff getcoeffs getdual getfid getfirst gethead getfname getlast getobjval getparam getrcost getreadcnt getreverse getsize getslack getsol gettail gettype getvars iseof ishidden isodd ln log makesos1 makesos2 maxlist minlist publish random read readln reset reverse round setcoeff sethidden setioerr setname setparam setrandseed settype sin splithead splittail sqrt strfmt substr timestamp unpublish write writeln ) ############################################################################################################################ # mmxprs module elements ############################################################################################################################ mmxprs_functions = %w( addmipsol basisstability calcsolinfo clearmipdir clearmodcut command copysoltoinit defdelayedrows defsecurevecs estimatemarginals fixglobal getbstat getdualray getiis getiissense getiistype getinfcause getinfeas getlb getloadedlinctrs getloadedmpvars getname getprimalray getprobstat getrange getsensrng getsize getsol getub getvars implies indicator isiisvalid isintegral loadbasis loadmipsol loadprob maximize minimize postsolve readbasis readdirs readsol refinemipsol rejectintsol repairinfeas resetbasis resetiis resetsol savebasis savemipsol savesol savestate selectsol setbstat setcallback setcbcutoff setgndata setlb setmipdir setmodcut setsol setub setucbdata stopoptimize unloadprob writebasis writedirs writeprob writesol xor ) mmxpres_constants = %w(XPRS_OPT XPRS_UNF XPRS_INF XPRS_UNB XPRS_OTH) mmxprs_parameters = %w(XPRS_colorder XPRS_enumduplpol XPRS_enummaxsol XPRS_enumsols XPRS_fullversion XPRS_loadnames XPRS_problem XPRS_probname XPRS_verbose) ############################################################################################################################ # mmsystem module elements ############################################################################################################################ mmsystem_functions = %w( addmonths copytext cuttext deltext endswith expandpath fcopy fdelete findfiles findtext fmove getasnumber getchar getcwd getdate getday getdaynum getdays getdirsep getendparse setendparse getenv getfsize getfstat getftime gethour getminute getmonth getmsec getpathsep getqtype setqtype getsecond getsepchar setsepchar getsize getstart setstart getsucc setsucc getsysinfo getsysstat gettime gettmpdir gettrim settrim getweekday getyear inserttext isvalid makedir makepath newtar newzip nextfield openpipe parseextn parseint parsereal parsetext pastetext pathmatch pathsplit qsort quote readtextline regmatch regreplace removedir removefiles setchar setdate setday setenv sethour setminute setmonth setmsec setsecond settime setyear sleep startswith system tarlist textfmt tolower toupper trim untar unzip ziplist ) mmsystem_parameters = %w(datefmt datetimefmt monthnames sys_endparse sys_fillchar sys_pid sys_qtype sys_regcache sys_sepchar) ############################################################################################################################ # mmjobs module elements ############################################################################################################################ mmjobs_instance_mgmt_functions = %w( clearaliases connect disconnect findxsrvs getaliases getbanner gethostalias sethostalias ) mmjobs_model_mgmt_functions = %w( compile detach getannidents getannotations getexitcode getgid getid getnode getrmtid getstatus getuid load reset resetmodpar run setcontrol setdefstream setmodpar setworkdir stop unload ) mmjobs_synchornization_functions = %w( dropnextevent getclass getfromgid getfromid getfromuid getnextevent getvalue isqueueempty nullevent peeknextevent send setgid setuid wait waitfor ) mmjobs_functions = mmjobs_instance_mgmt_functions + mmjobs_model_mgmt_functions + mmjobs_synchornization_functions mmjobs_parameters = %w(conntmpl defaultnode fsrvdelay fsrvnbiter fsrvport jobid keepalive nodenumber parentnumber) state :whitespace do # Spaces rule %r/\s+/m, Text # ! Comments rule %r((!).*$\n?), Comment::Single # (! Comments !) rule %r(\(!.*?!\))m, Comment::Multiline end # From Mosel documentation: # Constant strings of characters must be quoted with single (') or double quote (") and may extend over several lines. Strings enclosed in double quotes may contain C-like escape sequences introduced by the 'backslash' # character (\a \b \f \n \r \t \v \xxx with xxx being the character code as an octal number). # Each sequence is replaced by the corresponding control character (e.g. \n is the `new line' command) or, if no control character exists, by the second character of the sequence itself (e.g. \\ is replaced by '\'). # The escape sequences are not interpreted if they are contained in strings that are enclosed in single quotes. state :single_quotes do rule %r/'/, Str::Single, :pop! rule %r/[^']+/, Str::Single end state :double_quotes do rule %r/"/, Str::Double, :pop! rule %r/(\\"|\\[0-7]{1,3}\D|\\[abfnrtv]|\\\\)/, Str::Escape rule %r/[^"]/, Str::Double end state :base do rule %r{"}, Str::Double, :double_quotes rule %r{'}, Str::Single, :single_quotes rule %r{((0(x|X)[0-9a-fA-F]*)|(([0-9]+\.?[0-9]*)|(\.[0-9]+))((e|E)(\+|-)?[0-9]+)?)(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?}, Num rule %r{[~!@#\$%\^&\*\(\)\+`\-={}\[\]:;<>\?,\.\/\|\\]}, Punctuation # rule %r{'([^']|'')*'}, Str # rule %r/"(\\\\|\\"|[^"])*"/, Str rule %r/(true|false)\b/i, Name::Builtin rule %r/\b(#{core_keywords.join('|')})\b/i, Keyword rule %r/\b(#{core_functions.join('|')})\b/, Name::Builtin rule %r/\b(#{mmxprs_functions.join('|')})\b/, Name::Function rule %r/\b(#{mmxpres_constants.join('|')})\b/, Name::Constant rule %r/\b(#{mmxprs_parameters.join('|')})\b/i, Name::Property rule %r/\b(#{mmsystem_functions.join('|')})\b/i, Name::Function rule %r/\b(#{mmsystem_parameters.join('|')})\b/, Name::Property rule %r/\b(#{mmjobs_functions.join('|')})\b/i, Name::Function rule %r/\b(#{mmjobs_parameters.join('|')})\b/, Name::Property rule id, Name end state :root do mixin :whitespace mixin :base end end end end
38.309013
224
0.574726
083bc00587fdac75a9e65ea207037b206a09a388
2,796
# frozen_string_literal: true require 'uri' module BrickFTP module RESTfulAPI # Overview of uploading # # @see https://developers.files.com/#overview-of-uploading Overview of uploading # # ### Uploading files using the REST API is done in 3 stages: # # 1. {https://developers.files.com/#starting-a-new-upload Start a new upload} by sending a request to REST API to indicate intent to upload a file. # 2. {https://developers.files.com/#uploading-the-file-or-file-parts Upload the file} to the URL(s) provided by the REST API, possibly in parts via multiple uploads. # 3. {https://developers.files.com/#completing-an-upload Complete the upload} by notifying the REST API that the file upload has completed. # class UploadFile include Command CHUNK_SIZE_RANGE = 5_242_880..5_368_709_120 # At this point, you are to send a PUT request to the returned upload_uri with the file data, # along with the headers and parameters provided to you from BrickFTP. # # The upload_uri link is signed by BrickFTP and must be used within 15 minutes. # You will receive an HTTP 200 response with no body upon successful upload. # # Should you wish to upload the file in multiple parts (required if the file size exceeds 5 GB) # you will need to request an additional upload URL for the next part. # # @param [String] path Full path of the file or folder. Maximum of 550 characters. # @param [IO] data # @param [Integer, nil] chunk_size the chunk sizes are required to be between 5 MB and 5 GB. # This option is ignored if `data` is `StringIO`. # @return [BrickFTP::Types::File] File object # def call(path, data, chunk_size: nil) chunk_size = adjust_chunk_size(data, chunk_size) validate_range_of_chunk_size!(chunk_size) upload = StartUpload.new(client).call(path) chunk_io = BrickFTP::Utils::ChunkIO.new(data, chunk_size: chunk_size) rest = data.size chunk_io.each do |chunk| rest -= client.upload_file(upload.http_method, upload.upload_uri, chunk) break if !chunk_size || rest <= 0 upload = ContinueUpload.new(client).call(path, ref: upload.ref, part: upload.part_number + 1) end CompleteUpload.new(client).call(path, ref: upload.ref) end private # To single uploading if chunk_size less than equals data size. def adjust_chunk_size(data, chunk_size) chunk_size && chunk_size >= data.size ? nil : chunk_size end def validate_range_of_chunk_size!(chunk_size) raise ArgumentError, 'chunk_size must be between 5MB and 5GB' if chunk_size && !CHUNK_SIZE_RANGE.cover?(chunk_size) end end end end
41.731343
169
0.682403
7aecc9d62f9b1e52f1498c45cad4f7988969e3ae
438
require 'pdk/config/namespace' module PDK class Config class JSON < Namespace def parse_data(data, _filename) return {} if data.nil? || data.empty? require 'json' ::JSON.parse(data) rescue ::JSON::ParserError => e raise PDK::Config::LoadError, e.message end def serialize_data(data) require 'json' ::JSON.pretty_generate(data) end end end end
18.25
47
0.593607
bfc42684abad519515b0df3644b16133061f0f82
3,546
module ControllerHelpers include VCAP::CloudController HTTPS_ENFORCEMENT_SCENARIOS = [ { protocol: 'http', config_setting: nil, user: 'user', success: true }, { protocol: 'http', config_setting: nil, user: 'admin', success: true }, { protocol: 'https', config_setting: nil, user: 'user', success: true }, { protocol: 'https', config_setting: nil, user: 'admin', success: true }, # Next with https_required { protocol: 'http', config_setting: :https_required, user: 'user', success: false }, { protocol: 'http', config_setting: :https_required, user: 'admin', success: false }, { protocol: 'https', config_setting: :https_required, user: 'user', success: true }, { protocol: 'https', config_setting: :https_required, user: 'admin', success: true }, # Finally with https_required_for_admins { protocol: 'http', config_setting: :https_required_for_admins, user: 'user', success: true }, { protocol: 'http', config_setting: :https_required_for_admins, user: 'admin', success: false }, { protocol: 'https', config_setting: :https_required_for_admins, user: 'user', success: true }, { protocol: 'https', config_setting: :https_required_for_admins, user: 'admin', success: true } ] def self.description_for_inline_depth(depth, pagination=50) if depth "?inline-relations-depth=#{depth}&results-per-page=#{pagination}" else '' end end def query_params_for_inline_depth(depth, pagination=50) if depth { 'inline-relations-depth' => depth, 'results-per-page' => pagination } else { 'results-per-page' => pagination } end end def normalize_attributes(value) case value when Hash stringified = {} value.each do |k, v| stringified[k] = normalize_attributes(v) end stringified when Array value.collect { |x| normalize_attributes(x) } when Numeric, nil, true, false value when Time value.iso8601 else value.to_s end end def app FakeFrontController.new(TestConfig.config) end def headers_for(user, opts={}) opts = { email: Sham.email, https: false }.merge(opts) headers = {} token_coder = CF::UAA::TokenCoder.new(audience_ids: TestConfig.config[:uaa][:resource_id], skey: TestConfig.config[:uaa][:symmetric_secret], pkey: nil) scopes = opts[:scopes] if scopes.nil? && user scopes = user.admin? ? %w(cloud_controller.admin) : %w(cloud_controller.read cloud_controller.write) end if user user_token = token_coder.encode( user_id: user ? user.guid : (rand * 1_000_000_000).ceil, email: opts[:email], scope: scopes ) headers['HTTP_AUTHORIZATION'] = "bearer #{user_token}" end headers['HTTP_X_FORWARDED_PROTO'] = 'https' if opts[:https] headers end def json_headers(headers) headers.merge({ 'CONTENT_TYPE' => 'application/json' }) end def decoded_response(options={}) parse(last_response.body, options) end def parse(json, options={}) MultiJson.load(json, options) end def metadata decoded_response['metadata'] end def entity decoded_response['entity'] end def admin_user @admin_user ||= VCAP::CloudController::User.make(admin: true) end def admin_headers @admin_headers ||= headers_for(admin_user) end def escape_query(string) URI.encode(string, /[<>;:, ]/) end end
28.596774
106
0.642132
115b67d98fb25094af123205268827c4e48bc3f0
11,494
# If you need to modify the existing seed repository for your tests, # it is recommended that you make the changes on the `markdown` branch of the seed project repository, # which should only be used by tests in this file. See `/spec/factories.rb#project` for more info. class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps include SharedAuthentication include SharedPaths include SharedMarkdown step 'I own project "Delta"' do @project = Project.find_by(name: "Delta") @project ||= create(:project, :repository, name: "Delta", namespace: @user.namespace) @project.team << [@user, :master] end step 'I should see files from repository in markdown' do expect(current_path).to eq namespace_project_tree_path(@project.namespace, @project, "markdown") expect(page).to have_content "README.md" expect(page).to have_content "CHANGELOG" end step 'I should see rendered README which contains correct links' do expect(page).to have_content "Welcome to GitLab GitLab is a free project and repository management application" expect(page).to have_link "GitLab API doc" expect(page).to have_link "GitLab API website" expect(page).to have_link "Rake tasks" expect(page).to have_link "backup and restore procedure" expect(page).to have_link "GitLab API doc directory" expect(page).to have_link "Maintenance" end step 'I click on Gitlab API in README' do click_link "GitLab API doc" end step 'I should see correct document rendered' do expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/README.md") expect(page).to have_content "All API requests require authentication" end step 'I click on Rake tasks in README' do click_link "Rake tasks" end step 'I should see correct directory rendered' do expect(current_path).to eq namespace_project_tree_path(@project.namespace, @project, "markdown/doc/raketasks") expect(page).to have_content "backup_restore.md" expect(page).to have_content "maintenance.md" end step 'I click on GitLab API doc directory in README' do click_link "GitLab API doc directory" end step 'I should see correct doc/api directory rendered' do expect(current_path).to eq namespace_project_tree_path(@project.namespace, @project, "markdown/doc/api") expect(page).to have_content "README.md" expect(page).to have_content "users.md" end step 'I click on Maintenance in README' do click_link "Maintenance" end step 'I should see correct maintenance file rendered' do expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/raketasks/maintenance.md") expect(page).to have_content "bundle exec rake gitlab:env:info RAILS_ENV=production" end step 'I click on link "empty" in the README' do page.within('.readme-holder') do click_link "empty" end end step 'I click on link "id" in the README' do page.within('.readme-holder') do click_link "#id" end end step 'I navigate to the doc/api/README' do page.within '.tree-table' do click_link "doc" end page.within '.tree-table' do click_link "api" end page.within '.tree-table' do click_link "README.md" end end step 'I see correct file rendered' do expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/README.md") expect(page).to have_content "Contents" expect(page).to have_link "Users" expect(page).to have_link "Rake tasks" end step 'I click on users in doc/api/README' do click_link "Users" end step 'I should see the correct document file' do expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/users.md") expect(page).to have_content "Get a list of users." end step 'I click on raketasks in doc/api/README' do click_link "Rake tasks" end # Markdown branch When 'I visit markdown branch' do visit namespace_project_tree_path(@project.namespace, @project, "markdown") end When 'I visit markdown branch "README.md" blob' do visit namespace_project_blob_path(@project.namespace, @project, "markdown/README.md") end When 'I visit markdown branch "d" tree' do visit namespace_project_tree_path(@project.namespace, @project, "markdown/d") end When 'I visit markdown branch "d/README.md" blob' do visit namespace_project_blob_path(@project.namespace, @project, "markdown/d/README.md") end step 'I should see files from repository in markdown branch' do expect(current_path).to eq namespace_project_tree_path(@project.namespace, @project, "markdown") expect(page).to have_content "README.md" expect(page).to have_content "CHANGELOG" end step 'I see correct file rendered in markdown branch' do expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/README.md") expect(page).to have_content "Contents" expect(page).to have_link "Users" expect(page).to have_link "Rake tasks" end step 'I should see correct document rendered for markdown branch' do expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/README.md") expect(page).to have_content "All API requests require authentication" end step 'I should see correct directory rendered for markdown branch' do expect(current_path).to eq namespace_project_tree_path(@project.namespace, @project, "markdown/doc/raketasks") expect(page).to have_content "backup_restore.md" expect(page).to have_content "maintenance.md" end step 'I should see the users document file in markdown branch' do expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/users.md") expect(page).to have_content "Get a list of users." end # Expected link contents step 'The link with text "empty" should have url "tree/markdown"' do find('a', text: /^empty$/)['href'] == current_host + namespace_project_tree_path(@project.namespace, @project, "markdown") end step 'The link with text "empty" should have url "blob/markdown/README.md"' do find('a', text: /^empty$/)['href'] == current_host + namespace_project_blob_path(@project.namespace, @project, "markdown/README.md") end step 'The link with text "empty" should have url "tree/markdown/d"' do find('a', text: /^empty$/)['href'] == current_host + namespace_project_tree_path(@project.namespace, @project, "markdown/d") end step 'The link with text "empty" should have '\ 'url "blob/markdown/d/README.md"' do find('a', text: /^empty$/)['href'] == current_host + namespace_project_blob_path(@project.namespace, @project, "markdown/d/README.md") end step 'The link with text "ID" should have url "tree/markdownID"' do find('a', text: /^#id$/)['href'] == current_host + namespace_project_tree_path(@project.namespace, @project, "markdown") + '#id' end step 'The link with text "/ID" should have url "tree/markdownID"' do find('a', text: /^\/#id$/)['href'] == current_host + namespace_project_tree_path(@project.namespace, @project, "markdown") + '#id' end step 'The link with text "README.mdID" '\ 'should have url "blob/markdown/README.mdID"' do find('a', text: /^README.md#id$/)['href'] == current_host + namespace_project_blob_path(@project.namespace, @project, "markdown/README.md") + '#id' end step 'The link with text "d/README.mdID" should have '\ 'url "blob/markdown/d/README.mdID"' do find('a', text: /^d\/README.md#id$/)['href'] == current_host + namespace_project_blob_path(@project.namespace, @project, "d/markdown/README.md") + '#id' end step 'The link with text "ID" should have url "blob/markdown/README.mdID"' do find('a', text: /^#id$/)['href'] == current_host + namespace_project_blob_path(@project.namespace, @project, "markdown/README.md") + '#id' end step 'The link with text "/ID" should have url "blob/markdown/README.mdID"' do find('a', text: /^\/#id$/)['href'] == current_host + namespace_project_blob_path(@project.namespace, @project, "markdown/README.md") + '#id' end # Wiki step 'I go to wiki page' do click_link "Wiki" expect(current_path).to eq namespace_project_wiki_path(@project.namespace, @project, "home") end step 'I add various links to the wiki page' do fill_in "wiki[content]", with: "[test](test)\n[GitLab API doc](api)\n[Rake tasks](raketasks)\n" fill_in "wiki[message]", with: "Adding links to wiki" page.within '.wiki-form' do click_button "Create page" end end step 'Wiki page should have added links' do expect(current_path).to eq namespace_project_wiki_path(@project.namespace, @project, "home") expect(page).to have_content "test GitLab API doc Rake tasks" end step 'I add a header to the wiki page' do fill_in "wiki[content]", with: "# Wiki header\n" fill_in "wiki[message]", with: "Add header to wiki" page.within '.wiki-form' do click_button "Create page" end end step 'Wiki header should have correct id and link' do header_should_have_correct_id_and_link(1, 'Wiki header', 'wiki-header') end step 'I click on test link' do click_link "test" end step 'I see new wiki page named test' do expect(current_path).to eq namespace_project_wiki_path(@project.namespace, @project, "test") page.within(:css, ".nav-text") do expect(page).to have_content "Test" expect(page).to have_content "Create Page" end end When 'I go back to wiki page home' do visit namespace_project_wiki_path(@project.namespace, @project, "home") expect(current_path).to eq namespace_project_wiki_path(@project.namespace, @project, "home") end step 'I click on GitLab API doc link' do click_link "GitLab API" end step 'I see Gitlab API document' do expect(current_path).to eq namespace_project_wiki_path(@project.namespace, @project, "api") page.within(:css, ".nav-text") do expect(page).to have_content "Create" expect(page).to have_content "Api" end end step 'I click on Rake tasks link' do click_link "Rake tasks" end step 'I see Rake tasks directory' do expect(current_path).to eq namespace_project_wiki_path(@project.namespace, @project, "raketasks") page.within(:css, ".nav-text") do expect(page).to have_content "Create" expect(page).to have_content "Rake" end end step 'I go directory which contains README file' do visit namespace_project_tree_path(@project.namespace, @project, "markdown/doc/api") expect(current_path).to eq namespace_project_tree_path(@project.namespace, @project, "markdown/doc/api") end step 'I click on a relative link in README' do click_link "Users" end step 'I should see the correct markdown' do expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/users.md") expect(page).to have_content "List users" end step 'Header "Application details" should have correct id and link' do header_should_have_correct_id_and_link(2, 'Application details', 'application-details') end step 'Header "GitLab API" should have correct id and link' do header_should_have_correct_id_and_link(1, 'GitLab API', 'gitlab-api') end end
37.685246
156
0.715591
f868cdbe544c445dce7cee5f350f8385e4648c8a
3,518
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with this # work for additional information regarding copyright ownership. The ASF # licenses this file to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. require File.join(File.dirname(__FILE__), '../spec_helpers') Spec::Runner.configure do |config| config.include SpecHelpers end describe OSGi::Registry do it 'should be possible to set the containers from the OSGi environment variables' do ENV['OSGi'] = "foo;bar" OSGi.registry.containers.should == ["foo","bar"] end it 'should fall back on OSGI if the constant OSGi is not defined, issuing a warning' do ENV['OSGi'] = nil ENV['OSGI'] = "foo;bar" lambda {OSGi.registry.resolved_containers}.should show_warning "The correct constant to define for the OSGi containers is named OSGi" ENV['OSGi'].should == ENV['OSGI'] end it 'should not complain if OSGI is set and OSGi is also set' do ENV['OSGI'] = nil lambda {OSGi.registry.resolved_containers}.should_not show_warning "The correct constant to define for the OSGi containers is named OSGi" end it 'should be possible to modify the containers in the registry before the resolved_containers method is called' do lambda {OSGi.registry.containers << "hello"}.should_not raise_error lambda {OSGi.registry.containers = ["hello"]}.should_not raise_error end it 'should throw an exception when modifying the containers in the registry after the resolved_containers method is called' do OSGi.registry.resolved_containers lambda {OSGi.registry.containers << "hello"}.should raise_error(TypeError) lambda {OSGi.registry.containers = ["hello"]}.should raise_error(RuntimeError, /Cannot set containers, containers have been resolved already/) end end describe OSGi do it 'should give a handle over the OSGi containers registry' do OSGi.registry.should be_instance_of(::OSGi::Registry) end it 'should help determine whether a package is part of the framework given by the execution environment' do OSGi.is_framework_package?("com.mypackage").should be_false OSGi.is_framework_package?(OSGi::JAVASE16.packages.first).should be_true end end describe OSGi::GroupMatcher do it 'should use osgi as the default group for an artifact' do OSGi::GroupMatcher.instance.group("hello").should == "osgi" end it 'should use org.eclipse as the default group for Eclipse artifacts' do OSGi::GroupMatcher.instance.group("org.eclipse.core.resources").should == "org.eclipse" end it 'should let users specify their own groups' do OSGi::GroupMatcher.instance.group_matchers << Proc.new {|name| "bar" if name.match /foo$/} OSGi::GroupMatcher.instance.group("org.eclipse.core.resources").should == "org.eclipse" OSGi::GroupMatcher.instance.group("hello").should == "osgi" OSGi::GroupMatcher.instance.group("org.eclipse.core.foo").should == "bar" end end
41.880952
146
0.744457
38b2d7fbbff8e64178ce5bacb149f5ac789fdbcc
1,181
require 'rspec' RSpec.describe Deflate::HuffmanTable do let(:table) { Deflate::HuffmanTable.new(bootstrap) } describe "#initialize" do # the example documented in 3.2.2 of RFC1951 # https://tools.ietf.org/html/rfc1951 context "with alphabet ABCDEFGH" do let(:bootstrap) { {(65..69) => 3, (70..70) => 2, (71..72) => 4} } it "sets values correctly" do expect(table.values).to eq( [ Deflate::HuffmanLength.new(bit_count: 2, symbol: 70, code: 0), # F 00 Deflate::HuffmanLength.new(bit_count: 3, symbol: 65, code: 2), # A 010 Deflate::HuffmanLength.new(bit_count: 3, symbol: 66, code: 3), # B 011 Deflate::HuffmanLength.new(bit_count: 3, symbol: 67, code: 4), # C 100 Deflate::HuffmanLength.new(bit_count: 3, symbol: 68, code: 5), # D 101 Deflate::HuffmanLength.new(bit_count: 3, symbol: 69, code: 6), # E 110 Deflate::HuffmanLength.new(bit_count: 4, symbol: 71, code: 14), # G 1110 Deflate::HuffmanLength.new(bit_count: 4, symbol: 72, code: 15), # H 1111 ] ) end end end end
38.096774
85
0.577477
79b1ad645e562fbe9bf0e5698c66eb3d9726226f
1,483
class Sourcedocs < Formula desc "Generate Markdown files from inline source code documentation" homepage "https://github.com/eneko/SourceDocs" url "https://github.com/eneko/sourcedocs/archive/1.2.0.tar.gz" sha256 "edfbe37a267be4d5ddd795c74522dcbb72b6fd42e11a0922c3ad87f4bac0e55f" bottle do cellar :any_skip_relocation sha256 "32bc59646532b362651b126946cbf051a90b2b1da5d07a614d50fc0b0bc1efd1" => :catalina sha256 "3bfe25d253eecef289c822012efddc14d9bd331eba0f3f54fe88e7d0cf2aa924" => :mojave end depends_on :xcode => ["10.3", :build, :test] def install system "swift", "build", "--disable-sandbox", "-c", "release" bin.install ".build/release/sourcedocs" end test do assert_match "SourceDocs v#{version}", shell_output("#{bin}/sourcedocs version") # There are some issues with SourceKitten running in sandbox mode in Mojave # The following test has been disabled on Mojave until that issue is resolved # - https://github.com/Homebrew/homebrew/pull/50211 # - https://github.com/Homebrew/homebrew-core/pull/32548 if MacOS.version < "10.14" mkdir "foo" do system "swift", "package", "init" system "swift", "build", "--disable-sandbox" system "#{bin}/sourcedocs", "generate", "--spm-module", "foo", "--output-folder", testpath/"Documentation/Reference" assert_predicate testpath/"Documentation/Reference/README.md", :exist? end end end end
38.025641
90
0.701955
2194b2c57f9d6a39d02bed6cceaa19660bf476dd
2,689
class Perkeep < Formula desc "Lets you permanently keep your stuff, for life" homepage "https://perkeep.org/" license "Apache-2.0" stable do url "https://github.com/perkeep/perkeep.git", tag: "0.10", revision: "0cbe4d5e05a40a17efe7441d75ce0ffdf9d6b9f5" # gopherjs doesn't tag releases, so just pick the most recent revision for now resource "gopherjs" do url "https://github.com/gopherjs/gopherjs/archive/fce0ec30dd00773d3fa974351d04ce2737b5c4d9.tar.gz" sha256 "e5e6ede5f710fde77e48aa1f6a9b75f5afeb1163223949f76c1300ae44263b84" end depends_on "[email protected]" => :build end bottle do rebuild 1 sha256 cellar: :any_skip_relocation, catalina: "36f18ad54a3e656ac5da55fc438636aac922e107ad1082e0dad7353626f0db84" sha256 cellar: :any_skip_relocation, mojave: "51f41c16b3c4ea80d6a77c5badf28dca0ec323bd5aa2f1f90e855ce568b1c8ca" sha256 cellar: :any_skip_relocation, high_sierra: "b188c23945a51d253dc6c4435afaa509a2ddaf151124ef1f08a1186611041c92" end head do url "https://github.com/perkeep/perkeep.git" depends_on "go" => :build end depends_on "pkg-config" => :build conflicts_with "hello", because: "both install `hello` binaries" def install if build.stable? ENV["GOPATH"] = buildpath ENV["CAMLI_GOPHERJS_GOROOT"] = Formula["[email protected]"].opt_libexec (buildpath/"src/perkeep.org").install buildpath.children # Vendored version of gopherjs requires go 1.10, so use the newest available gopherjs, which # supports up to go 1.12 rm_rf buildpath/"src/perkeep.org/vendor/github.com/gopherjs/gopherjs" resource("gopherjs").stage buildpath/"src/perkeep.org/vendor/github.com/gopherjs/gopherjs" cd "src/perkeep.org" do system "go", "run", "make.go" end bin.install Dir["bin/*"].select { |f| File.executable? f } else system "go", "run", "make.go" bin.install Dir[".brew_home/go/bin/*"].select { |f| File.executable? f } end end plist_options manual: "perkeepd" def plist <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <true/> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/perkeepd</string> <string>-openbrowser=false</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> EOS end test do system bin/"pk-get", "-version" end end
30.556818
120
0.663444
5de407bc533fef8510054a0a82783b671a846f79
1,013
require 'ostruct' require 'digest' module CloudSesame module Domain module ClientModule module Caching class RailsCache < Base def initialize(client, searchable) ensure_environment_exists super end def fetch(params) Rails.cache.fetch(hexdigest(params)) do results = search params OpenStruct.new( status: results.status, hits: results.hits, facets: results.facets ) end end private def hexdigest(params) searchable_params = params.merge(searchable: @searchable) Digest::MD5.hexdigest Marshal.dump(searchable_params) end def ensure_environment_exists unless RailsCache.const_defined?(:Rails) raise Error::Caching, "Rails environment cannot be found" end end end end end end end
23.022727
71
0.548865
61217affd75269607cf6ad08f44baf8db0534e99
1,407
module FFaker module PhoneNumberCH extend ModuleUtils extend self COUNTRY_PREFIX = %w[+41 0041 0].freeze AREA_PREFIX = %w[21 22 24 26 27 31 32 33 34 41 43 44 51 52 56 58 61 62 71 81 91].freeze MOBILE_PREFIX = %w[74 75 76 77 78 79].freeze FREE_PHONE_PREFIX = %w[800].freeze SHARED_COST_PREFIX = %w[840 842 844 848].freeze PREMIUM_RATE_PREFIX = %w[900 901 906].freeze PHONE_NUMBER = ['#######', ' ### ## ##'].freeze def phone_number case rand(0..4) when 0 then home_work_phone_number when 1 then mobile_phone_number when 2 then free_phone_number when 3 then shared_cost_phone_number when 4 then premium_rate_phone_number end end def home_work_phone_number FFaker.numerify "#{COUNTRY_PREFIX.sample}#{AREA_PREFIX.sample}#{PHONE_NUMBER.sample}" end def mobile_phone_number FFaker.numerify "#{COUNTRY_PREFIX.sample}#{MOBILE_PREFIX.sample}#{PHONE_NUMBER.sample}" end def free_phone_number FFaker.numerify "#{COUNTRY_PREFIX.sample}#{FREE_PHONE_PREFIX.sample}#{PHONE_NUMBER.sample}" end def shared_cost_phone_number FFaker.numerify "#{COUNTRY_PREFIX.sample}#{SHARED_COST_PREFIX.sample}#{PHONE_NUMBER.sample}" end def premium_rate_phone_number FFaker.numerify "#{COUNTRY_PREFIX.sample}#{PREMIUM_RATE_PREFIX.sample}#{PHONE_NUMBER.sample}" end end end
31.266667
99
0.702914
28382fc45c51b47a4c96b20b43709af975ac56e1
704
require 'rdb2spreadsheet/rdb_client' module Rdb2spreadsheet class DataAdapter attr_reader :rdb_client, :spreadsheet_client def initialize(db_configs, spreadsheet_configs) @rdb_client = RdbClient.new(db_configs) @spreadsheet_client = SpreadsheetClient.new(spreadsheet_configs) end def import_all(book_key, sqls) @spreadsheet_client.open_book_by_key(book_key) sqls.each do |worksheet, sql| puts worksheet + ' updating' headers, records = @rdb_client.select(sql) next if headers.nil? || records.nil? @spreadsheet_client.update_worksheet(worksheet, headers, records) puts worksheet + ' updated' end end end end
29.333333
73
0.710227
799a65ac7c9acfa77e351213ae7b7cc3a4299ddc
1,528
class Abook < Formula desc "Address book with mutt support" homepage "http://abook.sourceforge.net/" url "https://downloads.sourceforge.net/project/abook/abook/0.5.6/abook-0.5.6.tar.gz" sha256 "0646f6311a94ad3341812a4de12a5a940a7a44d5cb6e9da5b0930aae9f44756e" head "git://git.code.sf.net/p/abook/git" bottle do sha256 "3aeddea7c0bb71c664a2df2d8974df26d156f25f5a2ff993060396f0af22b574" => :yosemite sha256 "87ee3c353da4421ac95d43dcf6581a8ee60f9c8b6c2a1821b498dabbab60942e" => :mavericks sha256 "882983ecabf61b120b50eb313c698bc85806d95dd8712375f64decd2f2ebce59" => :mountain_lion end devel do url "http://abook.sourceforge.net/devel/abook-0.6.0pre2.tar.gz" sha256 "59d444504109dd96816e003b3023175981ae179af479349c34fa70bc12f6d385" version "0.6.0pre2" # Remove `inline` from function implementation for clang compatibility patch :DATA end depends_on "readline" def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}" system "make", "install" end test do system "#{bin}/abook", "--formats" end end __END__ diff --git a/database.c b/database.c index 7c47ab6..53bdb9f 100644 --- a/database.c +++ b/database.c @@ -762,7 +762,7 @@ item_duplicate(list_item dest, list_item src) */ /* quick lookup by "standard" field number */ -inline int +int field_id(int i) { assert((i >= 0) && (i < ITEM_FIELDS));
29.384615
95
0.691754
03a9ebc243f2e4c0cf489581353ef75c59e00a74
3,906
# typed: strict # frozen_string_literal: true require "time" module Spoom # Execute git commands module Git extend T::Sig # Execute a `command` sig { params(command: String, arg: String, path: String).returns(ExecResult) } def self.exec(command, *arg, path: '.') return ExecResult.new( out: "", err: "Error: `#{path}` is not a directory.", status: false, exit_code: 1 ) unless File.directory?(path) T.unsafe(Open3).popen3(command, *arg, chdir: path) do |_, stdout, stderr, thread| status = T.cast(thread.value, Process::Status) ExecResult.new( out: stdout.read, err: stderr.read, status: T.must(status.success?), exit_code: T.must(status.exitstatus) ) end end # Git commands sig { params(arg: String, path: String).returns(ExecResult) } def self.checkout(*arg, path: ".") exec("git checkout -q #{arg.join(' ')}", path: path) end sig { params(arg: String, path: String).returns(ExecResult) } def self.diff(*arg, path: ".") exec("git diff #{arg.join(' ')}", path: path) end sig { params(arg: String, path: String).returns(ExecResult) } def self.log(*arg, path: ".") exec("git log #{arg.join(' ')}", path: path) end sig { params(arg: String, path: String).returns(ExecResult) } def self.rev_parse(*arg, path: ".") exec("git rev-parse --short #{arg.join(' ')}", path: path) end sig { params(arg: String, path: String).returns(ExecResult) } def self.show(*arg, path: ".") exec("git show #{arg.join(' ')}", path: path) end sig { params(path: String).returns(T.nilable(String)) } def self.current_branch(path: ".") result = exec("git branch --show-current", path: path) return nil unless result.status result.out.strip end # Utils # Get the commit epoch timestamp for a `sha` sig { params(sha: String, path: String).returns(T.nilable(Integer)) } def self.commit_timestamp(sha, path: ".") result = show("--no-notes --no-patch --pretty=%at #{sha}", path: path) return nil unless result.status result.out.strip.to_i end # Get the commit Time for a `sha` sig { params(sha: String, path: String).returns(T.nilable(Time)) } def self.commit_time(sha, path: ".") timestamp = commit_timestamp(sha, path: path) return nil unless timestamp epoch_to_time(timestamp.to_s) end # Get the last commit sha sig { params(path: String).returns(T.nilable(String)) } def self.last_commit(path: ".") result = rev_parse("HEAD", path: path) return nil unless result.status result.out.strip end # Translate a git epoch timestamp into a Time sig { params(timestamp: String).returns(Time) } def self.epoch_to_time(timestamp) Time.strptime(timestamp, "%s") end # Is there uncommited changes in `path`? sig { params(path: String).returns(T::Boolean) } def self.workdir_clean?(path: ".") diff("HEAD", path: path).out.empty? end # Get the hash of the commit introducing the `sorbet/config` file sig { params(path: String).returns(T.nilable(String)) } def self.sorbet_intro_commit(path: ".") result = Spoom::Git.log("--diff-filter=A --format='%h' -1 -- sorbet/config", path: path) return nil unless result.status out = result.out.strip return nil if out.empty? out end # Get the hash of the commit removing the `sorbet/config` file sig { params(path: String).returns(T.nilable(String)) } def self.sorbet_removal_commit(path: ".") result = Spoom::Git.log("--diff-filter=D --format='%h' -1 -- sorbet/config", path: path) return nil unless result.status out = result.out.strip return nil if out.empty? out end end end
31.248
94
0.614183
617a4d28e27f69dd0a03f5525b8cdb66cdf85f96
726
# frozen_string_literal: true require 'support' require 'mustermann/equality_map' RSpec.describe Mustermann::EqualityMap do before { GC.disable } after { GC.enable } describe :fetch do subject { Mustermann::EqualityMap.new } specify 'with existing entry' do next if subject.is_a? Hash subject.fetch("foo") { "foo" } result = subject.fetch("foo") { "bar" } expect(result).to be == "foo" end specify 'with GC-removed entry' do next if subject.is_a? Hash subject.fetch(String.new('foo')) { "foo" } expect(subject.map).to receive(:[]).and_return(nil) result = subject.fetch(String.new('foo')) { "bar" } expect(result).to be == "bar" end end end
26.888889
57
0.637741
7971eb8849db573eea34fe401a70e054b60251a5
9,559
# frozen_string_literal: true require 'spec_helper' describe IssuablesHelper do let(:label) { build_stubbed(:label) } let(:label2) { build_stubbed(:label) } describe '#users_dropdown_label' do let(:user) { build_stubbed(:user) } let(:user2) { build_stubbed(:user) } it 'returns unassigned' do expect(users_dropdown_label([])).to eq('Unassigned') end it 'returns selected user\'s name' do expect(users_dropdown_label([user])).to eq(user.name) end it 'returns selected user\'s name and counter' do expect(users_dropdown_label([user, user2])).to eq("#{user.name} + 1 more") end end describe '#group_dropdown_label' do let(:group) { create(:group) } let(:default) { 'default label' } it 'returns default group label when group_id is nil' do expect(group_dropdown_label(nil, default)).to eq('default label') end it 'returns "any group" when group_id is 0' do expect(group_dropdown_label('0', default)).to eq('Any group') end it 'returns group full path when a group was found for the provided id' do expect(group_dropdown_label(group.id, default)).to eq(group.full_name) end it 'returns default label when a group was not found for the provided id' do expect(group_dropdown_label(9999, default)).to eq('default label') end end describe '#issuable_labels_tooltip' do let(:label_entity) { LabelEntity.represent(label).as_json } let(:label2_entity) { LabelEntity.represent(label2).as_json } it 'returns label text with no labels' do expect(issuable_labels_tooltip([])).to eq(_('Labels')) end it 'returns label text with labels within max limit' do expect(issuable_labels_tooltip([label_entity])).to eq(label[:title]) end it 'returns label text with labels exceeding max limit' do expect(issuable_labels_tooltip([label_entity, label2_entity], limit: 1)).to eq("#{label[:title]}, and 1 more") end end describe '#issuables_state_counter_text' do let(:user) { create(:user) } describe 'state text' do before do allow(helper).to receive(:issuables_count_for_state).and_return(42) end it 'returns "Open" when state is :opened' do expect(helper.issuables_state_counter_text(:issues, :opened, true)) .to eq('<span>Open</span> <span class="badge badge-pill">42</span>') end it 'returns "Closed" when state is :closed' do expect(helper.issuables_state_counter_text(:issues, :closed, true)) .to eq('<span>Closed</span> <span class="badge badge-pill">42</span>') end it 'returns "Merged" when state is :merged' do expect(helper.issuables_state_counter_text(:merge_requests, :merged, true)) .to eq('<span>Merged</span> <span class="badge badge-pill">42</span>') end it 'returns "All" when state is :all' do expect(helper.issuables_state_counter_text(:merge_requests, :all, true)) .to eq('<span>All</span> <span class="badge badge-pill">42</span>') end end end describe '#issuable_reference' do context 'when show_full_reference truthy' do it 'display issuable full reference' do assign(:show_full_reference, true) issue = build_stubbed(:issue) expect(helper.issuable_reference(issue)).to eql(issue.to_reference(full: true)) end end context 'when show_full_reference falsey' do context 'when @group present' do it 'display issuable reference to @group' do project = build_stubbed(:project) assign(:show_full_reference, nil) assign(:group, project.namespace) issue = build_stubbed(:issue) expect(helper.issuable_reference(issue)).to eql(issue.to_reference(project.namespace)) end end context 'when @project present' do it 'display issuable reference to @project' do project = build_stubbed(:project) assign(:show_full_reference, nil) assign(:group, nil) assign(:project, project) issue = build_stubbed(:issue) expect(helper.issuable_reference(issue)).to eql(issue.to_reference(project)) end end end end describe '#updated_at_by' do let(:user) { create(:user) } let(:unedited_issuable) { create(:issue) } let(:edited_issuable) { create(:issue, last_edited_by: user, created_at: 3.days.ago, updated_at: 1.day.ago, last_edited_at: 2.days.ago) } let(:edited_updated_at_by) do { updatedAt: edited_issuable.last_edited_at.to_time.iso8601, updatedBy: { name: user.name, path: user_path(user) } } end it { expect(helper.updated_at_by(unedited_issuable)).to eq({}) } it { expect(helper.updated_at_by(edited_issuable)).to eq(edited_updated_at_by) } context 'when updated by a deleted user' do let(:edited_updated_at_by) do { updatedAt: edited_issuable.last_edited_at.to_time.iso8601, updatedBy: { name: User.ghost.name, path: user_path(User.ghost) } } end before do user.destroy end it 'returns "Ghost user" as edited_by' do expect(helper.updated_at_by(edited_issuable.reload)).to eq(edited_updated_at_by) end end end describe '#issuable_initial_data' do let(:user) { create(:user) } before do allow(helper).to receive(:current_user).and_return(user) allow(helper).to receive(:can?).and_return(true) stub_commonmark_sourcepos_disabled end it 'returns the correct data for an issue' do issue = create(:issue, author: user, description: 'issue text') @project = issue.project expected_data = { endpoint: "/#{@project.full_path}/-/issues/#{issue.iid}", updateEndpoint: "/#{@project.full_path}/-/issues/#{issue.iid}.json", canUpdate: true, canDestroy: true, issuableRef: "##{issue.iid}", markdownPreviewPath: "/#{@project.full_path}/preview_markdown", markdownDocsPath: '/help/user/markdown', lockVersion: issue.lock_version, projectPath: @project.path, projectNamespace: @project.namespace.path, initialTitleHtml: issue.title, initialTitleText: issue.title, initialDescriptionHtml: '<p dir="auto">issue text</p>', initialDescriptionText: 'issue text', initialTaskStatus: '0 of 0 tasks completed' } expect(helper.issuable_initial_data(issue)).to match(hash_including(expected_data)) end describe '#sentryIssueIdentifier' do let(:issue) { create(:issue, author: user) } before do assign(:project, issue.project) end it 'sets sentryIssueIdentifier to nil with no sentry issue ' do expect(helper.issuable_initial_data(issue)[:sentryIssueIdentifier]) .to be_nil end it 'sets sentryIssueIdentifier to sentry_issue_identifier' do sentry_issue = create(:sentry_issue, issue: issue) expect(helper.issuable_initial_data(issue)[:sentryIssueIdentifier]) .to eq(sentry_issue.sentry_issue_identifier) end end describe '#zoomMeetingUrl in issue' do let(:issue) { create(:issue, author: user) } before do assign(:project, issue.project) end shared_examples 'sets zoomMeetingUrl to nil' do specify do expect(helper.issuable_initial_data(issue)[:zoomMeetingUrl]) .to be_nil end end context 'with no "added" zoom mettings' do it_behaves_like 'sets zoomMeetingUrl to nil' context 'with multiple removed meetings' do before do create(:zoom_meeting, issue: issue, issue_status: :removed) create(:zoom_meeting, issue: issue, issue_status: :removed) end it_behaves_like 'sets zoomMeetingUrl to nil' end end context 'with "added" zoom meeting' do before do create(:zoom_meeting, issue: issue) end shared_examples 'sets zoomMeetingUrl to canonical meeting url' do specify do expect(helper.issuable_initial_data(issue)) .to include(zoomMeetingUrl: 'https://zoom.us/j/123456789') end end it_behaves_like 'sets zoomMeetingUrl to canonical meeting url' context 'with muliple "removed" zoom meetings' do before do create(:zoom_meeting, issue: issue, issue_status: :removed) create(:zoom_meeting, issue: issue, issue_status: :removed) end it_behaves_like 'sets zoomMeetingUrl to canonical meeting url' end end end end describe '#assignee_sidebar_data' do let(:user) { create(:user) } let(:merge_request) { nil } subject { helper.assignee_sidebar_data(user, merge_request: merge_request) } it 'returns hash of assignee data' do is_expected.to eql({ avatar_url: user.avatar_url, name: user.name, username: user.username }) end context 'with merge_request' do let(:merge_request) { build_stubbed(:merge_request) } where(can_merge: [true, false]) with_them do before do allow(merge_request).to receive(:can_be_merged_by?).and_return(can_merge) end it { is_expected.to include({ can_merge: can_merge })} end end end end
31.136808
141
0.646616
08c26364ffdce43bb270a1c4ff77053dd06fc3dc
7,084
require 'spec_helper' describe Opendata::Dataset::ResourceDownloadReportsController, type: :feature, dbscope: :example do let(:site) { cms_site } let!(:node_search_dataset) { create(:opendata_node_search_dataset, cur_site: site) } let!(:node) { create(:opendata_node_dataset, cur_site: site) } let(:now) { Time.zone.now.beginning_of_minute } let(:last_year) { now - 1.year - 1.month } let!(:report1) do create(:opendata_resource_download_report, cur_site: site, dataset_id: rand(10..20), resource_id: rand(10..20)) end let!(:report2) do create( :opendata_resource_download_report, cur_site: site, deleted: now, dataset_id: rand(30..40), resource_id: rand(30..40)) end let!(:report3) do create( :opendata_resource_download_report, cur_site: site, year_month: last_year.year * 100 + last_year.month, dataset_id: rand(30..40), resource_id: rand(30..40) ) end before { login_cms_user } describe "#index" do it do visit opendata_dataset_report_main_path(site: site, cid: node) within "form.search" do select "1#{I18n.t('datetime.prompts.month')}", from: "s[start_month]" select "12#{I18n.t('datetime.prompts.month')}", from: "s[end_month]" select I18n.t("activemodel.attributes.opendata/dataset_download_report/type.year"), from: "s[type]" click_on I18n.t("ss.buttons.search") end expect(page).to have_css("tr[data-dataset-id='#{report1.dataset_id}']", text: report1.dataset_name) expect(page).to have_css("tr[data-resource-id='#{report1.resource_id}']", text: report1.resource_name) expect(page).to have_css("tr[data-dataset-id='#{report2.dataset_id}']", text: report2.dataset_name) expect(page).to have_css("tr[data-resource-id='#{report2.resource_id}']", text: report2.resource_name) expect(page).to have_no_css("tr[data-dataset-id='#{report3.dataset_id}']", text: report3.dataset_name) expect(page).to have_no_css("tr[data-resource-id='#{report3.resource_id}']", text: report3.resource_name) within "form.search" do select "1#{I18n.t('datetime.prompts.month')}", from: "s[start_month]" select "12#{I18n.t('datetime.prompts.month')}", from: "s[end_month]" select I18n.t("activemodel.attributes.opendata/dataset_download_report/type.year"), from: "s[type]" fill_in "s[keyword]", with: report1.dataset_name click_on I18n.t("ss.buttons.search") end expect(page).to have_css("tr[data-dataset-id='#{report1.dataset_id}']", text: report1.dataset_name) expect(page).to have_css("tr[data-resource-id='#{report1.resource_id}']", text: report1.resource_name) expect(page).to have_no_css("tr[data-dataset-id='#{report2.dataset_id}']", text: report2.dataset_name) expect(page).to have_no_css("tr[data-resource-id='#{report2.resource_id}']", text: report2.resource_name) expect(page).to have_no_css("tr[data-dataset-id='#{report3.dataset_id}']", text: report3.dataset_name) expect(page).to have_no_css("tr[data-resource-id='#{report3.resource_id}']", text: report3.resource_name) within "form.search" do select "#{last_year.year}#{I18n.t('datetime.prompts.year')}", from: "s[start_year]" select "1#{I18n.t('datetime.prompts.month')}", from: "s[start_month]" select "#{last_year.year}#{I18n.t('datetime.prompts.year')}", from: "s[end_year]" select "12#{I18n.t('datetime.prompts.month')}", from: "s[end_month]" select I18n.t("activemodel.attributes.opendata/dataset_download_report/type.year"), from: "s[type]" fill_in "s[keyword]", with: "" click_on I18n.t("ss.buttons.search") end expect(page).to have_no_css("tr[data-dataset-id='#{report1.dataset_id}']", text: report1.dataset_name) expect(page).to have_no_css("tr[data-resource-id='#{report1.resource_id}']", text: report1.resource_name) expect(page).to have_no_css("tr[data-dataset-id='#{report2.dataset_id}']", text: report2.dataset_name) expect(page).to have_no_css("tr[data-resource-id='#{report2.resource_id}']", text: report2.resource_name) expect(page).to have_css("tr[data-dataset-id='#{report3.dataset_id}']", text: report3.dataset_name) expect(page).to have_css("tr[data-resource-id='#{report3.resource_id}']", text: report3.resource_name) end end describe "#download" do it do visit opendata_dataset_report_main_path(site: site, cid: node) within "form.search" do select I18n.t("activemodel.attributes.opendata/dataset_download_report/type.year"), from: "s[type]" click_on I18n.t("ss.buttons.search") end click_on I18n.t("ss.links.download") expect(page.response_headers["Transfer-Encoding"]).to eq "chunked" csv = ::SS::ChunkReader.new(page.html).to_a.join csv = csv.encode("UTF-8", "SJIS") table = ::CSV.parse(csv, headers: true) expect(table.headers[0]).to eq Opendata::Dataset.t("no") expect(table.headers[1]).to be_blank expect(table.headers[2]).to be_blank expect(table.headers[3]).to eq I18n.t("ss.url") expect(table.headers[4]).to eq Opendata::Dataset.t("area_ids") expect(table.headers[5]).to eq Opendata::Dataset.t("state") expect(table.headers[6]).to eq "#{now.year - 2}#{I18n.t('datetime.prompts.year')}" expect(table.headers[7]).to eq "#{now.year - 1}#{I18n.t('datetime.prompts.year')}" expect(table.headers[8]).to eq "#{now.year}#{I18n.t('datetime.prompts.year')}" expect(table.headers.length).to eq 9 expect(table.length).to eq 4 expect(table[0][Opendata::Dataset.t("no")]).to eq report1.dataset_id.to_s expect(table[0][1]).to eq "[#{report1.dataset_id}] #{report1.dataset_name}" expect(table[0][I18n.t("ss.url")]).to eq report1.dataset_url expect(table[0][Opendata::Dataset.t("area_ids")]).to eq report1.dataset_areas.join("\n") expect(table[0][Opendata::Dataset.t("state")]).to be_blank expect(table[1][Opendata::Dataset.t("no")]).to be_blank expect(table[1][2]).to eq "[#{report1.resource_id}] #{report1.resource_name}" expect(table[1][I18n.t("ss.url")]).to be_blank expect(table[1][Opendata::Dataset.t("area_ids")]).to be_blank expect(table[1][Opendata::Dataset.t("state")]).to be_blank expect(table[2][Opendata::Dataset.t("no")]).to eq report2.dataset_id.to_s expect(table[2][1]).to eq "[#{report2.dataset_id}] #{report2.dataset_name}" expect(table[2][I18n.t("ss.url")]).to eq report2.dataset_url expect(table[2][Opendata::Dataset.t("area_ids")]).to eq report2.dataset_areas.join("\n") expect(table[2][Opendata::Dataset.t("state")]).to be_blank expect(table[3][Opendata::Dataset.t("no")]).to be_blank expect(table[3][2]).to eq "[#{report2.resource_id}] #{report2.resource_name}" expect(table[3][I18n.t("ss.url")]).to be_blank expect(table[3][Opendata::Dataset.t("area_ids")]).to be_blank expect(table[3][Opendata::Dataset.t("state")]).to eq "削除: #{I18n.l(report2.deleted.to_date)}" end end end
56.672
124
0.675748
f8b50efe0ef160a59fed8770b6d115aba521ed59
362
module StashDatacite module Resource describe Subject do it 'leaves out FOS items with .non_fos scope' do items = [create(:subject), create(:subject), create(:subject, subject_scheme: 'fos')] expect(Subject.all.length).to eq(items.length) expect(Subject.all.non_fos.length).to eq(items.length - 1) end end end end
30.166667
93
0.668508
18d0537530d54296ab408b71cbf7844b4c02690d
120
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) require "kaminari/rectify/query" require "minitest/autorun"
24
58
0.758333
bb1b1ca8723f8d2e3b5c822bdb1d07c808d7813a
1,347
require_relative 'boot' require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "active_storage/engine" require "action_controller/railtie" require "action_mailer/railtie" # require "action_mailbox/engine" # require "action_text/engine" require "action_view/railtie" require "action_cable/engine" require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module MartianLibrary class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 6.0 # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. # Don't generate system test files. config.generators.system_tests = nil config.generators do |g| g.test_framework false g.stylesheets false g.javascripts false g.helper false g.channel assets: false end end end
30.613636
82
0.749814
ab9911662a924a917ff1d30bc97eb51586543f04
487
module DateTimeInput module Model extend ActiveSupport::Concern module ClassMethods def date_time_inputable(attribute) define_method("#{attribute}=") do |input| if input.is_a?(Hash) super(FormData.from_param(input).to_time) else super(input) end end define_method("#{attribute}_date_time_data") do FormData.new(public_send(attribute)) end end end end end
17.392857
55
0.593429
38d43597b0a6a1b472a3f50fda82ad301223cabe
111
# frozen_string_literal: true # Full-stack web application framework. # [https://rubyonrails.org] gem "rails"
18.5
39
0.756757
6a3ef8aef905730d262c5c4e91ed3c1d86ea90f3
379
# frozen_string_literal: true require "weatherizableAPI" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
23.6875
66
0.759894
332e3b3ef6a259faf8cf08cf9e8b3aff7ed8b5f1
16,309
require 'cli/ui' require 'colorize' require 'cli/ui' class Jewstore def self.go res = '' CLI::UI::Prompt.ask('JewelryStore v1.5.4') do |handler| handler.option('list') { |selection| selection; res = 'list' } handler.option('install') { |selection| selection; res = gets.chomp } end if res == 'list' puts 'all apps available are:'.colorize(:red) puts 'inkscape'.colorize(:grey) puts 'gparted'.colorize(:green) puts 'audacity'.colorize(:red) puts 'librewolf'.colorize(:blue) puts 'ferdi'.colorize(:purple) puts 'vscode'.colorize(:blue) puts 'emacs'.colorize(:purple) puts 'etcher'.colorize(:green) puts 'brave'.colorize(:red) puts 'stepmania'.colorize(:red) puts 'zoom'.colorize(:blue) puts 'schildichat'.colorize(:green) puts 'cpu-x'.colorize(:blue) puts 'atom'.colorize(:green) puts 'blender'.colorize(:yellow) puts 'krita'.colorize(:pink) puts 'gimp'.colorize(:white) puts 'vlc'.colorize(:yellow) puts 'obs'.colorize(:red) puts 'firefox'.colorize(:red) puts 'waterfox'.colorize(:blue) puts 'notepadqq'.colorize(:green) puts 'libreoffice'.colorize(:yellow) puts 'thunderbird'.colorize(:blue) end if res == 'bye' puts 'exiting'.colorize(:red) end if res == 'inkscape' puts 'i will install: InkScape x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) inkscaped = gets.chomp puts 'installing inkscape appimage'.colorize(:red) inkscape = system( "cd ~/ && wget https://media.inkscape.org/dl/resources/file/Inkscape-0a00cf5-x86_64.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'gparted' puts 'i will install: GParted x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) gpartedd = gets.chomp puts 'installing GParted appimage'.colorize(:red) gparted = system( "cd ~/ && wget https://apprepo.de/uploads/package/version/2022/02/06/102453/Gparted.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'audacity' puts 'i will install Audacity x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) audacityd = gets.chomp puts 'installing Audacity appimage'.colorize(:red) audacity = system( "cd ~/ && wget https://github.com/audacity/audacity/releases/download/Audacity-3.1.3/audacity-linux-3.1.3-x86_64.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'librewolf' puts 'i will install LibreWolf x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) librewolfd = gets.chomp puts 'installing LibreWolf AppImage'.colorize(:red) librewolf = system( "cd ~/ && wget https://download943.mediafire.com/91e2t4qw35wg/jif8wa50dm7c1by/LibreWolf.x86_64.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'ferdi' puts 'i will install Ferdi x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) ferdid = gets.chomp puts 'installing Ferdi AppImage'.colorize(:red) ferdi = system( "cd ~/ && wget https://github.com/getferdi/ferdi/releases/download/v5.8.0/Ferdi-5.8.0.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'vscode' puts 'i will install Code-Oss x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) coded = gets.chomp puts 'installing VsCode AppImage'.colorize(:red) code = system( "cd ~/ && wget https://github.com/zilti/code-oss.AppImage/releases/download/continuous/Code_OSS-x86_64.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'emacs' puts 'i will install emacs AppImage, Correct? (Press Enter)'.colorize(:red) emacsd = gets.chomp puts 'installing Emacs AppImage'.colorize(:red) emacs = system( "cd ~/ && wget https://github.com/probonopd/Emacs.AppImage/releases/download/continuous/Emacs-27.2.glibc2.16-x86_64.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'etcher' puts 'I will install Balena-Etcher x64 AppImage, Correct? (Press Enter)'.colorize(:red) etcherd = gets.chomp puts 'Installing Emacs AppImage'.colorize(:red) etcher = system( "cd ~/ && wget https://github.com/balena-io/etcher/releases/download/v1.7.8/balenaEtcher-1.7.8-x64.AppImage" ) puts 'App installed with success in your home'.colorize(:red) end if res == 'brave' puts 'I will install Brave x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) brave = gets.chomp puts 'Installing Brave AppImage'.colorize(:red) brave = system( "cd ~/ && wget https://apprepo.de/uploads/package/version/2022/02/05/055813/Brave.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'stepmania' puts 'I will install StepMania 5.1 beta x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) stepmaniad = gets.chomp puts 'Installing StepMania AppImage'.colorize(:red) stepmania = system( "cd ~/ && wget https://dl2.pling.com/api/files/download/j/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTYzMTUwODUxNiwidSI6bnVsbCwibHQiOiJkb3dubG9hZCIsInMiOiI0MmE1M2M2NjdiNDQ2NDIwODVlMDA5OGI5NWIxNDQ4MTY3N2ZhNmI1MjAyMDcwYTgxZjkxYjI2MDEwMjAzNTQ3MGVhNzFhM2VmZDNmZjJmNjkzZmQ5ODA2YzAxYjNjNmYxNWU2YzVmMGY4MWIyY2YwNDMwZmQ2ZTcwNmFmZjcyZiIsInQiOjE2NDc4ODE3NTIsInN0ZnAiOiJjYmRlYjg2YmM5YWE5MDFjM2ZiNzU1MmIzYWNmZDljNSIsInN0aXAiOiIyMDEuMjE2Ljc0LjIyMyJ9.5Pqzqpy4A6_2FjvxKrjN2fYy9CT68TaZKKmu_pXXlAc/StepMania-5.1-f1ebe8d-x86_64.AppImage " ) puts 'app installed with success in your home'.colorize(:red) end if res == 'zoom' puts 'I will install Zoom x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) zoomd = gets.chomp puts 'Installing Zoom AppImage'.colorize(:red) zoom = system( "cd ~/ && wget https://dl1.pling.com/api/files/download/j/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTYzMjY1MjY0NiwidSI6bnVsbCwibHQiOiJkb3dubG9hZCIsInMiOiJjY2IzOGY2MDUxZTA1ZmZlOWM2OTkxZWNiYmNjODljZDNhZDE0YWZjODY2NmY2YTM4MjkyMzZlNzI1MTc3ZGU1OWRiMGM4NzMyNDRjMDQxMDAwMDBmMDNhZjRjOGUwNzk3YTQzYTc2MDY5NzJhMmU3ZjAwNmIyYzk1ODg0N2MyNyIsInQiOjE2NDc4ODE4NDMsInN0ZnAiOiJjYmRlYjg2YmM5YWE5MDFjM2ZiNzU1MmIzYWNmZDljNSIsInN0aXAiOiIyMDEuMjE2Ljc0LjIyMyJ9.sf2N3V4wAvTwg_oGR9w-k3LUZcr5R3-1R0rbXj0DjnI/Zoom-5.7.31792.0820.glibc2.17-x86_64.AppImage " ) puts 'app installed with success in your home'.colorize(:red) end if res == 'schildichat' puts 'I will install SchildiChat x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) schatd = gets.chomp puts 'Installing SchildiChat AppImage'.colorize(:red) schat = system( "cd ~/ && wget https://dl2.pling.com/api/files/download/j/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTYwODIwNzkzMCwidSI6bnVsbCwibHQiOiJkb3dubG9hZCIsInMiOiIzMDdiM2MyNzdjNmEwNmJjNTUzOWIyZTRmOWJiZmJkNWFjZjM5NjhjYzc3MGI4YTU2OTZkNjcxOTgyNWVmYjg2YTc5M2NhMTQ5MzRmY2ZmODg0NTIwODdhMjUzNDkzOGJhZDE2NDY5MWEwZjQ4OTQzYzRjZDdhN2Y3ZTMzYmY3MCIsInQiOjE2NDc4ODI3NDcsInN0ZnAiOiJjYmRlYjg2YmM5YWE5MDFjM2ZiNzU1MmIzYWNmZDljNSIsInN0aXAiOiIyMDEuMjE2Ljc0LjIyMyJ9.HM7ynsB4H-AV0CHqvHin3rzitDgTZTU1dksEiRrKvBQ/SchildiChat-1.7.15.AppImage " ) puts 'app installed with success in your home'.colorize(:red) end if res == 'cpu-x' puts 'I will install CPU-X x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) cpuxd = gets.chomp puts 'Installing CPU-X AppImage'.colorize(:red) cpux = system( "cd ~/ && wget https://objects.githubusercontent.com/github-production-release-asset-2e65be/24292801/6b1fe73e-86e1-429c-88ea-ee41bd019276?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20220321%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20220321T162401Z&X-Amz-Expires=300&X-Amz-Signature=fa9da0fcd59276a5a1c2a6f6b0d447d7af5f7b7731d9c16b5d4e1e39311b54da&X-Amz-SignedHeaders=host&actor_id=97253814&key_id=0&repo_id=24292801&response-content-disposition=attachment%3B%20filename%3DCPU-X-x86_64.AppImage&response-content-type=application%2Foctet-stream " ) puts 'app installed with success in your home'.colorize(:red) end if res == 'atom' puts 'I will install Atom IDE x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) atomd = gets.chomp puts 'Installing Atom AppImage'.colorize(:red) atom = system( "cd ~/ && wget https://rsync.opensuse.org/repositories/home:/zilti:/appimages/AppImage/Atom-0-Build7.6.glibc2.17-x86_64.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'blender' puts 'I will install Blender x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) blenderd = gets.chomp puts 'Installing Blender AppImage'.colorize(:red) blender = system( "cd ~/ && wget https://dl2.pling.com/api/files/download/j/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTYwMjAxMzAyOCwidSI6bnVsbCwibHQiOiJkb3dubG9hZCIsInMiOiI1NjMyNTYzMzI3NmUwOWUxYmI0ZDNjNzc4YTM1ODk2ZGU3ZDQ2MGY5OTJlNDgzNWU3YjhkY2IyYTRlNTcwMmExYTIxNGJiYTI4NjBlMDY3N2Y0MDRiYTRkMWU4ZDAwNWMwODM3MGE3YzcyODk5MDlhNjk0ZGYwOTU0OTIxNzViOSIsInQiOjE2NDc5OTIyMjUsInN0ZnAiOiJhNzhmZmFhZTdkNDk3MDk2Y2ZhNjJmOTBmMmJiNGFmNyIsInN0aXAiOiIyMDEuMjE2Ljc0LjIyMyJ9.NadXu5Q82JaQycdTvoSvjATRLd9Q2iQUiTXTDeYs5c8/Blender-v2.90.0-x86_64.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'krita' puts 'I will install Krita x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) kritad = gets.chomp puts 'Installing Krita AppImage'.colorize(:red) krita = system( "cd ~/ && wget https://dl2.pling.com/api/files/download/j/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTYwMTkzMzc2OSwidSI6bnVsbCwibHQiOiJkb3dubG9hZCIsInMiOiJlZGE0NWMyODA0NWRlNDIxNDgzNzExZDc0ZDJlZGZjNzY4M2Y0YTljYmVjOGE2NzU5ZWZkMGMxYmQ3ZDYzNjkwOTgwYTJiOWY3NTllNTkwMWVmYTA4NGY3MWQ0OGQyZmQ0MzY1ZjRhOWM3YzJjNzlmNTk4OTg2MjMyNjAxNTQyNSIsInQiOjE2NDc5OTI0MjIsInN0ZnAiOiJhNzhmZmFhZTdkNDk3MDk2Y2ZhNjJmOTBmMmJiNGFmNyIsInN0aXAiOiIyMDEuMjE2Ljc0LjIyMyJ9.lRP10rJ_cyvF38FJ34WacH78A0yLtUjM5b_C9phRVR4/krita-4.3.0-x86_64.appimage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'gimp' puts 'I will install Gimp x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) gimpd = gets.chomp puts 'Installing Gimp AppImage'.colorize(:red) gimp = system( "cd ~/ && wget https://dl2.pling.com/api/files/download/j/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTYwMTkyNDUwNCwidSI6bnVsbCwibHQiOiJkb3dubG9hZCIsInMiOiI4MGQ4OTZjNGEwOWJiZmJiYzNkZDRjZWRjZWUwNDFkN2RmMjIzODMzMWFiZTc4YTE2YTg2NWE4NzQxODc1OTcyNmQ3N2Y1ZGE3ZTdlMTM4ZGNiOGE5MTIyMmQ0YWJkZmUyNmRhYjk5M2M3MWI2ODE3OGYxZTYxODhhNjQ1YmYzYiIsInQiOjE2NDc5OTI2NjEsInN0ZnAiOiJhNzhmZmFhZTdkNDk3MDk2Y2ZhNjJmOTBmMmJiNGFmNyIsInN0aXAiOiIyMDEuMjE2Ljc0LjIyMyJ9.CpkSnEc13pPiDg93ayIBOdJG87WSBLrJ8g10YqIcWME/GIMP_AppImage-git-2.10.21-20201001-withplugins-x86_64.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'vlc' puts 'I will install VLC x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) vlcd = gets.chomp puts 'Installing VLC AppImage'.colorize(:red) vlc = system( "cd ~/ && wget https://dl2.pling.com/api/files/download/j/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTYwMjAxMjYxMiwidSI6bnVsbCwibHQiOiJkb3dubG9hZCIsInMiOiIzZTEyODAzYjI5YzU5NTBlNjA1ODFjZmRiMjllMDBhZTJkMTBiYzYyOWVjOTdhZjUwNWQ5ZjM2ZmNkNDgzYjIxN2RhNmZkOGEwMmNhNzU1YTAyNDU3NjVmYWNhODlkNjdjYWNjYmVkNDkzZTdkMTQ0YWU0ZGE1ZmQwOWZiNWQ2MCIsInQiOjE2NDgyMjMzMDEsInN0ZnAiOiJiZWMwODFlNTQxYmUwN2Q3MDA2MjUzNjUxMTQ3MjVhYiIsInN0aXAiOiIyMDEuMjE2Ljc0LjIyMyJ9.vSGnJQl3ibt-pfAwzVRU73CC61VzdTOPQn9_BNv1l98/VLC_media_player-3.0.11.1-x86_64.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'obs' puts 'I will install OBS Studio x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) obsd = gets.chomp puts 'Installing OBS Studio AppImage'.colorize(:red) obs = system( "cd ~/ && wget https://dl1.pling.com/api/files/download/j/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTU5NjcxMjM3MywidSI6bnVsbCwibHQiOiJkb3dubG9hZCIsInMiOiI0YWRlNWM0NmZhYjUxN2U0YzVlYWFlZjg4MGRkMzE2NDI5ZTA0OGQxYmExZDFhZjM0MWUyMzFhNWM0N2U4Nzk2MWNiNjViMmRkNWNiNWI0OTFkMTA4MjViMWVkNGYzZGE0NzRjNDE4NjdhNmRlNjVmMDYwODZhNmFlNWY3OTRmYyIsInQiOjE2NDgyMjU0NTcsInN0ZnAiOiJiZWMwODFlNTQxYmUwN2Q3MDA2MjUzNjUxMTQ3MjVhYiIsInN0aXAiOiIyMDEuMjE2Ljc0LjIyMyJ9.fPk-JwiinAiuPwuTJdHO_73fihLl-3lJLi4d4ZQx0jE/obs-studio-plus-25.0.8-x86_64.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'firefox' puts 'I will install Firefox 70 x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) firefoxd = gets.chomp puts 'Installing Firefox AppImage'.colorize(:red) firefox = system( "cd ~/ && wget https://dl2.pling.com/api/files/download/j/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTU4Njc4ODA5MSwidSI6bnVsbCwibHQiOiJkb3dubG9hZCIsInMiOiJiMmE4N2NiOTc0YzczN2Q3MGM3OGYwZDIzYmNiMmM1YTIyNWQyOWY3YTlkMTQyNWY0M2E0NDY5NjVkODUxNjQ1NTQ5MzEzOWYyZDZiNDk0OWQ3ZmZjN2E2Mzc3ZTBkZjBmNDFiMjdiNTk1OWYwNGNhZWVhYWU3ODY5Mjc5MzM1NCIsInQiOjE2NDgyMjU1NDksInN0ZnAiOiJiZWMwODFlNTQxYmUwN2Q3MDA2MjUzNjUxMTQ3MjVhYiIsInN0aXAiOiIyMDEuMjE2Ljc0LjIyMyJ9.zhl7JZEFmFyfeWg5aJYVGufegmCMnqtSnrr0tu_CK2Q/Firefox-x86_64-20200413141725.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'waterfox' puts 'I will install Waterfox 50 x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) waterfoxd = gets.chomp puts 'Installing Waterfox AppImage'.colorize(:red) waterfox = system( "cd ~/ && wget https://dl2.pling.com/api/files/download/j/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTU0MjQ0OTA5NiwidSI6bnVsbCwibHQiOiJkb3dubG9hZCIsInMiOiI5NWFkODE1NGUzNGQzZjgwYzVkYzFlMDZmYzZkNDVlMTkzMThjZDEyZDE4ODA4NWRmNmVmNWM0YzU5ODM3ODgwYmFlMzQ4ZTVjYzM4MTkwZWViNWM3NWVkZDJmODY5MGJiNDE1ODdiZjRkMTA3ZmZmYjJiNjA1ODYzOGY5NzE5OSIsInQiOjE2NDgyMjU2MTIsInN0ZnAiOiJiZWMwODFlNTQxYmUwN2Q3MDA2MjUzNjUxMTQ3MjVhYiIsInN0aXAiOiIyMDEuMjE2Ljc0LjIyMyJ9.VqghsXgzV_NYfdTTTKKbqCCNYD9whsomV8Q4FDIjUEQ/Waterfox-0-Buildlp150.4.1.glibc2.17-x86_64.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'notepadqq' puts 'I will install Notepadqq x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) notepadqqd = gets.chomp puts 'Installing Notepadqq AppImage'.colorize(:red) notepadqq = system( "cd ~/ && wget https://objects.githubusercontent.com/github-production-release-asset-2e65be/3536442/f1e00584-3548-11e8-98bb-27c7bacfd184?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20220325%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20220325T152852Z&X-Amz-Expires=300&X-Amz-Signature=fb95bbe5774d7f64f9b26aad00fba76b3a6eb04a3f25f3576dd9e6b568fefdab&X-Amz-SignedHeaders=host&actor_id=97253814&key_id=0&repo_id=3536442&response-content-disposition=attachment%3B%20filename%3Dnotepadqq-.glibc2.14-x86_64.AppImage&response-content-type=application%2Foctet-stream" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'libreoffice' puts 'I will install Libreoffice 7.1 x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) libreofficed = gets.chomp puts 'Installing Libreoffice AppImage'.colorize(:red) libreoffice = system( "cd ~/ && wget https://dl2.pling.com/api/files/download/j/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTYwMTk1MzM5MiwidSI6bnVsbCwibHQiOiJkb3dubG9hZCIsInMiOiI5YmEwZWNjZGMzNWNkMDNiYWI3YmYyODA2NGIyN2NiNmY0MzZiOTg1MGQyNWQ5Y2JmYWZhY2Y3ZjA1M2YzOGU4MGVhNzMyYTIwNzk5MTQzNjBmMzUyYzNmY2E2MmE3NDA2NzRiZTM0MWJlNzA4OWI2NDdhNmZiYjg4OGRmMjJjOSIsInQiOjE2NDgyMjU3ODIsInN0ZnAiOiJiZWMwODFlNTQxYmUwN2Q3MDA2MjUzNjUxMTQ3MjVhYiIsInN0aXAiOiIyMDEuMjE2Ljc0LjIyMyJ9.jd6arR3X-PB_xOJCZqqthBXNq7bLTUu1_1OLtXdtdRg/LibreOffice-fresh.full.help-x86_64.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end if res == 'thunderbird' puts 'I will install Mozilla Thunderbird x86_64 AppImage, Correct? (Press Enter)'.colorize(:red) thunderbirdd = gets.chomp puts 'Installing Thunderbird AppImage'.colorize(:red) thunderbird = system( "cd ~/ && wget https://dl1.pling.com/api/files/download/j/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTYwMjAxNzA3NCwidSI6bnVsbCwibHQiOiJkb3dubG9hZCIsInMiOiI4MzRiNzdlNGViNmM3MTBhZmViMTk3M2M3MDU5MzRkMjZhZGM0YmE0MjdjYzY2YjcyYjU1YzZkODA3NzgwMzk3YmIzMDE3NmE0MGY4NzY3NTc2ODNjMGI4NWRiMDNmMWYxNzBjM2MzN2VhY2U3Nzk1MGMxNzI4ODY1ODlmNDRjZCIsInQiOjE2NDgyMjU4MTQsInN0ZnAiOiJiZWMwODFlNTQxYmUwN2Q3MDA2MjUzNjUxMTQ3MjVhYiIsInN0aXAiOiIyMDEuMjE2Ljc0LjIyMyJ9.Uyi_NA3tmdeJBmBIL_BvdL2Hlvt7ZOpdV4gsFt31suo/Thunderbird-78.3_20200925001233.AppImage" ) puts 'app installed with success in your home'.colorize(:red) end end end
67.954167
611
0.817279
b9a0945075a2e8707fa8c6574ea4cd378bc4bbb0
2,667
class Pdns < Formula desc "Authoritative nameserver" homepage "https://www.powerdns.com" url "https://downloads.powerdns.com/releases/pdns-4.1.1.tar.bz2" sha256 "08d388321c8a2c24ebe8d7e539f34a0ba2c0973313c168a1b5ecf507e4fb04ba" bottle do sha256 "470c9841912c8c2ef96c69c8426b4cfc17d10277c978c193015261d677c87651" => :high_sierra sha256 "857cb0232f168326f27f696b9ba2c1c1fe6577b21dcbca4f2179cdcae379704d" => :sierra sha256 "1e22069fb9c9b263a75f2361602d87923f72094225fa27ba4662b3a8bd1f2566" => :el_capitan end head do url "https://github.com/powerdns/pdns.git" depends_on "automake" => :build depends_on "autoconf" => :build depends_on "libtool" => :build depends_on "ragel" end option "with-postgresql", "Enable the PostgreSQL backend" option "with-remote", "enable the Remote backend" deprecated_option "pgsql" => "with-postgresql" deprecated_option "with-pgsql" => "with-postgresql" depends_on "pkg-config" => :build depends_on "boost" depends_on "lua" depends_on "openssl" depends_on "sqlite" depends_on "postgresql" => :optional def install # Fix "configure: error: cannot find boost/program_options.hpp" ENV["SDKROOT"] = MacOS.sdk_path if MacOS.version == :sierra args = %W[ --prefix=#{prefix} --sysconfdir=#{etc}/powerdns --with-lua --with-openssl=#{Formula["openssl"].opt_prefix} --with-sqlite3 ] # Include the PostgreSQL backend if requested if build.with? "postgresql" args << "--with-modules=gsqlite3 gpgsql" elsif build.with? "remote" args << "--with-modules=gsqlite3 remote" else # SQLite3 backend only is the default args << "--with-modules=gsqlite3" end system "./bootstrap" if build.head? system "./configure", *args system "make", "install" end plist_options :manual => "pdns_server start" def plist; <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <true/> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/pdns_server</string> </array> <key>EnvironmentVariables</key> <key>KeepAlive</key> <true/> <key>SHAuthorizationRight</key> <string>system.preferences</string> </dict> </plist> EOS end test do output = shell_output("#{sbin}/pdns_server --version 2>&1", 99) assert_match "PowerDNS Authoritative Server #{version}", output end end
28.677419
106
0.669666
21db165948e4c45dd91e39f56de4ac8e7ee596d6
608
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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/sheets_v4"
38
74
0.763158
6282124880d77b1a02746b6ec928d8f5c5bdd9e8
1,014
require_relative 'base' module Biblionet module Crawlers class PublisherCrawler < Base def initialize(options = {}) options[:folder] ||= 'lib/bookshark/storage/html_publisher_pages' options[:base_url] ||= 'http://www.biblionet.gr/com/' options[:page_type] ||= 'publisher' options[:extension] ||= '.html' options[:start] ||= 1 options[:finish] ||= 800 options[:step] ||= 100 super(options) end def crawl_and_save downloader = Extractors::Base.new spider do |url_to_download, file_to_save| downloader.load_page(url_to_download) # Create a new directory (does nothing if directory exists) path = File.dirname(file_to_save) FileUtils.mkdir_p path unless File.directory?(path) downloader.save_page(file_to_save) unless downloader.page.nil? or downloader.page.length < 1024 end end end end end
28.971429
105
0.601578
6a9c0b8b4443e9750fc427f3d2d0c36833ceb20f
721
# Capybara::Webkit.configure do |config| # # Enable debug mode. Prints a log of everything the driver is doing. # config.debug = true # # By default, requests to outside domains (anything besides localhost) will # # result in a warning. Several methods allow you to change this behavior. # # Silently return an empty 200 response for any requests to unknown URLs. # # Timeout if requests take longer than 5 seconds # config.timeout = 5 # # Don't raise errors when SSL certificates can't be validated # config.ignore_ssl_errors # # Don't load images # config.skip_image_loading # # Use a proxy # # Raise JavaScript errors as exceptions # config.raise_javascript_errors = true # end
28.84
79
0.718447
4ace0a6f0e9bc7e0bb058fc98b2a80edae2b0d1d
116
fail "ERROR: 'rake/gempackagetask' is obsolete and no longer supported. " + "Use 'rubygems/packagetask' instead."
38.666667
75
0.741379
017e8cf6a1642063b2f2cef007a2084f6149710e
414
module DuckPuncher class UniqueDuck < DelegateClass(Duck) attr_accessor :punch_options # # Required to play nice in a Set # def eql?(other) "#{target}-#{mod}" == "#{other.target}-#{other.mod}" end def hash target.to_s.hash + mod.to_s.hash + punch_options.to_s.hash end # # Sorting # def <=>(other) target <=> other.target end end end
15.333333
64
0.574879
bfb72bb09e0d791d0d71199fae00e91f08d57b2d
28,768
# Defines classes to deal with issues, and message formatting and defines constants with Issues. # @api public # module Puppet::Pops module Issues # Describes an issue, and can produce a message for an occurrence of the issue. # class Issue # The issue code # @return [Symbol] attr_reader :issue_code # A block producing the message # @return [Proc] attr_reader :message_block # Names that must be bound in an occurrence of the issue to be able to produce a message. # These are the names in addition to requirements stipulated by the Issue formatter contract; i.e. :label`, # and `:semantic`. # attr_reader :arg_names # If this issue can have its severity lowered to :warning, :deprecation, or :ignored attr_writer :demotable # Configures the Issue with required arguments (bound by occurrence), and a block producing a message. def initialize issue_code, *args, &block @issue_code = issue_code @message_block = block @arg_names = args @demotable = true end # Returns true if it is allowed to demote this issue def demotable? @demotable end # Formats a message for an occurrence of the issue with argument bindings passed in a hash. # The hash must contain a LabelProvider bound to the key `label` and the semantic model element # bound to the key `semantic`. All required arguments as specified by `arg_names` must be bound # in the given `hash`. # @api public # def format(hash ={}) # Create a Message Data where all hash keys become methods for convenient interpolation # in issue text. msgdata = MessageData.new(*arg_names) begin # Evaluate the message block in the msg data's binding msgdata.format(hash, &message_block) rescue StandardError => e MessageData raise RuntimeError, "Error while reporting issue: #{issue_code}. #{e.message}", caller end end end # Provides a binding of arguments passed to Issue.format to method names available # in the issue's message producing block. # @api private # class MessageData def initialize *argnames singleton = class << self; self end argnames.each do |name| singleton.send(:define_method, name) do @data[name] end end end def format(hash, &block) @data = hash instance_eval &block end # Obtains the label provider given as a key `:label` in the hash passed to #format. The label provider is # return if no arguments are given. If given an argument, returns the result of calling #label on the label # provider. # # @param args [Object] one object to obtain a label for or zero arguments to obtain the label provider # @return [LabelProvider,String] the label provider or label depending on if an argument is given or not # @raise [Puppet::Error] if no label provider is found def label(*args) args.empty? ? label_provider : label_provider.label(args[0]) end # Returns the label provider given as key `:label` in the hash passed to #format. # @return [LabelProvider] the label provider # @raise [Puppet::Error] if no label provider is found def label_provider label_provider = @data[:label] raise Puppet::Error, 'Label provider key :label must be set to produce the text of the message!' unless label_provider label_provider end # Returns the label provider given as a key in the hash passed to #format. # def semantic raise Puppet::Error, 'Label provider key :semantic must be set to produce the text of the message!' unless @data[:semantic] @data[:semantic] end end # Defines an issue with the given `issue_code`, additional required parameters, and a block producing a message. # The block is evaluated in the context of a MessageData which provides convenient access to all required arguments # via accessor methods. In addition to accessors for specified arguments, these are also available: # * `label` - a `LabelProvider` that provides human understandable names for model elements and production of article (a/an/the). # * `semantic` - the model element for which the issue is reported # # @param issue_code [Symbol] the issue code for the issue used as an identifier, should be the same as the constant # the issue is bound to. # @param args [Symbol] required arguments that must be passed when formatting the message, may be empty # @param block [Proc] a block producing the message string, evaluated in a MessageData scope. The produced string # should not end with a period as additional information may be appended. # # @see MessageData # @api public # def self.issue (issue_code, *args, &block) Issue.new(issue_code, *args, &block) end # Creates a non demotable issue. # @see Issue.issue # def self.hard_issue(issue_code, *args, &block) result = Issue.new(issue_code, *args, &block) result.demotable = false result end # @comment Here follows definitions of issues. The intent is to provide a list from which yardoc can be generated # containing more detailed information / explanation of the issue. # These issues are set as constants, but it is unfortunately not possible for the created object to easily know which # name it is bound to. Instead the constant has to be repeated. (Alternatively, it could be done by instead calling # #const_set on the module, but the extra work required to get yardoc output vs. the extra effort to repeat the name # twice makes it not worth it (if doable at all, since there is no tag to artificially construct a constant, and # the parse tag does not produce any result for a constant assignment). # This is allowed (3.1) and has not yet been deprecated. # @todo configuration # NAME_WITH_HYPHEN = issue :NAME_WITH_HYPHEN, :name do "#{label.a_an_uc(semantic)} may not have a name containing a hyphen. The name '#{name}' is not legal" end # When a variable name contains a hyphen and these are illegal. # It is possible to control if a hyphen is legal in a name or not using the setting TODO # @todo describe the setting # @api public # @todo configuration if this is error or warning # VAR_WITH_HYPHEN = issue :VAR_WITH_HYPHEN, :name do "A variable name may not contain a hyphen. The name '#{name}' is not legal" end # A class, definition, or node may only appear at top level or inside other classes # @todo Is this really true for nodes? Can they be inside classes? Isn't that too late? # @api public # NOT_TOP_LEVEL = hard_issue :NOT_TOP_LEVEL do "Classes, definitions, and nodes may only appear at toplevel or inside other classes" end NOT_ABSOLUTE_TOP_LEVEL = hard_issue :NOT_ABSOLUTE_TOP_LEVEL do "#{label.a_an_uc(semantic)} may only appear at toplevel" end CROSS_SCOPE_ASSIGNMENT = hard_issue :CROSS_SCOPE_ASSIGNMENT, :name do "Illegal attempt to assign to '#{name}'. Cannot assign to variables in other namespaces" end # Assignment can only be made to certain types of left hand expressions such as variables. ILLEGAL_ASSIGNMENT = hard_issue :ILLEGAL_ASSIGNMENT do "Illegal attempt to assign to '#{label.a_an(semantic)}'. Not an assignable reference" end # Variables are immutable, cannot reassign in the same assignment scope ILLEGAL_REASSIGNMENT = hard_issue :ILLEGAL_REASSIGNMENT, :name do if Validation::Checker4_0::RESERVED_PARAMETERS[name] "Cannot reassign built in (or already assigned) variable '$#{name}'" else "Cannot reassign variable '$#{name}'" end end # Variables facts and trusted ILLEGAL_RESERVED_ASSIGNMENT = hard_issue :ILLEGAL_RESERVED_ASSIGNMENT, :name do "Attempt to assign to a reserved variable name: '$#{name}'" end # Assignment cannot be made to numeric match result variables ILLEGAL_NUMERIC_ASSIGNMENT = issue :ILLEGAL_NUMERIC_ASSIGNMENT, :varname do "Illegal attempt to assign to the numeric match result variable '$#{varname}'. Numeric variables are not assignable" end # Assignment can only be made to certain types of left hand expressions such as variables. ILLEGAL_ASSIGNMENT_CONTEXT = hard_issue :ILLEGAL_ASSIGNMENT_CONTEXT do "Assignment not allowed here" end # parameters cannot have numeric names, clashes with match result variables ILLEGAL_NUMERIC_PARAMETER = issue :ILLEGAL_NUMERIC_PARAMETER, :name do "The numeric parameter name '$#{name}' cannot be used (clashes with numeric match result variables)" end # In certain versions of Puppet it may be allowed to assign to a not already assigned key # in an array or a hash. This is an optional validation that may be turned on to prevent accidental # mutation. # ILLEGAL_INDEXED_ASSIGNMENT = issue :ILLEGAL_INDEXED_ASSIGNMENT do "Illegal attempt to assign via [index/key]. Not an assignable reference" end # When indexed assignment ($x[]=) is allowed, the leftmost expression must be # a variable expression. # ILLEGAL_ASSIGNMENT_VIA_INDEX = hard_issue :ILLEGAL_ASSIGNMENT_VIA_INDEX do "Illegal attempt to assign to #{label.a_an(semantic)} via [index/key]. Not an assignable reference" end ILLEGAL_MULTI_ASSIGNMENT_SIZE = hard_issue :ILLEGAL_MULTI_ASSIGNMENT_SIZE, :expected, :actual do "Mismatched number of assignable entries and values, expected #{expected}, got #{actual}" end MISSING_MULTI_ASSIGNMENT_KEY = hard_issue :MISSING_MULTI_ASSIGNMENT_KEY, :key do "No value for required key '#{key}' in assignment to variables from hash" end APPENDS_DELETES_NO_LONGER_SUPPORTED = hard_issue :APPENDS_DELETES_NO_LONGER_SUPPORTED, :operator do "The operator '#{operator}' is no longer supported. See http://links.puppetlabs.com/remove-plus-equals" end # For unsupported operators (e.g. += and -= in puppet 4). # UNSUPPORTED_OPERATOR = hard_issue :UNSUPPORTED_OPERATOR, :operator do "The operator '#{operator}' is not supported." end # For operators that are not supported in specific contexts (e.g. '* =>' in # resource defaults) # UNSUPPORTED_OPERATOR_IN_CONTEXT = hard_issue :UNSUPPORTED_OPERATOR_IN_CONTEXT, :operator do "The operator '#{operator}' in #{label.a_an(semantic)} is not supported." end # For non applicable operators (e.g. << on Hash). # OPERATOR_NOT_APPLICABLE = hard_issue :OPERATOR_NOT_APPLICABLE, :operator, :left_value do "Operator '#{operator}' is not applicable to #{label.a_an(left_value)}." end COMPARISON_NOT_POSSIBLE = hard_issue :COMPARISON_NOT_POSSIBLE, :operator, :left_value, :right_value, :detail do "Comparison of: #{label(left_value)} #{operator} #{label(right_value)}, is not possible. Caused by '#{detail}'." end MATCH_NOT_REGEXP = hard_issue :MATCH_NOT_REGEXP, :detail do "Can not convert right match operand to a regular expression. Caused by '#{detail}'." end MATCH_NOT_STRING = hard_issue :MATCH_NOT_STRING, :left_value do "Left match operand must result in a String value. Got #{label.a_an(left_value)}." end # Some expressions/statements may not produce a value (known as right-value, or rvalue). # This may vary between puppet versions. # NOT_RVALUE = issue :NOT_RVALUE do "Invalid use of expression. #{label.a_an_uc(semantic)} does not produce a value" end # Appending to attributes is only allowed in certain types of resource expressions. # ILLEGAL_ATTRIBUTE_APPEND = hard_issue :ILLEGAL_ATTRIBUTE_APPEND, :name, :parent do "Illegal +> operation on attribute #{name}. This operator can not be used in #{label.a_an(parent)}" end ILLEGAL_NAME = hard_issue :ILLEGAL_NAME, :name do "Illegal name. The given name '#{name}' does not conform to the naming rule /^((::)?[a-z_]\w*)(::[a-z]\\w*)*$/" end ILLEGAL_PARAM_NAME = hard_issue :ILLEGAL_PARAM_NAME, :name do "Illegal parameter name. The given name '#{name}' does not conform to the naming rule /^[a-z_]\\w*$/" end ILLEGAL_VAR_NAME = hard_issue :ILLEGAL_VAR_NAME, :name do "Illegal variable name, The given name '#{name}' does not conform to the naming rule /^((::)?[a-z]\\w*)*((::)?[a-z_]\\w*)$/" end ILLEGAL_NUMERIC_VAR_NAME = hard_issue :ILLEGAL_NUMERIC_VAR_NAME, :name do "Illegal numeric variable name, The given name '#{name}' must be a decimal value if it starts with a digit 0-9" end # In case a model is constructed programmatically, it must create valid type references. # ILLEGAL_CLASSREF = hard_issue :ILLEGAL_CLASSREF, :name do "Illegal type reference. The given name '#{name}' does not conform to the naming rule" end # This is a runtime issue - storeconfigs must be on in order to collect exported. This issue should be # set to :ignore when just checking syntax. # @todo should be a :warning by default # RT_NO_STORECONFIGS = issue :RT_NO_STORECONFIGS do "You cannot collect exported resources without storeconfigs being set; the collection will be ignored" end # This is a runtime issue - storeconfigs must be on in order to export a resource. This issue should be # set to :ignore when just checking syntax. # @todo should be a :warning by default # RT_NO_STORECONFIGS_EXPORT = issue :RT_NO_STORECONFIGS_EXPORT do "You cannot collect exported resources without storeconfigs being set; the export is ignored" end # A hostname may only contain letters, digits, '_', '-', and '.'. # ILLEGAL_HOSTNAME_CHARS = hard_issue :ILLEGAL_HOSTNAME_CHARS, :hostname do "The hostname '#{hostname}' contains illegal characters (only letters, digits, '_', '-', and '.' are allowed)" end # A hostname may only contain letters, digits, '_', '-', and '.'. # ILLEGAL_HOSTNAME_INTERPOLATION = hard_issue :ILLEGAL_HOSTNAME_INTERPOLATION do "An interpolated expression is not allowed in a hostname of a node" end # Issues when an expression is used where it is not legal. # E.g. an arithmetic expression where a hostname is expected. # ILLEGAL_EXPRESSION = hard_issue :ILLEGAL_EXPRESSION, :feature, :container do "Illegal expression. #{label.a_an_uc(semantic)} is unacceptable as #{feature} in #{label.a_an(container)}" end # Issues when a variable is not a NAME # ILLEGAL_VARIABLE_EXPRESSION = hard_issue :ILLEGAL_VARIABLE_EXPRESSION do "Illegal variable expression. #{label.a_an_uc(semantic)} did not produce a variable name (String or Numeric)." end # Issues when an expression is used illegaly in a query. # query only supports == and !=, and not <, > etc. # ILLEGAL_QUERY_EXPRESSION = hard_issue :ILLEGAL_QUERY_EXPRESSION do "Illegal query expression. #{label.a_an_uc(semantic)} cannot be used in a query" end # If an attempt is made to make a resource default virtual or exported. # NOT_VIRTUALIZEABLE = hard_issue :NOT_VIRTUALIZEABLE do "Resource Defaults are not virtualizable" end # When an attempt is made to use multiple keys (to produce a range in Ruby - e.g. $arr[2,-1]). # This is not supported in 3x, but it allowed in 4x. # UNSUPPORTED_RANGE = issue :UNSUPPORTED_RANGE, :count do "Attempt to use unsupported range in #{label.a_an(semantic)}, #{count} values given for max 1" end # Issues when expressions that are not implemented or activated in the current version are used. # UNSUPPORTED_EXPRESSION = issue :UNSUPPORTED_EXPRESSION do "Expressions of type #{label.a_an(semantic)} are not supported in this version of Puppet" end ILLEGAL_RELATIONSHIP_OPERAND_TYPE = issue :ILLEGAL_RELATIONSHIP_OPERAND_TYPE, :operand do "Illegal relationship operand, can not form a relationship with #{label.a_an(operand)}. A Catalog type is required." end NOT_CATALOG_TYPE = issue :NOT_CATALOG_TYPE, :type do "Illegal relationship operand, can not form a relationship with something of type #{type}. A Catalog type is required." end BAD_STRING_SLICE_ARITY = issue :BAD_STRING_SLICE_ARITY, :actual do "String supports [] with one or two arguments. Got #{actual}" end BAD_STRING_SLICE_TYPE = issue :BAD_STRING_SLICE_TYPE, :actual do "String-Type [] requires all arguments to be integers (or default). Got #{actual}" end BAD_ARRAY_SLICE_ARITY = issue :BAD_ARRAY_SLICE_ARITY, :actual do "Array supports [] with one or two arguments. Got #{actual}" end BAD_HASH_SLICE_ARITY = issue :BAD_HASH_SLICE_ARITY, :actual do "Hash supports [] with one or more arguments. Got #{actual}" end BAD_INTEGER_SLICE_ARITY = issue :BAD_INTEGER_SLICE_ARITY, :actual do "Integer-Type supports [] with one or two arguments (from, to). Got #{actual}" end BAD_INTEGER_SLICE_TYPE = issue :BAD_INTEGER_SLICE_TYPE, :actual do "Integer-Type [] requires all arguments to be integers (or default). Got #{actual}" end BAD_COLLECTION_SLICE_TYPE = issue :BAD_COLLECTION_SLICE_TYPE, :actual do "A Type's size constraint arguments must be a single Integer type, or 1-2 integers (or default). Got #{label.a_an(actual)}" end BAD_FLOAT_SLICE_ARITY = issue :BAD_INTEGER_SLICE_ARITY, :actual do "Float-Type supports [] with one or two arguments (from, to). Got #{actual}" end BAD_FLOAT_SLICE_TYPE = issue :BAD_INTEGER_SLICE_TYPE, :actual do "Float-Type [] requires all arguments to be floats, or integers (or default). Got #{actual}" end BAD_SLICE_KEY_TYPE = issue :BAD_SLICE_KEY_TYPE, :left_value, :expected_classes, :actual do expected_text = if expected_classes.size > 1 "one of #{expected_classes.join(', ')} are" else "#{expected_classes[0]} is" end "#{label.a_an_uc(left_value)}[] cannot use #{actual} where #{expected_text} expected" end BAD_NOT_UNDEF_SLICE_TYPE = issue :BAD_NOT_UNDEF_SLICE_TYPE, :base_type, :actual do "#{base_type}[] argument must be a Type or a String. Got #{actual}" end BAD_TYPE_SLICE_TYPE = issue :BAD_TYPE_SLICE_TYPE, :base_type, :actual do "#{base_type}[] arguments must be types. Got #{actual}" end BAD_TYPE_SLICE_ARITY = issue :BAD_TYPE_SLICE_ARITY, :base_type, :min, :max, :actual do base_type_label = base_type.is_a?(String) ? base_type : label.a_an_uc(base_type) if max == -1 || max == Float::INFINITY "#{base_type_label}[] accepts #{min} or more arguments. Got #{actual}" elsif max && max != min "#{base_type_label}[] accepts #{min} to #{max} arguments. Got #{actual}" else "#{base_type_label}[] accepts #{min} #{label.plural_s(min, 'argument')}. Got #{actual}" end end BAD_TYPE_SPECIALIZATION = hard_issue :BAD_TYPE_SPECIALIZATION, :type, :message do "Error creating type specialization of #{label.a_an(type)}, #{message}" end ILLEGAL_TYPE_SPECIALIZATION = issue :ILLEGAL_TYPE_SPECIALIZATION, :kind do "Cannot specialize an already specialized #{kind} type" end ILLEGAL_RESOURCE_SPECIALIZATION = issue :ILLEGAL_RESOURCE_SPECIALIZATION, :actual do "First argument to Resource[] must be a resource type or a String. Got #{actual}." end EMPTY_RESOURCE_SPECIALIZATION = issue :EMPTY_RESOURCE_SPECIALIZATION do "Arguments to Resource[] are all empty/undefined" end ILLEGAL_HOSTCLASS_NAME = hard_issue :ILLEGAL_HOSTCLASS_NAME, :name do "Illegal Class name in class reference. #{label.a_an_uc(name)} cannot be used where a String is expected" end ILLEGAL_DEFINITION_NAME = hard_issue :ILLEGAL_DEFINITION_NAME, :name do "Unacceptable name. The name '#{name}' is unacceptable as the name of #{label.a_an(semantic)}" end CAPTURES_REST_NOT_LAST = hard_issue :CAPTURES_REST_NOT_LAST, :param_name do "Parameter $#{param_name} is not last, and has 'captures rest'" end CAPTURES_REST_NOT_SUPPORTED = hard_issue :CAPTURES_REST_NOT_SUPPORTED, :container, :param_name do "Parameter $#{param_name} has 'captures rest' - not supported in #{label.a_an(container)}" end REQUIRED_PARAMETER_AFTER_OPTIONAL = hard_issue :REQUIRED_PARAMETER_AFTER_OPTIONAL, :param_name do "Parameter $#{param_name} is required but appears after optional parameters" end MISSING_REQUIRED_PARAMETER = hard_issue :MISSING_REQUIRED_PARAMETER, :param_name do "Parameter $#{param_name} is required but no value was given" end NOT_NUMERIC = issue :NOT_NUMERIC, :value do "The value '#{value}' cannot be converted to Numeric." end UNKNOWN_FUNCTION = issue :UNKNOWN_FUNCTION, :name do "Unknown function: '#{name}'." end UNKNOWN_VARIABLE = issue :UNKNOWN_VARIABLE, :name do "Unknown variable: '#{name}'." end RUNTIME_ERROR = issue :RUNTIME_ERROR, :detail do "Error while evaluating #{label.a_an(semantic)}, #{detail}" end UNKNOWN_RESOURCE_TYPE = issue :UNKNOWN_RESOURCE_TYPE, :type_name do "Resource type not found: #{type_name.capitalize}" end ILLEGAL_RESOURCE_TYPE = hard_issue :ILLEGAL_RESOURCE_TYPE, :actual do "Illegal Resource Type expression, expected result to be a type name, or untitled Resource, got #{actual}" end DUPLICATE_TITLE = issue :DUPLICATE_TITLE, :title do "The title '#{title}' has already been used in this resource expression" end DUPLICATE_ATTRIBUTE = issue :DUPLICATE_ATTRIBUE, :attribute do "The attribute '#{attribute}' has already been set" end MISSING_TITLE = hard_issue :MISSING_TITLE do "Missing title. The title expression resulted in undef" end MISSING_TITLE_AT = hard_issue :MISSING_TITLE_AT, :index do "Missing title at index #{index}. The title expression resulted in an undef title" end ILLEGAL_TITLE_TYPE_AT = hard_issue :ILLEGAL_TITLE_TYPE_AT, :index, :actual do "Illegal title type at index #{index}. Expected String, got #{actual}" end EMPTY_STRING_TITLE_AT = hard_issue :EMPTY_STRING_TITLE_AT, :index do "Empty string title at #{index}. Title strings must have a length greater than zero." end UNKNOWN_RESOURCE = issue :UNKNOWN_RESOURCE, :type_name, :title do "Resource not found: #{type_name.capitalize}['#{title}']" end UNKNOWN_RESOURCE_PARAMETER = issue :UNKNOWN_RESOURCE_PARAMETER, :type_name, :title, :param_name do "The resource #{type_name.capitalize}['#{title}'] does not have a parameter called '#{param_name}'" end DIV_BY_ZERO = hard_issue :DIV_BY_ZERO do "Division by 0" end RESULT_IS_INFINITY = hard_issue :RESULT_IS_INFINITY, :operator do "The result of the #{operator} expression is Infinity" end # TODO_HEREDOC EMPTY_HEREDOC_SYNTAX_SEGMENT = issue :EMPTY_HEREDOC_SYNTAX_SEGMENT, :syntax do "Heredoc syntax specification has empty segment between '+' : '#{syntax}'" end ILLEGAL_EPP_PARAMETERS = issue :ILLEGAL_EPP_PARAMETERS do "Ambiguous EPP parameter expression. Probably missing '<%-' before parameters to remove leading whitespace" end DISCONTINUED_IMPORT = hard_issue :DISCONTINUED_IMPORT do "Use of 'import' has been discontinued in favor of a manifest directory. See http://links.puppetlabs.com/puppet-import-deprecation" end IDEM_EXPRESSION_NOT_LAST = issue :IDEM_EXPRESSION_NOT_LAST do "This #{label.label(semantic)} has no effect. A value was produced and then forgotten (one or more preceding expressions may have the wrong form)" end RESOURCE_WITHOUT_TITLE = issue :RESOURCE_WITHOUT_TITLE, :name do "This expression is invalid. Did you try declaring a '#{name}' resource without a title?" end IDEM_NOT_ALLOWED_LAST = hard_issue :IDEM_NOT_ALLOWED_LAST, :container do "This #{label.label(semantic)} has no effect. #{label.a_an_uc(container)} can not end with a value-producing expression without other effect" end RESERVED_WORD = hard_issue :RESERVED_WORD, :word do "Use of reserved word: #{word}, must be quoted if intended to be a String value" end FUTURE_RESERVED_WORD = issue :FUTURE_RESERVED_WORD, :word do "Use of future reserved word: '#{word}'" end RESERVED_TYPE_NAME = hard_issue :RESERVED_TYPE_NAME, :name do "The name: '#{name}' is already defined by Puppet and can not be used as the name of #{label.a_an(semantic)}." end UNMATCHED_SELECTOR = hard_issue :UNMATCHED_SELECTOR, :param_value do "No matching entry for selector parameter with value '#{param_value}'" end ILLEGAL_NODE_INHERITANCE = issue :ILLEGAL_NODE_INHERITANCE do "Node inheritance is not supported in Puppet >= 4.0.0. See http://links.puppetlabs.com/puppet-node-inheritance-deprecation" end ILLEGAL_OVERRIDEN_TYPE = issue :ILLEGAL_OVERRIDEN_TYPE, :actual do "Resource Override can only operate on resources, got: #{label.label(actual)}" end DUPLICATE_PARAMETER = hard_issue :DUPLICATE_PARAMETER, :param_name do "The parameter '#{param_name}' is declared more than once in the parameter list" end DUPLICATE_KEY = issue :DUPLICATE_KEY, :key do "The key '#{key}' is declared more than once" end RESERVED_PARAMETER = hard_issue :RESERVED_PARAMETER, :container, :param_name do "The parameter $#{param_name} redefines a built in parameter in #{label.the(container)}" end TYPE_MISMATCH = hard_issue :TYPE_MISMATCH, :expected, :actual do "Expected value of type #{expected}, got #{actual}" end MULTIPLE_ATTRIBUTES_UNFOLD = hard_issue :MULTIPLE_ATTRIBUTES_UNFOLD do "Unfolding of attributes from Hash can only be used once per resource body" end ILLEGAL_CATALOG_RELATED_EXPRESSION = hard_issue :ILLEGAL_CATALOG_RELATED_EXPRESSION do "This #{label.label(semantic)} appears in a context where catalog related expressions are not allowed" end SYNTAX_ERROR = hard_issue :SYNTAX_ERROR, :where do "Syntax error at #{where}" end ILLEGAL_CLASS_REFERENCE = hard_issue :ILLEGAL_CLASS_REFERENCE do 'Illegal class reference' end ILLEGAL_FULLY_QUALIFIED_CLASS_REFERENCE = hard_issue :ILLEGAL_FULLY_QUALIFIED_CLASS_REFERENCE do 'Illegal fully qualified class reference' end ILLEGAL_FULLY_QUALIFIED_NAME = hard_issue :ILLEGAL_FULLY_QUALIFIED_NAME do 'Illegal fully qualified name' end ILLEGAL_NAME_OR_BARE_WORD = hard_issue :ILLEGAL_NAME_OR_BARE_WORD do 'Illegal name or bare word' end ILLEGAL_NUMBER = hard_issue :ILLEGAL_NUMBER, :value do "Illegal number '#{value}'" end ILLEGAL_UNICODE_ESCAPE = issue :ILLEGAL_UNICODE_ESCAPE do "Unicode escape '\\u' was not followed by 4 hex digits or 1-6 hex digits in {} or was > 10ffff" end INVALID_HEX_NUMBER = hard_issue :INVALID_HEX_NUMBER, :value do "Not a valid hex number #{value}" end INVALID_OCTAL_NUMBER = hard_issue :INVALID_OCTAL_NUMBER, :value do "Not a valid octal number #{value}" end INVALID_DECIMAL_NUMBER = hard_issue :INVALID_DECIMAL_NUMBER, :value do "Not a valid decimal number #{value}" end NO_INPUT_TO_LEXER = hard_issue :NO_INPUT_TO_LEXER do "Internal Error: No string or file given to lexer to process." end UNRECOGNIZED_ESCAPE = issue :UNRECOGNIZED_ESCAPE, :ch do "Unrecognized escape sequence '\\#{ch}'" end UNCLOSED_QUOTE = hard_issue :UNCLOSED_QUOTE, :after, :followed_by do "Unclosed quote after #{after} followed by '#{followed_by}'" end UNCLOSED_MLCOMMENT = hard_issue :UNCLOSED_MLCOMMENT do 'Unclosed multiline comment' end EPP_INTERNAL_ERROR = hard_issue :EPP_INTERNAL_ERROR, :error do "Internal error: #{error}" end EPP_UNBALANCED_TAG = hard_issue :EPP_UNBALANCED_TAG do 'Unbalanced epp tag, reached <eof> without closing tag.' end EPP_UNBALANCED_COMMENT = hard_issue :EPP_UNBALANCED_COMMENT do 'Reaching end after opening <%# without seeing %>' end EPP_UNBALANCED_EXPRESSION = hard_issue :EPP_UNBALANCED_EXPRESSION do 'Unbalanced embedded expression - opening <% and reaching end of input' end HEREDOC_UNCLOSED_PARENTHESIS = hard_issue :HEREDOC_UNCLOSED_PARENTHESIS, :followed_by do "Unclosed parenthesis after '@(' followed by '#{followed_by}'" end HEREDOC_WITHOUT_END_TAGGED_LINE = hard_issue :HEREDOC_WITHOUT_END_TAGGED_LINE do 'Heredoc without end-tagged line' end HEREDOC_INVALID_ESCAPE = hard_issue :HEREDOC_INVALID_ESCAPE, :actual do "Invalid heredoc escape char. Only t, r, n, s, u, L, $ allowed. Got '#{actual}'" end HEREDOC_INVALID_SYNTAX = hard_issue :HEREDOC_INVALID_SYNTAX do 'Invalid syntax in heredoc expected @(endtag[:syntax][/escapes])' end HEREDOC_WITHOUT_TEXT = hard_issue :HEREDOC_WITHOUT_TEXT do 'Heredoc without any following lines of text' end HEREDOC_MULTIPLE_AT_ESCAPES = hard_issue :HEREDOC_MULTIPLE_AT_ESCAPES, :escapes do "An escape char for @() may only appear once. Got '#{escapes.join(', ')}'" end ILLEGAL_BOM = hard_issue :ILLEGAL_BOM, :format_name, :bytes do "Illegal #{format_name} Byte Order mark at beginning of input: #{bytes} - remove these from the puppet source" end end end
40.066852
150
0.732481
fff781f3f3785e7d3699cbe54a74e2abee9c5775
2,176
# frozen_string_literal: true # This controller allows management of Device records. class DevicesController < ApplicationController before_action :authenticate_user!, except: %i[index show build_config conf graph] # Index action. def index redirect_to browse_path end # Show action. def show @device = authorize Device.find(params[:id]) serve_image if params[:format] == 'jpg' end # New action. def new @device = authorize Device.new(user_id: current_user.id) end # Create action. def create @device = authorize Device.new(permitted_attributes(Device)) save_and_respond @device, :created, :create_success end # Edit action. def edit @device = authorize Device.find(params[:id]) end # Update action. def update @device = authorize Device.find(params[:id]) @device.assign_attributes permitted_attributes(@device) save_and_respond @device, :ok, :update_success end # Destroy action. def destroy @device = authorize Device.find(params[:id]) destroy_and_respond @device, @device.node end # Build action. def build @device = authorize Device.find(params[:id]) try_build if @device.can_build? redirect_to @device end # Build configuration action. def build_config show render plain: @device.build_config.delete("\r") end # Device configuration action. def conf show end # Graph action. def graph @device = authorize Device.find(params[:id]) respond_to do |format| format.png do send_data @device.graph.to_png, type: 'image/png', disposition: 'inline' end format.any { redirect_to format: :png } end end private def blob @device.image.blob end def serve_image return head(:not_found) unless @device.image.attached? expires_in 1.year, public: true send_data blob.service.download(blob.key), type: blob.content_type, disposition: 'inline' end def try_build if @device&.device_type&.build_provider&.build(@device) flash[:notice] = 'Build started.' else flash[:warning] = 'Build not available.' end end end
21.76
80
0.680147
116c324c1e9af9cf9f8509165c947e1cbf0b95c1
148
require 'test_helper' class ServicosProfissionaisControllerTest < ActionController::TestCase # test "the truth" do # assert true # end end
18.5
70
0.756757
38ebd8becf198a9bce3afb229d75b556c2fb50b6
172
# frozen_string_literal: true # Imported Workers model class ImportedWorker < ActiveRecord::Base validates :name, presence: true validates :email, presence: true end
21.5
41
0.77907
874cd9c8aece61362d87f68556067f34ccda6a98
194
ENV['SINATRA_ENV'] ||= "development" require 'bundler/setup' Bundler.require(:default, ENV['SINATRA_ENV']) ActiveRecord::Base.establish_connection(ENV['SINATRA_ENV'].to_sym) require_all 'app'
24.25
66
0.768041
ed774dee2b58429e8fe1298a04d9d4e61d4f7d63
5,204
require "spec_helper" describe Bunny::Channel do after :each do connection.close if connection.open? end let(:n) { 200 } shared_examples "publish confirms" do context "when publishing with confirms enabled" do it "increments delivery index" do ch = connection.create_channel expect(ch).not_to be_using_publisher_confirmations ch.confirm_select expect(ch).to be_using_publisher_confirmations q = ch.queue("", :exclusive => true) x = ch.default_exchange n.times do x.publish("xyzzy", :routing_key => q.name) end expect(ch.next_publish_seq_no).to eq n + 1 expect(ch.wait_for_confirms).to eq true sleep 0.25 expect(q.message_count).to eq n q.purge ch.close end describe "#wait_for_confirms" do it "should not hang when all the publishes are confirmed" do ch = connection.create_channel expect(ch).not_to be_using_publisher_confirmations ch.confirm_select expect(ch).to be_using_publisher_confirmations q = ch.queue("", :exclusive => true) x = ch.default_exchange n.times do x.publish("xyzzy", :routing_key => q.name) end expect(ch.next_publish_seq_no).to eq n + 1 expect(ch.wait_for_confirms).to eq true sleep 0.25 expect { Bunny::Timeout.timeout(2) do expect(ch.wait_for_confirms).to eq true end }.not_to raise_error end it "raises an error when called on a closed channel" do ch = connection.create_channel ch.confirm_select ch.close expect { ch.wait_for_confirms }.to raise_error(Bunny::ChannelAlreadyClosed) end end context "when some of the messages get nacked" do it "puts the nacks in the nacked_set" do ch = connection.create_channel expect(ch).not_to be_using_publisher_confirmations ch.confirm_select expect(ch).to be_using_publisher_confirmations q = ch.queue("", :exclusive => true) x = ch.default_exchange n.times do x.publish("xyzzy", :routing_key => q.name) end #be sneaky to simulate a nack nacked_tag = nil ch.instance_variable_get(:@unconfirmed_set_mutex).synchronize do expect(ch.unconfirmed_set).to_not be_empty nacked_tag = ch.unconfirmed_set.reduce(ch.next_publish_seq_no - 1) { |lowest, i| i < lowest ? i : lowest } ch.handle_ack_or_nack(nacked_tag, false, true) end expect(ch.nacked_set).not_to be_empty expect(ch.nacked_set).to include(nacked_tag) expect(ch.next_publish_seq_no).to eq n + 1 expect(ch.wait_for_confirms).to eq false expect(ch.nacked_set).not_to be_empty expect(ch.nacked_set).to include(nacked_tag) sleep 0.25 expect(q.message_count).to eq n q.purge ch.close end end end end context "with a multi-threaded connection" do let(:connection) do c = Bunny.new(:user => "bunny_gem", :password => "bunny_password", :vhost => "bunny_testbed", :continuation_timeout => 10000) c.start c end include_examples "publish confirms" it "returns only when all confirmations for publishes are received" do ch = connection.create_channel operations_log = [] operations_log_mutex = Mutex.new acks_received = Queue.new log_acks = proc do |tag, _, is_nack| operations_log_mutex.synchronize do operation = "#{'n' if is_nack}ack_#{tag}" operations_log << operation unless operations_log.include?(operation) end acks_received << true end ch.confirm_select(log_acks) x = ch.default_exchange q = ch.temporary_queue x.publish('msg', routing_key: q.name) # wait for the confirmation to arrive acks_received.pop # artificially simulate a slower ack. the test should work properly even # without this patch, but it's here just to be sure we catch it. def (x.channel).handle_ack_or_nack(delivery_tag_before_offset, multiple, nack) sleep 0.1 super end x.publish('msg', routing_key: q.name) x.publish('msg', routing_key: q.name) if x.wait_for_confirms operations_log_mutex.synchronize do operations_log << 'all_confirmed' end end # wait for all the confirmations to arrive acks_received.pop acks_received.pop expect(operations_log).to eq([ 'ack_1', 'ack_2', 'ack_3', 'all_confirmed', ]) end end context "with a single-threaded connection" do let(:connection) do c = Bunny.new(:user => "bunny_gem", :password => "bunny_password", :vhost => "bunny_testbed", :continuation_timeout => 10000, :threaded => false) c.start c end include_examples "publish confirms" end end
27.104167
151
0.613374
03491bd927ce3103b0f9950591e57c1125948291
2,097
require 'one_gadget/gadget' # https://gitlab.com/libcdb/libcdb/blob/master/libc/libc0.3-i686-2.19-7/lib/i386-gnu/i686/cmov/libc-2.19.so # # Intel 80386 # # GNU C Library (Debian GLIBC 2.19-7) stable release version 2.19, by Roland McGrath et al. # Copyright (C) 2014 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. # There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. # Compiled by GNU CC version 4.8.3. # Available extensions: # crypt add-on version 2.1 by Michael Glad and others # GNU Libidn by Simon Josefsson # BIND-8.2.3-T5B # libc ABIs: UNIQUE # For bug reporting instructions, please see: # <http://www.debian.org/Bugs/>. build_id = File.basename(__FILE__, '.rb').split('-').last OneGadget::Gadget.add(build_id, 454764, constraints: ["ebx is the GOT address of libc", "[esp+0x30] == NULL"], effect: "execve(\"/bin/sh\", esp+0x30, environ)") OneGadget::Gadget.add(build_id, 454790, constraints: ["ebx is the GOT address of libc", "[eax] == NULL || eax == NULL", "[[esp+0x8]] == NULL || [esp+0x8] == NULL"], effect: "execve(\"/bin/sh\", eax, [esp+0x8])") OneGadget::Gadget.add(build_id, 454794, constraints: ["ebx is the GOT address of libc", "[[esp+0x4]] == NULL || [esp+0x4] == NULL", "[[esp+0x8]] == NULL || [esp+0x8] == NULL"], effect: "execve(\"/bin/sh\", [esp+0x4], [esp+0x8])") OneGadget::Gadget.add(build_id, 610071, constraints: ["ebx is the GOT address of libc", "[esp+0x8] == NULL"], effect: "execl(\"/bin/sh\", \"sh\", [esp+0x8])") OneGadget::Gadget.add(build_id, 610077, constraints: ["ebx is the GOT address of libc", "eax == NULL"], effect: "execl(\"/bin/sh\", eax)") OneGadget::Gadget.add(build_id, 610081, constraints: ["ebx is the GOT address of libc", "[esp+0x4] == NULL"], effect: "execl(\"/bin/sh\", [esp+0x4])")
52.425
158
0.58989
bfa0fe6ccc0ae342802698f24fd428045f9c9692
865
require "rubygems" require "bundler/setup" Bundler.require(:default, :test) require "minitest/autorun" module Omise class Test < Minitest::Test def before_setup Omise.test! Omise.api_version = nil Omise.public_api_key = "pkey_test_4yq6tct0llin5nyyi5l" Omise.secret_api_key = "skey_test_4yq6tct0lblmed2yp5t" Omise.app_key = "app_test_4yq6tct0lblmed2yp5t" end def setup before_setup end def self.setup(&block) define_method :setup do before_setup instance_exec(&block) end end private def without_keys original_vault_key = Omise.vault_key original_api_key = Omise.api_key Omise.vault_key = nil Omise.api_key = nil yield Omise.vault_key = original_vault_key Omise.api_key = original_api_key end end end
19.222222
60
0.669364
915cbdd6b46305c199155340cbdc51f065c3de9e
156
module Private module Withdraws class DgbsController < ::Private::Withdraws::BaseController include ::Withdraws::Withdrawable end end end
19.5
63
0.730769
ff14e5b22e410b0aa61d19882c19f78ef7a5d678
2,422
require 'test_helper' class Elasticsearch::Model::ResponseTest < Test::Unit::TestCase context "Response" do class OriginClass def self.index_name; 'foo'; end def self.document_type; 'bar'; end end RESPONSE = { 'took' => '5', 'timed_out' => false, '_shards' => {'one' => 'OK'}, 'hits' => { 'hits' => [] } } setup do @search = Elasticsearch::Model::Searching::SearchRequest.new OriginClass, '*' @search.stubs(:execute!).returns(RESPONSE) end should "access klass, response, took, timed_out, shards" do response = Elasticsearch::Model::Response::Response.new OriginClass, @search assert_equal OriginClass, response.klass assert_equal @search, response.search assert_equal RESPONSE, response.response assert_equal '5', response.took assert_equal false, response.timed_out assert_equal 'OK', response.shards.one end should "wrap the raw Hash response in Hashie::Mash" do @search = Elasticsearch::Model::Searching::SearchRequest.new OriginClass, '*' @search.stubs(:execute!).returns({'hits' => { 'hits' => [] }, 'aggregations' => { 'dates' => 'FOO' }}) response = Elasticsearch::Model::Response::Response.new OriginClass, @search assert_respond_to response.response, :aggregations assert_equal 'FOO', response.response.aggregations.dates end should "load and access the results" do @search.expects(:execute!).returns(RESPONSE) response = Elasticsearch::Model::Response::Response.new OriginClass, @search assert_instance_of Elasticsearch::Model::Response::Results, response.results assert_equal 0, response.size end should "load and access the records" do @search.expects(:execute!).returns(RESPONSE) response = Elasticsearch::Model::Response::Response.new OriginClass, @search assert_instance_of Elasticsearch::Model::Response::Records, response.records assert_equal 0, response.size end should "delegate Enumerable methods to results" do @search.expects(:execute!).returns(RESPONSE) response = Elasticsearch::Model::Response::Response.new OriginClass, @search assert response.empty? end should "be initialized lazily" do @search.expects(:execute!).never Elasticsearch::Model::Response::Response.new OriginClass, @search end end end
35.617647
112
0.677952
d50851ae5c2e6ca6a444dbe6008b70add1669d0e
941
require_dependency "short_message/application_controller" module ShortMessage class MessagesController < ApplicationController def status unless params[:id].blank? or params[:status].blank? if message = ShortMessage::Message.where(message_key: params[:id]).first message.status_code = params[:status] message.save! ActiveSupport::Notifications.instrument('short_message.status_updated', options: { key: params[:id], status: params[:status] }) message = "Message #{params[:id]} has now status #{params[:status]}" else message = "Message #{params[:id]} not found!" status = 404 end else message = "Message ID or status not provided!" status = 400 end if Rails.version[0].to_i > 4 render plain: message, status: status else render text: message, status: status end end end end
31.366667
137
0.634431
21601d8a19ac1db6bfd92d47873d295726a280cc
4,298
module SparkApi module Models # =API Model Base class # Intended to be a lot like working with ActiveResource, this class adds most of the basic # active model type niceties. class Base extend Paginate include Dirty attr_accessor :attributes, :errors, :parent # More familiar accessor for our Spark API Id method def id self.Id end # Name of the resource as related to the path name def self.element_name # TODO I'd love to pull in active model at this point to provide default naming @element_name ||= "resource" end def self.element_name=(name) @element_name = name end # Resource path prefix, prepended to the url def self.prefix @prefix ||= "/" end def self.prefix=(prefix) @prefix = prefix end def resource_uri self.ResourceUri.sub(/^\/#{SparkApi.client.version}/, "") if persisted? end def self.path "#{prefix}#{element_name}" end def path if self.persisted? resource_uri.sub(/\/[0-9]{26}$/, "") else if @parent "#{@parent.class.path}/#{@parent.Id}#{self.class.path}" else self.class.path end end end def self.connection SparkApi.client end def connection self.class.connection end def initialize(attributes={}) @attributes = {} @errors = [] load(attributes, { :clean => true }) end def load(attributes, options = {}) attributes.each do |key,val| attribute_will_change!(key) unless options[:clean] @attributes[key.to_s] = val end end def self.get(options={}) collect(connection.get(path, options)) end def self.first(options={}) get(options).first end def self.count(options={}) connection.get(path, options.merge({:_pagination=>"count"})) end def method_missing(method_symbol, *arguments) method_name = method_symbol.to_s if method_name =~ /(=|\?|_will_change!)$/ case $1 when "=" write_attribute($`, arguments.first) # TODO figure out a nice way to present setters for the standard fields when "?" raise NoMethodError unless attributes.include?($`) attributes[$`] ? true : false when "_will_change!" raise NoMethodError unless attributes.include?($`) attribute_will_change!($`) end else return attributes[method_name] if attributes.include?(method_name) super end end def respond_to?(method_symbol, include_all=false) if super return true else method_name = method_symbol.to_s if method_name =~ /=$/ true elsif method_name =~ /(\?)$/ attributes.include?($`) elsif method_name =~ /(\w*)_will_change!$/ attributes.include?($1) else attributes.include?(method_name) end end end def parse_id(uri) uri[/\/.*\/(.+)$/, 1] end def persisted?; !@attributes['Id'].nil? && !@attributes['ResourceUri'].nil? end def to_param attributes['Id'] end def to_partial_path "#{underscore(resource_pluralized)}/#{underscore(self.class.name.split('::').last)}" end # can be overridden def resource_pluralized resource = self.class.name.split('::').last unless resource.split('').last == "s" resource = resource + "s" end resource end protected def write_attribute(attribute, value) attribute = attribute.to_s unless attributes[attribute] == value attribute_will_change!(attribute) attributes[attribute] = value end end private def underscore(string) string.to_s.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end end end end
24.843931
95
0.543741
e864ed42cf3186a1eb0deb15400e3dc4591d8fd2
1,111
require "application_system_test_case" class QuestionsTest < ApplicationSystemTestCase setup do @question = questions(:one) end test "visiting the index" do visit questions_url assert_selector "h1", text: "Questions" end test "creating a Question" do visit questions_url click_on "New Question" fill_in "Author", with: @question.author fill_in "Pubdate", with: @question.pubDate fill_in "Title", with: @question.title click_on "Create Question" assert_text "Question was successfully created" click_on "Back" end test "updating a Question" do visit questions_url click_on "Edit", match: :first fill_in "Author", with: @question.author fill_in "Pubdate", with: @question.pubDate fill_in "Title", with: @question.title click_on "Update Question" assert_text "Question was successfully updated" click_on "Back" end test "destroying a Question" do visit questions_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Question was successfully destroyed" end end
23.145833
53
0.707471
bb4684b9dfcabf1da28885c1adcacf4a7dd1d922
6,344
class PerconaServer < Formula desc "Drop-in MySQL replacement" homepage "https://www.percona.com" url "https://www.percona.com/downloads/Percona-Server-8.0/Percona-Server-8.0.17-8/source/tarball/percona-server-8.0.17-8.tar.gz" sha256 "0a96de68a71acce0c3c57cdd554b63a8f7c3026bd5aec88a384f76ce9ff4fced" bottle do sha256 "9df258ed7a61017087fd3ba1c4a2968f4fe5732c428a45455b9c4ba3faaa5b70" => :catalina sha256 "d76960aa4262d39beacb460fc47bffb71e31314afd9e57d381bd2a4b319d3425" => :mojave sha256 "2a832324afac70b9895d8b0f6017a7f93b7008f77bfffa16cf184ff505a0a027" => :high_sierra end pour_bottle? do reason "The bottle needs a var/mysql datadir (yours is var/percona)." satisfy { datadir == var/"mysql" } end depends_on "cmake" => :build # https://github.com/Homebrew/homebrew-core/issues/1475 # Needs at least Clang 3.3, which shipped alongside Lion. # Note: MySQL themselves don't support anything below Sierra. depends_on :macos => :yosemite depends_on "[email protected]" conflicts_with "mariadb", "mysql", :because => "percona, mariadb, and mysql install the same binaries." conflicts_with "mysql-connector-c", :because => "both install MySQL client libraries" conflicts_with "mariadb-connector-c", :because => "both install plugins" # https://bugs.mysql.com/bug.php?id=86711 # https://github.com/Homebrew/homebrew-core/pull/20538 fails_with :clang do build 800 cause "Wrong inlining with Clang 8.0, see MySQL Bug #86711" end resource "boost" do url "https://downloads.sourceforge.net/project/boost/boost/1.69.0/boost_1_69_0.tar.bz2" sha256 "8f32d4617390d1c2d16f26a27ab60d97807b35440d45891fa340fc2648b04406" end # Where the database files should be located. Existing installs have them # under var/percona, but going forward they will be under var/mysql to be # shared with the mysql and mariadb formulae. def datadir @datadir ||= (var/"percona").directory? ? var/"percona" : var/"mysql" end def install # -DINSTALL_* are relative to `CMAKE_INSTALL_PREFIX` (`prefix`) args = %W[ -DFORCE_INSOURCE_BUILD=1 -DCOMPILATION_COMMENT=Homebrew -DDEFAULT_CHARSET=utf8mb4 -DDEFAULT_COLLATION=utf8mb4_0900_ai_ci -DINSTALL_DOCDIR=share/doc/#{name} -DINSTALL_INCLUDEDIR=include/mysql -DINSTALL_INFODIR=share/info -DINSTALL_MANDIR=share/man -DINSTALL_MYSQLSHAREDIR=share/mysql -DINSTALL_PLUGINDIR=lib/plugin -DMYSQL_DATADIR=#{datadir} -DSYSCONFDIR=#{etc} -DWITH_SSL=yes -DWITH_UNIT_TESTS=OFF -DWITH_EMBEDDED_SERVER=ON -DENABLED_LOCAL_INFILE=1 -DWITH_INNODB_MEMCACHED=ON -DWITH_EDITLINE=system ] # MySQL >5.7.x mandates Boost as a requirement to build & has a strict # version check in place to ensure it only builds against expected release. # This is problematic when Boost releases don't align with MySQL releases. (buildpath/"boost").install resource("boost") args << "-DWITH_BOOST=#{buildpath}/boost" # Percona MyRocks does not compile on macOS # https://bugs.launchpad.net/percona-server/+bug/1741639 args.concat %w[-DWITHOUT_ROCKSDB=1] # TokuDB does not compile on macOS # https://bugs.launchpad.net/percona-server/+bug/1531446 args.concat %w[-DWITHOUT_TOKUDB=1] system "cmake", ".", *std_cmake_args, *args system "make" system "make", "install" (prefix/"mysql-test").cd do system "./mysql-test-run.pl", "status", "--vardir=#{Dir.mktmpdir}" end # Remove the tests directory rm_rf prefix/"mysql-test" # Don't create databases inside of the prefix! # See: https://github.com/Homebrew/homebrew/issues/4975 rm_rf prefix/"data" # Fix up the control script and link into bin. inreplace "#{prefix}/support-files/mysql.server", /^(PATH=".*)(")/, "\\1:#{HOMEBREW_PREFIX}/bin\\2" bin.install_symlink prefix/"support-files/mysql.server" # Install my.cnf that binds to 127.0.0.1 by default (buildpath/"my.cnf").write <<~EOS # Default Homebrew MySQL server config [mysqld] # Only allow connections from localhost bind-address = 127.0.0.1 EOS etc.install "my.cnf" end def post_install # Make sure the datadir exists datadir.mkpath unless (datadir/"mysql/user.frm").exist? ENV["TMPDIR"] = nil system bin/"mysqld", "--initialize-insecure", "--user=#{ENV["USER"]}", "--basedir=#{prefix}", "--datadir=#{datadir}", "--tmpdir=/tmp" end end def caveats s = <<~EOS We've installed your MySQL database without a root password. To secure it run: mysql_secure_installation MySQL is configured to only allow connections from localhost by default To connect run: mysql -uroot EOS if my_cnf = ["/etc/my.cnf", "/etc/mysql/my.cnf"].find { |x| File.exist? x } s += <<~EOS A "#{my_cnf}" from another install may interfere with a Homebrew-built server starting up correctly. EOS end s end plist_options :manual => "mysql.server start" def plist; <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <true/> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/mysqld_safe</string> <string>--datadir=#{datadir}</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{datadir}</string> </dict> </plist> EOS end test do # Expects datadir to be a completely clean dir, which testpath isn't. dir = Dir.mktmpdir system bin/"mysqld", "--initialize-insecure", "--user=#{ENV["USER"]}", "--basedir=#{prefix}", "--datadir=#{dir}", "--tmpdir=#{dir}" pid = fork do exec bin/"mysqld", "--bind-address=127.0.0.1", "--datadir=#{dir}" end sleep 2 output = shell_output("curl 127.0.0.1:3306") output.force_encoding("ASCII-8BIT") if output.respond_to?(:force_encoding) assert_match version.to_s, output ensure Process.kill(9, pid) Process.wait(pid) end end
33.21466
130
0.670082
b9e74f89cdff729cb893a9fb3f9e9e0d359e5ae5
824
# 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::CognitiveServices::VisualSearch::V1_0 module Models # # Defines values for ErrorSubCode # module ErrorSubCode UnexpectedError = "UnexpectedError" ResourceError = "ResourceError" NotImplemented = "NotImplemented" ParameterMissing = "ParameterMissing" ParameterInvalidValue = "ParameterInvalidValue" HttpNotAllowed = "HttpNotAllowed" Blocked = "Blocked" AuthorizationMissing = "AuthorizationMissing" AuthorizationRedundancy = "AuthorizationRedundancy" AuthorizationDisabled = "AuthorizationDisabled" AuthorizationExpired = "AuthorizationExpired" end end end
31.692308
70
0.73301
1df5da5979785167ffbdbe90a033f8d9da187998
2,762
module Redcar class Cocoa class TreeController include Redcar::Tree::Controller include Redcar::Project::LocalFilesystem def initialize(tree_mirror) @mirror = tree_mirror attach_listeners end # Open selected node path in default application # on double-click def activated(tree, node) Redcar::OpenDefaultApp::OpenDefaultAppCommand.new(node.path).run if node end # Attach change listeners to determine whether resource # files have been added or deleted. Checks are performed # when window or tree gains focus def attach_listeners Redcar.app.add_listener(:window_focussed) do |win| if tree = win.treebook.trees.detect {|t| t.tree_mirror == @mirror } @mirror.refresh tree.refresh end end win = Redcar.app.focussed_window win.treebook.add_listener(:tree_focussed) do |tree| if tree.tree_mirror == @mirror @mirror.refresh tree.refresh end end end # Show a context menu on click def right_click(tree, node) controller = self menu = Menu::Builder.build do if node and node.leaf? item("Open in Default App") { Redcar::OpenDefaultApp::OpenDefaultAppCommand.new(node.path).run } item("Move to Trash") { nodes = tree.selection.select {|n| n.path } basenames = nodes.map {|n| File.basename(n.path) } msg = "Really delete #{basenames.join(", ")}?" result = Application::Dialog.message_box(msg, :type => :question, :buttons => :yes_no) if result == :yes nodes.each do |n| controller.fs.delete(n.path) tree.tree_mirror.remove_node(n) end tree.tree_mirror.refresh tree.refresh end } separator end item("Add Resource...") { win = Redcar.app.focussed_window if path = Redcar::Application::Dialog.open_file({}) and File.dirname(path) != tree.tree_mirror.resource_files_path begin FileUtils.cp(path, tree.tree_mirror.resource_files_path) tree.tree_mirror.add_file(path) tree.refresh rescue Exception => e p e.message p e.backtrace Redcar::Application::Dialog.message_box("The selected file could not be copied: #{e.message}", "uh oh") end end } end Application::Dialog.popup_menu(menu, :pointer) end end end end
33.682927
126
0.558653
ab9891b127bb0904f527d466e4cfc66ff023a8d8
3,659
require 'mongrel' require 'stringio' require 'rack/content_length' require 'rack/chunked' module Rack module Handler class Mongrel < ::Mongrel::HttpHandler def self.run(app, options={}) environment = ENV['RACK_ENV'] || 'development' default_host = environment == 'development' ? 'localhost' : '0.0.0.0' server = ::Mongrel::HttpServer.new( options[:Host] || default_host, options[:Port] || 8080, options[:num_processors] || 950, options[:throttle] || 0, options[:timeout] || 60) # Acts like Rack::URLMap, utilizing Mongrel's own path finding methods. # Use is similar to #run, replacing the app argument with a hash of # { path=>app, ... } or an instance of Rack::URLMap. if options[:map] if app.is_a? Hash app.each do |path, appl| path = '/'+path unless path[0] == ?/ server.register(path, Rack::Handler::Mongrel.new(appl)) end elsif app.is_a? URLMap app.instance_variable_get(:@mapping).each do |(host, path, appl)| next if !host.nil? && !options[:Host].nil? && options[:Host] != host path = '/'+path unless path[0] == ?/ server.register(path, Rack::Handler::Mongrel.new(appl)) end else raise ArgumentError, "first argument should be a Hash or URLMap" end else server.register('/', Rack::Handler::Mongrel.new(app)) end yield server if block_given? server.run.join end def self.valid_options environment = ENV['RACK_ENV'] || 'development' default_host = environment == 'development' ? 'localhost' : '0.0.0.0' { "Host=HOST" => "Hostname to listen on (default: #{default_host})", "Port=PORT" => "Port to listen on (default: 8080)", "Processors=N" => "Number of concurrent processors to accept (default: 950)", "Timeout=N" => "Time before a request is dropped for inactivity (default: 60)", "Throttle=N" => "Throttle time between socket.accept calls in hundredths of a second (default: 0)", } end def initialize(app) @app = app end def process(request, response) env = Hash[request.params] env.delete "HTTP_CONTENT_TYPE" env.delete "HTTP_CONTENT_LENGTH" env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/" rack_input = request.body || StringIO.new('') rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding) env.update({"rack.version" => Rack::VERSION, "rack.input" => rack_input, "rack.errors" => $stderr, "rack.multithread" => true, "rack.multiprocess" => false, # ??? "rack.run_once" => false, "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http" }) env[QUERY_STRING] ||= "" status, headers, body = @app.call(env) begin response.status = status.to_i response.send_status(nil) headers.each { |k, vs| vs.split("\n").each { |v| response.header[k] = v } } response.send_header body.each { |part| response.write part response.socket.flush } ensure body.close if body.respond_to? :close end end end end end
34.196262
109
0.534026
ac3481499df1e6f4ab02d705844db80cdc1ff282
1,552
RSpec.describe Binary do it "has a version number" do expect(Binary::VERSION).not_to be nil end it "takes an integer and returns its binary representation" do expect(Binary.binary(7)).to eq("111") end it "takes non-integer input and returns nil" do expect(Binary.binary('hey')).to eq(nil) end it "takes an array of numbers and returns an array of their binary values" do expect(Binary.binary([1,2,3])).to eq(["1", "10", "11"]) end it "takes an array of numbers and returns nil for each non-integer element in the array" do expect(Binary.binary(['one','two',3])).to eq([nil, nil, "11"]) end it "takes a binary string and returns its integer representation" do expect(Binary.number("111")).to eq(7) end it "takes an array of binary strings and returns an array of their integer values" do expect(Binary.number(["1", "10", "11"])).to eq([1,2,3]) end it "returns number of bits in a number's binary representation" do expect(Binary.bits_count(7)).to eq(3) end it "returns number of ones in a number's binary representation" do expect(Binary.ones_count(7)).to eq(3) end it "returns number of zeros in a number's binary representation" do expect(Binary.zeros_count(9)).to eq(2) end it "returns an array of binaires of prime numbers" do expect(Binary.prime(9)).to eq(["10", "11", "101", "111"]) end it "returns a binary representation of a random number between 1 and the given number" do expect(["1", "10", "11"]).to include(Binary.random(3)) end end
31.04
93
0.681057
610e6d081572c37c2af415b733af1a7665831927
2,939
require 'spec_helper' require 'hydra/file_characterization/characterizers/fits_servlet' module Hydra::FileCharacterization::Characterizers describe FitsServlet do let(:fits) { Fits.new(filename) } describe "#call", unless: ENV['TRAVIS'] do subject { fits.call } context 'validfile' do let(:filename) { fixture_file('brendan_behan.jpeg') } it { is_expected.to include(%(<identity format="JPEG File Interchange Format" mimetype="image/jpeg")) } end context 'invalidFile' do let(:filename) { fixture_file('nofile.pdf') } it "raises an error" do expect { subject }.to raise_error(Hydra::FileCharacterization::FileNotFoundError) end end context 'corruptFile' do let(:filename) { fixture_file('brendan_broken.dxxd') } it { is_expected.to include(%(<identity format="Unknown Binary" mimetype="application/octet-stream")) } end context 'zip file should be characterized not its contents' do let(:filename) { fixture_file('archive.zip') } it { is_expected.to include(%(<identity format="ZIP Format" mimetype="application/zip"))} end end context 'when JHOVE adds non-xml' do # https://github.com/harvard-lts/fits/issues/20 subject { fits.call } before do expect(fits.logger).to receive(:warn) allow(fits).to receive(:internal_call).and_return( 'READBOX seen=true <?xml version="1.0" encoding="UTF-8"?> <fits xmlns="http://hul.harvard.edu/ois/xml/ns/fits/fits_output" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://hul.harvard.edu/ois/xml/ns/fits/fits_output http://hul.harvard.edu/ois/xml/xsd/fits/fits_output.xsd" version="0.8.2" timestamp="15/09/14 10:00 AM"> <identification/></fits>') end let(:filename) { fixture_file('brendan_behan.jpeg') } it { is_expected.not_to include('READBOX') } end context "when FITS itself adds non-xml" do # https://github.com/harvard-lts/fits/issues/46 subject { fits.call } before do expect(fits.logger).to receive(:warn) allow(fits).to receive(:internal_call).and_return( '2015-10-15 17:14:25,761 ERROR [main] ToolBelt:79 - Thread 1 error initializing edu.harvard.hul.ois.fits.tools.droid.Droid: edu.harvard.hul.ois.fits.exceptions.FitsToolException Message: DROID cannot run under Java 8 <?xml version="1.0" encoding="UTF-8"?> <fits xmlns="http://hul.harvard.edu/ois/xml/ns/fits/fits_output" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://hul.harvard.edu/ois/xml/ns/fits/fits_output http://hul.harvard.edu/ois/xml/xsd/fits/fits_output.xsd" version="0.8.2" timestamp="15/09/14 10:00 AM"> <identification/></fits>') end let(:filename) { fixture_file('brendan_behan.jpeg') } it { is_expected.not_to include('FitsToolException') } end end end
42.594203
293
0.680504
1db66f25640646100721e7347420b6a2912d352f
1,400
#-- # Copyright (c) 2019 Fuyuki Academy # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ module ErrorMessageModule extend ActiveSupport::Concern def has_error_detail?(key) if self.errors.details && self.errors.details.has_key?(key) self.errors.details[key].each do |datail| return true if datail.has_key?(:value) end end return false end end
37.837838
72
0.754286
61130b4196254dfc15894821ac4dc065d47b720b
689
require "chef/knife" require_relative "helpers/base_vsphere_command" # VspherePoolQuery extends the BaseVsphereCommand class Chef::Knife::VspherePoolQuery < Chef::Knife::BaseVsphereCommand banner 'knife vsphere pool query POOLNAME QUERY. See "https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.ComputeResource.html" for allowed QUERY values.' deps do Chef::Knife::BaseVsphereCommand.load_deps require "netaddr" end common_options # The main run method for poll_query # def run args = ARGV args[2] = "show" ui.warn "vsphere pool query is moving to vsphere pool show. Next time, please run" ui.warn args.join " " Chef::Knife.run(args) end end
27.56
155
0.738752
017bf8b25007729610eeac3b418a2c7e57f981ec
3,051
require 'test_helper' class UserTest < ActiveSupport::TestCase test '#github_url returns github url' do github_url = User.new(github: 'jroes').github_url assert_equal 'https://github.com/jroes', github_url end test 'public scope should only return public users' do user = users(:mockstar) private_user = users(:jroes) # Sanity check for fixture state assert_not user.private assert private_user.private result = User.public_profile assert_not_includes result, private_user assert_includes result, user end test 'able_to_edit_repo allows the correct rights' do u = User.new(github: "bob") r = Repo.new(user_name: "bob") assert u.able_to_edit_repo?(r) r2 = Repo.new(user_name: "neilmiddleton") assert_not u.able_to_edit_repo?(r2) end test 'valid_email? is true when valid' do assert User.new(email: '[email protected]').valid_email? end test 'valid_email? is false when bad' do assert_not User.new(email: 'a really bad e-mail address').valid_email? end test "user favorite_language?" do u = User.new(favorite_languages: ["ruby"]) assert u.favorite_language?("ruby") assert_not u.favorite_language?("java") end test "user has_favorite_languages?" do u = User.new(favorite_languages: ["ruby"]) assert u.has_favorite_languages? u = User.new(favorite_languages: []) assert_not u.has_favorite_languages? end test "account_delete_token should be created on first use" do u = User.new assert_nil u[:account_delete_token] assert_not_equal nil, u.account_delete_token end test "account_delete_token should be saved unless it is a new record" do u = User.new(email: "[email protected]", github: "abcabc123") assert_nil u.tap(&:account_delete_token).updated_at u.account_delete_token = nil u.save assert_not_equal u.updated_at, u.tap(&:account_delete_token).updated_at end test "user assignments to deliver updates assignments" do user = users(:mockstar) mock = Minitest::Mock.new mock.expect(:assign!, true) user.instance_variable_set(:@issue_assigner, mock) user.issue_assignments_to_deliver mock.verify end test "#own_repos_json" do VCR.use_cassette "fetcher_owned_repos_for_user_first_100" do assert_equal users(:mockstar).own_repos_json.last['name'], 'writings' end end test "#starred_repos_json" do VCR.use_cassette "fetcher_starred_repos_for_user" do assert_equal users(:mockstar).starred_repos_json.first['full_name'], 'tscanlin/next-blog' end end test "#subscribed_repos_json" do VCR.use_cassette "fetcher_subscribed_repos_for_user" do assert_equal users(:mockstar).subscribed_repos_json.first['full_name'], 'thoughtbot/suspenders' end end test "#fetcher" do assert users(:mockstar).fetcher.is_a? GithubFetcher::User end test "#repos_fetcher" do assert users(:mockstar).repos_fetcher(GithubFetcher::Repos::OWNED).is_a? GithubFetcher::Repos end end
28.514019
101
0.723697
181f04e02fbf7ee7882a6d9b2655ece104eeae9f
3,714
class Kubeseal < Formula desc "Kubernetes controller and tool for one-way encrypted Secrets" homepage "https://github.com/bitnami-labs/sealed-secrets" url "https://github.com/bitnami-labs/sealed-secrets.git", tag: "v0.16.0", revision: "392b871249268519157abcb9cf8a162396f6e02e" license "Apache-2.0" livecheck do url :stable regex(/^v?(\d+(?:\.\d+)+)$/i) end bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "6657e0cba1258478e3c1e5d5e25a7828cd5d8f242799e69428beb84cc36ae7c6" sha256 cellar: :any_skip_relocation, big_sur: "2a1ed17105b7150960ad0ff52a8a8af6a19ee68f6d6f0821c63cf5941a8b8f61" sha256 cellar: :any_skip_relocation, catalina: "b387aff195ecc80147c545e16d68264184bb1a7ab9cf4eac6b8d9b09afcf6faf" sha256 cellar: :any_skip_relocation, mojave: "57cbf276f5f8e0257692a72efdfab3950fc109d1c33a8f904af66d9d063edb6e" sha256 cellar: :any_skip_relocation, x86_64_linux: "d7cfc700c79b4a0f59daffa8044be0aa329a22719693cfb63b6727ad1ab64020" end depends_on "go" => :build def install system "make", "kubeseal", "DIRTY=" bin.install "kubeseal" end test do # ensure build reports the (git tag) version output = shell_output("#{bin}/kubeseal --version") assert_equal "kubeseal version: v#{version}", output.strip # ensure kubeseal can seal secrets secretyaml = [ "apiVersion: v1", "kind: Secret", "metadata:", " name: mysecret", " namespace: default", "type: Opaque", "data:", " username: YWRtaW4=", " password: MWYyZDFlMmU2N2Rm", ].join("\n") + "\n" cert = [ "-----BEGIN CERTIFICATE-----", "MIIErTCCApWgAwIBAgIQKBFEtKBDXcPklduZRLUirTANBgkqhkiG9w0BAQsFADAA", "MB4XDTE4MTEyNzE5NTE0NloXDTI4MTEyNDE5NTE0NlowADCCAiIwDQYJKoZIhvcN", "AQEBBQADggIPADCCAgoCggIBALff4ul8nqD+5mdaeFOJWzhah8v+AJeXZ2Ko4cBZ", "5PCWvbFQKAO+o2GwEZsUHaxP31eeUIAt0L/SjxaT9usoXK8QbtwRBV39H6iLI48+", "DP2v9AnZgN7G87lyqDufy5IdRyeYh0naTc9C8jWwoG8rDYR85Jxf+M/9grLb2yeD", "hAj+ziPTBr3t4hle/ob6pUUNh5I2rnoIT9lrCaRLTOhJqYofL4ld9ikDdCR0h2W9", "ZZCb9MnYNohng/7KCRWeyPEs+pDs5XiDCn4m4ObL4JJDhS4uIUiY0jstlN74wRul", "BZzn3WpjpDSLNa6wTpf/o91UplBUDEr9eWWsfGcgAw5iuKM46uWX7sAWQg65CqT3", "oR9JMJIRvNKbTEMfXRAIw0Imrox5E9B1uv3tCowFY4zQRNFUnEcCOonyOXGyVP8V", "gLMA+2f1vGyFYXjbPyC8dR/JZzUf9t+PfhitIU6eNjmeF5s319n0kfiC4e+/38Dv", "QN/uZ9MgUfa5pVcLKtX83Zu6vrNDOJT0iFil/WqHqo7BCtfAPX2o/2iXDhZDtcIV", "AafIu9HIuldEeAmfp7zAkFQEG+boL54kHsrvTljDkxHvl39eJuFqvZVdJAXcCVfO", "KyXyAdDk11XVhCyGMu93L7tffsmVVqgVcXU/vKupqjag/+xDTfRPhHCM1FrDMA7e", "ghuLAgMBAAGjIzAhMA4GA1UdDwEB/wQEAwIAATAPBgNVHRMBAf8EBTADAQH/MA0G", "CSqGSIb3DQEBCwUAA4ICAQATIoPga81tw0UQpPsGr+HR7pwKQTIp4zFFnlQJhR8U", "Kg1AyxXfOL+tK28xfTnMgKTXIcel+wsUbsseVDamJDZSs4dgwZFDxnV76WhbP67a", "XP1wHuu6H9PAt/NKV7iGpBL85mg88AlmpPYX5P++Pk5h+i6CenVFPDKwVHDc0vTB", "z4yO7MJmSmvGAkjAjmU0s37t3wfWyQpgID8uZmKNbvH8Ie0Y/fSuHz42HMOtb1SI", "5ck8jVpQgJwpfNVAy9fwwdyCdKKEGyGmo8oPYAT5Y9GFZh8dqoqVqATwJqLUe//V", "OEDxoRV+BXesbpJbJ8tOVtBHzoDU+tjx1jTchf2iWOPByIRQYNBvk25UWNnkdFLy", "f9PDrMo6axh+kjQTqrJ4JChL9qHXwSjTshaEcR272xD4vuRX+VMstQqRPwVElRnf", "o+MQ5YUiwulFnSykR5zY0U1jGdjywOzxRDLHsPo1WWnOuzfcHarM+YoMDnFzrOzJ", "EwP0zIygDpFytgh+Uq+ypKav7CHdA/yy/eWjDJI8b6gKB3mDB5pF+0KtBV61kbfF", "7+dVEtF0wQK+0CUdFtFRv3sk5Ud6wHrvMVTY7I4UcHVBe08DhrNJujHzTjolfXTj", "s0IweLRbZLe3m/9JLdW6WxylJSUBJhFJGASNwiAm9FwlwryLXzsjNHV/8Y6NkEnf", "JQ==", "-----END CERTIFICATE-----", ].join("\n") + "\n" File.write("cert.pem", cert) pipe_output("#{bin}/kubeseal --cert cert.pem", secretyaml) end end
45.851852
122
0.756327
386c53d13184bacf31df0c6f41d9c76c3415a427
76
require 'test_helper' class AttendeesHelperTest < ActionView::TestCase end
15.2
48
0.828947
d5ed514f9f6ee22b53f7ef0f5141985e985509a3
5,416
require "language_pack" require "pathname" require "yaml" require "digest/sha1" Encoding.default_external = Encoding::UTF_8 if defined?(Encoding) # abstract class that all the Ruby based Language Packs inherit from class LanguagePack::Base VENDOR_URL = "https://s3.amazonaws.com/heroku-buildpack-ruby" attr_reader :build_path, :cache_path # changes directory to the build_path # @param [String] the path of the build dir # @param [String] the path of the cache dir def initialize(build_path, cache_path=nil) @build_path = build_path @cache_path = cache_path @id = Digest::SHA1.hexdigest("#{Time.now.to_f}-#{rand(1000000)}")[0..10] Dir.chdir build_path end def self.===(build_path) raise "must subclass" end # name of the Language Pack # @return [String] the result def name raise "must subclass" end # list of default addons to install def default_addons raise "must subclass" end # config vars to be set on first push. # @return [Hash] the result # @not: this is only set the first time an app is pushed to. def default_config_vars raise "must subclass" end # process types to provide for the app # Ex. for rails we provide a web process # @return [Hash] the result def default_process_types raise "must subclass" end # this is called to build the slug def compile end # collection of values passed for a release # @return [String] in YAML format of the result def release setup_language_pack_environment { "addons" => default_addons, "config_vars" => default_config_vars, "default_process_types" => default_process_types }.to_yaml end # log output # Ex. log "some_message", "here", :someattr="value" def log(*args) args.concat [:id => @id] args.concat [:framework => self.class.to_s.split("::").last.downcase] start = Time.now.to_f log_internal args, :start => start if block_given? begin ret = yield finish = Time.now.to_f log_internal args, :status => "complete", :finish => finish, :elapsed => (finish - start) return ret rescue StandardError => ex finish = Time.now.to_f log_internal args, :status => "error", :finish => finish, :elapsed => (finish - start), :message => ex.message raise ex end end end private ################################## # sets up the environment variables for the build process def setup_language_pack_environment end def log_internal(*args) message = build_log_message(args) %x{ logger -p user.notice -t "slugc[$$]" "buildpack-ruby #{message}" } end def build_log_message(args) args.map do |arg| case arg when Float then "%0.2f" % arg when Array then build_log_message(arg) when Hash then arg.map { |k,v| "#{k}=#{build_log_message([v])}" }.join(" ") else arg end end.join(" ") end # display error message and stop the build process # @param [String] error message def error(message) Kernel.puts " !" message.split("\n").each do |line| Kernel.puts " ! #{line.strip}" end Kernel.puts " !" log "exit", :error => message exit 1 end # run a shell comannd and pipe stderr to stdout # @param [String] command to be run # @return [String] output of stdout and stderr def run(command) %x{ #{command} 2>&1 } end # run a shell command and pipe stderr to /dev/null # @param [String] command to be run # @return [String] output of stdout def run_stdout(command) %x{ #{command} 2>/dev/null } end # run a shell command and stream the ouput # @param [String] command to be run def pipe(command) output = "" IO.popen(command) do |io| until io.eof? buffer = io.gets output << buffer puts buffer end end output end # display a topic message # (denoted by ----->) # @param [String] topic message to be displayed def topic(message) Kernel.puts "-----> #{message}" $stdout.flush end # display a message in line # (indented by 6 spaces) # @param [String] message to be displayed def puts(message) message.split("\n").each do |line| super " #{line.strip}" end $stdout.flush end # create a Pathname of the cache dir # @return [Pathname] the cache dir def cache_base Pathname.new(cache_path) end # removes the the specified # @param [String] relative path from the cache_base def cache_clear(path) target = (cache_base + path) target.exist? && target.rmtree end # write cache contents # @param [String] path of contents to store. it will be stored using this a relative path from the cache_base. # @param [Boolean] defaults to true. if set to true, the cache store directory will be cleared before writing to it. def cache_store(path, clear_first=true) cache_clear(path) if clear_first cache_copy path, (cache_base + path) end # load cache contents # @param [String] relative path of the cache contents def cache_load(path) cache_copy (cache_base + path), path end # copy cache contents # @param [String] source directory # @param [String] destination directory def cache_copy(from, to) return false unless File.exist?(from) FileUtils.mkdir_p File.dirname(to) system("cp -a #{from}/. #{to}") end end
25.54717
118
0.651957
7990bcf03d1538a6f0d851736552b03c502a9195
9,877
#!/usr/bin/env ruby ### ### mdoc2man - mdoc to man converter ### ### Quick usage: mdoc2man.rb < mdoc_manpage.8 > man_manpage.8 ### ### Ported from Perl by Akinori MUSHA. ### ### Copyright (c) 2001 University of Illinois Board of Trustees ### Copyright (c) 2001 Mark D. Roth ### Copyright (c) 2002, 2003 Akinori MUSHA ### All rights reserved. ### ### Redistribution and use in source and binary forms, with or without ### modification, are permitted provided that the following conditions ### are met: ### 1. Redistributions of source code must retain the above copyright ### notice, this list of conditions and the following disclaimer. ### 2. Redistributions in binary form must reproduce the above copyright ### notice, this list of conditions and the following disclaimer in the ### documentation and/or other materials provided with the distribution. ### 3. All advertising materials mentioning features or use of this software ### must display the following acknowledgement: ### This product includes software developed by the University of ### Illinois at Urbana, and their contributors. ### 4. The University nor the names of their ### contributors may be used to endorse or promote products derived from ### this software without specific prior written permission. ### ### THIS SOFTWARE IS PROVIDED BY THE TRUSTEES AND CONTRIBUTORS ``AS IS'' AND ### ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ### IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ### ARE DISCLAIMED. IN NO EVENT SHALL THE TRUSTEES OR CONTRIBUTORS BE LIABLE ### FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ### DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ### OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ### HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT ### LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY ### OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF ### SUCH DAMAGE. ### ### $Id: mdoc2man.rb 52411 2015-10-31 06:22:46Z nobu $ ### class Mdoc2Man ANGLE = 1 OPTION = 2 PAREN = 3 RE_PUNCT = /^[!"'),\.\/:;>\?\]`]$/ def initialize @name = @date = @id = nil @refauthors = @reftitle = @refissue = @refdate = @refopt = nil @optlist = 0 ### 1 = bullet, 2 = enum, 3 = tag, 4 = item @oldoptlist = 0 @nospace = 0 ### 0, 1, 2 @enum = 0 @synopsis = true @reference = false @ext = false @extopt = false @literal = false end def mdoc2man(i, o) i.each { |line| if /^\./ !~ line o.print line o.print ".br\n" if @literal next end line.slice!(0, 1) next if /\\"/ =~ line line = parse_macro(line) and o.print line } initialize end def parse_macro(line) words = line.split retval = '' quote = [] dl = false while word = words.shift case word when RE_PUNCT next retval << word if word == ':' while q = quote.pop case q when OPTION retval << ']' when PAREN retval << ')' when ANGLE retval << '>' end end retval << word next when 'Li', 'Pf' @nospace = 1 next when 'Xo' @ext = true retval << ' ' unless retval.empty? || /[\n ]\z/ =~ retval next when 'Xc' @ext = false retval << "\n" unless @extopt break when 'Bd' @literal = true if words[0] == '-literal' retval << "\n" break when 'Ed' @literal = false break when 'Ns' @nospace = 1 if @nospace == 0 retval.chomp!(' ') next when 'No' retval.chomp!(' ') retval << words.shift next when 'Dq' retval << '``' begin retval << words.shift << ' ' end until words.empty? || RE_PUNCT =~ words[0] retval.chomp!(' ') retval << '\'\'' @nospace = 1 if @nospace == 0 && RE_PUNCT =~ words[0] next when 'Sq', 'Ql' retval << '`' << words.shift << '\'' @nospace = 1 if @nospace == 0 && RE_PUNCT =~ words[0] next # when 'Ic' # retval << '\\fB' << words.shift << '\\fP' # next when 'Oo' #retval << "[\\c\n" @extopt = true @nospace = 1 if @nospace == 0 retval << '[' next when 'Oc' @extopt = false retval << ']' next when 'Ao' @nospace = 1 if @nospace == 0 retval << '<' next when 'Ac' retval << '>' next end retval << ' ' if @nospace == 0 && !(retval.empty? || /[\n ]\z/ =~ retval) @nospace = 0 if @nospace == 1 case word when 'Dd' @date = words.join(' ') return nil when 'Dt' if words.size >= 2 && words[1] == '""' && /^(.*)\(([0-9])\)$/ =~ words[0] words[0] = $1 words[1] = $2 end @id = words.join(' ') return nil when 'Os' retval << '.TH ' << @id << ' "' << @date << '" "' << words.join(' ') << '"' break when 'Sh' retval << '.SH' @synopsis = (words[0] == 'SYNOPSIS') next when 'Xr' retval << '\\fB' << words.shift << '\\fP(' << words.shift << ')' << (words.shift||'') break when 'Rs' @refauthors = [] @reftitle = '' @refissue = '' @refdate = '' @refopt = '' @reference = true break when 'Re' retval << "\n" # authors while @refauthors.size > 1 retval << @refauthors.shift << ', ' end retval << 'and ' unless retval.empty? retval << @refauthors.shift # title retval << ', \\fI' << @reftitle << '\\fP' # issue retval << ', ' << @refissue unless @refissue.empty? # date retval << ', ' << @refdate unless @refdate.empty? # optional info retval << ', ' << @refopt unless @refopt.empty? retval << ".\n" @reference = false break when 'An' next when 'Dl' retval << ".nf\n" << '\\& ' dl = true next when 'Ux' retval << "UNIX" next when 'Bro' retval << '{' @nospace = 1 if @nospace == 0 next when 'Brc' retval.sub!(/ *\z/, '}') next end if @reference case word when '%A' @refauthors.unshift(words.join(' ')) break when '%T' @reftitle = words.join(' ') @reftitle.sub!(/^"/, '') @reftitle.sub!(/"$/, '') break when '%N' @refissue = words.join(' ') break when '%D' @refdate = words.join(' ') break when '%O' @refopt = words.join(' ') break end end case word when 'Nm' name = words.empty? ? @name : words.shift @name ||= name retval << ".br\n" if @synopsis retval << "\\fB" << name << "\\fP" @nospace = 1 if @nospace == 0 && RE_PUNCT =~ words[0] next when 'Nd' retval << '\\-' next when 'Fl' retval << '\\fB\\-' << words.shift << '\\fP' @nospace = 1 if @nospace == 0 && RE_PUNCT =~ words[0] next when 'Ar' retval << '\\fI' if words.empty? retval << 'file ...\\fP' else retval << words.shift << '\\fP' while words[0] == '|' retval << ' ' << words.shift << ' \\fI' << words.shift << '\\fP' end @nospace = 1 if @nospace == 0 && RE_PUNCT =~ words[0] next end when 'Cm' retval << '\\fB' << words.shift << '\\fP' while RE_PUNCT =~ words[0] retval << words.shift end next when 'Op' quote << OPTION @nospace = 1 if @nospace == 0 retval << '[' # words.push(words.pop + ']') next when 'Aq' quote << ANGLE @nospace = 1 if @nospace == 0 retval << '<' # words.push(words.pop + '>') next when 'Pp' retval << "\n" next when 'Ss' retval << '.SS' next end if word == 'Pa' && !quote.include?(OPTION) retval << '\\fI' retval << '\\&' if /^\./ =~ words[0] retval << words.shift << '\\fP' while RE_PUNCT =~ words[0] retval << words.shift end # @nospace = 1 if @nospace == 0 && RE_PUNCT =~ words[0] next end case word when 'Dv' retval << '.BR' next when 'Em', 'Ev' retval << '.IR' next when 'Pq' retval << '(' @nospace = 1 quote << PAREN next when 'Sx', 'Sy' retval << '.B ' << words.join(' ') break when 'Ic' retval << '\\fB' until words.empty? || RE_PUNCT =~ words[0] case words[0] when 'Op' words.shift retval << '[' words.push(words.pop + ']') next when 'Aq' words.shift retval << '<' words.push(words.pop + '>') next when 'Ar' words.shift retval << '\\fI' << words.shift << '\\fP' else retval << words.shift end retval << ' ' if @nospace == 0 end retval.chomp!(' ') retval << '\\fP' retval << words.shift unless words.empty? break when 'Bl' @oldoptlist = @optlist case words[0] when '-bullet' @optlist = 1 when '-enum' @optlist = 2 @enum = 0 when '-tag' @optlist = 3 when '-item' @optlist = 4 end break when 'El' @optlist = @oldoptlist next end if @optlist != 0 && word == 'It' case @optlist when 1 # bullets retval << '.IP \\(bu' when 2 # enum @enum += 1 retval << '.IP ' << @enum << '.' when 3 # tags retval << ".TP\n" case words[0] when 'Pa', 'Ev' words.shift retval << '.B' end when 4 # item retval << ".IP\n" end next end case word when 'Sm' case words[0] when 'off' @nospace = 2 when 'on' # retval << "\n" @nospace = 0 end words.shift next end retval << word end return nil if retval == '.' retval.sub!(/\A\.([^a-zA-Z])/, "\\1") # retval.chomp!(' ') while q = quote.pop case q when OPTION retval << ']' when PAREN retval << ')' when ANGLE retval << '>' end end # retval << ' ' unless @nospace == 0 || retval.empty? || /\n\z/ =~ retval retval << ' ' unless !@ext || @extopt || / $/ =~ retval retval << "\n" unless @ext || @extopt || retval.empty? || /\n\z/ =~ retval retval << ".fi\n" if dl return retval end def self.mdoc2man(i, o) new.mdoc2man(i, o) end end if $0 == __FILE__ Mdoc2Man.mdoc2man(ARGF, STDOUT) end
20.837553
79
0.552901
e2155bc68dffb6c39ed8f2e6051ab1edf8bd66ed
3,278
#!/usr/bin/env ruby # Television show renaming/moving utility. # # Attempts (often very wrongly) to extract the show title, season number, and # episode number from a file name, then copy it into a sorted location. # # TODO: # * OptionParser for: # * Destination directory # * Dry run # * Verbosity # * Extract compressed videos (such as multi-part RAR) # * Transcode/remux to uniform format # * Remove source directories for files that come nested in some mess # # # Copyright (C) 2013 Kyle Johnson <[email protected]> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require 'fileutils' # this is hax -- sorry #SOURCE_DIR = file.expand_path '~/downloads/' DEST_DIR = File.expand_path '~/var/media/visual/video/television/' VIDEO_EXTENSIONS = %w[ .mkv .avi .mp4 ] REGEX = [ /\b(?<series_title>\S+)\./, /[Ss](?<season>[0-9]{1,2})[Ee](?<episode>[0-9]{1,2})\./, /(?<misc_info>\S+)\./, # would be nice if this portion were consistent... /(?<extension>[^\.]+)$/ ].join NAME_MAP = { /mlp/ => 'my-little-pony-friendship-is-magic', /merlin/ => 'merlin' } def ingest_file path, match series = match[:series_title].downcase.tr_s '^a-z0-9', '-' NAME_MAP.each do |regex, title| if series.match regex series = title break end end new_file_name = "#{series}_S#{match[:season]}E#{match[:episode]}.#{match[:extension]}" puts "#{series}: S: #{match[:season]} E: #{match[:episode]} (#{match[:extension]})" FileUtils.mkdir_p File.join DEST_DIR, series, match[:season] destination = File.join DEST_DIR, series, match[:season], new_file_name p path File.rename path, destination end def ingest_dir dir Dir.chdir dir do Dir.foreach dir do |path| match = path.match REGEX #p path, match next unless match if File.directory? path ingest_dir File.join dir, path end unless VIDEO_EXTENSIONS.include? File.extname path warn "warning: unknown extension on possible match \"#{path}\"" next end ingest_file path, match end end end ARGV.each do |dir| unless File.directory? dir warn "skipping non-existent directory \"#{dir}\"" end ingest_dir File.expand_path dir end #ingest_dir SOURCE_DIR
26.435484
88
0.693411
f748047effb83d662f856ea9d2ee8d7c79f03eeb
988
require 'rest-client' class Game < ApplicationRecord # game.playlists returns a list of all playlists specific game belongs to has_many :playlist_games has_many :playlists, through: :playlist_games # game.users returns a list of all users who have starred the game has_many :user_game_stars has_many :users, through: :user_game_stars def self.create_new_game(date, home_team) team = Team.find_by(abbreviation: home_team) team_id = team["id"] url = "https://www.balldontlie.io/api/v1/games?team_ids[]=#{team_id}&start_date=#{date}&end_date=#{date}" request = RestClient::Request.execute( method: :get, url: url ) response = JSON.parse(request) game = response["data"][0] Game.create( id: game["id"], home: game["home_team"]["abbreviation"], away: game["visitor_team"]["abbreviation"], home_score: game["home_team_score"], away_score: game["visitor_team_score"], date: date, ) end end
29.939394
109
0.681174
bbe86ab1e2767f548dc713d4344a42eb177a90e9
1,336
# frozen_string_literal: true require "active_support" module InstStatsd class DefaultTracking def self.track_sql return if @sql_tracker @sql_tracker = InstStatsd::SqlTracker.new(blocked_names: ['SCHEMA']) ActiveSupport::Notifications.subscribe(/sql\.active_record/) {|*args| update_sql_count(*args)} end def self.track_active_record return if @ar_counter require 'aroi' ::Aroi::Instrumentation.instrument_creation! @ar_counter = InstStatsd::Counter.new('active_record') ActiveSupport::Notifications.subscribe(/instance\.active_record/) {|*args| update_active_record_count(*args)} end def self.track_cache return if @cache_read_counter @cache_read_counter = InstStatsd::Counter.new('cache.read') ActiveSupport::Notifications.subscribe(/cache_read\.active_support/) {|*args| update_cache_read_count(*args)} end private def self.update_sql_count(_name, _start, _finish, _id, payload) @sql_tracker.track payload.fetch(:name), payload.fetch(:sql) end def self.update_active_record_count(_name, _start, _finish, _id, payload) @ar_counter.track payload.fetch(:name, '') end def self.update_cache_read_count(_name, _start, _finish, _id, _payload) @cache_read_counter.track "read" end end end
29.688889
115
0.717814
ab5c4544d6ae1cdbce9335151d4b4722924b43cd
4,425
require 'spec_helper' require 'puppet/util/feature' describe Puppet::Util::Feature do before do @features = Puppet::Util::Feature.new("features") allow(@features).to receive(:warn) end it "should not call associated code when adding a feature" do $loaded_feature = false @features.add(:myfeature) { $loaded_feature = true} expect($loaded_feature).to eq(false) end it "should consider a feature absent when the feature load fails" do @features.add(:failer) { raise "foo" } expect(@features.failer?).to eq(false) end it "should consider a feature to be absent when the feature load returns false" do @features.add(:failer) { false } expect(@features.failer?).to eq(false) end it "should consider a feature to be absent when the feature load returns nil" do @features.add(:failer) { nil } expect(@features.failer?).to eq(false) end it "should consider a feature to be present when the feature load returns true" do @features.add(:available) { true } expect(@features.available?).to eq(true) end it "should consider a feature to be present when the feature load returns truthy" do @features.add(:available) { "yes" } expect(@features.available?).to eq(true) end it "should cache the results of a feature load via code block when the block returns true" do $loaded_feature = 0 @features.add(:myfeature) { $loaded_feature += 1; true } @features.myfeature? @features.myfeature? expect($loaded_feature).to eq(1) end it "should cache the results of a feature load via code block when the block returns false" do $loaded_feature = 0 @features.add(:myfeature) { $loaded_feature += 1; false } @features.myfeature? @features.myfeature? expect($loaded_feature).to eq(1) end it "should not cache the results of a feature load via code block when the block returns nil" do $loaded_feature = 0 @features.add(:myfeature) { $loaded_feature += 1; nil } @features.myfeature? @features.myfeature? expect($loaded_feature).to eq(2) end it "should invalidate the cache for the feature when loading" do @features.add(:myfeature) { false } expect(@features).not_to be_myfeature @features.add(:myfeature) expect(@features).to be_myfeature end it "should support features with libraries" do expect { @features.add(:puppet, :libs => %w{puppet}) }.not_to raise_error end it "should consider a feature to be present if all of its libraries are present" do @features.add(:myfeature, :libs => %w{foo bar}) expect(@features).to receive(:require).with("foo") expect(@features).to receive(:require).with("bar") expect(@features).to be_myfeature end it "should log and consider a feature to be absent if any of its libraries are absent" do @features.add(:myfeature, :libs => %w{foo bar}) expect(@features).to receive(:require).with("foo").and_raise(LoadError) allow(@features).to receive(:require).with("bar") expect(@features).to receive(:debug_once) expect(@features).not_to be_myfeature end it "should change the feature to be present when its libraries become available" do @features.add(:myfeature, :libs => %w{foo bar}) times_feature_require_called = 0 expect(@features).to receive(:require).twice().with("foo") do times_feature_require_called += 1 if times_feature_require_called == 1 raise LoadError else nil end end allow(@features).to receive(:require).with("bar") allow(Puppet::Util::RubyGems::Source).to receive(:source).and_return(Puppet::Util::RubyGems::Gems18Source) times_clear_paths_called = 0 allow_any_instance_of(Puppet::Util::RubyGems::Gems18Source).to receive(:clear_paths) { times_clear_paths_called += 1 } expect(@features).to receive(:debug_once) expect(@features).not_to be_myfeature expect(@features).to be_myfeature expect(times_clear_paths_called).to eq(3) end it "should cache load failures when configured to do so" do Puppet[:always_retry_plugins] = false @features.add(:myfeature, :libs => %w{foo bar}) expect(@features).to receive(:require).with("foo").and_raise(LoadError) expect(@features).not_to be_myfeature # second call would cause an expectation exception if 'require' was # called a second time expect(@features).not_to be_myfeature end end
34.038462
122
0.700565
620970f77d7a6e86f0261cb152d47baefd0cfb45
1,129
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'rubygems' require 'bundler/setup' require 'rspec' require 'webmock/rspec' if ENV['COVERAGE'] require 'coveralls' require 'simplecov' Coveralls.wear! SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter ] SimpleCov.start do add_filter '.bundle/' add_filter 'spec' end end if ENV['CODECLIMATE_REPORT'] WebMock.disable_net_connect!(allow: 'codeclimate.com') require 'codeclimate-test-reporter' CodeClimate::TestReporter.start end require 'fluent/test' require 'fluent/plugin/filter_ec2meta_injection' # Disable Test::Unit module Test::Unit::RunCount; def run(*); end; end # refs https://github.com/grosser/parallel_tests/issues/189 Test::Unit::AutoRunner.need_auto_run = false if defined?(Test::Unit::AutoRunner) path = Pathname.new(Dir.pwd) Dir[path.join('spec/support/**/*.rb')].map { |f| require f } RSpec.configure do |config| config.before(:all) do Fluent::Test.setup end config.order = :random Kernel.srand config.seed end
22.58
80
0.734278
030def99dc4ed969ffa91bd585f404fbb158d004
1,319
require 'test_helper' class NewExperimentWorkflowTest < ActionDispatch::IntegrationTest fixtures :all test "new workflow with new patient" do get new_user_session_path assert_response :success # login post_via_redirect new_user_session_path, :user => { :email => users(:user).email, :password => 'monkey' } assert_equal root_path, path # start new experiment workflow get new_workflows_experiment_path assert_response :success # new patient form get new_workflows_patient_path, :format => :js assert_response :success # create patient post_via_redirect workflows_patients_path, :test_subject => { :code => 'NEW007', :site_id => users(:user).site_id, :samples_attributes => { 0 => { :sample_type => 'milk', :barcode => 'lksdjflksjdf' } } }, :format => :js patient = TestSubject.find_by_code('NEW007') assert_equal 1, patient.samples.count assert_response :success # create experiment post_via_redirect workflows_experiments_path, :experiment => { :sample_id => patient.samples.first.id, :name => 'Workflow experiment', :experiment_type_id => experiment_types(:one).id } experiment = Experiment.find_by_name('Workflow experiment') assert_equal sample_experiment_path(experiment.sample, experiment), path end end
38.794118
223
0.721759
e25b36f295eb5d38356a403966143444b2685c29
938
require 'proto/nyx_post_services_pb' module NyxPost module Service class Post < Nyx::PostService::Service # The method should match with Nyx::PostService::Service (rpc :GetPost, ...) def get_post(post_req, _unused_call) # Find by id, just hardcoded for the example my_post = { id: '1', title: 'GPG Keys', description: 'Howto create a GPG Key with Tails Linux.' } Nyx::GetPostReply.new(post: my_post) end def get_posts(post_req, _unused_call) my_posts = NyxPost::DB.new.get_all Nyx::GetPostsReply.new(posts: my_posts) end def create_post(post_req, _unused_call) post = NyxPost::DB.new.create(post_req.title, post_req.description) Nyx::CreateReply.new(post: post) end def delete(post_req, _unused_call) msg = NyxPost::DB.new.destroy(post_req.id) Nyx::DeleteReply.new(message: msg) end end end end
30.258065
105
0.65565
bf8b83474ec6afd3d43fef0acc2e843232dae982
204
# frozen_literal_string: true # Load app_errors.rb here to include when testing without requiring additional # `require` in spec file require_relative 'app_errors' def clear_screen print `clear` end
18.545455
78
0.794118
ab056c8ff4d46540fda5bd18edabc92e8c285009
2,255
require 'rubygems' require 'sequel' require 'logger' $: << '../lib' DB = Sequel.connect(ENV['DATABASE_URL'] || 'sqlite:/') CREATE_TABLES_FILE = File.join(File.dirname(__FILE__), 'create_tables.rb') require CREATE_TABLES_FILE Sequel::Model.plugin :defaults_setter Sequel::Model.plugin :validation_helpers Sequel::Model.plugin :forme Sequel::Model.plugin :association_pks Sequel::Model.plugin :prepared_statements Sequel::Model.plugin :prepared_statements_associations Dir['models/*.rb'].each{|f| require f} def DB.reset [:albums_tags, :tags, :tracks, :albums, :artists].each{|t| DB[t].delete} artist = Artist.create(:name=>'Elvis') album = artist.add_album(:name=>'Elvis Presley', :release_date=>'1956-03-23', :release_party_time=>'1956-03-24 14:05:06', :debut_album=>true, :out_of_print=>false) album.add_track(:name=>'Blue Suede Shoes', :number=>1, :length=>2.0) album.add_track(:name=>"I'm Counting On You", :number=>2, :length=>2.4) rock = album.add_tag(:name=>'Rock & Roll') album.add_tag(:name=>'Country') album = artist.add_album(:name=>'Blue Hawaii', :release_date=>'1961-10-01', :release_party_time=>'1961-10-02 14:05:06', :debut_album=>false, :out_of_print=>true) album.add_track(:name=>'Blue Hawaii', :number=>1, :length=>2.6) album.add_track(:name=>"Almost Always True", :number=>2, :length=>2.4) album.add_tag(rock) album.add_tag(:name=>'Hawaiian') artist = Artist.create(:name=>'The Beatles') album = artist.add_album(:name=>'Please Please Me', :release_date=>'1963-03-22', :release_party_time=>'1963-03-25 14:05:06', :debut_album=>true, :out_of_print=>false) album.add_track(:name=>'I Saw Her Standing There', :number=>1, :length=>2.9) album.add_track(:name=>"I'm Counting On You", :number=>2, :length=>2.4) album.add_tag(rock) pop = album.add_tag(:name=>'Pop') album = artist.add_album(:name=>'With The Beatles', :release_date=>'1963-11-22', :release_party_time=>'1963-11-21 14:05:06', :debut_album=>false, :out_of_print=>true) album.add_track(:name=>"It Won't Be Long", :number=>1, :length=>2.1) album.add_track(:name=>"All I've Got to Do", :number=>2, :length=>2.0) album.add_tag(rock) album.add_tag(pop) end DB.reset if DB.database_type == :sqlite DB.loggers << Logger.new($stdout)
44.215686
168
0.7051
210b9104ad89da2124d905cfbcca3ffdf2f8d4d6
772
# frozen_string_literal: true module Leftovers module Processors class Parameterize include ComparableInstance def initialize(then_processor) @then_processor = then_processor freeze end def process(str, current_node, matched_node, acc) return unless str @then_processor.process(str.parameterize, current_node, matched_node, acc) rescue NoMethodError Leftovers.error <<~MESSAGE Tried using the String#parameterize method, but the activesupport gem was not available and/or not required `gem install activesupport`, and/or add `requires: ['active_support', 'active_support/core_ext/string']` to your .leftovers.yml MESSAGE end freeze end end end
26.62069
137
0.69171
26a80ec4f1e4cea197d71d721edd69bc49ab8d24
113
Dir['../lib/*.rb'].each { |f| require_relative f } MATRIX_SIZE = 30 Life.new(MATRIX_SIZE, MATRIX_SIZE + 10).go
18.833333
50
0.672566
38c2ca138325699e5d689c33fbe6686392aa9a35
936
# frozen_string_literal: true def mock_pro_grammar(*args) args.flatten! binding = args.first.is_a?(Binding) ? args.shift : binding() options = args.last.is_a?(Hash) ? args.pop : {} input = InputTester.new(*args) output = StringIO.new redirect_pro_grammar_io(input, output) do binding.pro_grammar(options) end output.string end # Set I/O streams. Out defaults to an anonymous StringIO. def redirect_pro_grammar_io(new_in, new_out = StringIO.new) old_in = ProGrammar.config.input old_out = ProGrammar.config.output ProGrammar.config.input = new_in ProGrammar.config.output = new_out begin yield ensure ProGrammar.config.input = old_in ProGrammar.config.output = old_out end end class InputTester def initialize(*actions) @orig_actions = actions.dup @actions = actions end def readline(*) @actions.shift end def rewind @actions = @orig_actions.dup end end
19.914894
62
0.719017
ed3f03d2f29657a187cd6ce73ff081f4b783d76d
2,734
class Unity::EC2::VPC < Unity::EC2::Base def list list = [] # filter the collection to just nanobox instances filter = [{'Name' => 'tag:Nanobox', 'Value' => 'true'}] # query the api res = manager.DescribeVpcs('Filter' => filter) # extract the instance collection vpcs = res["DescribeVpcsResponse"]["vpcSet"] # short-circuit if the collection is empty return [] if vpcs.nil? # vpcs might not be a collection, but a single item collection = begin if vpcs['item'].is_a? Array vpcs['item'] else [vpcs['item']] end end # grab the vpcs and process them collection.each do |vpc| list << process(vpc) end list end def show(name) list.each do |vpc| if vpc[:name] == name return vpc end end # return nil if we can't find it nil end def create(name) # short-circuit if this already exists existing = show(name) if existing logger.info("VPC '#{name}' already exists") return existing end # create the vpc logger.info("Creating VPC '#{name}'") vpc = create_vpc # tag the vpc logger.info("Tagging VPC '#{name}'") tag_vpc(vpc['vpcId'], name) show(name) end protected def create_vpc cidr = "10.#{subnet_int}.0.0/16" logger.info "Found available network #{cidr}" # create the vpc with a unique cidr block res = manager.CreateVpc( 'CidrBlock' => cidr ) # extract the response res["CreateVpcResponse"]["vpc"] end def tag_vpc(id, name) # tag the vpc res = manager.CreateTags( 'ResourceId' => id, 'Tag' => [ { 'Key' => 'Nanobox', 'Value' => 'true' }, { 'Key' => 'Name', 'Value' => "Nanobox-Unity-#{name}" }, { 'Key' => 'EnvName', 'Value' => name } ] ) end def subnet_int # this could be more advanced. Essentially, let's just see how many # vpcs exist, and add one res = manager.DescribeVpcs() # extract the instance collection vpcs = res["DescribeVpcsResponse"]["vpcSet"] collection = begin if vpcs['item'].is_a? Array vpcs['item'] else [vpcs['item']] end end (collection.count || 0) + 1 end def process(data) { id: data["vpcId"], name: (process_tag(data['tagSet']['item'], 'EnvName') rescue 'unknown'), subnet: data["cidrBlock"] } end def process_tag(tags, key) tags.each do |tag| if tag['key'] == key return tag['value'] end end '' end end
19.811594
80
0.537308
034da9ea5c083609fd2f3001234fb2131de0fdc0
94
class StatiqueController < ApplicationController def accueil end def contact end end
11.75
48
0.776596
62bb4c6acaf27fa979c4c3d77076469b46c70fd0
15,435
#encoding: UTF-8 require File.expand_path("../helper", __FILE__) class TestRakeApplication < Rake::TestCase def setup super @app = Rake.application @app.options.rakelib = [] end def setup_command_line(*options) ARGV.clear options.each do |option| ARGV << option end end def test_display_exception_details obj = Object.new obj.instance_eval("def #{__method__}; raise 'test'; end", "ruby") begin obj.__send__(__method__) rescue => ex end out, err = capture_io do @app.display_error_message ex end assert_empty out assert_match "rake aborted!", err assert_match __method__.to_s, err end def test_display_exception_details_bad_encoding begin raise "El Niño is coming!".force_encoding("US-ASCII") rescue => ex end out, err = capture_io do @app.display_error_message ex end assert_empty out assert_match "El Niño is coming!", err.force_encoding("UTF-8") end def test_display_exception_details_cause skip "Exception#cause not implemented" unless Exception.method_defined? :cause begin raise "cause a" rescue begin raise "cause b" rescue => ex end end out, err = capture_io do @app.display_error_message ex end assert_empty out assert_match "cause a", err assert_match "cause b", err end def test_display_exception_details_cause_loop skip "Exception#cause not implemented" unless Exception.method_defined? :cause skip if jruby9? # https://github.com/jruby/jruby/issues/3654 begin begin raise "cause a" rescue => a begin raise "cause b" rescue raise a end end rescue => ex end out, err = capture_io do @app.display_error_message ex end assert_empty out assert_match "cause a", err assert_match "cause b", err end def test_display_tasks @app.options.show_tasks = :tasks @app.options.show_task_pattern = // @app.last_description = "COMMENT" @app.define_task(Rake::Task, "t") out, = capture_io do @app.instance_eval { display_tasks_and_comments } end assert_match(/^rake t/, out) assert_match(/# COMMENT/, out) end def test_display_tasks_with_long_comments @app.terminal_columns = 80 @app.options.show_tasks = :tasks @app.options.show_task_pattern = // numbers = "1234567890" * 8 @app.last_description = numbers @app.define_task(Rake::Task, "t") out, = capture_io do @app.instance_eval { display_tasks_and_comments } end assert_match(/^rake t/, out) assert_match(/# #{numbers[0, 65]}\.\.\./, out) end def test_display_tasks_with_task_name_wider_than_tty_display @app.terminal_columns = 80 @app.options.show_tasks = :tasks @app.options.show_task_pattern = // task_name = "task name" * 80 @app.last_description = "something short" @app.define_task(Rake::Task, task_name) out, = capture_io do @app.instance_eval { display_tasks_and_comments } end # Ensure the entire task name is output and we end up showing no description assert_match(/rake #{task_name} # .../, out) end def test_display_tasks_with_very_long_task_name_to_a_non_tty_shows_name_and_comment @app.options.show_tasks = :tasks @app.options.show_task_pattern = // @app.tty_output = false description = "something short" task_name = "task name" * 80 @app.last_description = "something short" @app.define_task(Rake::Task, task_name) out, = capture_io do @app.instance_eval { display_tasks_and_comments } end # Ensure the entire task name is output and we end up showing no description assert_match(/rake #{task_name} # #{description}/, out) end def test_display_tasks_with_long_comments_to_a_non_tty_shows_entire_comment @app.options.show_tasks = :tasks @app.options.show_task_pattern = // @app.tty_output = false @app.last_description = "1234567890" * 8 @app.define_task(Rake::Task, "t") out, = capture_io do @app.instance_eval { display_tasks_and_comments } end assert_match(/^rake t/, out) assert_match(/# #{@app.last_description}/, out) end def test_truncating_comments_to_a_non_tty @app.terminal_columns = 80 @app.options.show_tasks = :tasks @app.options.show_task_pattern = // @app.tty_output = false numbers = "1234567890" * 8 @app.last_description = numbers @app.define_task(Rake::Task, "t") out, = capture_io do @app.instance_eval { display_tasks_and_comments } end assert_match(/^rake t/, out) assert_match(/# #{numbers[0, 65]}\.\.\./, out) end def test_describe_tasks @app.options.show_tasks = :describe @app.options.show_task_pattern = // @app.last_description = "COMMENT" @app.define_task(Rake::Task, "t") out, = capture_io do @app.instance_eval { display_tasks_and_comments } end assert_match(/^rake t$/, out) assert_match(/^ {4}COMMENT$/, out) end def test_show_lines @app.options.show_tasks = :lines @app.options.show_task_pattern = // @app.last_description = "COMMENT" @app.define_task(Rake::Task, "t") @app["t"].locations << "HERE:1" out, = capture_io do @app.instance_eval { display_tasks_and_comments } end assert_match(/^rake t +[^:]+:\d+ *$/, out) end def test_finding_rakefile rakefile_default assert_match(/Rakefile/i, @app.instance_eval { have_rakefile }) end def test_not_finding_rakefile @app.instance_eval { @rakefiles = ["NEVER_FOUND"] } assert(! @app.instance_eval do have_rakefile end) assert_nil @app.rakefile end def test_load_rakefile rakefile_unittest @app.instance_eval do handle_options options.silent = true load_rakefile end assert_equal "rakefile", @app.rakefile.downcase assert_equal @tempdir, Dir.pwd end def test_load_rakefile_doesnt_print_rakefile_directory_from_same_dir rakefile_unittest _, err = capture_io do @app.instance_eval do # pretend we started from the unittest dir @original_dir = File.expand_path(".") raw_load_rakefile end end assert_empty err end def test_load_rakefile_from_subdir rakefile_unittest Dir.chdir "subdir" @app.instance_eval do handle_options options.silent = true load_rakefile end assert_equal "rakefile", @app.rakefile.downcase assert_equal @tempdir, Dir.pwd end def test_load_rakefile_prints_rakefile_directory_from_subdir rakefile_unittest Dir.chdir "subdir" app = Rake::Application.new app.options.rakelib = [] _, err = capture_io do app.instance_eval do raw_load_rakefile end end assert_equal "(in #{@tempdir}\)\n", err end def test_load_rakefile_doesnt_print_rakefile_directory_from_subdir_if_silent rakefile_unittest Dir.chdir "subdir" _, err = capture_io do @app.instance_eval do handle_options options.silent = true raw_load_rakefile end end assert_empty err end def test_load_rakefile_not_found skip if jruby9? ARGV.clear Dir.chdir @tempdir ENV["RAKE_SYSTEM"] = "not_exist" @app.instance_eval do handle_options options.silent = true end ex = assert_raises(RuntimeError) do @app.instance_eval do raw_load_rakefile end end assert_match(/no rakefile found/i, ex.message) end def test_load_from_system_rakefile rake_system_dir @app.instance_eval do handle_options options.silent = true options.load_system = true options.rakelib = [] load_rakefile end assert_equal @system_dir, @app.system_dir assert_nil @app.rakefile rescue SystemExit flunk "failed to load rakefile" end def test_load_from_calculated_system_rakefile rakefile_default def @app.standard_system_dir "__STD_SYS_DIR__" end ENV["RAKE_SYSTEM"] = nil @app.instance_eval do handle_options options.silent = true options.load_system = true options.rakelib = [] load_rakefile end assert_equal "__STD_SYS_DIR__", @app.system_dir rescue SystemExit flunk "failed to find system rakefile" end def test_terminal_columns old_rake_columns = ENV["RAKE_COLUMNS"] ENV["RAKE_COLUMNS"] = "42" app = Rake::Application.new assert_equal 42, app.terminal_columns ensure if old_rake_columns ENV["RAKE_COLUMNS"] = old_rake_columns else ENV.delete "RAKE_COLUMNS" end end def test_windows assert ! (@app.windows? && @app.unix?) end def test_loading_imports loader = util_loader @app.instance_eval do add_loader("dummy", loader) add_import("x.dummy") load_imports end # HACK no assertions end def test_building_imported_files_on_demand loader = util_loader @app.instance_eval do intern(Rake::Task, "x.dummy").enhance do loader.make_dummy end add_loader("dummy", loader) add_import("x.dummy") load_imports end # HACK no assertions end def test_handle_options_should_not_strip_options_from_argv assert [email protected] valid_option = "--trace" setup_command_line(valid_option) @app.handle_options assert ARGV.include?(valid_option) assert @app.options.trace end def test_handle_options_trace_default_is_stderr setup_command_line("--trace") @app.handle_options assert_equal STDERR, @app.options.trace_output assert @app.options.trace end def test_handle_options_trace_overrides_to_stdout setup_command_line("--trace=stdout") @app.handle_options assert_equal STDOUT, @app.options.trace_output assert @app.options.trace end def test_handle_options_trace_does_not_eat_following_task_names assert [email protected] setup_command_line("--trace", "sometask") @app.handle_options assert ARGV.include?("sometask") assert @app.options.trace end def test_good_run ran = false ARGV << '--rakelib=""' @app.options.silent = true @app.instance_eval do intern(Rake::Task, "default").enhance { ran = true } end rakefile_default out, err = capture_io do @app.run end assert ran assert_empty err assert_equal "DEFAULT\n", out end def test_display_task_run ran = false setup_command_line("-f", "-s", "--tasks", '--rakelib=""') @app.last_description = "COMMENT" @app.define_task(Rake::Task, "default") out, = capture_io { @app.run } assert @app.options.show_tasks assert ! ran assert_match(/rake default/, out) assert_match(/# COMMENT/, out) end def test_display_prereqs ran = false setup_command_line("-f", "-s", "--prereqs", '--rakelib=""') @app.last_description = "COMMENT" t = @app.define_task(Rake::Task, "default") t.enhance([:a, :b]) @app.define_task(Rake::Task, "a") @app.define_task(Rake::Task, "b") out, = capture_io { @app.run } assert @app.options.show_prereqs assert ! ran assert_match(/rake a$/, out) assert_match(/rake b$/, out) assert_match(/rake default\n( *(a|b)\n){2}/m, out) end def test_bad_run @app.intern(Rake::Task, "default").enhance { fail } setup_command_line("-f", "-s", '--rakelib=""') _, err = capture_io { assert_raises(SystemExit) { @app.run } } assert_match(/see full trace/i, err) ensure ARGV.clear end def test_bad_run_with_trace @app.intern(Rake::Task, "default").enhance { fail } setup_command_line("-f", "-s", "-t") _, err = capture_io { assert_raises(SystemExit) { @app.run } } refute_match(/see full trace/i, err) ensure ARGV.clear end def test_bad_run_with_backtrace @app.intern(Rake::Task, "default").enhance { fail } setup_command_line("-f", "-s", "--backtrace") _, err = capture_io { assert_raises(SystemExit) { @app.run } } refute_match(/see full trace/, err) ensure ARGV.clear end CustomError = Class.new(RuntimeError) def test_bad_run_includes_exception_name @app.intern(Rake::Task, "default").enhance { raise CustomError, "intentional" } setup_command_line("-f", "-s") _, err = capture_io { assert_raises(SystemExit) { @app.run } } assert_match(/CustomError: intentional/, err) end def test_rake_error_excludes_exception_name @app.intern(Rake::Task, "default").enhance { fail "intentional" } setup_command_line("-f", "-s") _, err = capture_io { assert_raises(SystemExit) { @app.run } } refute_match(/RuntimeError/, err) assert_match(/intentional/, err) end def cause_supported? ex = StandardError.new ex.respond_to?(:cause) end def test_printing_original_exception_cause custom_error = Class.new(StandardError) @app.intern(Rake::Task, "default").enhance { begin raise custom_error, "Original Error" rescue custom_error raise custom_error, "Secondary Error" end } setup_command_line("-f", "-s") _ ,err = capture_io { assert_raises(SystemExit) { @app.run } } if cause_supported? assert_match(/Original Error/, err) end assert_match(/Secondary Error/, err) ensure ARGV.clear end def test_run_with_bad_options @app.intern(Rake::Task, "default").enhance { fail } setup_command_line("-f", "-s", "--xyzzy") assert_raises(SystemExit) { capture_io { @app.run } } ensure ARGV.clear end def test_standard_exception_handling_invalid_option out, err = capture_io do e = assert_raises SystemExit do @app.standard_exception_handling do raise OptionParser::InvalidOption, "blah" end end assert_equal 1, e.status end assert_empty out assert_equal "invalid option: blah\n", err end def test_standard_exception_handling_other out, err = capture_io do e = assert_raises SystemExit do @app.standard_exception_handling do raise "blah" end end assert_equal 1, e.status end assert_empty out assert_match "rake aborted!\n", err assert_match "blah\n", err end def test_standard_exception_handling_system_exit out, err = capture_io do e = assert_raises SystemExit do @app.standard_exception_handling do exit 0 end end assert_equal 0, e.status end assert_empty out assert_empty err end def test_standard_exception_handling_system_exit_nonzero out, err = capture_io do e = assert_raises SystemExit do @app.standard_exception_handling do exit 5 end end assert_equal 5, e.status end assert_empty out assert_empty err end def util_loader loader = Object.new loader.instance_variable_set :@load_called, false def loader.load(arg) raise ArgumentError, arg unless arg == "x.dummy" @load_called = true end loader.instance_variable_set :@make_dummy_called, false def loader.make_dummy @make_dummy_called = true end loader end end
23.350983
85
0.666537
f8e1d1df4f2df6e5f661a9a74122fa5d47b81335
586
require 'octokit' class GitHubIssues def initialize raise 'The GITHUB_ACCESS_TOKEN environment variable must be set to run this application.' unless ENV['GITHUB_ACCESS_TOKEN'] @client = Octokit::Client.new(access_token: ENV['GITHUB_ACCESS_TOKEN']) @client.auto_paginate = true end def issues_list issues.map do |issue| { title: issue[:title], body: issue[:body], repo_name: issue[:repository][:full_name], url: issue[:url] } end end private def issues @client.user_issues(filter: 'created') end end
20.928571
127
0.663823
39144111da506ffd2405c9b700d117190f195613
299
require 'yaml' require 'dh_easy/core' require 'dh_easy/config' require 'dh_easy_override/core' require 'dh_easy/router/version' require 'dh_easy/router/plugin' require 'dh_easy/router/parser' require 'dh_easy/router/seeder' require 'dh_easy/router/finisher' module DhEasy module Router end end
19.933333
33
0.799331
e95711d097892aa669b22fdafc80c90910bad67b
887
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'viaggiatreno/version' Gem::Specification.new do |gem| gem.name = "viaggiatreno" gem.version = Viaggiatreno::VERSION gem.authors = ["Michele Bologna"] gem.email = ["[email protected]"] gem.description = %q{A web scraper to fetch real time information on train riding the Italian railway system (viaggiatreno/trenitalia)} gem.summary = %q{A scraper for real time information on Italian railway system (viaggiatreno)} gem.homepage = "" gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.add_dependency "nokogiri" end
42.238095
139
0.667418
396bf42a1848066ab6ed81de77f01a912bf5db66
1,968
QueryGateway::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_assets = false # Compress both stylesheets and JavaScripts config.assets.js_compressor = :uglifier config.assets.css_compressor = :scss # Specifies the header that your server uses for sending files # (comment out if your front-end server doesn't support this) config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) # config.log_level = :debug # Use a different logger for distributed setups # config.logger = SyslogLogger.new # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( search.js ) # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify end
37.132075
104
0.763211
f8d3ae4f2c3b16e11a271742c0a765e0c28d6326
893
# frozen_string_literal: true require 'rails_helper' module Bulkrax RSpec.describe ExporterJob, type: :job do subject(:exporter_job) { described_class.new } let(:exporter) { FactoryBot.create(:bulkrax_exporter) } let(:bulkrax_exporter_run) { FactoryBot.create(:bulkrax_exporter_run, exporter: exporter) } before do allow(Bulkrax::Exporter).to receive(:find).with(1).and_return(exporter) allow(exporter).to receive(:exporter_runs).and_return([bulkrax_exporter_run]) allow(exporter).to receive(:mapping).and_return("title" => {}) exporter.setup_export_path allow(exporter.parser).to receive(:write_files).and_return(exporter.exporter_export_path) end describe 'successful job', clean_downloads: true do it 'calls export' do expect(exporter).to receive(:export) exporter_job.perform(1) end end end end
33.074074
95
0.717805
f7a4972225302a217824d2a40786a9e750ab58b2
160
Rails.application.routes.draw do root 'home#index' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
26.666667
101
0.76875
08f5ebd6e6cf53372cc812262469f88a3eaef70d
814
# This file is auto-generated by the code_generator # # Cookbook Name:: kernel-modules # Spec:: default # # Copyright:: 2017, The Authors, All Rights Reserved. require 'spec_helper' describe 'kernel-modules::metadata' do let(:metadata_file) do File.join(File.dirname(__FILE__), '../../../metadata.rb') end it 'has a metadata file' do expect(File.exist?(metadata_file)) end it 'is parsable metadata' do m = Chef::Cookbook::Metadata.new expect { m.from_file(metadata_file) }.not_to raise_error end it 'has a license' do m = Chef::Cookbook::Metadata.new m.from_file(metadata_file) expect(m.license).not_to be_empty end it 'has a description' do m = Chef::Cookbook::Metadata.new m.from_file(metadata_file) expect(m.description).not_to be_empty end end
22.611111
61
0.697789
e2e492057cbe5481c8495ecbb75777bf057ea363
190
class QueryVersionSerializer < ActiveModel::Serializer attributes :id, :body, :created_at, :updated_at, :parameters, :author_name, :query_id, :version, :comment, :commit_sha, :summary end
47.5
130
0.773684
1ad2341f2fe38ebb5d0d197dd5eb55c3cd91a269
7,239
class Spree::InvoiceMailer < Spree::BaseMailer include AbstractController::Callbacks include LiquidVarsHelper add_template_helper(Spree::CurrencyHelper) add_template_helper(DateHelper) before_action :set_mail_type def reminder_email(invoice, override_account_email_settings = false, dev_preview = false) return unless load_invoice(invoice) && @invoice.balance_due? vendor = @invoice.vendor # get email template using the name of this mailer method as the slug template = get_template(vendor, __method__.to_s, dev_preview) # set up @body and @options (@options includes subject, from, cc, bcc) setup_liquid_email(template) # merge liquid @options with original mail_to and copy_to arrays and return to options hash options = set_liquid_mail_options(@invoice, dev_preview, override_account_email_settings) #attach invoice filename = "#{@invoice.vendor.name.squish.downcase.tr(" ","_")}_#{@invoice.number}_#{@invoice.end_date.strftime('%Y_%m_%d')}.pdf" attachments[filename] = @invoice.pdf_invoice_for_invoice.pdf if options[:to].present? && (vendor.send_invoice_reminder || vendor.send_mail_to_my_company || dev_preview) mail(options) @invoice.update_columns(reminder_sent_at: Time.current) if vendor.send_invoice_reminder end end def past_due_email(invoice, override_account_email_settings = false, dev_preview = false) return unless load_invoice(invoice) && @invoice.balance_due? vendor = @invoice.vendor # get email template using the name of this mailer method as the slug template = get_template(vendor, __method__.to_s, dev_preview) # set up @body and @options (@options includes subject, from, cc, bcc) setup_liquid_email(template) # merge liquid @options with original mail_to and copy_to arrays and return to options hash options = set_liquid_mail_options(@invoice, dev_preview, override_account_email_settings) #attach inovice filename = "#{@invoice.vendor.name.squish.downcase.tr(" ","_")}_#{@invoice.number}_#{@invoice.end_date.strftime('%Y_%m_%d')}.pdf" attachments[filename] = @invoice.pdf_invoice_for_invoice.pdf if options[:to].present? && (vendor.send_invoice_past_due || vendor.send_mail_to_my_company || dev_preview) mail(options) @invoice.update_columns(past_due_sent_at: Time.current) if vendor.send_invoice_past_due end end def weekly_invoice_email(invoice, override_account_email_settings = false, resend = false, dev_preview = false) return unless load_invoice(invoice) vendor = @invoice.vendor # get email template using the name of this mailer method as the slug template = get_template(vendor, __method__.to_s, dev_preview) # set up @body and @options (@options includes subject, from, cc, bcc) setup_liquid_email(template) mail_to = @invoice.account.collect_customer_emails({override_account_email_settings: override_account_email_settings}) mail_to = [] unless @invoice.vendor.send_weekly_invoice_email if mail_to.empty? && @invoice.vendor.send_mail_to_my_company mail_to = @invoice.vendor.valid_emails end copy_to = @invoice.vendor.send_cc_to_my_company ? @invoice.vendor.valid_emails : [] mail_to = mail_to.compact.uniq copy_to = copy_to.compact.uniq if mail_to.present? if copy_to.present? options = merge_or_append_email_headers(@options, {to: mail_to, from: from_address(@invoice.vendor), cc: copy_to}) else options = merge_or_append_email_headers(@options, {to: mail_to, from: from_address(@invoice.vendor)}) end update_invoice_sent_at elsif @invoice.vendor.send_mail_to_my_company options = merge_or_append_email_headers(@options, {to: @invoice.vendor.valid_emails, from: from_address(@invoice.vendor)}) elsif dev_preview # let's preview the mailer even if there's no mail_to options = merge_or_append_email_headers(@options, {to: "[email protected]", from: from_address(@invoice.vendor), cc: copy_to}) end filename = "#{@invoice.account.name.squish.downcase.tr(" ","_")}_#{@invoice.end_date.strftime('%Y_%m_%d')}.pdf" attachments[filename] = @invoice.pdf_invoice_for_invoice.pdf if options[:to].present? && (vendor.send_weekly_invoice_email || vendor.send_cc_to_my_company || dev_preview) mail(options) update_invoice_sent_at if vendor.send_weekly_invoice_email end end private def load_invoice(invoice) @invoice = invoice.respond_to?(:id) ? invoice : Spree::Invoice.find(invoice) rescue nil @order = @invoice.try(:orders).try(:first) @invoice.present? && @invoice.orders.any?{ |o| o.send_emails? } end def set_liquid_mail_options(invoice, dev_preview = false, override_account_email_settings = false) # grab all user emails associated with the customer mail_to = invoice.account.collect_customer_emails({override_account_email_settings: override_account_email_settings}) # next, grab user emails and communication settings associated with the vendor # then go through and check which vendor users are signed up to receive emails (checks settings vs order state / notification being sent) copy_to = invoice.vendor.users.map do |recipient| recipient.email if !recipient.is_admin? && !recipient.stop_all_emails && recipient.order_finalized end copy_to += invoice.vendor.valid_emails if invoice.vendor.send_cc_to_my_company mail_to = mail_to.compact.uniq copy_to = copy_to.compact.uniq if mail_to.present? if copy_to.present? options = merge_or_append_email_headers(@options, {to: mail_to, from: from_address(invoice.vendor), cc: copy_to}) else options = merge_or_append_email_headers(@options, {to: mail_to, from: from_address(invoice.vendor)}) end update_invoice_sent_at elsif invoice.vendor.send_mail_to_my_company options = merge_or_append_email_headers(@options, {to: invoice.vendor.valid_emails, from: from_address(invoice.vendor)}) elsif dev_preview # let's preview the mailer even if there's no mail_to options = merge_or_append_email_headers(@options, {to: "[email protected]", from: from_address(invoice.vendor), cc: copy_to}) else options = merge_or_append_email_headers(@options, {from: from_address(invoice.vendor)}) end return options end def setup_liquid_email(email_template) @liquid_vars = set_order_liquid_vars(@order) # set up liquid vars @liquid_vars = @liquid_vars.merge(set_invoice_liquid_vars(@invoice)) if @invoice @body = email_template.render(@liquid_vars) # render email body with template + liquid var values @options = email_template.mail_options # get template headers, e.g., subject, from, cc, bcc headers # render subject with liquid var values if @options[:subject].present? @options[:subject] = Liquid::Template.parse(@options[:subject]).render(@liquid_vars) rescue @options[:subject] end end def set_mail_type @mail_type = "invoice" end def update_invoice_sent_at @invoice.orders.where(invoiced_at: nil).update_all(invoiced_at: Time.current) @invoice.orders.update_all(invoice_sent_at: Time.current) end end
43.608434
141
0.745545
382a6273460d094df66babf308018d954143b7b9
640
cask "ueli" do version "8.10.0" sha256 "38e9b6f4558ba32350cd1bdf516e5e70fb04d06f2365420531781c1b09793c58" # github.com/oliverschwendener/ueli/ was verified as official when first introduced to the cask url "https://github.com/oliverschwendener/ueli/releases/download/v#{version}/ueli-#{version}.dmg" appcast "https://github.com/oliverschwendener/ueli/releases.atom" name "Ueli" desc "Keystroke launcher" homepage "https://ueli.app/" app "ueli.app" uninstall quit: "ueli" zap trash: [ "~/Library/Logs/ueli", "~/Library/Application Support/ueli", "~/Library/Preferences/com.electron.ueli.plist", ] end
29.090909
99
0.732813
b9b6b1cd1604e4e1f20651c16c0bafa889a8e307
1,010
require "rails_helper" RSpec.describe Child, type: :model do subject(:model) { build(:child) } it { is_expected.to define_enum_for(:gender).with_values(male: 1, female: 2, other: 3) } it { is_expected.to validate_presence_of(:date_of_birth) } it { is_expected.to validate_presence_of(:gender) } it_behaves_like "name identifiable model" do let(:model_class) { described_class } end describe "#age" do subject(:age) { travel_to(current_time) { model.age } } let(:model) { build(:child, date_of_birth: date_of_birth) } let(:current_time) { "2020-11-10 11:10" } context "when the birthday already occurred in the current year" do let(:date_of_birth) { "2010-11-01" } it "returns the correct age" do is_expected.to be 10 end end context "when the birthday is coming up later in the current year" do let(:date_of_birth) { "2010-12-01" } it "returns the correct age" do is_expected.to be 9 end end end end
26.578947
90
0.667327
28f21c5c062084dd57260d9412cbcd87794dc7f6
3,516
module TLSTestKit class TLSVersionTest < Inferno::Test title 'Server supports TLS' description %( Verify that a server supports TLS. ) id :tls_version_test class << self def versions { OpenSSL::SSL::SSL2_VERSION => 'SSL 2.0', OpenSSL::SSL::SSL3_VERSION => 'SSL 3.0', OpenSSL::SSL::TLS1_VERSION => 'TLS 1.0', OpenSSL::SSL::TLS1_1_VERSION => 'TLS 1.1', OpenSSL::SSL::TLS1_2_VERSION => 'TLS 1.2', OpenSSL::SSL::TLS1_3_VERSION => 'TLS 1.3', } end def version_keys @version_keys ||= versions.keys end def minimum_allowed_version @minimum_allowed_version ||= config.options[:minimum_allowed_version].presence || version_keys.first end def maximum_allowed_version @maximum_allowed_version ||= config.options[:maximum_allowed_version].presence || version_keys.last end def allowed_versions @allowed_versions ||= version_keys.select do |version| minimum_allowed_index = version_keys.find_index(minimum_allowed_version) || 0 maximum_allowed_index = version_keys.find_index(maximum_allowed_version) || version_keys.length - 1 version_index = version_keys.find_index(version) version_index >= minimum_allowed_index && version_index <= maximum_allowed_index end end def required_versions @required_versions ||= config.options[:required_versions].presence || [] end def version_allowed?(version) allowed_versions.include? version end def version_forbidden?(version) !version_allowed? version end def version_required?(version) required_versions.include? version end end input :url run do uri = URI(url) host = uri.host port = uri.port tls_support_verified = false self.class.versions.each do |version, version_string| http = Net::HTTP.new(host, port) http.use_ssl = true http.min_version = version http.max_version = version http.verify_mode = OpenSSL::SSL::VERIFY_PEER begin http.request_get(uri) if self.class.version_forbidden? version add_message('error', "Server incorrectly allowed #{version_string} connection.") elsif self.class.version_required? version add_message('info', "Server correctly allowed #{version_string} connection as required.") tls_support_verified = true else add_message('info', "Server allowed #{version_string} connection.") tls_support_verified = true end rescue StandardError => e if self.class.version_required? version add_message('error', "Server incorrectly denied #{version_string} connection: #{e.message}") elsif self.class.version_forbidden? version add_message('info', "Server correctly denied #{version_string} connection as required.") else add_message('info', "Server denied #{version_string} connection.") end end end errors_found = messages.any? { |message| message[:type] == 'error' } assert !errors_found, 'Server did not permit/deny the connections with the correct TLS versions' assert tls_support_verified, 'Server did not support any allowed TLS versions.' end end end
32.555556
111
0.633675
87d90099e1b8cb37ddeb7fd3c30728b7411442c3
85
class Patterns::ActivityFeedsController < ApplicationController def index; end end
21.25
63
0.835294
01e0fc9df5f1314ce1bd9d56aa870f16d8a3a3ff
136
# boolean_1 = !true boolean_1 = false # boolean_2 = !true && !true boolean_2 = false # boolean_3 = !(700 / 10 == 70) boolean_3 = false
17
31
0.647059
e28bf4468c9559f0688a3d9b2dd89520b2fd3bc8
136
require_relative 'distance_conversions' module FixnumExtension refine Fixnum do include ::Geodesy::DistanceConversions end end
17
42
0.808824
e2009146c91f37e0c9b93c130ec01b429f6b2d70
764
begin require 'rubygems' require 'test/unit' require 'active_support' require 'active_support/inflector' if RUBY_VERSION >= "1.9.0" require 'csv' else require 'fastercsv' end require File.dirname(__FILE__) + '/../lib/to_csv' rescue LoadError puts 'to_csv tests rely on active_support, and fastercsv if ruby version < 1.9' end class User COLUMNS = %w(id name age) attr_accessor *COLUMNS def self.human_attribute_name(attribute) attribute.to_s.humanize end def initialize(params={}) params.each { |key, value| self.send("#{key}=", value); } self end def attributes COLUMNS.inject({}) { |attributes, attribute| attributes.merge(attribute => send(attribute)) } end def is_old? age > 40 end end
20.105263
97
0.683246
26bf5a4aa1aa2cb78f5fe11a80b6d7ab3dd57e49
800
cask "expressvpn" do version "10.8.0.2" sha256 "31da59779c3e5e388ef84e5186791a81dab8c272c8d1d0809d633850d5f80fb9" url "https://www.expressvpn.works/clients/mac/expressvpn_mac_#{version}_release.pkg" name "ExpressVPN" desc "VPN client for secure internet access and private browsing" homepage "https://www.expressvpn.works/" livecheck do url "https://www.expressvpn.works/clients/latest/mac" strategy :header_match end pkg "expressvpn_mac_#{version}_release.pkg" uninstall launchctl: "com.expressvpn.ExpressVPN.agent", script: { executable: "#{appdir}/ExpressVPN.app/Contents/Resources/uninstall.tool", input: ["Yes"], sudo: true, }, pkgutil: "com.expressvpn.ExpressVPN" end
32
87
0.6725
61bbf9bbcdead132e535175779d3abb7cfbeed6f
128
json.extract! helado, :id, :nombre, :precio, :sabor, :tipo, :created_at, :updated_at json.url helado_url(helado, format: :json)
42.666667
84
0.726563