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
|
---|---|---|---|---|---|
0160ee72c937ca326f92a17d34d1995f47a390ca | 576 | maintainer "GoTime Inc."
maintainer_email "[email protected]"
license "Apache 2.0"
description "Installs/Configures zookeeper"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))
version "0.1"
recipe "zookeeper::ebs_volume", "Attaches or creates an EBS volume for zookeeper."
recipe "zookeeper::source", "Installs zookeeper from source and sets up configuration."
%w{ ubuntu debian centos redhat fedora }.each do |os|
supports os
end
%w{ build-essential runit subversion maven java ant }.each do |cb|
depends cb
end
| 32 | 87 | 0.723958 |
1d83b0cfbd838a9e771006be250897e85f48b794 | 100 | # frozen_string_literal: true
module HTML
class Pipeline
VERSION = '2.11.1'.freeze
end
end
| 12.5 | 29 | 0.71 |
6aeebdf31c07653df6e7b3758b31b0facd6fbb39 | 911 | require 'folder_zipper/version'
require 'zip'
module Zip
class FolderZipper
attr_reader :output_file, :input_folder
def initialize(input_folder, output_file = nil)
# Delete last '/' from path if it present.
@input_folder = input_folder.sub(/\/$/, '')
@output_file = output_file || "#{@input_folder}.zip"
end
def compress!(delete_input_folder: false)
files = files_path_and_name
Zip::File.open(output_file, 'w') do |zipfile|
files.each { |file| zipfile.add(file[:name], file[:path]) }
end
FileUtils.rm_rf(input_folder) if delete_input_folder
end
private
def files_path_and_name
files_path = Dir["#{input_folder}/**/**"]
files_path.delete(output_file)
files_path.map do |file_path|
{
path: file_path,
name: file_path.sub("#{input_folder}/", '')
}
end
end
end
end
| 26.028571 | 67 | 0.628979 |
1a80ef5f64ee5ec12eea8ece5294235fae8de94e | 468 | require 'spec_helper'
require 'tomograph/tomogram/action'
RSpec.describe Tomograph::Tomogram::Action do
describe '#find_responses' do
let(:status) { '' }
let(:responses) { [{ 'status' => status }] }
subject do
described_class.new(path: '', method: '', content_type: '', request: '', responses: responses, resource: '')
end
it 'returns responses' do
expect(subject.find_responses(status: status)).to eq(responses)
end
end
end
| 26 | 114 | 0.660256 |
1822217d7d09495feceaf50e247476bd8d29f626 | 4,153 | class UnivsController < ApplicationController
#before_action :authenticate_user!, except: [:index, show]
load_and_authorize_resource
before_action :set_univ, only: [:show, :edit, :update, :destroy]
# 조회수
impressionist actions: [:show]
# GET /univs
# GET /univs.json
def index
@univs = Univ.all
end
# GET /univs/1
# GET /univs/1.json
def show
@univs_true = 0
if @univ.KOSAF == true
@univs_true += 1
end
if @univ.blue_ladder == true
@univs_true += 1
end
if @univ.teps == true
@univs_true += 1
end
if @univ.dbpia == true
@univs_true += 1
end
if @univ.riss == true
@univs_true += 1
end
if @univ.ms_office == true
@univs_true += 1
end
if @univ.aws_credit_normal== true
@univs_true += 1
end
if @univ.aws_credit_100 == true
@univs_true += 1
end
if @univ.github == true
@univs_true += 1
end
if @univ.jet_brain == true
@univs_true += 1
end
if @univ.job_planet == true
@univs_true += 1
end
if @univ.win10 == true
@univs_true += 1
end
if @univ.inflearn == true
@univs_true += 1
end
if @univ.edwith == true
@univs_true += 1
end
if @univ.goorm_ide == true
@univs_true += 1
end
if @univ.KFC == true
@univs_true += 1
end
if @univ.adobe == true
@univs_true += 1
end
if @univ.AOC == true
@univs_true += 1
end
if @univ.Y_goon == true
@univs_true += 1
end
if @univ.matlab == true
@univs_true += 1
end
if @univ.autodesk == true
@univs_true += 1
end
if @univ.samsung_dreamclass == true
@univs_true += 1
end
if @univ.korail_youth == true
@univs_true += 1
end
if @univ.lh == true
@univs_true += 1
end
if @univ.software == true
@univs_true += 1
end
if @univ.dreamspon == true
@univs_true += 1
end
if @univ.everytime == true
@univs_true += 1
end
if @univ.etc == true
@univs_true += 1
end
end
# GET /univs/new
def new
@univ = Univ.new
end
# GET /univs/1/edit
def edit
end
# POST /univs
# POST /univs.json
def create
@univ = Univ.new(univ_params)
respond_to do |format|
if @univ.save
format.html { redirect_to @univ, notice: '대학이 추가되었습니다.' }
format.json { render :show, status: :created, location: @univ }
else
format.html { render :new }
format.json { render json: @univ.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /univs/1
# PATCH/PUT /univs/1.json
def update
respond_to do |format|
if @univ.update(univ_params)
format.html { redirect_to @univ, notice: '대학 정보가 수정되었습니다.' }
format.json { render :show, status: :ok, location: @univ }
else
format.html { render :edit }
format.json { render json: @univ.errors, status: :unprocessable_entity }
end
end
end
# DELETE /univs/1
# DELETE /univs/1.json
def destroy
@univ.destroy
respond_to do |format|
format.html { redirect_to searches_univ_path, notice: '목록에서 대학이 삭제되었습니다.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_univ
@univ = Univ.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def univ_params
params.require(:univ).permit(:univ_name_kor, :univ_name_eng, :univ_nickname, :banner_image, :logo_image, :img_name, :email_url, :content, :etc_content, :KOSAF, :blue_ladder, :dbpia, :riss, :ms_office, :aws_credit_normal, :aws_credit_100, :github, :jet_brain, :job_planet, :win10, :inflearn, :edwith, :goorm_ide, :KFC, :adobe, :AOC, :Y_goon, :etc, :etc_content, :matlab, :samsung_dreamclass, :korail_youth, :lh, :software, :autodesk, :dreamspon, :everytime, :teps)
end
end
| 21.518135 | 469 | 0.579581 |
2669ec98526347374d669d85c9b20aaa7e6046b4 | 812 | #!/usr/bin/env ruby -rubygems
%w(hpricot open-uri).each(&method(:require))
fields, genres = (Hpricot(open("http://www.rubyquiz.com/quiz136.html")) / "p.example").map{|e| e.inner_html}
fields = fields.split
genres = genres.split "<br />"
unpacktypes=Hash.new("A30")
unpacktypes["TAG"]="A3"
unpacktypes["year"]="A4"
unpacktypes["genre"]="c"
unpackstr=fields.map{|x| unpacktypes[x]}.join
id3=Hash.new
raw=open('/home/bloom/scratch/music/rondo.mp3') do |f|
f.seek(f.lstat.size-128)
f.read
end
values=raw.unpack(unpackstr)
fields.zip(values).each do |field,value|
id3[field]=value
end
fail if id3["TAG"]!="TAG"
if id3["comment"].length==30 and id3["comment"][-2]==0
id3["track"]=id3["comment"][-1]
id3["comment"]=id3["comment"][0..-2].strip
end
id3["genre"]=genres[id3["genre"]] || "Unknown"
p id3
| 22.555556 | 108 | 0.674877 |
f836ff8fc8f8eb482fca6bbc7a360d41fbc0f0a6 | 2,965 | # License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
postgres = node['private_chef']['postgresql']
erchef = node['private_chef']['opscode-erchef']
pg_user erchef['sql_user'] do
password PrivateChef.credentials.get('opscode_erchef', 'sql_password')
superuser false
end
pg_user erchef['sql_ro_user'] do
password PrivateChef.credentials.get('opscode_erchef', 'sql_ro_password')
superuser false
end
pg_database 'opscode_chef' do
owner erchef['sql_user']
notifies :deploy, 'pg_sqitch[/opt/opscode/embedded/service/opscode-erchef/schema/baseline]', :immediately
end
# For existing installations, make sure the database owner is set to sql_user
ruby_block 'set opscode_chef ownership' do
block do
EcPostgres.with_connection(node, 'opscode_chef') do |connection|
connection.exec("ALTER DATABASE opscode_chef OWNER TO #{erchef['sql_user']};")
end
end
end
# Note that the sqitch migrations below only trigger when we create the database.
# At this time, we're using partybus to apply upgrade-related sqitch migrations,
# so that we can also apply any necessary data migrations (not yet managed through sqitch)
# at that time.
pg_sqitch '/opt/opscode/embedded/service/opscode-erchef/schema/baseline' do
hostname postgres['vip']
port postgres['port']
username postgres['db_connection_superuser'] || postgres['db_superuser']
password PrivateChef.credentials.get('postgresql', 'db_superuser_password')
database 'opscode_chef'
sslmode postgres['sslmode']
action :nothing
notifies :deploy, 'pg_sqitch[/opt/opscode/embedded/service/opscode-erchef/schema]', :immediately
end
pg_sqitch '/opt/opscode/embedded/service/opscode-erchef/schema' do
hostname postgres['vip']
port postgres['port']
username postgres['db_connection_superuser'] || postgres['db_superuser']
password PrivateChef.credentials.get('postgresql', 'db_superuser_password')
database 'opscode_chef'
sslmode postgres['sslmode']
action :nothing
end
pg_user_table_access erchef['sql_user'] do
database 'opscode_chef'
schema 'public'
access_profile :write
only_if { is_data_master? }
end
pg_user_table_access erchef['sql_ro_user'] do
database 'opscode_chef'
schema 'public'
access_profile :read
only_if { is_data_master? }
end
# Cleanup old enterprise-chef-server-schema
directory '/opt/opscode/embedded/service/enterprise-chef-server-schema' do
recursive true
action :delete
end
| 34.08046 | 107 | 0.765261 |
62cc6f5c7e208d32cc510dbd7507be90f335af44 | 6,690 | =begin
#Swagger Petstore
#This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
OpenAPI spec version: 1.0.6
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
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.
=end
require 'uri'
module SwaggerClient
class Configuration
# Defines url scheme
attr_accessor :scheme
# Defines url host
attr_accessor :host
# Defines url base path
attr_accessor :base_path
# Defines API keys used with API Key authentications.
#
# @return [Hash] key: parameter name, value: parameter value (API key)
#
# @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
# config.api_key['api_key'] = 'xxx'
attr_accessor :api_key
# Defines API key prefixes used with API Key authentications.
#
# @return [Hash] key: parameter name, value: API key prefix
#
# @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
# config.api_key_prefix['api_key'] = 'Token'
attr_accessor :api_key_prefix
# Defines the username used with HTTP basic authentication.
#
# @return [String]
attr_accessor :username
# Defines the password used with HTTP basic authentication.
#
# @return [String]
attr_accessor :password
# Defines the access token (Bearer) used with OAuth2.
attr_accessor :access_token
# Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
# details will be logged with `logger.debug` (see the `logger` attribute).
# Default to false.
#
# @return [true, false]
attr_accessor :debugging
# Defines the logger used for debugging.
# Default to `Rails.logger` (when in Rails) or logging to STDOUT.
#
# @return [#debug]
attr_accessor :logger
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
# The time limit for HTTP request in seconds.
# Default to 0 (never times out).
attr_accessor :timeout
### TLS/SSL setting
# Set this to false to skip verifying SSL certificate when calling API from https server.
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :verify_ssl
### TLS/SSL setting
# Set this to false to skip verifying SSL host name
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :verify_ssl_host
### TLS/SSL setting
# Set this to customize the certificate file to verify the peer.
#
# @return [String] the path to the certificate file
#
# @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
# https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
attr_accessor :ssl_ca_cert
### TLS/SSL setting
# Client certificate file (for client certificate)
attr_accessor :cert_file
### TLS/SSL setting
# Client private key file (for client certificate)
attr_accessor :key_file
# Set this to customize parameters encoding of array parameter with multi collectionFormat.
# Default to nil.
#
# @see The params_encoding option of Ethon. Related source code:
# https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96
attr_accessor :params_encoding
attr_accessor :inject_format
attr_accessor :force_ending_format
def initialize
@scheme = 'https'
@host = 'petstore.swagger.io'
@base_path = '/v2'
@api_key = {}
@api_key_prefix = {}
@timeout = 0
@verify_ssl = true
@verify_ssl_host = true
@params_encoding = nil
@cert_file = nil
@key_file = nil
@debugging = false
@inject_format = false
@force_ending_format = false
@logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
yield(self) if block_given?
end
# The default Configuration object.
def self.default
@@default ||= Configuration.new
end
def configure
yield(self) if block_given?
end
def scheme=(scheme)
# remove :// from scheme
@scheme = scheme.sub(/:\/\//, '')
end
def host=(host)
# remove http(s):// and anything after a slash
@host = host.sub(/https?:\/\//, '').split('/').first
end
def base_path=(base_path)
# Add leading and trailing slashes to base_path
@base_path = "/#{base_path}".gsub(/\/+/, '/')
@base_path = "" if @base_path == "/"
end
def base_url
url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '')
URI.encode(url)
end
# Gets API key (with prefix if set).
# @param [String] param_name the parameter name of API key auth
def api_key_with_prefix(param_name)
if @api_key_prefix[param_name]
"#{@api_key_prefix[param_name]} #{@api_key[param_name]}"
else
@api_key[param_name]
end
end
# Gets Basic Auth token string
def basic_auth_token
'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
end
# Returns Auth Settings hash for api client.
def auth_settings
{
'petstore_auth' =>
{
type: 'oauth2',
in: 'header',
key: 'Authorization',
value: "Bearer #{access_token}"
},
'api_key' =>
{
type: 'api_key',
in: 'header',
key: 'api_key',
value: api_key_with_prefix('api_key')
},
}
end
end
end
| 30.135135 | 271 | 0.650224 |
f8027247ee140cd1189aa547a6cdd05904c2047e | 1,040 | #
# Be sure to run `pod spec lint MUCycleScrollView.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
s.name = "MUCycleScrollView"
s.version = "1.0.0"
s.summary = "swift3.x实现的轮播图"
s.description = <<-DESC
这是一个用swift3.x,实现iOS的banner,这里是第一次上传,希望大家支持。
DESC
s.homepage = "https://github.com/muchangqing/MUCycleScrollView"
s.license = "MIT"
s.author = "大好时光"
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/muchangqing/MUCycleScrollView.git", :tag => "{s.version}" }
s.source_files = "CycleScrollView", "MUCycleScrollView/CycleScrollView/*"
s.frameworks = 'UIKit', 'Foundation'
s.requires_arc = true
s.dependency "Kingfisher"
end
| 26 | 108 | 0.649038 |
abc184d60be9191f227577552ed865913c81f5f9 | 5,148 | #!/usr/local/bin/ruby
# -*- coding: utf-8 -*-
#
# 予約一覧
#
class ReservationListOld
Base = "/rsv_list_old"
def initialize( params, page )
@serach = nil
if params["search"] != nil
@serach = params["search"]
end
if page == nil
@page = 1
else
@page = page.to_i
end
@page_line = 100
@autoRsv = {} # 自動予約のIDリスト
@reserve = DBreserve.new()
end
def getData()
programs = DBprograms.new
filter = DBfilter.new
now = Time.now.to_i
if @serach != nil
title2 = "%#{@serach}%"
else
title2 = nil
end
DBaccess.new().open do |db|
if (row = filter.select( db, type: FilConst::AutoRsv )) != nil
row.each do |r|
@autoRsv[ r[:id].to_i ] = true
end
end
@total_size = @reserve.count( db, tstart: now, titleL: title2)
@pageNum = 1
if @total_size > @page_line
@pageNum = @total_size / @page_line
if @pageNum > 0
@pageNum += 1 if (@total_size - ( @page_line * @pageNum )) > 0
end
end
limit = nil
if @pageNum > 1
limit = "LIMIT #{@page_line} OFFSET #{@page_line * (@page - 1 )}"
end
order = " order by r.start desc"
r = @reserve.selectSP( db, tstart: now, titleL: title2, limit: limit, order: order )
return r
end
nil
end
#
# pageのセレクト
#
def pageSel( )
r = []
r << %Q{<ul class="pagination inline-block">}
1.upto( @pageNum ) do |p|
cl = "waves-effect"
cl += " active" if @page == p
href = sprintf("%s/%d",Base,p)
r << %Q{ <li class="#{cl}"><a href="#{href}">#{p}</a></li>}
end
r << %Q{</ul>}
r.join("\n")
end
def printTD( str, clas: nil, id: nil, rid: nil, style: nil )
attr = ""
attr += %Q{class="#{clas.join(" ")}" } if clas != nil
attr += %Q{id="#{id}" } if id != nil
attr += %Q{rid="#{rid}" } if rid != nil
attr += %Q{style="#{style}" } if style != nil
%Q{ <td #{attr}> #{str} </td>}
end
def printTR( data, id: nil, clas: nil )
attr = []
attr << %Q(class="#{clas.join(" ")}") if clas != nil
attr << %Q(id="#{id}") if id != nil
a = [ %Q{ <tr #{attr.join(" ")}> } ]
a += data
a << %Q{ </tr> }
a.join("\n")
end
#
# データの表示
#
def printTable()
r = []
data = getData()
if data != nil
count = @page > 1 ? ( @page_line * ( @page - 1 ) + 1) : 1
clas = %w( nowrap ) #item
data.each do |t|
next if t[:stat] == RsvConst::RecNow
clasS = %w( nowrap )
time = Commlib::stet_to_s( t[:start], t[:end] )
if t[:type] == 0
type = "手動"
else
if @autoRsv[ t[:keyid] ] == true
type = %Q(<a href="/search/fil/#{t[:keyid]}"> 自動 </a>)
else
type = "自動(除)"
end
end
title = %Q(<a class="dialog" rid="#{t[:id]}"> #{t[:title]} </a>)
bg = nil
id = nil
cate = t[:category]
bg = %Q(color#{cate})
( stat, clasS, bg, recf ) = Commlib::statAna( t, clasS, bg )
st = ( Time.at(t[:start]) - 3600 ).strftime("%Y-%m-%d/%H")
day = %Q(<a href="rsv_tbl/#{st}"> #{time[0]} </a>)
time2 = %Q(<a href="rsv_tbl/#{st}"> #{time[1]} #{time[2]} </a>)
if TSFT == true
ftp_stat = case t[:ftp_stat]
when RsvConst::Ftp_Complete then "○"
when RsvConst::Ftp_AbNormal then "×"
when RsvConst::Off then "未"
else "−"
end
else
ftp_stat = ""
end
# packectchk
pc = "未"
if PacketChkRun == true
clasP = %w( nowrap center )
if t[:stat] == RsvConst::AbNormalEnd or
t[:stat] == RsvConst::RecStop or
t[:stat] == RsvConst::RecStop2 or
t[:stat] == RsvConst::NotUse
pc = "-"
elsif t[:dropNum ] != nil
( drer, pcr, execerror ) = @reserve.parseDropNum( t[:dropNum ] )
if execerror > 0
pc = "失敗"
else
pc = drer
clasP << "packchk"
if drer > PacketChk_threshold
clasP << "alertR"
elsif pcr > 0
clasP << "alertY"
end
end
end
end
td = []
td << printTD( count, clas: clas )
td << printTD( t[:name],clas: clas )
td << printTD( day,clas: clas )
td << printTD( time2,clas: clas )
td << printTD( stat,clas: clasS, id: id )
if TSFT == true
td << printTD( ftp_stat,clas: clas )
end
if PacketChkRun == true
if execerror == 0
td << printTD( pc, clas: clasP, rid: t[:id] )
else
td << printTD( pc, clas: clasP )
end
end
td << printTD( type,clas: clas )
td << printTD( title,clas: clas )
r << printTR( td, clas: [ bg ] )
count += 1
end
end
r.join("\n")
end
end
| 25.485149 | 90 | 0.449301 |
6ae3e8ce1aa31d750ee58273b4e6bc1e2e93b79d | 991 | Pod::Spec.new do |spec|
spec.name = 'mokoSocketIo'
spec.version = '0.2.0'
spec.homepage = 'https://github.com/icerockdev/moko-socket-io'
spec.source = { :git => "https://github.com/icerockdev/moko-socket-io.git", :tag => "release/#{spec.version}" }
spec.authors = 'IceRock Development'
spec.license = { :type => 'Apache 2', :file => 'LICENSE.md' }
spec.summary = 'Swift additions to Kotlin/Native library'
spec.module_name = "#{spec.name}"
spec.source_files = "socket-io/src/iosMain/swift/**/*.{h,m,swift}"
spec.resources = "socket-io/src/iosMain/bundle/**/*"
spec.dependency 'Socket.IO-Client-Swift', '~> 15.2.0'
spec.ios.deployment_target = '11.0'
spec.swift_version = '5.0'
spec.pod_target_xcconfig = {
'VALID_ARCHS' => '$(ARCHS_STANDARD_64_BIT)'
}
end
| 43.086957 | 133 | 0.532795 |
9105000ee885e941c9668815c3a0836588fed0c3 | 124 | class AddEventSeatGeekId < ActiveRecord::Migration
def change
add_column :events, :seatgeekeventid, :string
end
end
| 20.666667 | 50 | 0.774194 |
91d664a0e49fc2210229ff539d3ea4cd7640ee35 | 17,763 | # frozen_string_literal: true
RSpec.describe Blacklight::FacetsHelperBehavior do
let(:blacklight_config) { Blacklight::Configuration.new }
before do
allow(helper).to receive(:blacklight_config).and_return blacklight_config
end
describe "has_facet_values?" do
let(:empty) { double(items: [], name: 'empty') }
let(:response) { instance_double(Blacklight::Solr::Response) }
it "is true if there are any facets to display" do
a = double(items: [1, 2], name: 'a')
b = double(items: %w[b c], name: 'b')
fields = [a, b, empty]
expect(helper.has_facet_values?(fields, response)).to be true
end
it "is false if all facets are empty" do
expect(helper.has_facet_values?([empty], response)).to be false
end
describe "different config" do
let(:blacklight_config) { Blacklight::Configuration.new { |config| config.add_facet_field 'basic_field', if: false } }
it "is false if no facets are displayable" do
a = double(items: [1, 2], name: 'basic_field')
expect(helper.has_facet_values?([a], response)).to be false
end
end
end
describe "should_render_facet?" do
let(:blacklight_config) do
Blacklight::Configuration.new do |config|
config.add_facet_field 'basic_field'
config.add_facet_field 'no_show', show: false
config.add_facet_field 'helper_show', show: :my_custom_check
config.add_facet_field 'helper_with_an_arg_show', show: :my_custom_check_with_an_arg
config.add_facet_field 'lambda_show', show: ->(_context, _config, _field) { true }
config.add_facet_field 'lambda_no_show', show: ->(_context, _config, _field) { false }
end
end
it "renders facets with items" do
a = double(items: [1, 2], name: 'basic_field')
expect(helper.should_render_facet?(a)).to be true
end
it "does not render facets without items" do
empty = double(items: [], name: 'basic_field')
expect(helper.should_render_facet?(empty)).to be false
end
it "does not render facets where show is set to false" do
a = double(items: [1, 2], name: 'no_show')
expect(helper.should_render_facet?(a)).to be false
end
it "calls a helper to determine if it should render a field" do
allow(controller).to receive_messages(my_custom_check: true)
a = double(items: [1, 2], name: 'helper_show')
expect(helper.should_render_facet?(a)).to be true
end
it "calls a helper to determine if it should render a field" do
a = double(items: [1, 2], name: 'helper_with_an_arg_show')
allow(controller).to receive(:my_custom_check_with_an_arg).with(blacklight_config.facet_fields['helper_with_an_arg_show'], a).and_return(true)
expect(helper.should_render_facet?(a)).to be true
end
it "evaluates a Proc to determine if it should render a field" do
a = double(items: [1, 2], name: 'lambda_show')
expect(helper.should_render_facet?(a)).to be true
a = double(items: [1, 2], name: 'lambda_no_show')
expect(helper.should_render_facet?(a)).to be false
end
end
describe "should_collapse_facet?" do
let(:blacklight_config) do
Blacklight::Configuration.new do |config|
config.add_facet_field 'basic_field'
config.add_facet_field 'no_collapse', collapse: false
end
end
it "is collapsed by default" do
expect(helper.should_collapse_facet?(blacklight_config.facet_fields['basic_field'])).to be true
end
it "does not be collapsed if the configuration says so" do
expect(helper.should_collapse_facet?(blacklight_config.facet_fields['no_collapse'])).to be false
end
it "does not be collapsed if it is in the params" do
params[:f] = ActiveSupport::HashWithIndifferentAccess.new(basic_field: [1], no_collapse: [2])
expect(helper.should_collapse_facet?(blacklight_config.facet_fields['basic_field'])).to be false
expect(helper.should_collapse_facet?(blacklight_config.facet_fields['no_collapse'])).to be false
end
end
describe "facet_by_field_name" do
it "retrieves the facet from the response given a string" do
facet_config = double(query: nil, field: 'b', key: 'a')
facet_field = double
allow(helper).to receive(:facet_configuration_for_field).with('b').and_return(facet_config)
response = instance_double(Blacklight::Solr::Response, aggregations: { 'b' => facet_field })
expect(helper.facet_by_field_name('b', response)).to eq facet_field
end
end
describe "render_facet_partials" do
let(:a) { double(items: [1, 2]) }
let(:b) { double(items: %w[b c]) }
let(:response) { instance_double(Blacklight::Solr::Response) }
it "tries to render all provided facets" do
empty = double(items: [])
fields = [a, b, empty]
expect(helper).to receive(:render_facet_limit).with(a, {})
expect(helper).to receive(:render_facet_limit).with(b, {})
expect(helper).to receive(:render_facet_limit).with(empty, {})
helper.render_facet_partials fields, response: response
end
it "defaults to the configured facets" do
allow(Deprecation).to receive(:warn)
expect(helper).to receive(:facet_field_names) { [a, b] }
expect(helper).to receive(:render_facet_limit).with(a, {})
expect(helper).to receive(:render_facet_limit).with(b, {})
helper.render_facet_partials
expect(Deprecation).to have_received(:warn).twice
end
end
describe "render_facet_limit" do
let(:blacklight_config) do
Blacklight::Configuration.new do |config|
config.add_facet_field 'basic_field'
config.add_facet_field 'component_field', component: true
config.add_facet_field 'non_rendering_component_field', component: true, if: false
config.add_facet_field 'pivot_facet_field', pivot: %w[a b]
config.add_facet_field 'my_pivot_facet_field_with_custom_partial', partial: 'custom_facet_partial', pivot: %w[a b]
config.add_facet_field 'my_facet_field_with_custom_partial', partial: 'custom_facet_partial'
end
end
let(:mock_custom_facet) { double(name: 'my_facet_field_with_custom_partial', items: [1, 2, 3]) }
it "sets basic local variables" do
mock_facet = double(name: 'basic_field', items: [1, 2, 3])
expect(helper).to receive(:render).with(hash_including(partial: 'facet_limit',
locals: {
field_name: 'basic_field',
facet_field: helper.blacklight_config.facet_fields['basic_field'],
display_facet: mock_facet
}))
helper.render_facet_limit(mock_facet)
end
it "renders a facet _not_ declared in the configuration" do
mock_facet = double(name: 'asdf', items: [1, 2, 3])
expect(helper).to receive(:render).with(hash_including(partial: 'facet_limit'))
helper.render_facet_limit(mock_facet)
end
it "gets the partial name from the configuration" do
expect(helper).to receive(:render).with(hash_including(partial: 'custom_facet_partial'))
helper.render_facet_limit(mock_custom_facet)
end
it "uses a partial layout for rendering the facet frame" do
expect(helper).to receive(:render).with(hash_including(layout: 'facet_layout'))
helper.render_facet_limit(mock_custom_facet)
end
it "allows the caller to opt-out of facet layouts" do
expect(helper).to receive(:render).with(hash_including(layout: nil))
helper.render_facet_limit(mock_custom_facet, layout: nil)
end
it "renders the facet_pivot partial for pivot facets" do
mock_facet = double(name: 'pivot_facet_field', items: [1, 2, 3])
expect(helper).to receive(:render).with(hash_including(partial: 'facet_pivot'))
helper.render_facet_limit(mock_facet)
end
it "lets you override the rendered partial for pivot facets" do
mock_facet = double(name: 'my_pivot_facet_field_with_custom_partial', items: [1, 2, 3])
expect(helper).to receive(:render).with(hash_including(partial: 'custom_facet_partial'))
helper.render_facet_limit(mock_facet)
end
it "lets you override the rendered partial for pivot facets" do
mock_facet = double(name: 'component_field')
expect(helper).to receive(:render).with(an_instance_of(Blacklight::FacetFieldListComponent))
helper.render_facet_limit(mock_facet)
end
it "lets you override the rendered partial for pivot facets" do
mock_facet = double(name: 'non_rendering_component_field')
expect(helper.render_facet_limit(mock_facet)).to be_blank
end
end
describe "render_facet_limit_list" do
subject { helper.render_facet_limit_list(paginator, 'type_solr_field') }
let(:f1) { Blacklight::Solr::Response::Facets::FacetItem.new(hits: '792', value: 'Book') }
let(:f2) { Blacklight::Solr::Response::Facets::FacetItem.new(hits: '65', value: 'Musical Score') }
let(:paginator) { Blacklight::Solr::FacetPaginator.new([f1, f2], limit: 10) }
before do
allow(helper).to receive(:search_action_path) do |*args|
search_catalog_path *args
end
end
it "draws a list of elements" do
expect(subject).to have_selector 'li', count: 2
expect(subject).to have_selector 'li:first-child a.facet-select', text: 'Book'
expect(subject).to have_selector 'li:nth-child(2) a.facet-select', text: 'Musical Score'
end
context "when one of the facet items is rendered as nil" do
# An app may override render_facet_item to filter out some undesired facet items by returning nil.
before do
allow(helper.method(:render_facet_item)).to receive(:owner).and_return(self.class)
# allow_any_instance_of(Blacklight::FacetItemComponent).to receive(:overridden_helper_methods?).and_return(true)
allow(helper).to receive(:render_facet_item).and_return('<a class="facet-select">Book</a>'.html_safe, nil)
end
it "draws a list of elements" do
expect(subject).to have_selector 'li', count: 1
expect(subject).to have_selector 'li:first-child a.facet-select', text: 'Book'
end
end
end
describe "facet_field_in_params?" do
it "checks if the facet field is selected in the user params" do
allow(helper).to receive_messages(params: { f: { "some-field" => ["x"] } })
expect(helper).to be_facet_field_in_params("some-field")
expect(helper.facet_field_in_params?("other-field")).not_to be true
end
end
describe "facet_params" do
it "extracts the facet parameters for a field" do
allow(helper).to receive_messages(params: { f: { "some-field" => ["x"] } })
expect(helper.facet_params("some-field")).to match_array ["x"]
end
it "uses the blacklight key to extract the right fields" do
blacklight_config.add_facet_field "some-key", field: "some-field"
allow(helper).to receive_messages(params: { f: { "some-key" => ["x"] } })
expect(helper.facet_params("some-key")).to match_array ["x"]
expect(helper.facet_params("some-field")).to match_array ["x"]
end
end
describe "facet_field_in_params?" do
let(:search_state) { double }
before do
allow(helper).to receive_messages(search_state: search_state)
end
it "checks if any value is selected for a given facet" do
allow(search_state).to receive(:has_facet?).with(having_attributes(key: 'some-facet')).and_return(true)
expect(helper.facet_field_in_params?("some-facet")).to eq true
end
it "is false if no value for facet is selected" do
allow(search_state).to receive(:has_facet?).with(having_attributes(key: 'some-facet')).and_return(false)
expect(helper.facet_field_in_params?("some-facet")).to eq false
end
end
describe "facet_in_params?" do
let(:search_state) { double }
before do
allow(helper).to receive_messages(search_state: search_state)
allow(search_state).to receive(:has_facet?).with(having_attributes(key: 'some-facet'), value: 'x').and_return(true)
allow(search_state).to receive(:has_facet?).with(having_attributes(key: 'some-facet'), value: 'y').and_return(false)
end
it "checks if a particular value is set in the facet params" do
expect(helper.facet_in_params?("some-facet", "x")).to eq true
expect(helper.facet_in_params?("some-facet", "y")).to eq false
end
end
describe "render_facet_value" do
let(:item) { double(value: 'A', hits: 10) }
let(:search_state) { double(has_facet?: false, add_facet_params_and_redirect: { controller: 'catalog' }) }
before do
allow(helper).to receive(:facet_configuration_for_field).with('simple_field').and_return(Blacklight::Configuration::FacetField.new(key: 'simple_field', query: nil, date: nil, helper_method: nil, single: false, url_method: nil))
allow(helper).to receive(:facet_display_value).and_return('Z')
allow(helper).to receive(:search_state).and_return(search_state)
allow(helper).to receive(:search_action_path) do |*args|
search_catalog_path *args
end
end
describe "simple case" do
let(:expected_html) { '<span class="facet-label"><a class="facet-select" href="/catalog">Z</a></span><span class="facet-count">10</span>' }
it "uses facet_display_value" do
result = helper.render_facet_value('simple_field', item)
expect(result).to be_equivalent_to(expected_html).respecting_element_order
end
end
describe "when :url_method is set" do
let(:expected_html) { '<span class="facet-label"><a class="facet-select" href="/blabla">Z</a></span><span class="facet-count">10</span>' }
it "uses that method" do
allow(helper).to receive(:facet_configuration_for_field).with('simple_field').and_return(Blacklight::Configuration::FacetField.new(key: 'simple_field', query: nil, date: nil, helper_method: nil, single: false, url_method: :test_method))
allow(helper).to receive(:test_method).with('simple_field', item).and_return('/blabla')
result = helper.render_facet_value('simple_field', item)
expect(result).to be_equivalent_to(expected_html).respecting_element_order
end
end
describe "when :suppress_link is set" do
let(:expected_html) { '<span class="facet-label">Z</span><span class="facet-count">10</span>' }
it "suppresses the link" do
result = helper.render_facet_value('simple_field', item, suppress_link: true)
expect(result).to be_equivalent_to(expected_html).respecting_element_order
end
end
end
describe "#facet_display_value" do
it "justs be the facet value for an ordinary facet" do
allow(helper).to receive(:facet_configuration_for_field).with('simple_field').and_return(double(query: nil, date: nil, helper_method: nil, url_method: nil))
expect(helper.facet_display_value('simple_field', 'asdf')).to eq 'asdf'
end
it "allows you to pass in a :helper_method argument to the configuration" do
allow(helper).to receive(:facet_configuration_for_field).with('helper_field').and_return(double(query: nil, date: nil, url_method: nil, helper_method: :my_facet_value_renderer))
allow(helper).to receive(:my_facet_value_renderer).with('qwerty').and_return('abc')
expect(helper.facet_display_value('helper_field', 'qwerty')).to eq 'abc'
end
it "extracts the configuration label for a query facet" do
allow(helper).to receive(:facet_configuration_for_field).with('query_facet').and_return(double(query: { 'query_key' => { label: 'XYZ' } }, date: nil, helper_method: nil, url_method: nil))
expect(helper.facet_display_value('query_facet', 'query_key')).to eq 'XYZ'
end
it "localizes the label for date-type facets" do
allow(helper).to receive(:facet_configuration_for_field).with('date_facet').and_return(double('date' => true, :query => nil, :helper_method => nil, :url_method => nil))
expect(helper.facet_display_value('date_facet', '2012-01-01')).to eq 'Sun, 01 Jan 2012 00:00:00 +0000'
end
it "localizes the label for date-type facets with the supplied localization options" do
allow(helper).to receive(:facet_configuration_for_field).with('date_facet').and_return(double('date' => { format: :short }, :query => nil, :helper_method => nil, :url_method => nil))
expect(helper.facet_display_value('date_facet', '2012-01-01')).to eq '01 Jan 00:00'
end
end
describe "#facet_field_id" do
it "is the parameterized version of the facet field" do
expect(helper.facet_field_id(double(key: 'some field'))).to eq "facet-some-field"
end
end
describe '#facet_field_presenter' do
let(:facet_config) { Blacklight::Configuration::FacetField.new(key: 'x').normalize! }
let(:display_facet) { double }
it 'wraps the facet data in a presenter' do
presenter = helper.facet_field_presenter(facet_config, display_facet)
expect(presenter).to be_a_kind_of Blacklight::FacetFieldPresenter
expect(presenter.facet_field).to eq facet_config
expect(presenter.display_facet).to eq display_facet
expect(presenter.view_context).to eq helper
end
it 'uses the facet config to determine the presenter class' do
stub_const('SomePresenter', Class.new(Blacklight::FacetFieldPresenter))
facet_config.presenter = SomePresenter
presenter = helper.facet_field_presenter(facet_config, display_facet)
expect(presenter).to be_a_kind_of SomePresenter
end
end
end
| 44.96962 | 244 | 0.690199 |
11604b38bf29ff6257d5d4edb1e84cdbbf5783e0 | 1,777 | # frozen_string_literal: true
require_relative '../../helper'
describe Bade::Parser do
include ASTHelper
context 'static text detection' do
it 'detects normal text' do
source = <<~BADE
| abc
BADE
ast = n(:root,
n(:static_text, value: 'abc'),
newline)
assert_ast ast, source
end
it 'detects normal text with escaped interpolation syntax' do
source = '| Here is some text & other text. For example Mumford \#{ and sons.'
ast = n(:root,
n(:static_text, value: 'Here is some text & other text. For example Mumford #{ and sons.'))
assert_ast ast, source
end
it 'detects text containing interpolation syntax' do
source = <<~BADE
| abc \#{abc}
| Here is some text & other text. For example Mumford \#{'&'} and sons.
| Here is some text & other text. For example Mumford &{'&'} and sons.
BADE
ast = n(:root,
n(:static_text, value: 'abc '),
n(:output, value: 'abc'),
newline,
n(:static_text, value: 'Here is some text & other text. For example Mumford '),
n(:output, value: "'&'"),
n(:static_text, value: ' and sons.'),
newline,
n(:static_text, value: 'Here is some text & other text. For example Mumford '),
n(:output, value: "'&'", escaped: true),
n(:static_text, value: ' and sons.'),
newline)
assert_ast ast, source
end
it 'detects text with @' do
source = '| Here is some text @bla and @ ha.'
ast = n(:root,
n(:static_text, value: 'Here is some text @bla and @ ha.'))
assert_ast ast, source
end
end
end
| 28.206349 | 105 | 0.544176 |
ed9267d1fd9f30915d29ff4d7c41e10d82ce88d6 | 5,515 | require 'set'
module Volt
class Computation
@@current = nil
@@flush_queue = Set.new
def self.current=(val)
@@current = val
end
def self.current
@@current
end
# @param [Proc] the code to run when the computation needs to compute
def initialize(computation)
@computation = computation
@invalidations = []
end
# Runs the computation, called on initial run and
# when changed!
def compute!
@invalidated = false
unless @stopped
@computing = true
run_in do
if @computation.arity > 0
# Pass in the Computation so it can be canceled from within
@computation.call(self)
else
@computation.call
end
end
@computing = false
end
end
def on_invalidate(&callback)
if @invalidated
# Call invalidate now, since its already invalidated
# Computation.run_without_tracking do
queue_flush!
callback.call
# end
else
# Store the invalidation
@invalidations << callback
end
end
# Calling invalidate removes the computation from all of
# its dependencies. This keeps its dependencies from
# invalidating it again.
def invalidate!
unless @invalidated
@invalidated = true
queue_flush! unless @stopped
invalidations = @invalidations
@invalidations = []
invalidations.each(&:call)
end
end
# Stop re-run of the computations
def stop
unless @stopped
@stopped = true
invalidate!
end
end
def stopped?
@stopped
end
# Runs in this computation as the current computation, returns the computation
def run_in
previous = Computation.current
Computation.current = self
begin
yield
ensure
Computation.current = previous
end
self
end
# Run a block without tracking any dependencies
def self.run_without_tracking
previous = Computation.current
Computation.current = nil
begin
return_value = yield
ensure
Computation.current = previous
end
return_value
end
def self.flush!
fail "Can't flush while in a flush" if @flushing
@flushing = true
# clear any timers
@@timer = nil
computations = @@flush_queue
@@flush_queue = Set.new
computations.each(&:compute!)
@flushing = false
end
def queue_flush!
@@flush_queue << self
# If we are in the browser, we queue a flush for the next tick
# If we are not in the browser, the user must manually flush
if Volt.in_browser?
unless @@timer
# Flush once everything else has finished running
@@timer = `setImmediate(function() { self.$class()['$flush!'](); })`
end
end
end
end
end
class Proc
def watch!
computation = Volt::Computation.new(self)
# Initial run
computation.compute!
# return the computation
computation
end
# Watches a proc until the value returned equals the passed
# in value. When the value matches, the block is called.
#
# @param the value to match
# @return [Volt::Computation] the initial computation is returned.
def watch_until!(value, &block)
computation = proc do |comp|
# First fetch the value
result = call
if result == value
# Values match
# call the block
Volt::Computation.run_without_tracking do
block.call
end
# stop the computation
comp.stop
end
end.watch!
computation
end
# Does an watch and if the result is a promise, resolves the promise.
# #watch_and_resolve! takes two procs, one for the promise resolution (then), and
# one for promise rejection (fail).
#
# Example:
# -> { }
def watch_and_resolve!(success, failure=nil, yield_nil_for_unresolved_promise=false)
# Keep results between runs
result = nil
computation = proc do |comp|
result = call
last_promise = nil
if result.is_a?(Promise)
last_promise = result
# Often you want a to be alerted that an unresolved promise is waiting
# to be resolved.
if yield_nil_for_unresolved_promise && !result.resolved?
success.call(nil)
end
# The handler gets called once the promise resolves or is rejected.
handler = lambda do |&after_handle|
# Check to make sure that a new value didn't get reactively pushed
# before the promise resolved.
if last_promise.is_a?(Promise) && last_promise == result
# Don't resolve if the computation was stopped
unless comp.stopped?
# Call the passed in proc
after_handle.call
end
# Clear result for GC
result = nil
end
end
result.then do |final|
# Call the success proc passing in the resolved value
handler.call { success.call(final) }
end.fail do |err|
# call the fail callback, passing in the error
handler.call { failure.call(err) if failure }
end
else
success.call(result)
# Clear result for GC
result = nil
end
end.watch!
# Return the computation
computation
end
end
| 23.568376 | 86 | 0.599093 |
ff16637d5dc07a424a0814873156bc15c1bd3588 | 100 | module Kaui
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
end
| 16.666667 | 46 | 0.76 |
5df95677611503d2d31ec49e69b0144d64e29dcd | 19 | george "washington" | 19 | 19 | 0.842105 |
4a59e053938126fd62f2e15f65d5dae13ba77d84 | 1,306 | maintainer "Opscode, Inc."
maintainer_email "[email protected]"
license "Apache 2.0"
description "Sets up a local gem server repository or mirror"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))
version "0.8.3"
recipe "gems", "Empty, use one of the other recipes"
recipe "gems::server", "Sets up a local gem server repository"
recipe "gems::mirror", "Crons an rsync of rubyforge"
depends "apache2"
depends "rsync"
suggests "ruby" # :-)
%w{ ubuntu debian }.each do |os|
supports os
end
attribute "gem_server",
:display_name => "Gem Server",
:description => "Hash of Gem Server attributes",
:type => "hash"
attribute "gem_server/virtual_host_name",
:display_name => "Gem Server Virtual Hostname",
:description => "Apache ServerName for the virtual host",
:default => "gems.domain"
attribute "gem_server/virtual_host_alias",
:display_name => "Gem Server Virtual Host Aliases",
:description => "Array of Apache ServerAlias'es",
:type => "array",
:default => "gems"
attribute "gem_server/directory",
:display_name => "Gem Server Directory",
:description => "Filesystem location of where the gems repository is served from",
:default => "/srv/gems"
| 34.368421 | 84 | 0.667688 |
2660ac688dcf2f17297ed6fd9333fa594d86846b | 5,401 | require 'net/http'
require 'net/https'
require 'pathname'
# Copyright (c) 2008 Caio Chassot
# with parts from Exception Notifier plugin, Copyright (c) 2005 Jamis Buck
#
# 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 RailzScout
extend self
mattr_accessor :config
@@config = {
:url => nil,
:username => 'RailzScout',
:project => 'Inbox',
:area => 'Misc',
:title => nil,
:body => nil,
:email => nil,
:force_new => false,
:ignore_exceptions => [ (ActiveRecord::RecordNotFound if defined? ActiveRecord::RecordNotFound),
(ActionController::RoutingError if defined? ActionController::RoutingError),
(ActionController::UnknownController if defined? ActionController::UnknownController),
(ActionController::UnknownAction if defined? ActionController::UnknownAction),
(CGI::Session::CookieStore::TamperedWithCookie if defined? CGI::Session::CookieStore::TamperedWithCookie),
].compact
}
mattr_accessor :sections
@@sections = %w[ request session environment backtrace ]
def create_bug_form_data(bug_params, sep = '&')
bug = config.merge(bug_params)
params = {
:ScoutUserName => bug[:username],
:ScoutProject => bug[:project],
:ScoutArea => bug[:area],
:Description => bug[:title],
:Extra => bug[:body],
:Email => bug[:email],
:ForceNewBug => (bug[:force_new] ? 1 : 0),
:FriendlyResponse => 0, # 1 to response in HTML, 0 as XML
}
# create a url encoded data string
params.map {|k,v| "#{urlencode(k.to_s)}=#{urlencode(v.to_s)}" }.join(sep)
end
def submit_bug(exception, controller, request, data={})
bug_params = {}
bug_params[:title] = build_title(exception, controller)
bug_params[:body] = render(data.merge({
:rails_root => rails_root,
:controller => controller,
:host => (request.env["HTTP_X_FORWARDED_HOST"] || request.env["HTTP_HOST"]),
:request => request,
:exception => exception,
:backtrace => sanitize_backtrace(exception.backtrace),
:data => data,
:sections => sections }))
uri = URI.parse(config[:url])
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == "https" # enable SSL/TLS
http.start do
response = http.request_post(uri.path, create_bug_form_data(bug_params))
raise "RailzScout post to FogBugz failed: #{response.body}" unless response.body =~ /<Success>/
end
end
def render(assigns)
view_path = Pathname.new("#{File.dirname(__FILE__)}/../views").cleanpath.to_s
ActionView::TemplateFinder.process_view_paths(view_path) if defined? ActionView::TemplateFinder
view = ActionView::Base.new(view_path, assigns, self)
view.extend ExceptionNotifierHelper
view.render "exception_notifier/exception_notification"
end
def controller_name; "exception_notifier" end
alias_method :controller_path, :controller_name
def self.logger; RAILS_DEFAULT_LOGGER end
private
def sanitize_backtrace(trace)
re = Regexp.new(/^#{Regexp.escape(rails_root)}/)
trace.map { |line| Pathname.new(line.gsub(re, "[RAILS_ROOT]")).cleanpath.to_s }
end
def rails_root
@rails_root ||= Pathname.new(RAILS_ROOT).cleanpath.to_s
end
def urlencode(str)
str.gsub(/[^a-zA-Z0-9_\.\-]/n) {|s| sprintf('%%%02x', s[0]) }
end
def build_title(exception, controller)
file, line, method = ''
app_root = Regexp.new( RAILS_ROOT )
filtered = exception.backtrace.select{ |line| line =~ app_root }
unless filtered.empty?
file, line, method = filtered[0].gsub( RAILS_ROOT, '' ).split(':')
method.gsub!("in `", '').gsub!("'", '')
"#{file}:#{line} in #{method} (#{exception.class}) from #{controller.controller_name}##{controller.action_name}"
else
"(#{exception.class}) from #{controller.controller_name}##{controller.action_name}"
end
end
# Removes the object id so cases will be seen as the same issue
# So #<AuthController:0x24cdb94> becomes #<AuthController>
def remove_object_id(message)
message.gsub(/:0x[a-z0-9]{7}/, '')
end
end
| 39.713235 | 134 | 0.654694 |
03198dad65d93106d9084149cb195492165aa1a9 | 511 | module SpreeGopayIntegration::OrdersControllerDecorator
def self.prepended(base)
base.before_action :check_payment_status, only: :show
end
def check_payment_status
order = Spree::Order.find_by!(number: params[:id])
payment = order.payments.last
if payment.payment_method.kind_of?(Spree::PaymentMethod::Gopay)
GopayHelper.check_status(payment.source.gopay_payment_id)
end
end
end
::Spree::OrdersController.prepend(SpreeGopayIntegration::OrdersControllerDecorator) | 26.894737 | 83 | 0.765166 |
791189728e33c9c42485cb82ef9cb5655cdb13d5 | 183 | activate :blog do |blog|
end
activate :ogp do |ogp|
ogp.namespaces = {
fb: data.ogp.fb,
og: data.ogp.og
}
ogp.base_url = 'http://myblog.foo.tld/'
ogp.blog = true
end
| 15.25 | 41 | 0.617486 |
abf0c1c92430948ec4c5bc3cb6452446c24ef3af | 47 | module Microsoft
VERSION = "0.1.0.alpha"
end
| 11.75 | 25 | 0.702128 |
d5ee94746f97e271f180caea6734bafbb11a22e4 | 59 | json.partial! "blog_posts/blog_post", blog_post: @blog_post | 59 | 59 | 0.813559 |
1c9b1fa6975feb7b031d296c344520bbd23d5df4 | 126 | class RenameFirstNameToName < ActiveRecord::Migration
def change
rename_column :employees, :first_name, :name
end
end
| 21 | 53 | 0.777778 |
2875e10d349127c75355692261aec61d389c8806 | 72 | require 'builder'
require_relative 'rodf/spreadsheet'
module RODF
end
| 10.285714 | 35 | 0.805556 |
1d0a61364b01634d379f917ebe9d4f027b972300 | 2,158 | # frozen_string_literal: true
# == Subscribable concern
#
# Users can subscribe to these models.
#
# Used by Issue, MergeRequest, Label
#
module Subscribable
extend ActiveSupport::Concern
included do
has_many :subscriptions, dependent: :destroy, as: :subscribable # rubocop:disable Cop/ActiveRecordDependent
end
def subscribed?(user, project = nil)
return false unless user
if subscription = subscriptions.find_by(user: user, project: project)
subscription.subscribed
else
subscribed_without_subscriptions?(user, project)
end
end
# Override this method to define custom logic to consider a subscribable as
# subscribed without an explicit subscription record.
def subscribed_without_subscriptions?(user, project)
false
end
def subscribers(project)
subscriptions_available(project)
.where(subscribed: true)
.map(&:user)
end
def toggle_subscription(user, project = nil)
unsubscribe_from_other_levels(user, project)
find_or_initialize_subscription(user, project)
.update(subscribed: !subscribed?(user, project))
end
def subscribe(user, project = nil)
unsubscribe_from_other_levels(user, project)
find_or_initialize_subscription(user, project)
.update(subscribed: true)
end
def unsubscribe(user, project = nil)
unsubscribe_from_other_levels(user, project)
find_or_initialize_subscription(user, project)
.update(subscribed: false)
end
private
def unsubscribe_from_other_levels(user, project)
other_subscriptions = subscriptions.where(user: user)
other_subscriptions =
if project.blank?
other_subscriptions.where.not(project: nil)
else
other_subscriptions.where(project: nil)
end
other_subscriptions.update_all(subscribed: false)
end
def find_or_initialize_subscription(user, project)
subscriptions
.find_or_initialize_by(user_id: user.id, project_id: project.try(:id))
end
def subscriptions_available(project)
t = Subscription.arel_table
subscriptions
.where(t[:project_id].eq(nil).or(t[:project_id].eq(project.try(:id))))
end
end
| 24.804598 | 111 | 0.734013 |
5daa863a32522d9714f0ecac2d7cce1f7c430f9b | 5,523 | #!/usr/bin/env ruby
$: << '.'
$: << '..'
$: << '../lib'
$: << '../ext'
if __FILE__ == $0
while (i = ARGV.index('-I'))
x = ARGV.slice!(i, 2)
$: << x[1]
end
end
require 'optparse'
require 'ox'
require 'perf'
require 'files'
begin
require 'nokogiri'
rescue Exception => e
end
begin
require 'libxml'
rescue Exception => e
end
$verbose = 0
$ox_only = false
$all_cbs = false
$filename = nil # nil indicates new file names perf.xml will be created and used
$filesize = 1000 # KBytes
$iter = 100
$strio = false
$pos = false
$smart = false
opts = OptionParser.new
opts.on("-v", "increase verbosity") { $verbose += 1 }
opts.on("-x", "ox only") { $ox_only = true }
opts.on("-a", "all callbacks") { $all_cbs = true }
opts.on("-b", "html smart") { $smart = true }
opts.on("-p", "update position") { $pos = true; $all_cbs = true }
opts.on("-z", "use StringIO instead of file") { $strio = true }
opts.on("-f", "--file [String]", String, "filename") { |f| $filename = f }
opts.on("-i", "--iterations [Int]", Integer, "iterations") { |it| $iter = it }
opts.on("-s", "--size [Int]", Integer, "file size in KBytes") { |s| $filesize = s }
opts.on("-h", "--help", "Show this display") { puts opts; Process.exit!(0) }
opts.parse(ARGV)
$xml_str = nil
# size is in Kbytes
def create_file(filename, size)
head = %{<?xml version="1.0"?>
<?ox version="1.0" mode="object" circular="no" xsd_date="no"?>
<!DOCTYPE table PUBLIC "-//ox//DTD TABLE 1.0//EN" "http://www.ohler.com/DTDs/TestTable-1.0.dtd">
<table>
}
tail = %{</table>
}
row = %{ <!-- row %08d element -->
<row id="%08d">
<cell id="A" type="Fixnum">1234</cell>
<cell id="B" type="String">A string.</cell>
<cell id="C" type="String">This is a longer string that stretches over a larger number of characters.</cell>
<cell id="D" type="Float">-12.345</cell>
<cell id="E" type="Date">2011-09-18 23:07:26 +0900</cell>
<cell id="F" type="Image"><![CDATA[xx00xx00xx00xx00xx00xx00xx00xx00xx00xx00xx00xx00xx00xx00xx00xx00xx00xx00xx00]]></cell>
</row>
}
cnt = (size * 1000 - head.size - tail.size) / row.size
File.open(filename, "w") do |f|
f.write(head)
cnt.times do |i|
f.write(row % [i,i])
end
f.write(tail)
end
end
class OxSax < ::Ox::Sax
def error(message, line, column); puts message; end
end
class OxAllSax < OxSax
def start_element(name); end
def attr(name, str); end
def attr_value(name, value); end
def end_element(name); end
def text(str); end
def value(value); end
def instruct(target); end
def doctype(value); end
def comment(value); end
def cdata(value); end
end
class OxPosAllSax < OxAllSax
def initialize()
@line = nil
@column = nil
end
end
unless defined?(::Nokogiri).nil?
class NoSax < Nokogiri::XML::SAX::Document
def error(message); puts message; end
def warning(message); puts message; end
end
class NoAllSax < NoSax
def start_element(name, attrs = []); end
def characters(text); end
def cdata_block(string); end
def comment(string); end
def end_document(); end
def end_element(name); end
def start_document(); end
def xmldecl(version, encoding, standalone); end
end
end
unless defined?(::LibXML).nil?
class LxSax
include LibXML::XML::SaxParser::Callbacks
end
class LxAllSax < LxSax
def on_start_element(element, attributes); end
def on_cdata_block(cdata); end
def on_characters(chars); end
def on_comment(msg); end
def on_end_document(); end
def on_end_element(element); end
def on_end_element_ns(name, prefix, uri); end
def on_error(msg); end
def on_external_subset(name, external_id, system_id); end
def on_has_external_subset(); end
def on_has_internal_subset(); end
def on_internal_subset(name, external_id, system_id); end
def on_is_standalone(); end
def on_processing_instruction(target, data); end
def on_reference(name); end
def on_start_document(); end
def on_start_element_ns(name, attributes, prefix, uri, namespaces); end
end
end
if $filename.nil?
create_file('perf.xml', $filesize)
$filename = 'perf.xml'
end
$xml_str = File.read($filename)
puts "A #{$filesize} KByte XML file was parsed #{$iter} times for this test."
$handler = nil
perf = Perf.new
perf.add('Ox::Sax', 'sax_parse') {
input = $strio ? StringIO.new($xml_str) : IO.open(IO.sysopen($filename))
Ox.sax_parse($handler, input, :smart => $smart)
input.close
}
perf.before('Ox::Sax') { $handler = $all_cbs ? ($pos ? OxPosAllSax.new() : OxAllSax.new()) : OxSax.new() }
unless $ox_only
unless defined?(::Nokogiri).nil?
perf.add('Nokogiri::XML::Sax', 'parse') {
input = $strio ? StringIO.new($xml_str) : IO.open(IO.sysopen($filename))
$handler.parse(input)
input.close
}
perf.before('Nokogiri::XML::Sax') { $handler = Nokogiri::XML::SAX::Parser.new($all_cbs ? NoAllSax.new() : NoSax.new()) }
end
unless defined?(::LibXML).nil?
perf.add('LibXML::XML::Sax', 'parse') {
input = $strio ? StringIO.new($xml_str) : IO.open(IO.sysopen($filename))
parser = LibXML::XML::SaxParser.io(input)
parser.callbacks = $handler
parser.parse()
input.close
}
perf.before('LibXML::XML::Sax') { $handler = $all_cbs ? LxAllSax.new() : LxSax.new() }
end
end
perf.run($iter)
| 29.222222 | 125 | 0.620677 |
39a3a598048ba418140b374a671ca01733f68d7c | 2,978 | ######################################
## 은행 개인 대출 거래내역
######################################
require 'net/http'
require 'uri'
require 'json'
require 'base64'
require 'uri'
# ========== HTTP 기본 함수 ==========
def http_sender(url, token, body)
uri = URI.parse(url)
puts('url = ' + url)
puts('uri.request_uri = ' + uri.request_uri)
headers = {
'Content-Type'=>'application/json',
'Authorization'=>'Bearer ' + token
}
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url, headers)
request.body = URI::encode(body.to_json)
response = http.request(request)
puts(response.code)
puts(URI.decode(response.body))
return response
end
# ========== HTTP 함수 ==========
# ========== Toekn 재발급 ==========
def request_token(url, client_id, client_secret)
uri = URI.parse(url)
authHeader = Base64.strict_encode64(client_id + ':' + client_secret)
headers = {
'Accept'=> 'application/json',
'Content-Type'=> 'application/x-www-form-urlencoded',
'Authorization'=> 'Basic ' + authHeader
}
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url, headers)
request.body = 'grant_type=client_credentials&scope=read'
response = http.request(request)
return response
end
# ========== Toekn 재발급 ==========
response = nil
# API서버 샌드박스 도메인
CODEF_URL = 'https://tsandbox.codef.io';
TOKEN_URL = 'https://toauth.codef.io/oauth/token';
SANDBOX_CLIENT_ID = 'ef27cfaa-10c1-4470-adac-60ba476273f9'; # CODEF 샌드박스 클라이언트 아이디
SANDBOX_SECERET_KEY = '83160c33-9045-4915-86d8-809473cdf5c3'; # CODEF 샌드박스 클라이언트 시크릿
# 은행 개인 대출 거래내역
transaction_list_path = '/v1/kr/bank/b/loan/transaction-list'
# 기 발급된 토큰
token =''
# BodyData
body = {
'connectedId':'sandbox_connectedId',
'organization':'0004',
'account':'7526090400000',
'startDate':'20190601',
'endDate':'20190708',
'orderBy':'0',
'inquiryType':'1',
'accountLoanExecNo':''
}
# CODEF API 요청
response_codef_api = http_sender(CODEF_URL + transaction_list_path, token, body)
if response_codef_api.code == '200'
puts('정상처리')
# token error
elsif response_codef_api.code == '401'
dict = JSON.parse(response_codef_api.body)
# invalid_token
puts('error = ' + dict['error'])
# Cannot convert access token to JSON
puts('error_description = ' + dict['error_description'])
# reissue token
response_oauth = request_token(TOKEN_URL, SANDBOX_CLIENT_ID, SANDBOX_SECERET_KEY);
puts('response_oauth.code = ' + response_oauth.code)
puts('response_oauth.code = ' + response_oauth.body)
if response_oauth.code == '200'
dict = JSON.parse(response_oauth.body)
# reissue_token
token = dict['access_token']
puts('access_token = ' + token)
# request codef_api
response = http_sender(CODEF_URL + transaction_list_path, token, body)
else
puts('토큰발급 오류')
end
else
puts('API 요청 오류')
end
| 25.237288 | 88 | 0.640698 |
ff46ffcb035806dee78a0f302d9e4f881d71fdd1 | 1,082 | require 'uri'
require_relative 'http_method'
module MicrosoftKiotaAbstractions
class RequestInfo
attr_reader :uri, :content, :http_method
@@binary_content_type = 'application/octet-stream'
@@content_type_header = 'Content-Type'
def uri=(arg)
@uri = URI(arg)
end
def http_method=(method)
@http_method = HttpMethod::HTTP_METHOD[method]
end
def query_parameters
@query_parameters ||= Hash.new
end
def headers
@headers ||= Hash.new
end
def set_stream_content(value = $stdin)
@content = value
@headers[@@content_type_header] = @@binary_content_type
end
def set_content_from_parsable(value, serializer_factory, content_type)
begin
writer = serializer_factory.get_serialization_writer(content_type)
headers[@@content_type_header] = content_type
writer.write_object_value(nil, value);
this.content = writer.get_serialized_content();
rescue => exception
raise Exception.new "could not serialize payload"
end
end
end
end
| 24.590909 | 75 | 0.68207 |
e8c7af1c8d280306a796edd1ff6acd8364433926 | 1,398 | class CodingQuestion < ActiveRecord::Base
attr_accessible :creator_id, :description,:max_grade, :staff_comments, :data, :include_sol_qn_id, :is_auto_grading, :title
include Assessment
belongs_to :creator, class_name: "User"
has_many :std_coding_answers, foreign_key: "qn_id", dependent: :destroy
has_many :asm_qns, as: :qn, dependent: :destroy
has_one :comment_topic, as: :topic
belongs_to :include_sol_qn, class_name: "CodingQuestion"
before_create :set_default_data
after_update :update_test_limit
def data_hash
JSON.parse(self.data)
end
def set_default_data
unless self.data
self.data = '{"type":"do","language":"python","prefill":""}'
end
end
def prefilled_code
data_hash["prefill"] || "#Prefilled code \n#Auto generated"
end
def included_code
data_hash["included"] || ""
end
def test_code
data_hash["included"] || ""
end
def test_limit
data_hash["testLimit"] || 0
end
def update_test_limit
if changed_attributes.has_key? "data"
old_data_hash = JSON.parse(changed_attributes["data"])
diff = test_limit.to_i - old_data_hash["testLimit"].to_i
if diff != 0
Thread.start {
std_coding_answers.each do |std_answer|
std_answer.test_left = [0, std_answer.test_left + diff].max
std_answer.save
end
}
end
end
end
end
| 24.103448 | 124 | 0.677396 |
2105101fceb012be291163180a949d14d5921fe8 | 7,068 | # Cookbook:: wordpress
# Resource:: wordpress_site
#
# Copyright:: 2015, OpenStreetMap Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "securerandom"
default_action :create
property :site, :kind_of => String, :name_property => true
property :aliases, :kind_of => [String, Array]
property :directory, :kind_of => String
property :version, :kind_of => String
property :database_name, :kind_of => String, :required => true
property :database_user, :kind_of => String, :required => true
property :database_password, :kind_of => String, :required => true
property :database_prefix, :kind_of => String, :default => "wp_"
property :urls, :kind_of => Hash, :default => {}
property :reload_apache, :kind_of => [TrueClass, FalseClass], :default => true
action :create do
version = new_resource.version || Chef::Wordpress.current_version
node.normal_unless[:wordpress][:sites][new_resource.site] = {}
node.normal[:wordpress][:sites][new_resource.site][:directory] = site_directory
node.normal_unless[:wordpress][:sites][new_resource.site][:auth_key] = SecureRandom.base64(48)
node.normal_unless[:wordpress][:sites][new_resource.site][:secure_auth_key] = SecureRandom.base64(48)
node.normal_unless[:wordpress][:sites][new_resource.site][:logged_in_key] = SecureRandom.base64(48)
node.normal_unless[:wordpress][:sites][new_resource.site][:nonce_key] = SecureRandom.base64(48)
node.normal_unless[:wordpress][:sites][new_resource.site][:auth_salt] = SecureRandom.base64(48)
node.normal_unless[:wordpress][:sites][new_resource.site][:secure_auth_salt] = SecureRandom.base64(48)
node.normal_unless[:wordpress][:sites][new_resource.site][:logged_in_salt] = SecureRandom.base64(48)
node.normal_unless[:wordpress][:sites][new_resource.site][:nonce_salt] = SecureRandom.base64(48)
mysql_user "#{new_resource.database_user}@localhost" do
password new_resource.database_password
end
mysql_database new_resource.database_name do
permissions "#{new_resource.database_user}@localhost" => :all
end
declare_resource :directory, site_directory do
owner node[:wordpress][:user]
group node[:wordpress][:group]
mode "755"
end
subversion site_directory do
action :sync
repository "https://core.svn.wordpress.org/tags/#{version}"
user node[:wordpress][:user]
group node[:wordpress][:group]
ignore_failure true
end
wp_config = edit_file "#{site_directory}/wp-config-sample.php" do |line|
line.gsub!(/database_name_here/, new_resource.database_name)
line.gsub!(/username_here/, new_resource.database_user)
line.gsub!(/password_here/, new_resource.database_password)
line.gsub!(/wp_/, new_resource.database_prefix)
line.gsub!(/('AUTH_KEY', *)'put your unique phrase here'/, "\\1'#{node[:wordpress][:sites][new_resource.site][:auth_key]}'")
line.gsub!(/('SECURE_AUTH_KEY', *)'put your unique phrase here'/, "\\1'#{node[:wordpress][:sites][new_resource.site][:secure_auth_key]}'")
line.gsub!(/('LOGGED_IN_KEY', *)'put your unique phrase here'/, "\\1'#{node[:wordpress][:sites][new_resource.site][:logged_in_key]}'")
line.gsub!(/('NONCE_KEY', *)'put your unique phrase here'/, "\\1'#{node[:wordpress][:sites][new_resource.site][:nonce_key]}'")
line.gsub!(/('AUTH_SALT', *)'put your unique phrase here'/, "\\1'#{node[:wordpress][:sites][new_resource.site][:auth_salt]}'")
line.gsub!(/('SECURE_AUTH_SALT', *)'put your unique phrase here'/, "\\1'#{node[:wordpress][:sites][new_resource.site][:secure_auth_salt]}'")
line.gsub!(/('LOGGED_IN_SALT', *)'put your unique phrase here'/, "\\1'#{node[:wordpress][:sites][new_resource.site][:logged_in_salt]}'")
line.gsub!(/('NONCE_SALT', *)'put your unique phrase here'/, "\\1'#{node[:wordpress][:sites][new_resource.site][:nonce_salt]}'")
if line =~ /define\('WP_DEBUG'/
line += "\n"
line += "/**\n"
line += " * Don't allow file editing.\n"
line += " */\n"
line += "define('DISALLOW_FILE_EDIT', true);\n"
line += "define('FORCE_SSL_LOGIN', true);\n"
line += "define('FORCE_SSL_ADMIN', true);\n"
end
line
end
file "#{site_directory}/wp-config.php" do
owner node[:wordpress][:user]
group node[:wordpress][:group]
mode "644"
content wp_config
end
declare_resource :directory, "#{site_directory}/wp-content/uploads" do
owner "www-data"
group "www-data"
mode "755"
end
file "#{site_directory}/sitemap.xml" do
action :delete
end
file "#{site_directory}/sitemap.xml.gz" do
action :delete
end
cookbook_file "#{site_directory}/googlefac54c35e800caab.html" do
cookbook "wordpress"
owner node[:wordpress][:user]
group node[:wordpress][:group]
mode "644"
backup false
end
ssl_certificate new_resource.site do
domains [new_resource.site] + Array(new_resource.aliases)
end
apache_site new_resource.site do
cookbook "wordpress"
template "apache.erb"
directory site_directory
variables :aliases => Array(new_resource.aliases),
:urls => new_resource.urls
reload_apache false
end
http_request "https://#{new_resource.site}/wp-admin/upgrade.php" do
action :nothing
url "https://#{new_resource.site}/wp-admin/upgrade.php?step=1"
subscribes :get, "subversion[#{site_directory}]"
end
wordpress_plugin "wp-fail2ban" do
site new_resource.site
reload_apache false
end
script "#{site_directory}/wp-content/plugins/wp-fail2ban" do
action :nothing
interpreter "php"
cwd site_directory
user "wordpress"
code <<-WP_FAIL2BAN
<?php
@include "wp-config.php";
@include_once "wp-includes/functions.php";
@include_once "wp-admin/includes/plugin.php";
activate_plugin("wp-fail2ban/wp-fail2ban.php", '', false, false);
?>
WP_FAIL2BAN
subscribes :run, "wordpress_plugin[wp-fail2ban]"
end
end
action :delete do
wordpress_plugin "wp-fail2ban" do
action :delete
site new_resource.site
reload_apache false
end
apache_site new_resource.site do
action :delete
reload_apache false
end
declare_resource :directory, site_directory do
action :delete
recursive true
end
mysql_database new_resource.database_name do
action :drop
end
mysql_user "#{new_resource.database_user}@localhost" do
action :drop
end
end
action_class do
include Chef::Mixin::EditFile
def site_directory
new_resource.directory || "/srv/#{new_resource.site}"
end
end
def after_created
notifies :reload, "service[apache2]" if reload_apache
end
| 34.144928 | 144 | 0.707414 |
1c855dd0acdae69836ba85027784ac1761cce6bc | 1,020 | module Aliyun
module Verify
class Client
VERIFY_URL = 'http://aliyunverifyidcard.haoservice.com/idcard/VerifyIdcardv2'
attr_accessor :card_no, :name
def initialize(card_no, name, app_code = ENV['app_code'])
@name = name
@card_no = card_no
@app_code = app_code
end
def verify_idcard
OpenStruct.new(http_call)
end
def http_call
begin
uri = URI.parse(VERIFY_URL)
params = { cardNo: card_no, realName: name }
uri.query = URI.encode_www_form(params)
http = Net::HTTP.new(uri.host, uri.port).start
request = Net::HTTP::Get.new(uri.request_uri, { 'Authorization' => "APPCODE #{@app_code}" })
res = http.request(request)
if res.is_a?(Net::HTTPOK)
JSON.parse(res.body)
else
{ error_code: 98, reason: res.inspect }
end
rescue => e
{ error_code: 99, reason: e.to_s }
end
end
end
end
end | 26.842105 | 102 | 0.568627 |
1ae9b05459f8e04b09ef3730afeea268f6e478d2 | 2,319 | require 'test_helper'
require 'enumerize/integrations/rspec'
describe Enumerize::Integrations::RSpec do
class Should
include Enumerize::Integrations::RSpec
end
let(:klass) do
Class.new do
extend Enumerize
end
end
let(:should) { Should.new }
let(:object) { klass.new }
describe '#description' do
before do
klass.enumerize(:sex, :in => [:male, :female])
end
it 'returns description without default value' do
matcher = should.enumerize(:sex).in(:male, :female)
matcher.description.must_equal 'enumerize :sex in: "female", "male"'
end
it 'returns description with default value' do
matcher = should.enumerize(:sex).in(:male, :female).with_default(:male)
matcher.description.must_equal 'enumerize :sex in: "female", "male" with "male" as default value'
end
end
describe '#matches?' do
before do
klass.enumerize(:sex, :in => [:male, :female])
end
it 'returns true' do
matcher = should.enumerize(:sex).in(:male, :female)
matcher.matches?(object).must_equal true
end
it 'returns false' do
matcher = should.enumerize(:sex).in(:bar)
matcher.matches?(object).must_equal false
end
end
describe '#failure_message' do
before do
klass.enumerize(:sex, :in => [:male, :female], :default => :male)
end
it 'returns failure message for invalid :in option' do
matcher = should.enumerize(:sex).in(:bar)
matcher.subject = object
expected = ' expected :sex to allow value: "bar", but it allows "female", "male" instead'
matcher.failure_message.must_equal expected
end
it 'returns failure message for invalid :with_default option' do
matcher = should.enumerize(:sex).in(:male, :female).with_default(:foo)
matcher.subject = object
expected = ' expected :sex to have "foo" as default value, but it sets "male" instead'
matcher.failure_message.must_equal expected
end
it 'returns failure message for ivalid :in option with default value' do
matcher = should.enumerize(:sex).in(:bar).with_default(:male)
matcher.subject = object
expected = ' expected :sex to allow value: "bar", but it allows "female", "male" instead'
matcher.failure_message.must_equal expected
end
end
end
| 30.116883 | 103 | 0.667098 |
e284f31f7ee46a8d02cdb0b43d5029650134385d | 9,747 | require 'gon'
class ApplicationController < ActionController::Base
include Gitlab::CurrentSettings
include GitlabRoutingHelper
PER_PAGE = 20
before_filter :authenticate_user_from_token!
before_filter :authenticate_user!
before_filter :reject_blocked!
before_filter :check_password_expiration
before_filter :ldap_security_check
before_filter :default_headers
before_filter :add_gon_variables
before_filter :configure_permitted_parameters, if: :devise_controller?
before_filter :require_email, unless: :devise_controller?
protect_from_forgery with: :exception
helper_method :abilities, :can?, :current_application_settings
helper_method :github_import_enabled?, :gitlab_import_enabled?, :bitbucket_import_enabled?
rescue_from Encoding::CompatibilityError do |exception|
log_exception(exception)
render "errors/encoding", layout: "errors", status: 500
end
rescue_from ActiveRecord::RecordNotFound do |exception|
log_exception(exception)
render "errors/not_found", layout: "errors", status: 404
end
protected
# From https://github.com/plataformatec/devise/wiki/How-To:-Simple-Token-Authentication-Example
# https://gist.github.com/josevalim/fb706b1e933ef01e4fb6
def authenticate_user_from_token!
user_token = if params[:authenticity_token].presence
params[:authenticity_token].presence
elsif params[:private_token].presence
params[:private_token].presence
end
user = user_token && User.find_by_authentication_token(user_token.to_s)
if user
# Notice we are passing store false, so the user is not
# actually stored in the session and a token is needed
# for every request. If you want the token to work as a
# sign in token, you can simply remove store: false.
sign_in user, store: false
end
end
def authenticate_user!(*args)
# If user is not signed-in and tries to access root_path - redirect him to landing page
if current_application_settings.home_page_url.present?
if current_user.nil? && controller_name == 'dashboard' && action_name == 'show'
redirect_to current_application_settings.home_page_url and return
end
end
super(*args)
end
def log_exception(exception)
application_trace = ActionDispatch::ExceptionWrapper.new(env, exception).application_trace
application_trace.map!{ |t| " #{t}\n" }
logger.error "\n#{exception.class.name} (#{exception.message}):\n#{application_trace.join}"
end
def reject_blocked!
if current_user && current_user.blocked?
sign_out current_user
flash[:alert] = "Your account is blocked. Retry when an admin has unblocked it."
redirect_to new_user_session_path
end
end
def after_sign_in_path_for(resource)
if resource.is_a?(User) && resource.respond_to?(:blocked?) && resource.blocked?
sign_out resource
flash[:alert] = "Your account is blocked. Retry when an admin has unblocked it."
new_user_session_path
else
stored_location_for(:redirect) || stored_location_for(resource) || root_path
end
end
def abilities
Ability.abilities
end
def can?(object, action, subject)
abilities.allowed?(object, action, subject)
end
def project
unless @project
namespace = params[:namespace_id]
id = params[:project_id] || params[:id]
# Redirect from
# localhost/group/project.git
# to
# localhost/group/project
#
if id =~ /\.git\Z/
redirect_to request.original_url.gsub(/\.git\Z/, '') and return
end
@project = Project.find_with_namespace("#{namespace}/#{id}")
if @project and can?(current_user, :read_project, @project)
@project
elsif current_user.nil?
@project = nil
authenticate_user!
else
@project = nil
render_404 and return
end
end
@project
end
def repository
@repository ||= project.repository
rescue Grit::NoSuchPathError(e)
log_exception(e)
nil
end
def authorize_project!(action)
return access_denied! unless can?(current_user, action, project)
end
def authorize_labels!
# Labels should be accessible for issues and/or merge requests
authorize_read_issue! || authorize_read_merge_request!
end
def access_denied!
render "errors/access_denied", layout: "errors", status: 404
end
def not_found!
render "errors/not_found", layout: "errors", status: 404
end
def git_not_found!
render "errors/git_not_found", layout: "errors", status: 404
end
def method_missing(method_sym, *arguments, &block)
if method_sym.to_s =~ /^authorize_(.*)!$/
authorize_project!($1.to_sym)
else
super
end
end
def render_403
head :forbidden
end
def render_404
render file: Rails.root.join("public", "404"), layout: false, status: "404"
end
def require_non_empty_project
redirect_to @project if @project.empty_repo?
end
def no_cache_headers
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
end
def default_headers
headers['X-Frame-Options'] = 'DENY'
headers['X-XSS-Protection'] = '1; mode=block'
headers['X-UA-Compatible'] = 'IE=edge'
headers['X-Content-Type-Options'] = 'nosniff'
headers['Strict-Transport-Security'] = 'max-age=31536000' if Gitlab.config.gitlab.https
end
def add_gon_variables
gon.default_issues_tracker = Project.new.default_issue_tracker.to_param
gon.api_version = API::API.version
gon.relative_url_root = Gitlab.config.gitlab.relative_url_root
gon.default_avatar_url = URI::join(Gitlab.config.gitlab.url, ActionController::Base.helpers.image_path('no_avatar.png')).to_s
if current_user
gon.current_user_id = current_user.id
gon.api_token = current_user.private_token
end
end
def check_password_expiration
if current_user && current_user.password_expires_at && current_user.password_expires_at < Time.now && !current_user.ldap_user?
redirect_to new_profile_password_path and return
end
end
def ldap_security_check
if current_user && current_user.requires_ldap_check?
unless Gitlab::LDAP::Access.allowed?(current_user)
sign_out current_user
flash[:alert] = "Access denied for your LDAP account."
redirect_to new_user_session_path
end
end
end
def event_filter
filters = cookies['event_filter'].split(',') if cookies['event_filter'].present?
@event_filter ||= EventFilter.new(filters)
end
def gitlab_ldap_access(&block)
Gitlab::LDAP::Access.open { |access| block.call(access) }
end
# JSON for infinite scroll via Pager object
def pager_json(partial, count)
html = render_to_string(
partial,
layout: false,
formats: [:html]
)
render json: {
html: html,
count: count
}
end
def view_to_html_string(partial)
render_to_string(
partial,
layout: false,
formats: [:html]
)
end
def configure_permitted_parameters
devise_parameter_sanitizer.sanitize(:sign_in) { |u| u.permit(:username, :email, :password, :login, :remember_me) }
end
def hexdigest(string)
Digest::SHA1.hexdigest string
end
def require_email
if current_user && current_user.temp_oauth_email?
redirect_to profile_path, notice: 'Please complete your profile with email address' and return
end
end
def set_filters_params
params[:sort] ||= 'created_desc'
params[:scope] = 'all' if params[:scope].blank?
params[:state] = 'opened' if params[:state].blank?
@filter_params = params.dup
if @project
@filter_params[:project_id] = @project.id
elsif @group
@filter_params[:group_id] = @group.id
else
# TODO: this filter ignore issues/mr created in public or
# internal repos where you are not a member. Enable this filter
# or improve current implementation to filter only issues you
# created or assigned or mentioned
#@filter_params[:authorized_only] = true
end
@filter_params
end
def set_filter_values(collection)
assignee_id = @filter_params[:assignee_id]
author_id = @filter_params[:author_id]
milestone_id = @filter_params[:milestone_id]
@sort = @filter_params[:sort]
@assignees = User.where(id: collection.pluck(:assignee_id))
@authors = User.where(id: collection.pluck(:author_id))
@milestones = Milestone.where(id: collection.pluck(:milestone_id))
if assignee_id.present? && !assignee_id.to_i.zero?
@assignee = @assignees.find_by(id: assignee_id)
end
if author_id.present? && !author_id.to_i.zero?
@author = @authors.find_by(id: author_id)
end
if milestone_id.present? && !milestone_id.to_i.zero?
@milestone = @milestones.find_by(id: milestone_id)
end
end
def get_issues_collection
set_filters_params
issues = IssuesFinder.new.execute(current_user, @filter_params)
set_filter_values(issues)
issues
end
def get_merge_requests_collection
set_filters_params
merge_requests = MergeRequestsFinder.new.execute(current_user, @filter_params)
set_filter_values(merge_requests)
merge_requests
end
def github_import_enabled?
OauthHelper.enabled_oauth_providers.include?(:github)
end
def gitlab_import_enabled?
OauthHelper.enabled_oauth_providers.include?(:gitlab)
end
def bitbucket_import_enabled?
OauthHelper.enabled_oauth_providers.include?(:bitbucket) && Gitlab::BitbucketImport.public_key.present?
end
end
| 29.27027 | 131 | 0.706987 |
bbb11b8f310a035de1aa981b07e82ecf9b586b4e | 5,428 | require_relative '../../spec_helper'
require 'stringio'
describe "StringIO#initialize when passed [Object, mode]" do
before :each do
@io = StringIO.allocate
end
it "uses the passed Object as the StringIO backend" do
@io.send(:initialize, str = "example", "r")
@io.string.should equal(str)
end
it "sets the mode based on the passed mode" do
io = StringIO.allocate
io.send(:initialize, "example", "r")
io.closed_read?.should be_false
io.closed_write?.should be_true
io = StringIO.allocate
io.send(:initialize, "example", "rb")
io.closed_read?.should be_false
io.closed_write?.should be_true
io = StringIO.allocate
io.send(:initialize, "example", "r+")
io.closed_read?.should be_false
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", "rb+")
io.closed_read?.should be_false
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", "w")
io.closed_read?.should be_true
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", "wb")
io.closed_read?.should be_true
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", "w+")
io.closed_read?.should be_false
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", "wb+")
io.closed_read?.should be_false
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", "a")
io.closed_read?.should be_true
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", "ab")
io.closed_read?.should be_true
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", "a+")
io.closed_read?.should be_false
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", "ab+")
io.closed_read?.should be_false
io.closed_write?.should be_false
end
it "allows passing the mode as an Integer" do
io = StringIO.allocate
io.send(:initialize, "example", IO::RDONLY)
io.closed_read?.should be_false
io.closed_write?.should be_true
io = StringIO.allocate
io.send(:initialize, "example", IO::RDWR)
io.closed_read?.should be_false
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", IO::WRONLY)
io.closed_read?.should be_true
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", IO::WRONLY | IO::TRUNC)
io.closed_read?.should be_true
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", IO::RDWR | IO::TRUNC)
io.closed_read?.should be_false
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", IO::WRONLY | IO::APPEND)
io.closed_read?.should be_true
io.closed_write?.should be_false
io = StringIO.allocate
io.send(:initialize, "example", IO::RDWR | IO::APPEND)
io.closed_read?.should be_false
io.closed_write?.should be_false
end
it "raises a #{frozen_error_class} when passed a frozen String in truncate mode as StringIO backend" do
io = StringIO.allocate
lambda { io.send(:initialize, "example".freeze, IO::TRUNC) }.should raise_error(frozen_error_class)
end
it "tries to convert the passed mode to a String using #to_str" do
obj = mock('to_str')
obj.should_receive(:to_str).and_return("r")
@io.send(:initialize, "example", obj)
@io.closed_read?.should be_false
@io.closed_write?.should be_true
end
it "raises an Errno::EACCES error when passed a frozen string with a write-mode" do
(str = "example").freeze
lambda { @io.send(:initialize, str, "r+") }.should raise_error(Errno::EACCES)
lambda { @io.send(:initialize, str, "w") }.should raise_error(Errno::EACCES)
lambda { @io.send(:initialize, str, "a") }.should raise_error(Errno::EACCES)
end
end
describe "StringIO#initialize when passed [Object]" do
before :each do
@io = StringIO.allocate
end
it "uses the passed Object as the StringIO backend" do
@io.send(:initialize, str = "example")
@io.string.should equal(str)
end
it "sets the mode to read-write" do
@io.send(:initialize, "example")
@io.closed_read?.should be_false
@io.closed_write?.should be_false
end
it "tries to convert the passed Object to a String using #to_str" do
obj = mock('to_str')
obj.should_receive(:to_str).and_return("example")
@io.send(:initialize, obj)
@io.string.should == "example"
end
it "automatically sets the mode to read-only when passed a frozen string" do
(str = "example").freeze
@io.send(:initialize, str)
@io.closed_read?.should be_false
@io.closed_write?.should be_true
end
end
describe "StringIO#initialize when passed no arguments" do
before :each do
@io = StringIO.allocate
end
it "is private" do
StringIO.should have_private_instance_method(:initialize)
end
it "sets the mode to read-write" do
@io.send(:initialize, "example")
@io.closed_read?.should be_false
@io.closed_write?.should be_false
end
it "uses an empty String as the StringIO backend" do
@io.send(:initialize)
@io.string.should == ""
end
end
| 29.182796 | 105 | 0.687915 |
bb9b0472e256dd0aa5046e01ccc926ca65c1f537 | 90 | class Article < ActiveRecord::Base
acts_as_archive :indexes => [ :id, :deleted_at ]
end
| 22.5 | 50 | 0.722222 |
5d116a1cf279628a0e1d1d1e1164df20a89d675b | 1,782 | # frozen_string_literal: true
# typed: strict
require 'sorbet-runtime'
require_relative 'expression'
module MonkeyLang
# The main interface for visitors of the AST
module Visitor
extend T::Sig
extend T::Helpers
extend T::Generic
interface!
sig { abstract.params(expr: BinaryExpression).void }
def visit_binary_expression(expr); end
sig { abstract.params(expr: UnaryExpression).void }
def visit_unary_expression(expr); end
sig { abstract.params(expr: GroupingExpression).void }
def visit_group_expression(expr); end
sig { abstract.params(expr: LiteralExpression).void }
def visit_literal_expression(expr); end
sig { abstract.params(expr: LetExpression).void }
def visit_let_expression(expr); end
sig { abstract.params(expr: VariableExpression).void }
def visit_variable_expression(expr); end
sig { abstract.params(expr: AssignmentExpression).void }
def visit_assignment_expression(expr); end
sig { abstract.params(expr: BlockExpression).void }
def visit_block_expression(expr); end
sig { abstract.params(expr: IfExpression).void }
def visit_if_expression(expr); end
sig { abstract.params(expr: LogicalExpression).void }
def visit_logical_expression(expr); end
sig { abstract.params(expr: WhileExpression).void }
def visit_while_expression(expr); end
sig { abstract.params(expr: CallExpression).void }
def visit_call_expression(expr); end
sig { abstract.params(expr: FunctionExpression).void }
def visit_function_expression(expr); end
sig { abstract.params(expr: ReturnExpression).void }
def visit_return_expression(expr); end
sig { abstract.params(expr: PrintExpression).void }
def visit_print_expression(expr); end
end
end
| 29.213115 | 60 | 0.731762 |
b956360527d34bf58048638ee4a859285bc975a7 | 7,539 | # TL;DR: YOU SHOULD DELETE THIS FILE
#
# This file was generated by Cucumber-Rails and is only here to get you a head start
# These step definitions are thin wrappers around the Capybara/Webrat API that lets you
# visit pages, interact with widgets and make assertions about page content.
#
# If you use these step definitions as basis for your features you will quickly end up
# with features that are:
#
# * Hard to maintain
# * Verbose to read
#
# A much better approach is to write your own higher level step definitions, following
# the advice in the following blog posts:
#
# * http://benmabey.com/2008/05/19/imperative-vs-declarative-scenarios-in-user-stories.html
# * http://dannorth.net/2011/01/31/whose-domain-is-it-anyway/
# * http://elabs.se/blog/15-you-re-cuking-it-wrong
#
require 'uri'
require 'cgi'
require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths"))
require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "selectors"))
module WithinHelpers
def with_scope(locator)
locator ? within(*selector_for(locator)) { yield } : yield
end
end
World(WithinHelpers)
# Single-line step scoper
When /^(.*) within (.*[^:])$/ do |step, parent|
with_scope(parent) { When step }
end
# Multi-line step scoper
When /^(.*) within (.*[^:]):$/ do |step, parent, table_or_string|
with_scope(parent) { When "#{step}:", table_or_string }
end
Given /^(?:|I )am on (.+)$/ do |page_name|
visit path_to(page_name)
end
When /^(?:|I )go to (.+)$/ do |page_name|
visit path_to(page_name)
end
When /^(?:|I )press "([^"]*)"$/ do |button|
click_button(button)
end
When /^(?:|I )follow "([^"]*)"$/ do |link|
click_link(link)
end
When /^(?:|I )fill in "([^"]*)" with "([^"]*)"$/ do |field, value|
fill_in(field, :with => value)
end
When /^(?:|I )fill in "([^"]*)" for "([^"]*)"$/ do |value, field|
fill_in(field, :with => value)
end
# Use this to fill in an entire form with data from a table. Example:
#
# When I fill in the following:
# | Account Number | 5002 |
# | Expiry date | 2009-11-01 |
# | Note | Nice guy |
# | Wants Email? | |
#
# TODO: Add support for checkbox, select or option
# based on naming conventions.
#
When /^(?:|I )fill in the following:$/ do |fields|
fields.rows_hash.each do |name, value|
When %{I fill in "#{name}" with "#{value}"}
end
end
When /^(?:|I )select "([^"]*)" from "([^"]*)"$/ do |value, field|
select(value, :from => field)
end
When /^(?:|I )check "([^"]*)"$/ do |field|
check(field)
end
When /^(?:|I )uncheck "([^"]*)"$/ do |field|
uncheck(field)
end
When /^(?:|I )choose "([^"]*)"$/ do |field|
choose(field)
end
When /^(?:|I )attach the file "([^"]*)" to "([^"]*)"$/ do |path, field|
attach_file(field, File.expand_path(path))
end
Then /^(?:|I )should see "([^"]*)"$/ do |text|
if page.respond_to? :should
page.should have_content(text)
else
assert page.has_content?(text)
end
end
Then /^(?:|I )should see \/([^\/]*)\/$/ do |regexp|
regexp = Regexp.new(regexp)
if page.respond_to? :should
page.should have_xpath('//*', :text => regexp)
else
assert page.has_xpath?('//*', :text => regexp)
end
end
Then /^(?:|I )should not see "([^"]*)"$/ do |text|
if page.respond_to? :should
page.should have_no_content(text)
else
assert page.has_no_content?(text)
end
end
Then /^(?:|I )should not see \/([^\/]*)\/$/ do |regexp|
regexp = Regexp.new(regexp)
if page.respond_to? :should
page.should have_no_xpath('//*', :text => regexp)
else
assert page.has_no_xpath?('//*', :text => regexp)
end
end
Then /^the "([^"]*)" field(?: within (.*))? should contain "([^"]*)"$/ do |field, parent, value|
with_scope(parent) do
field = find_field(field)
field_value = (field.tag_name == 'textarea') ? field.text : field.value
if field_value.respond_to? :should
field_value.should =~ /#{value}/
else
assert_match(/#{value}/, field_value)
end
end
end
Then /^the "([^"]*)" field(?: within (.*))? should not contain "([^"]*)"$/ do |field, parent, value|
with_scope(parent) do
field = find_field(field)
field_value = (field.tag_name == 'textarea') ? field.text : field.value
if field_value.respond_to? :should_not
field_value.should_not =~ /#{value}/
else
assert_no_match(/#{value}/, field_value)
end
end
end
Then /^the "([^"]*)" field should have the error "([^"]*)"$/ do |field, error_message|
element = find_field(field)
classes = element.find(:xpath, '..')[:class].split(' ')
form_for_input = element.find(:xpath, 'ancestor::form[1]')
using_formtastic = form_for_input[:class].include?('formtastic')
error_class = using_formtastic ? 'error' : 'field_with_errors'
if classes.respond_to? :should
classes.should include(error_class)
else
assert classes.include?(error_class)
end
if page.respond_to?(:should)
if using_formtastic
error_paragraph = element.find(:xpath, '../*[@class="inline-errors"][1]')
error_paragraph.should have_content(error_message)
else
page.should have_content("#{field.titlecase} #{error_message}")
end
else
if using_formtastic
error_paragraph = element.find(:xpath, '../*[@class="inline-errors"][1]')
assert error_paragraph.has_content?(error_message)
else
assert page.has_content?("#{field.titlecase} #{error_message}")
end
end
end
Then /^the "([^"]*)" field should have no error$/ do |field|
element = find_field(field)
classes = element.find(:xpath, '..')[:class].split(' ')
if classes.respond_to? :should
classes.should_not include('field_with_errors')
classes.should_not include('error')
else
assert !classes.include?('field_with_errors')
assert !classes.include?('error')
end
end
Then /^the "([^"]*)" checkbox(?: within (.*))? should be checked$/ do |label, parent|
with_scope(parent) do
field_checked = find_field(label)['checked']
if field_checked.respond_to? :should
field_checked.should be_true
else
assert field_checked
end
end
end
Then /^the "([^"]*)" checkbox(?: within (.*))? should not be checked$/ do |label, parent|
with_scope(parent) do
field_checked = find_field(label)['checked']
if field_checked.respond_to? :should
field_checked.should be_false
else
assert !field_checked
end
end
end
Then /^(?:|I )should be on (.+)$/ do |page_name|
current_path = URI.parse(current_url).path
if current_path.respond_to? :should
current_path.should == path_to(page_name)
else
assert_equal path_to(page_name), current_path
end
end
Then /^(?:|I )should have the following query string:$/ do |expected_pairs|
query = URI.parse(current_url).query
actual_params = query ? CGI.parse(query) : {}
expected_params = {}
expected_pairs.rows_hash.each_pair{|k,v| expected_params[k] = v.split(',')}
if actual_params.respond_to? :should
actual_params.should == expected_params
else
assert_equal expected_params, actual_params
end
end
Then /^show me the page$/ do
save_and_open_page
end
# For popup confirmations - need JavaScript support!
# See http://stackoverflow.com/questions/2458632/how-to-test-a-confirm-dialog-with-cucumber
# I can't seem to get the Firefox gem to work on the MathLAN.
When /^(?:|I )confirm (?:|the )popup$/ do
#page.driver.browser.switch_to.alert.accept
pending
end
When /^(?:|I )dismiss (?:|the )popup$/ do
#page.driver.browser.switch_to.alert.dismiss
pending
end
| 28.026022 | 100 | 0.651545 |
91054aa02bafb0a25534f4a6100b6edb8819d72e | 1,135 | ########################################################################
# AwsIamUser +aws_iam_user+ terrform resource,
#
# {https://www.terraform.io/docs/providers/aws/r/iam_user.html Terraform Docs}
########################################################################
class GeoEngineer::Resources::AwsIamUser < GeoEngineer::Resource
validate -> { validate_required_attributes([:name]) }
after :initialize, -> {
_terraform_id -> { NullObject.maybe(remote_resource)._terraform_id }
}
after :initialize, -> {
_geo_id -> { name.to_s }
}
def to_terraform_state
tfstate = super
tfstate[:primary][:attributes] = {
'name' => name,
'force_destroy' => (force_destroy || 'false')
}
tfstate
end
def support_tags?
false
end
def self._all_remote_users(provider)
AwsClients.iam(provider).list_users.each.map(&:users).flatten.map(&:to_h)
end
def self._fetch_remote_resources(provider)
_all_remote_users(provider).map do |user|
{
_terraform_id: user[:user_name],
_geo_id: user[:user_name],
name: user[:user_name]
}
end
end
end
| 26.395349 | 78 | 0.580617 |
0178fc0a07f8675240d606dee6b980ef16dd0166 | 551 | # frozen_string_literal: true
require 'spec_helper'
describe Types::PermissionTypes::Vulnerability do
it do
expected_permissions = %i[read_vulnerability_feedback create_vulnerability_feedback destroy_vulnerability_feedback
update_vulnerability_feedback create_vulnerability create_vulnerability_export
admin_vulnerability admin_vulnerability_issue_link]
expected_permissions.each do |permission|
expect(described_class).to have_graphql_field(permission)
end
end
end
| 34.4375 | 118 | 0.758621 |
21440359d99576396b9c0ef8ea8fe53e8a6f7714 | 2,855 | =begin
vim: set sw=2:
Copyright (c) 2009, Gennady Bystritsky <[email protected]>
Distributed under the MIT Licence.
This is free software. See 'LICENSE' for details.
You must read and accept the license prior to use.
Author: Gennady Bystritsky ([email protected])
=end
module SK
class Numeral
ROMAN_SHORTENED = [
[1000, "M"], [900, "CM"], [500, "D"], [400, "CD"], [100, "C"], [90, "XC"], [50, "L"], [40, "XL"], [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]
]
ROMAN_CLASSIC = [
[1000, "M"], [500, "D"], [100, "C"], [50, "L"], [10, "X"], [5, "V"], [1, "I"]
]
class << self
def to_roman(number, shortened = true)
return 'N' if number.zero?
raise RangeError, "Must be within 0-3999" if number < 0 || number > 3999
(shortened == true ? ROMAN_SHORTENED : ROMAN_CLASSIC).inject(["", number]) { |(result, number), (order, roman)|
[ result + roman * (number / order), number % order ]
}.first
end
end
end
end
if $0 == __FILE__
require 'test/unit'
require 'mocha'
module SK
class NumeralTest < Test::Unit::TestCase
def test_to_roman_range
assert_raises(RangeError) {
SK::Numeral.to_roman(-1)
}
assert_equal "N", SK::Numeral.to_roman(0)
assert_equal "N", SK::Numeral.to_roman(0, false)
assert_equal "MMMCMXCIX", SK::Numeral.to_roman(3999)
assert_equal "MMMDCCCCLXXXXVIIII", SK::Numeral.to_roman(3999, false)
assert_raises(RangeError) {
SK::Numeral.to_roman(4000)
}
end
def test_to_roman_classic
assert_equal "I", SK::Numeral.to_roman(1, false)
assert_equal "IIII", SK::Numeral.to_roman(4, false)
assert_equal "V", SK::Numeral.to_roman(5, false)
assert_equal "VI", SK::Numeral.to_roman(6, false)
assert_equal "VIIII", SK::Numeral.to_roman(9, false)
assert_equal "X", SK::Numeral.to_roman(10, false)
assert_equal "XVIIII", SK::Numeral.to_roman(19, false)
assert_equal "XXI", SK::Numeral.to_roman(21, false)
assert_equal "CLXXX", SK::Numeral.to_roman(180, false)
assert_equal "DCCCCXXXXVIIII", SK::Numeral.to_roman(949, false)
end
def test_to_roman_short
assert_equal "I", SK::Numeral.to_roman(1)
assert_equal "IV", SK::Numeral.to_roman(4)
assert_equal "V", SK::Numeral.to_roman(5)
assert_equal "VI", SK::Numeral.to_roman(6)
assert_equal "IX", SK::Numeral.to_roman(9)
assert_equal "X", SK::Numeral.to_roman(10)
assert_equal "XIX", SK::Numeral.to_roman(19)
assert_equal "XXI", SK::Numeral.to_roman(21)
assert_equal "CLXXX", SK::Numeral.to_roman(180)
assert_equal "CMXLIX", SK::Numeral.to_roman(949)
end
def setup
end
end
end
end
| 32.816092 | 155 | 0.603503 |
e91c053980ea80388a06e3727b768d1c1e5f250a | 6,230 | # MdTranslator - minitest of
# reader / mdJson / module_metadata
# History:
# Stan Smith 2018-06-20 refactored to use mdJson construction helpers
# Stan Smith 2017-01-16 added parent class to run successfully within rake
# Stan Smith 2016-10-21 original script
require_relative 'mdjson_test_parent'
require 'adiwg/mdtranslator/readers/mdJson/modules/module_metadata'
class TestReaderMdJsonMetadata < TestReaderMdJsonParent
# set variables for test
@@NameSpace = ADIWG::Mdtranslator::Readers::MdJson::Metadata
# instance classes needed in script
TDClass = MdJsonHashWriter.new
# build mdJson test file in hash
mdHash = TDClass.build_metadata_full
@@mdHash = mdHash
def test_metadata_schema
errors = TestReaderMdJsonParent.testSchema(@@mdHash, 'metadata.json')
assert_empty errors
end
def test_complete_metadata_object
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_empty metadata[:metadataInfo]
refute_empty metadata[:resourceInfo]
assert_equal 2, metadata[:lineageInfo].length
assert_equal 2, metadata[:distributorInfo].length
assert_equal 2, metadata[:associatedResources].length
assert_equal 2, metadata[:additionalDocuments].length
assert_equal 2, metadata[:funding].length
assert hResponse[:readerExecutionPass]
assert_empty hResponse[:readerExecutionMessages]
end
def test_metadata_empty_metadataInfo
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn['metadataInfo'] = {}
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_nil metadata
refute hResponse[:readerExecutionPass]
assert_equal 1, hResponse[:readerExecutionMessages].length
assert_includes hResponse[:readerExecutionMessages],
'ERROR: mdJson reader: metadata-info object is missing'
end
def test_metadata_missing_metadataInfo
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn.delete('metadataInfo')
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_nil metadata
refute hResponse[:readerExecutionPass]
assert_equal 1, hResponse[:readerExecutionMessages].length
assert_includes hResponse[:readerExecutionMessages],
'ERROR: mdJson reader: metadata-info object is missing'
end
def test_metadata_empty_resourceInfo
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn['resourceInfo'] = {}
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_nil metadata
refute hResponse[:readerExecutionPass]
assert_equal 1, hResponse[:readerExecutionMessages].length
assert_includes hResponse[:readerExecutionMessages],
'ERROR: mdJson reader: resource-info object is missing'
end
def test_metadata_missing_resourceInfo
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn.delete('resourceInfo')
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_nil metadata
refute hResponse[:readerExecutionPass]
assert_equal 1, hResponse[:readerExecutionMessages].length
assert_includes hResponse[:readerExecutionMessages],
'ERROR: mdJson reader: resource-info object is missing'
end
def test_metadata_empty_elements
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn['resourceLineage'] = []
hIn['resourceDistribution'] = []
hIn['associatedResource'] = []
hIn['additionalDocumentation'] = []
hIn['funding'] = []
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_empty metadata[:metadataInfo]
refute_empty metadata[:resourceInfo]
assert_empty metadata[:lineageInfo]
assert_empty metadata[:distributorInfo]
assert_empty metadata[:associatedResources]
assert_empty metadata[:additionalDocuments]
assert_empty metadata[:funding]
assert hResponse[:readerExecutionPass]
assert_empty hResponse[:readerExecutionMessages]
end
def test_metadata_missing_elements
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn.delete('resourceLineage')
hIn.delete('resourceDistribution')
hIn.delete('associatedResource')
hIn.delete('additionalDocumentation')
hIn.delete('funding')
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_empty metadata[:metadataInfo]
refute_empty metadata[:resourceInfo]
assert_empty metadata[:lineageInfo]
assert_empty metadata[:distributorInfo]
assert_empty metadata[:associatedResources]
assert_empty metadata[:additionalDocuments]
assert_empty metadata[:funding]
assert hResponse[:readerExecutionPass]
assert_empty hResponse[:readerExecutionMessages]
end
def test_empty_metadata_object
TestReaderMdJsonParent.loadEssential
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack({}, hResponse)
assert_nil metadata
assert hResponse[:readerExecutionPass]
assert_equal 1, hResponse[:readerExecutionMessages].length
assert_includes hResponse[:readerExecutionMessages],
'WARNING: mdJson reader: metadata object is empty'
end
end
| 33.675676 | 77 | 0.712039 |
628785aec0f9c56e15d7c0b85c8f37b9c12fcd7f | 6,238 | # frozen_string_literal: true
require 'case_transform'
require 'simple_schema_serializers/declaration_error'
require 'simple_schema_serializers/serializable'
require 'simple_schema_serializers/hash_schema_generator'
require 'simple_schema_serializers/hash_dsl'
require 'simple_schema_serializers/array_dsl'
require 'simple_schema_serializers/combo_dsl'
module SimpleSchemaSerializers
##
# A base class for defining serializers of type `object` (i.e. hashes).
#
# In addition to the +Serializer+ functionality, it supplies the
# attribute DSL for declaring the properties of the serialized object,
# and provides implementations for +serialize+ and +schema+.
#
# You are likely better off inheriting from +Serializer+, but if you
# wish to extend an existing class with serialization functionality
# you can include this mixin instead. Doing so will not register any
# serializer aliases by default, so you will need to explicitly register
# any you wish to use.
class HashSerializer
# The DSL methods for declaring a HashSerializable
module ClassMethods
include Serializable
include HashDSL
def registered_serializers
@registered_serializers ||= {}
end
def attributes
@attributes ||= []
end
def attribute_defaults(args = nil)
@attribute_defaults ||= {}
@attribute_defaults[:key_transform] = key_transformer if key_transformer
@attribute_defaults.merge!(args) if args
@attribute_defaults
end
def schema_options(args = nil)
@schema_options ||= {}
@schema_options.merge!(args) if args
@schema_options
end
def inherit_configuration_from(other_hash_serializable, include_attributes: false)
# class inheritance should get everything. Anonymous instances, e.g. has_serializable
# and array_serializable are trickier.
# TODO: it defintely shouldn't inherit attributes. it probably shouldn't
# inherit attribute_defaults? should it inherit schema_options?
registered_serializers.merge!(other_hash_serializable.registered_serializers)
if include_attributes
attributes.concat(other_hash_serializable.attributes)
attribute_defaults.merge!(other_hash_serializable.attribute_defaults)
end
@key_transformer ||= other_hash_serializable.key_transformer
schema_options.merge!(other_hash_serializable.schema_options)
end
def ref_name
@name
end
def transform_keys(method = nil, &block)
@key_transformer = block || method
end
def key_transformer
@key_transformer
end
def key_inflection(inflection)
# :camel_lower, :dash, :underscore, :camel, :unaltered
transform_keys(CaseTransform.method(inflection))
end
def one_of(&block)
combo_serializer('one_of', &block)
end
def any_of(&block)
combo_serializer('any_of', &block)
end
def all_of(&block)
combo_serializer('all_of', &block)
end
def combo_serializer(type, &block)
raise DeclarationError, 'Can only define one of `one_of`/`all_of`/`any_of`' if @combo
@combo = ComboDSL.new(self, type).invoke(&block)
end
##
# Declare an alias for a serializer.
# For example, if you define a custom +UriSerializer+ class, you can register an alias to allow you
# to use +:uri+ in your attribute definitions instead of the instance.
#
# When you use the +Serializer+ base class, common primitives such as +:string+ are already registered.
#
# Options:
# [with_optional] Also register an optional form of the serializer with a trailing question mark,
# e.g. +:uri? => UriSerializer.optional+
# [override] By default, registering twice with the same name is forbidden. You can declare this
# intention explicitly by setting this to true.
# [aliases] An array of other names to also use with the same serializer.
# rubocop:disable Metrics/ParameterLists
def register_serializer(name, serializer, with_optional: true, override: false, aliases: [], default_options: {})
if !override && registered_serializers[name.to_s]
raise DeclarationError, "Serializer alias #{name} has already been registered. If you wish to "\
'override the alias, pass option `override: true`'
end
registered_serializers[name.to_s] = [serializer, default_options]
register_serializer("#{name}?", serializer.optional, with_optional: false, override: override) if with_optional
aliases.each do |alias_name|
register_serializer(alias_name, serializer, with_optional: with_optional, override: override)
end
name
end
# rubocop:enable Metrics/ParameterLists
def serialize(resource, options = {})
return @combo.serialize(resource, options) if @combo
serializer_instance = new(resource, options)
attributes.each_with_object({}) do |attribute, hash|
next if attribute.skip?(serializer_instance)
hash[attribute.key(serializer_instance)] = attribute.serialize(serializer_instance)
end
end
def schema(additional_options = {})
additional_options = additional_options.dup
return @combo.schema(additional_options) if @combo
HashSchemaGenerator.new(self, additional_options).schema
end
def lookup_serializer(alias_name)
return alias_name if alias_name.respond_to?(:serialize)
serializer, = registered_serializers[alias_name.to_s]
raise DeclarationError, "Serializer for alias not found: #{alias_name.inspect}" unless serializer
serializer
end
end
extend ClassMethods
attr_reader :object, :options
def initialize(object, options)
@object = object
@options = options
end
def self.inherited(child_class)
child_class.extend(ClassMethods)
child_class.inherit_configuration_from(self, include_attributes: true)
super
end
end
end
| 36.479532 | 119 | 0.6874 |
e29d022f9f61f23ac1611f810e2cb4efdea0828c | 1,438 | require 'rails_vue_js_spec_helper'
require_relative "../support/test_controller"
include VueJsSpecUtils
describe "Action Component", type: :feature, js: true do
before :each do
class ActionTestController < TestController
def test
render json: { }, status: 200
end
end
allow_any_instance_of(ActionTestController).to receive(:expect_params)
end
describe "emit attribute" do
it "if set, emits event directly when action is submitted (not waiting for success or failure)" do
Rails.application.routes.append do
post '/action_test', to: 'action_test#test', as: 'action_emit'
end
Rails.application.reload_routes!
class ExamplePage < Matestack::Ui::Page
def response
action action_config do
button text: "Click me!"
end
toggle show_on: "action_submitted" do
plain "action submitted!"
end
end
def action_config
return {
method: :post,
path: action_emit_path,
data: {
foo: "bar"
},
emit: "action_submitted"
}
end
end
visit "/example"
expect_any_instance_of(ActionTestController).to receive(:expect_params)
.with(hash_including(:foo => "bar"))
click_button "Click me!"
expect(page).to have_content("action submitted!")
end
end
end
| 25.22807 | 102 | 0.614047 |
1dbfa5a1df4258dd2d9ab1be39d2100bdda74c39 | 1,176 | require 'helper'
class TestVars < Test::Unit::TestCase
context "a lua jit" do
setup do
@lua = Language::Lua.new()
end
should "create a string variable" do
@lua.var("str", "This is a string")
assert_equal "This is a string", @lua.var("str")
end
should "create a number variable" do
@lua.var("num", 123)
assert_equal 123.0, @lua.var("num")
end
should "create a boolean variable" do
@lua.var("yes", true)
@lua.var("no", false)
assert_equal true, @lua.var("yes")
assert_equal false, @lua.var("no")
end
should "create a nil variable" do
@lua.var("null", NIL)
assert_equal NIL, @lua.var("null")
end
should "create a table" do
@lua.var("table", ["string", 123, true, NIL])
table = @lua.var("table")
assert_equal 4, table.size()
assert_equal "string", table[1.0]
assert_equal 123.0, table[2.0]
assert_equal true, table[3.0]
assert_equal NIL, table[4.0]
end
should "create a hash" do
@lua.var("hash", {"string" => 123})
hash = @lua.var("hash")
assert_equal 123.0, hash["string"]
end
end
end
| 24 | 54 | 0.583333 |
0808cdd92172c370cd7f5670b6cfce873f9c0995 | 326 | require 'rubygems'
require 'rspec'
require 'pathname'
require 'tempfile'
require 'engines'
module RSpec
module Core
module SharedExampleGroup
def summary(url, &block)
describe "(#{url})" do
subject { Engines.create(url) }
instance_eval(&block)
end
end
end
end
end
| 16.3 | 41 | 0.622699 |
338501e8b12656468ca5dc2597ccf938933a8485 | 1,459 | require 'minitest/autorun'
require_relative '../lib/tenji_maker'
class TenjiMakerTest < Minitest::Test
# ここから下�?��?スト�?�変更不可 =====================
def setup
@tenji_maker = TenjiMaker.new
end
def test_a_hi_ru
tenji = @tenji_maker.to_tenji('A HI RU')
assert_equal <<~TENJI.chomp, tenji
o- o- oo
-- o- -o
-- oo --
TENJI
end
def test_ki_ri_n
tenji = @tenji_maker.to_tenji('KI RI N')
assert_equal <<~TENJI.chomp, tenji
o- o- --
o- oo -o
-o -- oo
TENJI
end
def test_si_ma_u_ma
tenji = @tenji_maker.to_tenji('SI MA U MA')
assert_equal <<~TENJI.chomp, tenji
o- o- oo o-
oo -o -- -o
-o oo -- oo
TENJI
end
def test_ni_wa_to_ri
tenji = @tenji_maker.to_tenji('NI WA TO RI')
assert_equal <<~TENJI.chomp, tenji
o- -- -o o-
o- -- oo oo
o- o- o- --
TENJI
end
def test_hi_yo_ko
tenji = @tenji_maker.to_tenji('HI YO KO')
assert_equal <<~TENJI.chomp, tenji
o- -o -o
o- -o o-
oo o- -o
TENJI
end
def test_ki_tu_ne
tenji = @tenji_maker.to_tenji('KI TU NE')
assert_equal <<~TENJI.chomp, tenji
o- oo oo
o- -o o-
-o o- o-
TENJI
end
# ここから上�?��?スト�?�変更不可 =====================
def test_ya_yu
tenji = @tenji_maker.to_tenji('YA YU')
assert_equal <<~TENJI.chomp, tenji
-o -o
-- --
o- oo
TENJI
end
# 独自の�?ストパターンを追�?するのは自由で�?
end
| 19.453333 | 48 | 0.544894 |
e9c09e00790dd65d25d5d142e808d926356e1295 | 906 | # Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional assets.
Rails.application.config.assets.precompile.concat(
%w[
admin.css
api_v2.css
market.css
admin.js
api_v2.js
funds.js
html5.js
market.js
]
)
# Precompile all available locales
Rails.application.config.assets.precompile.concat(
Dir.glob(Rails.root.join('app/assets/javascripts/locales/*.js.erb'))
.map { |f| File.join('locales', File.basename(f, '.erb')) }
)
Dir.chdir 'vendor/assets/yarn_components' do
Dir['yarn_components/**/*.{jpg,jpeg,png,gif,svg}'].each do |path|
Rails.application.config.assets.precompile << path
end
end
| 26.647059 | 76 | 0.718543 |
2614a40caabcc04d0db5be5cf9f8f7b5adf9fb18 | 1,637 | # frozen_string_literal: true
# Cloud Foundry Java Buildpack
# Copyright 2013-2019 the original author or authors.
#
# 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 'java_buildpack/util/play/pre22'
module JavaBuildpack
module Util
module Play
# Encapsulate inspection and modification of Play dist applications up to and including Play 2.1.x.
class Pre22Dist < Pre22
protected
# (see JavaBuildpack::Util::Play::Base#augment_classpath)
def augment_classpath
if version.start_with? '2.0'
@droplet.additional_libraries.link_to lib_dir
else
additional_classpath = @droplet.additional_libraries.sort.map do |additional_library|
"$scriptdir/#{additional_library.relative_path_from(root)}"
end
update_file start_script, /^classpath=\"(.*)\"$/, "classpath=\"#{additional_classpath.join(':')}:\\1\""
end
end
# (see JavaBuildpack::Util::Play::Base#lib_dir)
def lib_dir
root + 'lib'
end
alias root find_single_directory
end
end
end
end
| 30.314815 | 115 | 0.682346 |
b912a0c9a5cd7d7fdea64ca5223f2db33e8daeb2 | 974 | class ImageUpload < ApplicationRecord
belongs_to :user, optional: true
belongs_to :content, polymorphic: true
# This is the old way we uploaded files -- now we're transitioning to ActiveStorage's has_one_attached
has_attached_file :src,
path: 'content/uploads/:style/:filename',
styles: {
thumb: '100x100>',
small: '190x190#',
square: '280x280#',
medium: '300x300>',
large: '600x600>',
hero: '800x800>'
},
filename_cleaner: -> (filename) {
[
SecureRandom.uuid,
File.extname(filename).downcase
].join
}
# has_one_attached :upload
validates_attachment_content_type :src, content_type: /\Aimage\/.*\Z/
before_destroy :delete_s3_image
# Point content IDs to generalized content_id for cocoon
alias_attribute 'character_id', :content_id
#alias_attribute ...
def delete_s3_image
# todo: put this in a task for faster delete response times
src.destroy
end
end
| 26.324324 | 104 | 0.676591 |
ab536965c467b95486996f9f08e7cc01ad261a98 | 1,193 | require 'integration_test_helper'
include Warden::Test::Helpers
class SignInFlowTest < ActionDispatch::IntegrationTest
setup do
Warden.test_mode!
set_default_settings
end
teardown do
Capybara.reset_sessions!
Warden.test_reset!
end
def sign_out
visit '/'
within("div#above-header") do
click_on("Logout")
end
end
test "a browser should be able to sign in and be shown the home page" do
sign_in
assert_equal '/en', current_path
sign_out
end
test "an admin should be able to sign in and be shown the topics page" do
sign_in("[email protected]")
assert_equal '/admin/topics', current_path
sign_out
end
test "an agent should be able to sign in and be shown the topics page" do
sign_in("[email protected]")
assert_equal '/admin/topics', current_path
sign_out
end
test "an editor should be able to sign in and be shown the categories page" do
sign_in("[email protected]")
assert_equal '/en', current_path
sign_out
end
test "a browser visiting an admin page should be redirected to login in their locale" do
visit '/admin'
assert_equal '/en/users/sign_in', current_path
end
end
| 22.509434 | 90 | 0.704107 |
b9d52249bbb6f6cf17538cb74872cf34f33b69fd | 1,991 | require 'time'
require_relative 'accessible'
require_relative 'linked_list'
require_relative 'stats'
module Caches
class TTL
include Accessible
prepend Stats
attr_accessor :ttl, :refresh
attr_accessor :data, :nodes, :max_keys
private :data, :nodes, :max_keys
def initialize(options = {})
self.ttl = options.fetch(:ttl) { 3600 }
self.refresh = !!(options.fetch(:refresh, false))
self.max_keys = options[:max_keys]
initialize_data
end
def [](key)
unless data.has_key?(key)
record_cache_miss
return nil
end
if current?(key)
record_cache_hit
data.fetch(key).fetch(:value).tap {
if refresh
data[key][:time] = current_time
nodes.move_to_head(data[key][:node])
end
}
else
record_cache_miss
delete(key)
nil
end
end
def []=(key, val)
if data.has_key?(key)
node = data[key][:node]
nodes.move_to_head(node)
else
if full?
evicted_node = nodes.pop
data.delete(evicted_node.value)
end
node = nodes.prepend(key)
end
data[key] = {time: current_time, value: val, node: node}
end
def delete(key)
node = data[key][:node]
nodes.delete(node)
hash = data.delete(key)
hash.fetch(:value)
end
def size
nodes.length
end
def keys
data.keys
end
def values
data.values.map { |h| h.fetch(:value) }
end
def clear
initialize_data
end
private
def initialize_data
self.data = {}
self.nodes = LinkedList.new
self
end
def current?(key)
expiration_time(key) >= current_time
end
def expiration_time(key)
data.fetch(key).fetch(:time) + ttl
end
def full?
max_keys && size >= max_keys
end
def current_time
Time.now
end
end
end
| 18.961905 | 62 | 0.566047 |
287b9504fe37eff5fc4d2b624cdbfe23b4b86b68 | 611 | # frozen_string_literal: true
module Algebra
module CoreExt
# Namespace of modules, which extend core numeric classes
module Numeric
# Module to prepend to classes of numerics. Provides ability to multiply
# on monomials.
module Multiplication
# Returns result of multiplication on monomial if one is provided as an
# argument, or result of regular multiplications otherwise
# @param [Object] other
# object to multiply to
def *(other)
other.is_a?(Algebra::Monomial) ? other * self : super
end
end
end
end
end
| 29.095238 | 79 | 0.659574 |
87130ffeaecb649c01262d22108605423f65e8c6 | 90 | Then("I should see {string}") do |content|
expect(page).to have_content content
end
| 22.5 | 42 | 0.7 |
6a623ea90b2613f8de18af7723291de4f2f48e44 | 691 | # Copyright 2012, Dell
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class Scaffolds::CmdbAttributesController < ApplicationController
active_scaffold :cmdb_attribute do |conf|
end
end
| 34.55 | 74 | 0.771346 |
0395cd893334baa142ae84a8fc0b8571060dbdf0 | 658 | class User < ApplicationRecord
has_many :entries
def self.max_user
max = User.maximum(:db)
max.nil? ? 0 : max
end
def self.find_or_create_user_by_jwt_token(token)
begin
decoded_token = JWT.decode(token, nil, false)
user_data = decoded_token.find do |el|
el['iss'] == "accounts.google.com"
end
email = user_data["email"]
u = User.find_by(:name => email)
if u.nil?
u = User.create(
:name => user_data["email"],
:token => SecureRandom.hex,
:db => max_user + 1,
)
u.save!
end
u
rescue => e
return nil
end
end
end
| 20.5625 | 51 | 0.553191 |
034e90d67cf543b8a756ffad7e05a44c14397fdb | 865 | cask "drawio" do
version "13.9.8"
sha256 "854d8c3a964d0f6317a433201317562dfae258038f0b58ae52d0965f5979e0be"
# github.com/jgraph/drawio-desktop/ was verified as official when first introduced to the cask
url "https://github.com/jgraph/drawio-desktop/releases/download/v#{version}/draw.io-#{version}.dmg"
appcast "https://github.com/jgraph/drawio-desktop/releases.atom"
name "draw.io Desktop"
homepage "https://www.draw.io/"
app "draw.io.app"
zap trash: [
"~/Library/Application Support/draw.io",
"~/Library/Caches/com.jgraph.drawio.desktop",
"~/Library/Logs/draw.io",
"~/Library/Preferences/com.jgraph.drawio.desktop.helper.plist",
"~/Library/Preferences/com.jgraph.drawio.desktop.plist",
"~/Library/Saved Application State/com.jgraph.drawio.desktop.savedState",
"~/Library/WebKit/com.jgraph.drawio.desktop",
]
end
| 37.608696 | 101 | 0.732948 |
b95d5982003e03e78eef6aae44df640f37ec0cb9 | 3,148 | class Isync < Formula
desc "Synchronize a maildir with an IMAP server"
homepage "https://isync.sourceforge.io/"
revision 1
head "https://git.code.sf.net/p/isync/isync.git"
stable do
url "https://downloads.sourceforge.net/project/isync/isync/1.3.1/isync-1.3.1.tar.gz"
sha256 "68cb4643d58152097f01c9b3abead7d7d4c9563183d72f3c2a31d22bc168f0ea"
# Patch to fix detection of OpenSSL 1.1
# https://sourceforge.net/p/isync/bugs/51/
patch :DATA
end
bottle do
cellar :any
sha256 "d4ea3fd276458ae669596cc955beee0d2cb38ab217fc51c5c6c2acb6c73de260" => :catalina
sha256 "7863e1861cc119853fadc35ff6afe7f13bf1e420f22b70e77d0bb32997943329" => :mojave
sha256 "2da1bd2fef7c6eb9af331a0536e02df8dd0bc9b0fc42eb534ec8499a87f8c197" => :high_sierra
sha256 "a19f503aa9490146a19a4197e8e0190cffad685c7fdba0582544c44ee96f1fe5" => :sierra
sha256 "970bc89bc0e2bf3d0c0eda0b9aad32ce370a67abeb826c54c601c9421cc5e05a" => :x86_64_linux
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "berkeley-db"
depends_on "[email protected]"
uses_from_macos "zlib"
def install
# Regenerated for HEAD, and because of our patch
if build.head?
system "./autogen.sh"
else
system "autoreconf", "-fiv"
end
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
--disable-silent-rules
]
system "./configure", *args
system "make", "install"
end
plist_options :manual => "isync"
def plist; <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/usr/bin:/bin:/usr/sbin:/sbin:#{HOMEBREW_PREFIX}/bin</string>
</dict>
<key>KeepAlive</key>
<false/>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/mbsync</string>
<string>-a</string>
</array>
<key>StartInterval</key>
<integer>300</integer>
<key>RunAtLoad</key>
<true />
<key>StandardErrorPath</key>
<string>/dev/null</string>
<key>StandardOutPath</key>
<string>/dev/null</string>
</dict>
</plist>
EOS
end
test do
system bin/"mbsync-get-cert", "duckduckgo.com:443"
end
end
__END__
diff -pur isync-1.3.1/configure.ac isync-1.3.1-fixed/configure.ac
--- isync-1.3.1/configure.ac 2019-05-28 15:44:13.000000000 +0200
+++ isync-1.3.1-fixed/configure.ac 2019-09-07 15:39:55.000000000 +0200
@@ -94,7 +94,7 @@ if test "x$ob_cv_with_ssl" != xno; then
sav_LDFLAGS=$LDFLAGS
LDFLAGS="$LDFLAGS $SSL_LDFLAGS"
AC_CHECK_LIB(dl, dlopen, [LIBDL=-ldl])
- AC_CHECK_LIB(crypto, CRYPTO_lock, [LIBCRYPTO=-lcrypto])
+ AC_CHECK_LIB(crypto, HMAC_Update, [LIBCRYPTO=-lcrypto])
AC_CHECK_LIB(ssl, SSL_connect,
[SSL_LIBS="-lssl $LIBCRYPTO $LIBDL" have_ssl_paths=yes])
LDFLAGS=$sav_LDFLAGS
| 31.48 | 115 | 0.658513 |
082db41712fef7208508ded608837c55439700d8 | 79 | require 'test_helper'
class EducationalsHelperTest < ActionView::TestCase
end
| 15.8 | 51 | 0.835443 |
01f3b533e7a9f1cff9fab6147fa97b53e226d416 | 4,356 | module Rules
class RuleProcessor
attr_accessor :applied_rules
def initialize
@rule_builder = RuleBuilder.new
@applied_rules = []
end
def define_rules
add_rule_a
add_rule_b
add_rule_unlock_unsuccessful
end
def add_rule_a
rule_attributes = {}
rule_field_attributes = []
rule_field_attributes << {rule_field_name: 'ActionRuleField',
data_key: 'action',
matching_value: 'update'}
rule_field_attributes << {rule_field_name: 'ObjectRuleField',
data_key: 'object_type',
matching_value: 'Lock'}
rule_field_attributes << {rule_field_name: 'SuccessRuleField',
data_key: 'success',
matching_value: true}
rule_field_attributes << {rule_field_name: 'TimeRuleField',
data_key: 'created_at',
matching_value: '10:59'..'12:59'}
rule_field_attributes << {rule_field_name: 'UserRuleField',
data_key: 'actor_id',
matching_value: 101768}
rule_attributes[:rule_field_attributes] = rule_field_attributes
rule_attributes[:action] = Actions::BasicAction.new('')
rule_attributes[:subscribers] = %w([email protected] [email protected])
@rule_builder.add_rule(rule_attributes)
end
def add_rule_b
rule_attributes = {}
rule_field_attributes = []
rule_field_attributes << {rule_field_name: 'ActionRuleField',
data_key: 'action',
matching_value: 'update'}
rule_field_attributes << {rule_field_name: 'ObjectRuleField',
data_key: 'object_type',
matching_value: 'Lock'}
rule_field_attributes << {rule_field_name: 'SuccessRuleField',
data_key: 'success',
matching_value: true}
rule_field_attributes << {rule_field_name: 'TimeRuleField',
data_key: 'created_at',
matching_value: '2:59'..'23:59'}
rule_field_attributes << {rule_field_name: 'UserRuleField',
data_key: 'actor_id',
matching_value: 101768}
rule_attributes[:rule_field_attributes] = rule_field_attributes
rule_attributes[:action] = Actions::BasicAction.new('')
rule_attributes[:subscribers] = %w([email protected] [email protected])
@rule_builder.add_rule(rule_attributes)
end
def add_rule_unlock_unsuccessful
rule_attributes = {}
rule_field_attributes = []
rule_field_attributes << {rule_field_name: 'ActionRuleField',
data_key: 'action',
matching_value: 'unlock'}
rule_field_attributes << {rule_field_name: 'ObjectRuleField',
data_key: 'object_type',
matching_value: 'Lock'}
rule_field_attributes << {rule_field_name: 'SuccessRuleField',
data_key: 'success',
matching_value: false}
rule_field_attributes << {rule_field_name: 'UserRuleField',
data_key: 'actor_id',
matching_value: 101768}
rule_attributes[:rule_field_attributes] = rule_field_attributes
message = 'Dear user! Your unlock was unsuccessful! Best regards, Service Team.'
rule_attributes[:action] = Actions::SendEmailAction.new(message)
rule_attributes[:subscribers] = %w([email protected] [email protected])
@rule_builder.add_rule(rule_attributes)
end
def apply_rules(data_to_match)
@applied_rules = []
@rule_builder.rules.each do |rule|
if rule.rule_match? data_to_match
# Applying the matched rule
puts "Rule matched=#{rule}"
rule.run_action
@applied_rules << rule
end
end
end
end
end | 44 | 87 | 0.55326 |
6211eead6f7cc5baca4b4ada6b62e5565c08f74d | 1,515 | # rubocop: disable Metrics/CyclomaticComplexity
class Game
attr_reader :switch_player
attr_reader :who_won
WINNING_COMBINATIONS = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]].freeze
def initialize
reset
end
def valid_movement?(first_player, second_player, new_movement)
begin
is_integer = true if Integer(new_movement)
rescue StandardError
is_integer = false
end
if is_integer
if new_movement.to_i >= 1 && new_movement.to_i <= 9
return first_player.none?(new_movement.to_i) && second_player.none?(new_movement.to_i)
end
end
false
end
def finished?(first_player_movements, second_player_movements)
if player_win?(first_player_movements)
@who_won = 1
return true
elsif player_win?(second_player_movements)
@who_won = 2
return true
elsif first_player_movements.length + second_player_movements.length == 9
@who_won = 0
return true
else
@who_won = -1
end
false
end
def player_win?(player_movements)
return false unless player_movements.length >= 3
WINNING_COMBINATIONS.each do |combination|
return true if (combination - player_movements).empty?
end
false
end
def new_movement(player, movement)
player.push(movement)
@switch_player = !@switch_player
player
end
def reset()
@switch_player = false
@who_won = -1
end
end
# rubocop: enable Metrics/CyclomaticComplexity
| 22.61194 | 120 | 0.671947 |
6a9e2aef30f75d6b9a60c97019e16b0033e2ef71 | 2,513 | # encoding: UTF-8
# frozen_string_literal: true
describe PaymentAddress do
context '.create' do
let(:member) { create(:member, :level_3) }
let!(:account) { member.get_account(:btc) }
let!(:wallet) { Wallet.joins(:currencies).find_by(currencies: { id: :btc }) }
let(:secret) { 's3cr3t' }
let(:details) { { 'a' => 'b', 'b' => 'c' } }
let!(:addr) { create(:payment_address, :btc_address, address: nil, secret: secret, wallet_id: wallet.id) }
it 'generate address after commit' do
AMQP::Queue.expects(:enqueue).with(:deposit_coin_address, { member_id: member.id, wallet_id: wallet.id }, { persistent: true })
member.payment_address(wallet.id)
end
it 'updates secret' do
expect {
addr.update(secret: 'new_secret')
}.to change { addr.reload.secret_encrypted }.and change { addr.reload.secret }.to 'new_secret'
end
it 'updates details' do
expect {
addr.update(details: details)
}.to change { addr.reload.details_encrypted }.and change { addr.reload.details }.to details
end
it 'long secret' do
expect {
addr.update(secret: Faker::String.random(1024))
}.to raise_error ActiveRecord::ValueTooLong
end
it 'long details' do
expect {
addr.update(details: { test: Faker::String.random(1024) })
}.to raise_error ActiveRecord::ValueTooLong
end
end
context 'methods' do
context 'status' do
let(:member) { create(:member, :level_3) }
let!(:account) { member.get_account(:btc) }
let!(:wallet) { Wallet.joins(:currencies).find_by(currencies: { id: :btc }) }
context 'pending' do
let!(:addr) { create(:payment_address, :btc_address, address: nil, wallet_id: wallet.id) }
it { expect(addr.status).to eq 'pending' }
end
context 'active' do
let!(:addr) { create(:payment_address, :btc_address, wallet_id: wallet.id) }
it { expect(addr.status).to eq 'active' }
end
context 'disabled' do
before do
wallet.update(status: 'disabled')
end
let!(:addr) { create(:payment_address, :btc_address, wallet_id: wallet.id) }
it { expect(addr.status).to eq 'disabled' }
end
context 'retired' do
before do
wallet.update(status: 'retired')
end
let!(:addr) { create(:payment_address, :btc_address, wallet_id: wallet.id) }
it { expect(addr.status).to eq 'retired' }
end
end
end
end
| 30.277108 | 133 | 0.615201 |
f8a8c9b8e2278c7dc8af87f28524dcbdbe949426 | 209 | FactoryBot.define do
factory :assessment_section_properties do
association :assessment, factory: :assignment
association :section
due_date { 1.minute.from_now }
is_hidden { false }
end
end
| 23.222222 | 49 | 0.741627 |
010a890179c81173b4f0ed547a1ae2a3c5053e75 | 15,242 | =begin
#NSX-T Manager API
#VMware NSX-T Manager REST API
OpenAPI spec version: 2.3.0.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.3.1
=end
require 'date'
module NSXT
class TelemetryProxy
# Link to this resource
attr_accessor :_self
# The server will populate this field when returing the resource. Ignored on PUT and POST.
attr_accessor :_links
# Schema for this resource
attr_accessor :_schema
# The _revision property describes the current revision of the resource. To prevent clients from overwriting each other's changes, PUT operations must include the current _revision of the resource, which clients should obtain by issuing a GET operation. If the _revision provided in a PUT request is missing or stale, the operation will be rejected.
attr_accessor :_revision
# Indicates system owned resource
attr_accessor :_system_owned
# Defaults to ID if not set
attr_accessor :display_name
# Description of this resource
attr_accessor :description
# Opaque identifiers meaningful to the API user
attr_accessor :tags
# ID of the user who created this resource
attr_accessor :_create_user
# Protection status is one of the following: PROTECTED - the client who retrieved the entity is not allowed to modify it. NOT_PROTECTED - the client who retrieved the entity is allowed to modify it REQUIRE_OVERRIDE - the client who retrieved the entity is a super user and can modify it, but only when providing the request header X-Allow-Overwrite=true. UNKNOWN - the _protection field could not be determined for this entity.
attr_accessor :_protection
# Timestamp of resource creation
attr_accessor :_create_time
# Timestamp of last modification
attr_accessor :_last_modified_time
# ID of the user who last modified this resource
attr_accessor :_last_modified_user
# Unique identifier of this resource
attr_accessor :id
# The type of this resource.
attr_accessor :resource_type
# Specify the user name used to authenticate with the proxy server, if required.
attr_accessor :username
# Specify the password used to authenticate with the proxy server, if required. A GET call on /telemetry/config returns a non-meaningful password to maintain security. To change the password to a new value, issue a PUT call after updating this field. To remove the password, issue a PUT call after emptying this field. To retain a previously set password, issue a PUT call keeping the non-meaningful value obtained from the GET call.
attr_accessor :password
# The scheme accepted by the proxy server. Specify one of HTTP and HTTPS.
attr_accessor :scheme
# Specify the fully qualified domain name, or ip address, of the proxy server.
attr_accessor :hostname
# Specify the port of the proxy server.
attr_accessor :port
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.include?(value)
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'_self' => :'_self',
:'_links' => :'_links',
:'_schema' => :'_schema',
:'_revision' => :'_revision',
:'_system_owned' => :'_system_owned',
:'display_name' => :'display_name',
:'description' => :'description',
:'tags' => :'tags',
:'_create_user' => :'_create_user',
:'_protection' => :'_protection',
:'_create_time' => :'_create_time',
:'_last_modified_time' => :'_last_modified_time',
:'_last_modified_user' => :'_last_modified_user',
:'id' => :'id',
:'resource_type' => :'resource_type',
:'username' => :'username',
:'password' => :'password',
:'scheme' => :'scheme',
:'hostname' => :'hostname',
:'port' => :'port'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'_self' => :'SelfResourceLink',
:'_links' => :'Array<ResourceLink>',
:'_schema' => :'String',
:'_revision' => :'Integer',
:'_system_owned' => :'BOOLEAN',
:'display_name' => :'String',
:'description' => :'String',
:'tags' => :'Array<Tag>',
:'_create_user' => :'String',
:'_protection' => :'String',
:'_create_time' => :'Integer',
:'_last_modified_time' => :'Integer',
:'_last_modified_user' => :'String',
:'id' => :'String',
:'resource_type' => :'String',
:'username' => :'String',
:'password' => :'String',
:'scheme' => :'String',
:'hostname' => :'String',
:'port' => :'Integer'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
if attributes.has_key?(:'_self')
self._self = attributes[:'_self']
end
if attributes.has_key?(:'_links')
if (value = attributes[:'_links']).is_a?(Array)
self._links = value
end
end
if attributes.has_key?(:'_schema')
self._schema = attributes[:'_schema']
end
if attributes.has_key?(:'_revision')
self._revision = attributes[:'_revision']
end
if attributes.has_key?(:'_system_owned')
self._system_owned = attributes[:'_system_owned']
end
if attributes.has_key?(:'display_name')
self.display_name = attributes[:'display_name']
end
if attributes.has_key?(:'description')
self.description = attributes[:'description']
end
if attributes.has_key?(:'tags')
if (value = attributes[:'tags']).is_a?(Array)
self.tags = value
end
end
if attributes.has_key?(:'_create_user')
self._create_user = attributes[:'_create_user']
end
if attributes.has_key?(:'_protection')
self._protection = attributes[:'_protection']
end
if attributes.has_key?(:'_create_time')
self._create_time = attributes[:'_create_time']
end
if attributes.has_key?(:'_last_modified_time')
self._last_modified_time = attributes[:'_last_modified_time']
end
if attributes.has_key?(:'_last_modified_user')
self._last_modified_user = attributes[:'_last_modified_user']
end
if attributes.has_key?(:'id')
self.id = attributes[:'id']
end
if attributes.has_key?(:'resource_type')
self.resource_type = attributes[:'resource_type']
end
if attributes.has_key?(:'username')
self.username = attributes[:'username']
end
if attributes.has_key?(:'password')
self.password = attributes[:'password']
end
if attributes.has_key?(:'scheme')
self.scheme = attributes[:'scheme']
end
if attributes.has_key?(:'hostname')
self.hostname = attributes[:'hostname']
end
if attributes.has_key?(:'port')
self.port = attributes[:'port']
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
if !@display_name.nil? && @display_name.to_s.length > 255
invalid_properties.push("invalid value for 'display_name', the character length must be smaller than or equal to 255.")
end
if [email protected]? && @description.to_s.length > 1024
invalid_properties.push("invalid value for 'description', the character length must be smaller than or equal to 1024.")
end
if @scheme.nil?
invalid_properties.push("invalid value for 'scheme', scheme cannot be nil.")
end
if @hostname.nil?
invalid_properties.push("invalid value for 'hostname', hostname cannot be nil.")
end
if @port.nil?
invalid_properties.push("invalid value for 'port', port cannot be nil.")
end
return 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 !@display_name.nil? && @display_name.to_s.length > 255
return false if [email protected]? && @description.to_s.length > 1024
return false if @scheme.nil?
scheme_validator = EnumAttributeValidator.new('String', ["HTTP", "HTTPS"])
return false unless scheme_validator.valid?(@scheme)
return false if @hostname.nil?
return false if @port.nil?
return true
end
# Custom attribute writer method with validation
# @param [Object] display_name Value to be assigned
def display_name=(display_name)
if !display_name.nil? && display_name.to_s.length > 255
fail ArgumentError, "invalid value for 'display_name', the character length must be smaller than or equal to 255."
end
@display_name = display_name
end
# Custom attribute writer method with validation
# @param [Object] description Value to be assigned
def description=(description)
if !description.nil? && description.to_s.length > 1024
fail ArgumentError, "invalid value for 'description', the character length must be smaller than or equal to 1024."
end
@description = description
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] scheme Object to be assigned
def scheme=(scheme)
validator = EnumAttributeValidator.new('String', ["HTTP", "HTTPS"])
unless validator.valid?(scheme)
fail ArgumentError, "invalid value for 'scheme', must be one of #{validator.allowable_values}."
end
@scheme = scheme
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 &&
_self == o._self &&
_links == o._links &&
_schema == o._schema &&
_revision == o._revision &&
_system_owned == o._system_owned &&
display_name == o.display_name &&
description == o.description &&
tags == o.tags &&
_create_user == o._create_user &&
_protection == o._protection &&
_create_time == o._create_time &&
_last_modified_time == o._last_modified_time &&
_last_modified_user == o._last_modified_user &&
id == o.id &&
resource_type == o.resource_type &&
username == o.username &&
password == o.password &&
scheme == o.scheme &&
hostname == o.hostname &&
port == o.port
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[_self, _links, _schema, _revision, _system_owned, display_name, description, tags, _create_user, _protection, _create_time, _last_modified_time, _last_modified_user, id, resource_type, username, password, scheme, hostname, port].hash
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.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the 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 # or else data not found in attributes(hash), not an issue as the data can be optional
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 :DateTime
DateTime.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
temp_model = NSXT.const_get(type).new
temp_model.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)
next if value.nil?
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.849138 | 508 | 0.628198 |
110c1ecf6207aaab76c4f4f4ba5c7cc29f543bca | 523 | module WebpackDriver
class Asset
attr_reader :id, :files, :size
def initialize(attrs)
@id = attrs['id'].to_sym
@size = attrs['size']
@files = attrs['files']
end
def file
files.first
end
def has_source_map?
files.length > 1 && files.last.end_with?('.map')
end
def self.record(map, attrs)
id = attrs['id'].to_sym
map[id] = Asset.new(attrs)
end
end
end
| 18.678571 | 60 | 0.478011 |
03f1b1e962d0c193544511290f1bf380ca2909b6 | 2,318 | # frozen_string_literal: true
require "action_cable"
require "motion"
module Motion
class Channel < ActionCable::Channel::Base
include ActionCableExtentions::DeclarativeStreams
include ActionCableExtentions::LogSuppression
ACTION_METHODS = Set.new(["process_motion"]).freeze
private_constant :ACTION_METHODS
# Don't use the ActionCable huertistic for deciding what actions can be
# called from JavaScript. Instead, hard-code the list so we can make other
# methods public without worrying about them being called from JavaScript.
def self.action_methods
ACTION_METHODS
end
attr_reader :component_connection
def subscribed
state, client_version = params.values_at("state", "version")
if Gem::Version.new(Motion::VERSION) < Gem::Version.new(client_version)
raise IncompatibleClientError.new(Motion::VERSION, client_version)
end
@component_connection =
ComponentConnection.from_state(state, log_helper: log_helper)
synchronize
rescue => error
reject
handle_error(error, "connecting a component")
end
def unsubscribed
component_connection&.close
@component_connection = nil
end
def process_motion(data)
motion, raw_event = data.values_at("name", "event")
component_connection.process_motion(motion, Event.from_raw(raw_event))
synchronize
end
def process_broadcast(broadcast, message)
component_connection.process_broadcast(broadcast, message)
synchronize
end
private
def synchronize
streaming_from(component_connection.broadcasts, to: :process_broadcast)
component_connection.if_render_required do |component|
transmit(renderer.render(component))
end
end
def handle_error(error, context)
log_helper.error("An error occurred while #{context}", error: error)
end
def log_helper
@log_helper ||= LogHelper.for_channel(self)
end
# Memoize the renderer on the connection so that it can be shared accross
# all components. `ActionController::Renderer` is already thread-safe and
# designed to be reused.
def renderer
connection.instance_eval do
@_motion_renderer ||= Motion.build_renderer_for(self)
end
end
end
end
| 26.643678 | 78 | 0.715272 |
f827e488f18b1561c9067cb89eb714a2261122c6 | 84 | json.array! @d_dungeoneers, partial: 'd_dungeoneers/d_dungeoneer', as: :d_dungeoneer | 84 | 84 | 0.809524 |
1ac732d87666bd0d4592e81a2e1f1a1a30a2c07f | 1,186 | class System::TimeController < ApplicationController
def index
system_info.timezone = Timezone.new
@timezone = system_info.timezone
@ntp = Ntp.new
if request.post?
if params[:timezone]
@timezone.attributes = params[:timezone]
if @timezone.save
flash[:notice] = "Saved successfully"
end
end
if params[:ntp]
@ntp.attributes = params[:ntp]
@ntp.save
end
redirect_to :action => "index"
end
end
def timezone_change_country
@timezone = Timezone.new
@timezone.country = params["country"]
@timezone.locality = ""
render :partial => 'timezone_cities', :object => @timezone.cities
end
def timezone_change_locality
@timezone = Timezone.new
@timezone.country = params["country"]
@timezone.city = params["city"]
render :partial => 'timezone_localities', :object => @timezone.localities
end
def check_ntp
if Ntp.test(params[:server])
render :text => "<span style='color: green;'>ok</span>"
elsif !params[:server].blank?
render :text => "<span style='color: red'>err</span>"
else
render :text => ""
end
end
end
| 25.234043 | 77 | 0.625632 |
62062d0ad3ba53f4f8e6fb7ba911225f8007bcee | 1,731 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Auxiliary
include Msf::Exploit::Remote::Tcp
include Msf::Auxiliary::Scanner
include Msf::Auxiliary::Report
def initialize
super(
'Name' => 'Rsync Unauthenticated List Command',
'Description' => 'List all (listable) modules from a rsync daemon',
'Author' => 'ikkini',
'References' =>
[
['URL', 'http://rsync.samba.org/ftp/rsync/rsync.html']
],
'License' => MSF_LICENSE
)
register_options(
[
Opt::RPORT(873)
], self.class)
end
def run_host(ip)
connect
version = sock.get_once
print_good("#{ip}:#{rport} - rsync #{version.strip} found")
report_service(:host => ip, :port => rport, :proto => 'tcp', :name => 'rsync')
report_note(
:host => ip,
:proto => 'tcp',
:port => rport,
:type => 'rsync_version',
:data => version.strip
)
# making sure we match the version of the server
sock.puts("#{version}")
# the listing command
sock.puts("\n")
listing = sock.get(20)
disconnect
return if listing.blank?
print_good("#{ip}:#{rport} - rsync listing found")
listing.gsub!('@RSYNCD: EXIT', '') # not interested in EXIT message
listing_sanitized = Rex::Text.to_hex_ascii(listing.strip)
vprint_status("#{ip}:#{rport} - #{version.rstrip} #{listing_sanitized}")
report_note(
:host => ip,
:proto => 'tcp',
:port => rport,
:type => 'rsync_listing',
:data => listing_sanitized
)
end
end
| 25.455882 | 82 | 0.586366 |
6a65d369eb6fbc4ce94f9c3fda4f20c369d9a72e | 11,172 | module ::JdbcSpec
module ActiveRecordExtensions
def sqlite3_connection(config)
parse_sqlite3_config!(config)
config[:url] ||= "jdbc:sqlite:#{config[:database]}"
config[:driver] ||= "org.sqlite.JDBC"
jdbc_connection(config)
end
def parse_sqlite3_config!(config)
config[:database] ||= config[:dbfile]
# Allow database path relative to RAILS_ROOT, but only if
# the database path is not the special path that tells
# Sqlite to build a database only in memory.
if Object.const_defined?(:RAILS_ROOT) && ':memory:' != config[:database]
config[:database] = File.expand_path(config[:database], RAILS_ROOT)
end
end
end
module SQLite3
def self.adapter_matcher(name, *)
name =~ /sqlite/i ? self : false
end
def self.column_selector
[/sqlite/i, lambda {|cfg,col| col.extend(::JdbcSpec::SQLite3::Column)}]
end
def self.jdbc_connection_class
::ActiveRecord::ConnectionAdapters::Sqlite3JdbcConnection
end
module Column
def init_column(name, default, *args)
@default = '' if default =~ /NULL/
end
def type_cast(value)
return nil if value.nil?
case type
when :string then value
when :integer then JdbcSpec::SQLite3::Column.cast_to_integer(value)
when :primary_key then defined?(value.to_i) ? value.to_i : (value ? 1 : 0)
when :float then value.to_f
when :datetime then JdbcSpec::SQLite3::Column.cast_to_date_or_time(value)
when :date then JdbcSpec::SQLite3::Column.cast_to_date_or_time(value)
when :time then JdbcSpec::SQLite3::Column.cast_to_time(value)
when :decimal then self.class.value_to_decimal(value)
when :boolean then self.class.value_to_boolean(value)
else value
end
end
def type_cast_code(var_name)
case type
when :integer then "JdbcSpec::SQLite3::Column.cast_to_integer(#{var_name})"
when :datetime then "JdbcSpec::SQLite3::Column.cast_to_date_or_time(#{var_name})"
when :date then "JdbcSpec::SQLite3::Column.cast_to_date_or_time(#{var_name})"
when :time then "JdbcSpec::SQLite3::Column.cast_to_time(#{var_name})"
else
super
end
end
private
def simplified_type(field_type)
case field_type
when /boolean/i then :boolean
when /text/i then :string
when /int/i then :integer
when /float/i then :float
when /real/i then @scale == 0 ? :integer : :decimal
when /datetime/i then :datetime
when /date/i then :date
when /time/i then :time
when /blob/i then :binary
end
end
def extract_precision(sql_type)
case sql_type
when /^(real)\((\d+)(,\d+)?\)/i then $2.to_i
else super
end
end
def extract_scale(sql_type)
case sql_type
when /^(real)\((\d+)\)/i then 0
when /^(real)\((\d+)(,(\d+))\)/i then $4.to_i
else super
end
end
# Post process default value from JDBC into a Rails-friendly format (columns{-internal})
def default_value(value)
# jdbc returns column default strings with actual single quotes around the value.
return $1 if value =~ /^'(.*)'$/
value
end
def self.cast_to_integer(value)
return nil if value =~ /NULL/ or value.to_s.empty? or value.nil?
return (value.to_i) ? value.to_i : (value ? 1 : 0)
end
def self.cast_to_date_or_time(value)
return value if value.is_a? Date
return nil if value.blank?
guess_date_or_time((value.is_a? Time) ? value : cast_to_time(value))
end
def self.cast_to_time(value)
return value if value.is_a? Time
time_array = ParseDate.parsedate value
time_array[0] ||= 2000; time_array[1] ||= 1; time_array[2] ||= 1;
Time.send(ActiveRecord::Base.default_timezone, *time_array) rescue nil
end
def self.guess_date_or_time(value)
(value.hour == 0 and value.min == 0 and value.sec == 0) ?
Date.new(value.year, value.month, value.day) : value
end
end
def adapter_name #:nodoc:
'SQLite'
end
def supports_count_distinct? #:nodoc:
sqlite_version >= '3.2.6'
end
def supports_autoincrement? #:nodoc:
sqlite_version >= '3.1.0'
end
def sqlite_version
@sqlite_version ||= select_value('select sqlite_version(*)')
end
def modify_types(tp)
tp[:primary_key] = "INTEGER PRIMARY KEY AUTOINCREMENT"
tp[:float] = { :name => "REAL" }
tp[:decimal] = { :name => "REAL" }
tp[:datetime] = { :name => "DATETIME" }
tp[:timestamp] = { :name => "DATETIME" }
tp[:time] = { :name => "TIME" }
tp[:date] = { :name => "DATE" }
tp[:boolean] = { :name => "BOOLEAN" }
tp
end
def quote(value, column = nil) # :nodoc:
return value.quoted_id if value.respond_to?(:quoted_id)
case value
when String
if column && column.type == :binary
"'#{quote_string(column.class.string_to_binary(value))}'"
elsif column.respond_to?(:primary) && column.primary
value.to_i.to_s
else
"'#{quote_string(value)}'"
end
else super
end
end
def quote_column_name(name) #:nodoc:
name = name.to_s
# Did not find reference on values needing quoting, but these
# happen in AR unit tests
if name == "references" || name =~ /-/
%Q("#{name}")
else
name
end
end
def quote_string(str)
str.gsub(/'/, "''")
end
def quoted_true
%Q{'t'}
end
def quoted_false
%Q{'f'}
end
def add_column(table_name, column_name, type, options = {})
if option_not_null = options[:null] == false
option_not_null = options.delete(:null)
end
add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
add_column_options!(add_column_sql, options)
execute(add_column_sql)
if option_not_null
alter_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} NOT NULL"
end
end
def remove_column(table_name, column_name) #:nodoc:
cols = columns(table_name).collect {|col| col.name}
cols.delete(column_name)
cols = cols.join(', ')
table_backup = table_name + "_backup"
@connection.begin
execute "CREATE TEMPORARY TABLE #{table_backup}(#{cols})"
insert "INSERT INTO #{table_backup} SELECT #{cols} FROM #{table_name}"
execute "DROP TABLE #{table_name}"
execute "CREATE TABLE #{table_name}(#{cols})"
insert "INSERT INTO #{table_name} SELECT #{cols} FROM #{table_backup}"
execute "DROP TABLE #{table_backup}"
@connection.commit
end
def change_column(table_name, column_name, type, options = {}) #:nodoc:
execute "ALTER TABLE #{table_name} ALTER COLUMN #{column_name} #{type_to_sql(type, options[:limit])}"
end
def change_column_default(table_name, column_name, default) #:nodoc:
execute "ALTER TABLE #{table_name} ALTER COLUMN #{column_name} SET DEFAULT #{quote(default)}"
end
def rename_column(table_name, column_name, new_column_name) #:nodoc:
execute "ALTER TABLE #{table_name} ALTER COLUMN #{column_name} RENAME TO #{new_column_name}"
end
def rename_table(name, new_name)
execute "ALTER TABLE #{name} RENAME TO #{new_name}"
end
def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
log(sql,name) do
@connection.execute_update(sql)
clear_query_cache
end
table = sql.split(" ", 4)[2]
id_value || last_insert_id(table, nil)
end
def last_insert_id(table, sequence_name)
Integer(select_value("SELECT SEQ FROM SQLITE_SEQUENCE WHERE NAME = '#{table}'"))
end
def add_limit_offset!(sql, options) #:nodoc:
if options[:limit]
sql << " LIMIT #{options[:limit]}"
sql << " OFFSET #{options[:offset]}" if options[:offset]
end
end
def tables
@connection.tables.select {|row| row.to_s !~ /^sqlite_/i }
end
def remove_index(table_name, options = {})
execute "DROP INDEX #{quote_column_name(index_name(table_name, options))}"
end
def indexes(table_name, name = nil)
result = select_rows("SELECT name, sql FROM sqlite_master WHERE tbl_name = '#{table_name}' AND type = 'index'", name)
result.collect do |row|
name = row[0]
index_sql = row[1]
unique = (index_sql =~ /unique/i)
cols = index_sql.match(/\((.*)\)/)[1].gsub(/,/,' ').split
::ActiveRecord::ConnectionAdapters::IndexDefinition.new(table_name, name, unique, cols)
end
end
def recreate_database(name)
tables.each{ |table| drop_table(table) }
end
def _execute(sql, name = nil)
if ActiveRecord::ConnectionAdapters::JdbcConnection::select?(sql)
@connection.execute_query(sql)
else
affected_rows = @connection.execute_update(sql)
ActiveRecord::ConnectionAdapters::JdbcConnection::insert?(sql) ? last_insert_id(sql.split(" ", 4)[2], nil) : affected_rows
end
end
def select(sql, name=nil)
execute(sql, name).map do |row|
record = {}
row.each_key do |key|
if key.is_a?(String)
record[key.sub(/^"?\w+"?\./, '')] = row[key]
end
end
record
end
end
def table_structure(table_name)
returning structure = @connection.execute_query("PRAGMA table_info(#{quote_table_name(table_name)})") do
raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty?
end
end
def columns(table_name, name = nil) #:nodoc:
table_structure(table_name).map do |field|
::ActiveRecord::ConnectionAdapters::JdbcColumn.new(@config, field['name'], field['dflt_value'], field['type'], field['notnull'] == 0)
end
end
# SELECT ... FOR UPDATE is redundant since the table is locked.
def add_lock!(sql, options) #:nodoc:
sql
end
end
end
module ActiveRecord
module ConnectionAdapters
class JdbcColumn < Column
def self.string_to_binary(value)
value.gsub(/\0|%/n) do |b|
case b
when "\0" then "%00"
when "\%" then "%25"
end
end
end
def self.binary_to_string(value)
value.gsub(/%00|%25/n) do |b|
case b
when "%00" then "\0"
when "%25" then "%"
end
end
end
end
end
end
| 32.011461 | 182 | 0.596849 |
5da48780c2cfb64d08ca1c06e3c5230ceac7a62f | 5,196 | #
# Author:: Tim Dysinger (<[email protected]>)
# Author:: Christopher Brown ([email protected])
# Copyright:: Copyright (c) 2008 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper.rb')
require 'open-uri'
describe Ohai::System, "plugin eucalyptus" do
before(:each) do
@plugin = get_plugin("eucalyptus")
end
shared_examples_for "!eucalyptus" do
it "should NOT attempt to fetch the eucalyptus metadata" do
expect(OpenURI).not_to receive(:open)
@plugin.run
end
end
shared_examples_for "eucalyptus" do
before(:each) do
@http_client = double("Net::HTTP client")
allow(@plugin).to receive(:http_client).and_return(@http_client)
expect(@http_client).to receive(:get).
with("/").twice.
and_return(double("Net::HTTP Response", :body => "2012-01-12", :code => "200"))
expect(@http_client).to receive(:get).
with("/2012-01-12/meta-data/").
and_return(double("Net::HTTP Response", :body => "instance_type\nami_id\nsecurity-groups", :code => "200"))
expect(@http_client).to receive(:get).
with("/2012-01-12/meta-data/instance_type").
and_return(double("Net::HTTP Response", :body => "c1.medium", :code => "200"))
expect(@http_client).to receive(:get).
with("/2012-01-12/meta-data/ami_id").
and_return(double("Net::HTTP Response", :body => "ami-5d2dc934", :code => "200"))
expect(@http_client).to receive(:get).
with("/2012-01-12/meta-data/security-groups").
and_return(double("Net::HTTP Response", :body => "group1\ngroup2", :code => "200"))
expect(@http_client).to receive(:get).
with("/2012-01-12/user-data/").
and_return(double("Net::HTTP Response", :body => "By the pricking of my thumb...", :code => "200"))
end
it "should recursively fetch all the eucalyptus metadata" do
allow(IO).to receive(:select).and_return([[],[1],[]])
t = double("connection")
allow(t).to receive(:connect_nonblock).and_raise(Errno::EINPROGRESS)
allow(Socket).to receive(:new).and_return(t)
@plugin.run
expect(@plugin[:eucalyptus]).not_to be_nil
expect(@plugin[:eucalyptus]['instance_type']).to eq("c1.medium")
expect(@plugin[:eucalyptus]['ami_id']).to eq("ami-5d2dc934")
expect(@plugin[:eucalyptus]['security_groups']).to eql ['group1', 'group2']
end
end
describe "with eucalyptus mac and metadata address connected" do
it_should_behave_like "eucalyptus"
before(:each) do
allow(IO).to receive(:select).and_return([[],[1],[]])
@plugin[:network] = { "interfaces" => { "eth0" => { "addresses" => { "d0:0d:95:47:6E:ED"=> { "family" => "lladdr" } } } } }
end
end
describe "without eucalyptus mac and metadata address connected" do
it_should_behave_like "!eucalyptus"
before(:each) do
@plugin[:network] = { "interfaces" => { "eth0" => { "addresses" => { "ff:ff:95:47:6E:ED"=> { "family" => "lladdr" } } } } }
end
end
describe "with eucalyptus cloud file" do
it_should_behave_like "eucalyptus"
before(:each) do
allow(File).to receive(:exist?).with('/etc/chef/ohai/hints/eucalyptus.json').and_return(true)
allow(File).to receive(:read).with('/etc/chef/ohai/hints/eucalyptus.json').and_return('')
allow(File).to receive(:exist?).with('C:\chef\ohai\hints/eucalyptus.json').and_return(true)
allow(File).to receive(:read).with('C:\chef\ohai\hints/eucalyptus.json').and_return('')
end
end
describe "without cloud file" do
it_should_behave_like "!eucalyptus"
before(:each) do
@plugin[:network] = {:interfaces => {}}
allow(File).to receive(:exist?).with('/etc/chef/ohai/hints/eucalyptus.json').and_return(false)
allow(File).to receive(:exist?).with('C:\chef\ohai\hints/eucalyptus.json').and_return(false)
end
end
describe "with ec2 cloud file" do
it_should_behave_like "!eucalyptus"
before(:each) do
@plugin[:network] = {:interfaces => {}}
allow(File).to receive(:exist?).with('/etc/chef/ohai/hints/eucalyptus.json').and_return(false)
allow(File).to receive(:exist?).with('C:\chef\ohai\hints/eucalyptus.json').and_return(false)
allow(File).to receive(:exist?).with('C:\chef\ohai\hints/ec2.json').and_return(true)
allow(File).to receive(:exist?).with('/etc/chef/ohai/hints/ec2.json').and_return(true)
allow(File).to receive(:read).with('/etc/chef/ohai/hints/ec2.json').and_return('')
allow(File).to receive(:read).with('C:\chef\ohai\hints/ec2.json').and_return('')
end
end
end
| 40.913386 | 129 | 0.659546 |
ed26de58833937ededacbca18feac2249c530da8 | 550 | class Item
attr_accessor :productCode, :name, :price
def initialize(productCode, name, price)
@productCode = productCode
@name = name
@price = price
end
def validate!
check_data_valid
return true
end
private
def check_data_valid
raise InvalidItemError, 'product code must be a string' if [email protected]_of?(String)
raise InvalidItemError, 'name must be a string' if [email protected]_of?(String)
raise InvalidItemError, 'price is not a float number' if @price.to_f != @price
end
end
| 25 | 99 | 0.7 |
f84b00907fa5d4cf0c5bfdc9a2c5c851e8453483 | 1,953 |
def create_api_conn(&block)
host = Rails.configuration.genieacs_api_host
port = Rails.configuration.genieacs_api_port
use_ssl = Rails.configuration.genieacs_api_use_ssl
if block_given?
Net::HTTP.start(host, port, {use_ssl: use_ssl}, &Proc.new)
else
http = Net::HTTP.new(host, port)
http.use_ssl = use_ssl
return http
end
end
def query_resource(http, resource, query, projection = nil, skip = nil, limit = nil, sort = nil)
args = {}
args['query'] = ActiveSupport::JSON.encode(query) if query
args['projection'] = projection.join(',') if projection
args['skip'] = skip if skip
args['limit'] = limit if limit
args['sort'] = ActiveSupport::JSON.encode(sort) if sort
host = Rails.configuration.genieacs_api_host
port = Rails.configuration.genieacs_api_port
use_ssl = Rails.configuration.genieacs_api_use_ssl
request = Net::HTTP::Get.new("/#{resource}?#{args.to_query}")
http.request request do |res|
total = res['Total'].to_i
timestamp = res['Date'].to_time
if not block_given?
ret = {timestamp: timestamp, total: total, result: []}
end
counter = 0
line = ''
res.read_body() do |chunk|
chunk.each_line() do |l|
line += l
next if not line.end_with?($/)
if line.end_with?(",#{$/}")
obj = JSON.parse(line[0...0-",#{$/}".length])
if ret
ret[:result] << obj
else
yield(obj, counter, total, timestamp)
end
counter += 1
line = ''
elsif line != $/ and line != "[#{$/}" and line != "]#{$/}"
obj = JSON.parse(line[0...0-"#{$/}".length])
if ret
ret[:result] << obj
else
yield(obj, counter, total, timestamp)
end
counter += 1
end
line = ''
end
end
if ret
return ret
else
yield(nil, 0, total, timestamp) if counter == 0
end
end
end
| 27.507042 | 96 | 0.582181 |
ab35f172d125c3b783cd6ffcd470a359c35d00ae | 1,842 | #
# Author:: Doug MacEachern <[email protected]>
# Cookbook:: windows
# Resource:: shortcut
#
# Copyright:: 2010-2017, VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
property :name, String
property :target, String
property :arguments, String
property :description, String
property :cwd, String
property :iconlocation, String
load_current_value do |desired|
require 'win32ole' if RUBY_PLATFORM =~ /mswin|mingw32|windows/
link = WIN32OLE.new('WScript.Shell').CreateShortcut(desired.name)
name desired.name
target(link.TargetPath)
arguments(link.Arguments)
description(link.Description)
cwd(link.WorkingDirectory)
iconlocation(link.IconLocation)
end
action :create do
converge_if_changed do
converge_by "creating shortcut #{new_resource.name}" do
link = WIN32OLE.new('WScript.Shell').CreateShortcut(new_resource.name)
link.TargetPath = new_resource.target unless new_resource.target.nil?
link.Arguments = new_resource.arguments unless new_resource.arguments.nil?
link.Description = new_resource.description unless new_resource.description.nil?
link.WorkingDirectory = new_resource.cwd unless new_resource.cwd.nil?
link.IconLocation = new_resource.iconlocation unless new_resource.iconlocation.nil?
# ignoring: WindowStyle, Hotkey
link.Save
end
end
end
| 34.111111 | 89 | 0.762758 |
7a0616a8d7784585d77951f864df8f23993076c6 | 8,630 | =begin
#Xero Payroll UK
#This is the Xero Payroll API for orgs in the UK region.
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.3.1
=end
require 'time'
require 'date'
module XeroRuby::PayrollUk
require 'bigdecimal'
class LeaveEarningsLine
# Xero identifier for payroll leave earnings rate
attr_accessor :earnings_rate_id
# Rate per unit for leave earnings line
attr_accessor :rate_per_unit
# Leave earnings number of units
attr_accessor :number_of_units
# Leave earnings fixed amount. Only applicable if the EarningsRate RateType is Fixed
attr_accessor :fixed_amount
# The amount of the earnings line.
attr_accessor :amount
# Identifies if the leave earnings is taken from the timesheet. False for leave earnings line
attr_accessor :is_linked_to_timesheet
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'earnings_rate_id' => :'earningsRateID',
:'rate_per_unit' => :'ratePerUnit',
:'number_of_units' => :'numberOfUnits',
:'fixed_amount' => :'fixedAmount',
:'amount' => :'amount',
:'is_linked_to_timesheet' => :'isLinkedToTimesheet'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'earnings_rate_id' => :'String',
:'rate_per_unit' => :'Float',
:'number_of_units' => :'Float',
:'fixed_amount' => :'Float',
:'amount' => :'Float',
:'is_linked_to_timesheet' => :'Boolean'
}
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 `XeroRuby::PayrollUk::LeaveEarningsLine` 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 `XeroRuby::PayrollUk::LeaveEarningsLine`. 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?(:'earnings_rate_id')
self.earnings_rate_id = attributes[:'earnings_rate_id']
end
if attributes.key?(:'rate_per_unit')
self.rate_per_unit = attributes[:'rate_per_unit']
end
if attributes.key?(:'number_of_units')
self.number_of_units = attributes[:'number_of_units']
end
if attributes.key?(:'fixed_amount')
self.fixed_amount = attributes[:'fixed_amount']
end
if attributes.key?(:'amount')
self.amount = attributes[:'amount']
end
if attributes.key?(:'is_linked_to_timesheet')
self.is_linked_to_timesheet = attributes[:'is_linked_to_timesheet']
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
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?
true
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 &&
earnings_rate_id == o.earnings_rate_id &&
rate_per_unit == o.rate_per_unit &&
number_of_units == o.number_of_units &&
fixed_amount == o.fixed_amount &&
amount == o.amount &&
is_linked_to_timesheet == o.is_linked_to_timesheet
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
[earnings_rate_id, rate_per_unit, number_of_units, fixed_amount, amount, is_linked_to_timesheet].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 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 # or else data not found in attributes(hash), not an issue as the data can be optional
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 :DateTime
DateTime.parse(parse_date(value))
when :Date
Date.parse(parse_date(value))
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BigDecimal
BigDecimal(value.to_s)
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
XeroRuby::PayrollUk.const_get(type).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(downcase: false)
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
key = downcase ? attr : param
hash[key] = _to_hash(value, downcase: downcase)
end
hash
end
# Returns the object in the form of hash with snake_case
def to_attributes
to_hash(downcase: true)
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, downcase: false)
if value.is_a?(Array)
value.map do |v|
v.to_hash(downcase: downcase)
end
elsif value.is_a?(Hash)
{}.tap do |hash|
value.map { |k, v| hash[k] = _to_hash(v, downcase: downcase) }
end
elsif value.respond_to? :to_hash
value.to_hash(downcase: downcase)
else
value
end
end
def parse_date(datestring)
if datestring.include?('Date')
date_pattern = /\/Date\((-?\d+)(\+\d+)?\)\//
original, date, timezone = *date_pattern.match(datestring)
date = (date.to_i / 1000)
Time.at(date).utc.strftime('%Y-%m-%dT%H:%M:%S%z').to_s
else # handle date 'types' for small subset of payroll API's
Time.parse(datestring).strftime('%Y-%m-%dT%H:%M:%S').to_s
end
end
end
end
| 31.845018 | 216 | 0.632097 |
ac418bca7f989d7399528dde7e825086dbf97254 | 3,591 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require
require "ponzu"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.default_locale = :en
# Configure locale loading to enable nested directories
# http://edgeguides.rubyonrails.org/i18n.html#translationsfor-active-recordmodels
Rails::Application::Railties.engines.map{|e| e.root}.push(Rails.root).each do |engine_root|
if File.exists?(engine_root.join('config/locales/'))
config.i18n.load_path += Dir[engine_root.join('config', 'locales', '**', '*.{rb,yml}')]
end
end
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
################################################################
######## We want to move all this stuff to the Conference object
# Use the manifest file (default: no)
config.use_manifest = false
######### Conference configuration ##########
# Set the modules customized for the current event
# config.conference_module = 'Jsdb2013'
# config.conference_module = 'PonzuDemo'
# # Set the dates for which to show timetables and poster maps and meet ups
# config.conference_dates = {
# :time_table => ['28', '29', '30', '31'].map{|day| "2013-5-#{day}"},
# :'presentation/poster' => ['30'].map{|day| "2013-5-#{day}"},
# :meet_up => ['27', '28', '29', '30', '31'].map{|day| "2013-5-#{day}"}
# }
# config.support_email = "[email protected]"
end
end
| 42.75 | 100 | 0.687274 |
215c1478087086642bb61592337bd9ad52df2f87 | 580 | module FH
class Company::Lodging
attr_reader :name,
:is_self_lodging,
:url,
:phone,
:address,
:pk,
:is_pickup_available
def initialize(lodging)
@name = lodging[:name]
@is_self_lodging = lodging[:is_self_lodging]
@url = lodging[:url]
@phone = lodging[:phone]
@address = lodging[:address]
@pk = lodging[:pk]
@is_pickup_available = lodging[:is_pickup_available]
end
end
end
| 26.363636 | 58 | 0.484483 |
7a9c02dca615325d38fe0929ec6e5bd844114588 | 313 | require 'rails_helper'
RSpec.describe Game, type: :model do
it {
should have_one(:favourite).dependent(:destroy)
}
it { should validate_presence_of(:name) }
it { should validate_presence_of(:description) }
it { should validate_presence_of(:price) }
it { should validate_presence_of(:image) }
end
| 26.083333 | 51 | 0.728435 |
ab4f3ebc74402a381a10eca7694ff3185d2f393f | 3,864 | #! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/pops'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '../parser/parser_rspec_helper')
describe "validating 4x" do
include ParserRspecHelper
include PuppetSpec::Pops
let(:acceptor) { Puppet::Pops::Validation::Acceptor.new() }
let(:validator) { Puppet::Pops::Validation::ValidatorFactory_4_0.new().validator(acceptor) }
def validate(model)
validator.validate(model)
acceptor
end
it 'should raise error for illegal names' do
pending "validation was too strict, now too relaxed - validation missing"
expect(validate(fqn('Aaa'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_NAME)
expect(validate(fqn('AAA'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_NAME)
end
it 'should raise error for illegal variable names' do
expect(validate(fqn('Aaa').var())).to have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME)
expect(validate(fqn('AAA').var())).to have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME)
expect(validate(fqn('aaa::_aaa').var())).to have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME)
end
it 'should not raise error for variable name with underscore first in first name segment' do
expect(validate(fqn('_aa').var())).to_not have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME)
expect(validate(fqn('::_aa').var())).to_not have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME)
end
context 'for non productive expressions' do
[ '1',
'3.14',
"'a'",
'"a"',
'"${$a=10}"', # interpolation with side effect
'false',
'true',
'default',
'undef',
'[1,2,3]',
'{a=>10}',
'if 1 {2}',
'if 1 {2} else {3}',
'if 1 {2} elsif 3 {4}',
'unless 1 {2}',
'unless 1 {2} else {3}',
'1 ? 2 => 3',
'1 ? { 2 => 3}',
'-1',
'-foo()', # unary minus on productive
'1+2',
'1<2',
'(1<2)',
'!true',
'!foo()', # not on productive
'$a',
'$a[1]',
'name',
'Type',
'Type[foo]'
].each do |expr|
it "produces error for non productive: #{expr}" do
source = "#{expr}; $a = 10"
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::IDEM_EXPRESSION_NOT_LAST)
end
it "does not produce error when last for non productive: #{expr}" do
source = " $a = 10; #{expr}"
expect(validate(parse(source))).to_not have_issue(Puppet::Pops::Issues::IDEM_EXPRESSION_NOT_LAST)
end
end
[
'if 1 {$a = 1}',
'if 1 {2} else {$a=1}',
'if 1 {2} elsif 3 {$a=1}',
'unless 1 {$a=1}',
'unless 1 {2} else {$a=1}',
'$a = 1 ? 2 => 3',
'$a = 1 ? { 2 => 3}',
'Foo[a] -> Foo[b]',
'($a=1)',
'foo()',
'$a.foo()'
].each do |expr|
it "does not produce error when for productive: #{expr}" do
source = "#{expr}; $x = 1"
expect(validate(parse(source))).to_not have_issue(Puppet::Pops::Issues::IDEM_EXPRESSION_NOT_LAST)
end
end
['class', 'define', 'node'].each do |type|
it "flags non productive expression last in #{type}" do
source = <<-SOURCE
#{type} nope {
1
}
end
SOURCE
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::IDEM_NOT_ALLOWED_LAST)
end
end
end
context 'for reserved words' do
['function', 'private', 'type', 'attr'].each do |word|
it "produces an error for the word '#{word}'" do
source = "$a = #{word}"
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESERVED_WORD)
end
end
end
def parse(source)
Puppet::Pops::Parser::Parser.new().parse_string(source)
end
end
| 30.425197 | 105 | 0.586439 |
e2fc907fd05df64b957dac0f5e10c9ccebda5dc7 | 16,684 | # frozen_string_literal: true
require 'fast_spec_helper'
require 'rspec-parameterized'
require_relative '../../support/stub_settings_source'
require_relative '../../../sidekiq_cluster/cli'
require_relative '../../support/helpers/next_instance_of'
RSpec.describe Gitlab::SidekiqCluster::CLI, stub_settings_source: true do # rubocop:disable RSpec/FilePath
include NextInstanceOf
let(:cli) { described_class.new('/dev/null') }
let(:timeout) { Gitlab::SidekiqCluster::DEFAULT_SOFT_TIMEOUT_SECONDS }
let(:default_options) do
{ env: 'test', directory: Dir.pwd, max_concurrency: 50, min_concurrency: 0, dryrun: false, timeout: timeout }
end
let(:sidekiq_exporter_enabled) { false }
let(:sidekiq_exporter_port) { '3807' }
let(:sidekiq_health_checks_port) { '3807' }
let(:config_file) { Tempfile.new('gitlab.yml') }
let(:config) do
{
'test' => {
'monitoring' => {
'sidekiq_exporter' => {
'address' => 'localhost',
'enabled' => sidekiq_exporter_enabled,
'port' => sidekiq_exporter_port
},
'sidekiq_health_checks' => {
'address' => 'localhost',
'enabled' => sidekiq_exporter_enabled,
'port' => sidekiq_health_checks_port
}
}
}
}
end
let(:supervisor) { instance_double(Gitlab::SidekiqCluster::SidekiqProcessSupervisor) }
let(:metrics_cleanup_service) { instance_double(Prometheus::CleanupMultiprocDirService, execute: nil) }
before do
stub_env('RAILS_ENV', 'test')
config_file.write(YAML.dump(config))
config_file.close
allow(::Settings).to receive(:source).and_return(config_file.path)
::Settings.reload!
allow(Gitlab::ProcessManagement).to receive(:write_pid)
allow(Gitlab::SidekiqCluster::SidekiqProcessSupervisor).to receive(:instance).and_return(supervisor)
allow(supervisor).to receive(:supervise)
allow(Prometheus::CleanupMultiprocDirService).to receive(:new).and_return(metrics_cleanup_service)
end
after do
config_file.unlink
end
describe '#run' do
context 'without any arguments' do
it 'raises CommandError' do
expect { cli.run([]) }.to raise_error(described_class::CommandError)
end
end
context 'with arguments' do
it 'starts the Sidekiq workers' do
expect(Gitlab::SidekiqCluster).to receive(:start)
.with([['foo']], default_options)
.and_return([])
cli.run(%w(foo))
end
it 'allows the special * selector' do
worker_queues = %w(foo bar baz)
expect(Gitlab::SidekiqConfig::CliMethods)
.to receive(:worker_queues).and_return(worker_queues)
expect(Gitlab::SidekiqCluster)
.to receive(:start).with([worker_queues], default_options).and_return([])
cli.run(%w(*))
end
it 'raises an error when the arguments contain newlines' do
invalid_arguments = [
["foo\n"],
["foo\r"],
%W[foo b\nar]
]
invalid_arguments.each do |arguments|
expect { cli.run(arguments) }.to raise_error(described_class::CommandError)
end
end
context 'with --negate flag' do
it 'starts Sidekiq workers for all queues in all_queues.yml except the ones in argv' do
expect(Gitlab::SidekiqConfig::CliMethods).to receive(:worker_queues).and_return(['baz'])
expect(Gitlab::SidekiqCluster).to receive(:start)
.with([['baz']], default_options)
.and_return([])
cli.run(%w(foo -n))
end
end
context 'with --max-concurrency flag' do
it 'starts Sidekiq workers for specified queues with a max concurrency' do
expect(Gitlab::SidekiqConfig::CliMethods).to receive(:worker_queues).and_return(%w(foo bar baz))
expect(Gitlab::SidekiqCluster).to receive(:start)
.with([%w(foo bar baz), %w(solo)], default_options.merge(max_concurrency: 2))
.and_return([])
cli.run(%w(foo,bar,baz solo -m 2))
end
end
context 'with --min-concurrency flag' do
it 'starts Sidekiq workers for specified queues with a min concurrency' do
expect(Gitlab::SidekiqConfig::CliMethods).to receive(:worker_queues).and_return(%w(foo bar baz))
expect(Gitlab::SidekiqCluster).to receive(:start)
.with([%w(foo bar baz), %w(solo)], default_options.merge(min_concurrency: 2))
.and_return([])
cli.run(%w(foo,bar,baz solo --min-concurrency 2))
end
end
context 'with --timeout flag' do
it 'when given', 'starts Sidekiq workers with given timeout' do
expect(Gitlab::SidekiqCluster).to receive(:start)
.with([['foo']], default_options.merge(timeout: 10))
.and_return([])
cli.run(%w(foo --timeout 10))
end
it 'when not given', 'starts Sidekiq workers with default timeout' do
expect(Gitlab::SidekiqCluster).to receive(:start)
.with([['foo']], default_options.merge(timeout: Gitlab::SidekiqCluster::DEFAULT_SOFT_TIMEOUT_SECONDS))
.and_return([])
cli.run(%w(foo))
end
end
context 'with --list-queues flag' do
it 'errors when given --list-queues and --dryrun' do
expect { cli.run(%w(foo --list-queues --dryrun)) }.to raise_error(described_class::CommandError)
end
it 'prints out a list of queues in alphabetical order' do
expected_queues = [
'epics:epics_update_epics_dates',
'epics_new_epic_issue',
'new_epic',
'todos_destroyer:todos_destroyer_confidential_epic'
]
allow(Gitlab::SidekiqConfig::CliMethods).to receive(:query_queues).and_return(expected_queues.shuffle)
expect(cli).to receive(:puts).with([expected_queues])
cli.run(%w(--queue-selector feature_category=epics --list-queues))
end
end
context 'queue namespace expansion' do
it 'starts Sidekiq workers for all queues in all_queues.yml with a namespace in argv' do
expect(Gitlab::SidekiqConfig::CliMethods).to receive(:worker_queues).and_return(['cronjob:foo', 'cronjob:bar'])
expect(Gitlab::SidekiqCluster).to receive(:start)
.with([['cronjob', 'cronjob:foo', 'cronjob:bar']], default_options)
.and_return([])
cli.run(%w(cronjob))
end
end
context "with --queue-selector" do
where do
{
'memory-bound queues' => {
query: 'resource_boundary=memory',
included_queues: %w(project_export),
excluded_queues: %w(merge)
},
'memory- or CPU-bound queues' => {
query: 'resource_boundary=memory,cpu',
included_queues: %w(auto_merge:auto_merge_process project_export),
excluded_queues: %w(merge)
},
'high urgency CI queues' => {
query: 'feature_category=continuous_integration&urgency=high',
included_queues: %w(pipeline_cache:expire_job_cache pipeline_cache:expire_pipeline_cache),
excluded_queues: %w(merge)
},
'CPU-bound high urgency CI queues' => {
query: 'feature_category=continuous_integration&urgency=high&resource_boundary=cpu',
included_queues: %w(pipeline_cache:expire_pipeline_cache),
excluded_queues: %w(pipeline_cache:expire_job_cache merge)
},
'CPU-bound high urgency non-CI queues' => {
query: 'feature_category!=continuous_integration&urgency=high&resource_boundary=cpu',
included_queues: %w(new_issue),
excluded_queues: %w(pipeline_cache:expire_pipeline_cache)
},
'CI and SCM queues' => {
query: 'feature_category=continuous_integration|feature_category=source_code_management',
included_queues: %w(pipeline_cache:expire_job_cache merge),
excluded_queues: %w(mailers)
}
}
end
with_them do
it 'expands queues by attributes' do
expect(Gitlab::SidekiqCluster).to receive(:start) do |queues, opts|
expect(opts).to eq(default_options)
expect(queues.first).to include(*included_queues)
expect(queues.first).not_to include(*excluded_queues)
[]
end
cli.run(%W(--queue-selector #{query}))
end
it 'works when negated' do
expect(Gitlab::SidekiqCluster).to receive(:start) do |queues, opts|
expect(opts).to eq(default_options)
expect(queues.first).not_to include(*included_queues)
expect(queues.first).to include(*excluded_queues)
[]
end
cli.run(%W(--negate --queue-selector #{query}))
end
end
it 'expands multiple queue groups correctly' do
expect(Gitlab::SidekiqCluster)
.to receive(:start)
.with([['chat_notification'], ['project_export']], default_options)
.and_return([])
cli.run(%w(--queue-selector feature_category=chatops&has_external_dependencies=true resource_boundary=memory&feature_category=importers))
end
it 'allows the special * selector' do
worker_queues = %w(foo bar baz)
expect(Gitlab::SidekiqConfig::CliMethods)
.to receive(:worker_queues).and_return(worker_queues)
expect(Gitlab::SidekiqCluster)
.to receive(:start).with([worker_queues], default_options).and_return([])
cli.run(%w(--queue-selector *))
end
it 'errors when the selector matches no queues' do
expect(Gitlab::SidekiqCluster).not_to receive(:start)
expect { cli.run(%w(--queue-selector has_external_dependencies=true&has_external_dependencies=false)) }
.to raise_error(described_class::CommandError)
end
it 'errors on an invalid query multiple queue groups correctly' do
expect(Gitlab::SidekiqCluster).not_to receive(:start)
expect { cli.run(%w(--queue-selector unknown_field=chatops)) }
.to raise_error(Gitlab::SidekiqConfig::WorkerMatcher::QueryError)
end
end
end
context 'metrics server' do
let(:trapped_signals) { described_class::TERMINATE_SIGNALS + described_class::FORWARD_SIGNALS }
let(:metrics_dir) { Dir.mktmpdir }
before do
stub_env('prometheus_multiproc_dir', metrics_dir)
end
after do
FileUtils.rm_rf(metrics_dir, secure: true)
end
context 'starting the server' do
context 'without --dryrun' do
before do
allow(Gitlab::SidekiqCluster).to receive(:start).and_return([])
end
it 'wipes the metrics directory' do
expect(metrics_cleanup_service).to receive(:execute)
cli.run(%w(foo))
end
context 'when there are no sidekiq_health_checks settings set' do
let(:sidekiq_exporter_enabled) { true }
it 'does not start a sidekiq metrics server' do
expect(MetricsServer).not_to receive(:fork)
cli.run(%w(foo))
end
end
context 'when the sidekiq_exporter.port setting is not set' do
let(:sidekiq_exporter_enabled) { true }
it 'does not start a sidekiq metrics server' do
expect(MetricsServer).not_to receive(:fork)
cli.run(%w(foo))
end
end
context 'when sidekiq_exporter.enabled setting is not set' do
let(:config) do
{
'test' => {
'monitoring' => {
'sidekiq_exporter' => {},
'sidekiq_health_checks' => {
'address' => 'localhost',
'enabled' => sidekiq_exporter_enabled,
'port' => sidekiq_health_checks_port
}
}
}
}
end
it 'does not start a sidekiq metrics server' do
expect(MetricsServer).not_to receive(:fork)
cli.run(%w(foo))
end
end
context 'with a blank sidekiq_exporter setting' do
let(:config) do
{
'test' => {
'monitoring' => {
'sidekiq_exporter' => nil,
'sidekiq_health_checks' => nil
}
}
}
end
it 'does not start a sidekiq metrics server' do
expect(MetricsServer).not_to receive(:fork)
cli.run(%w(foo))
end
it 'does not throw an error' do
expect { cli.run(%w(foo)) }.not_to raise_error
end
end
context 'with valid settings' do
using RSpec::Parameterized::TableSyntax
where(:sidekiq_exporter_enabled, :sidekiq_exporter_port, :sidekiq_health_checks_port, :start_metrics_server) do
true | '3807' | '3907' | true
true | '3807' | '3807' | false
false | '3807' | '3907' | false
false | '3807' | '3907' | false
end
with_them do
specify do
if start_metrics_server
expect(MetricsServer).to receive(:fork).with('sidekiq', metrics_dir: metrics_dir, reset_signals: trapped_signals)
else
expect(MetricsServer).not_to receive(:fork)
end
cli.run(%w(foo))
end
end
end
context 'when a PID is specified' do
it 'writes the PID to a file' do
expect(Gitlab::ProcessManagement).to receive(:write_pid).with('/dev/null')
cli.option_parser.parse!(%w(-P /dev/null))
cli.run(%w(foo))
end
end
context 'when no PID is specified' do
it 'does not write a PID' do
expect(Gitlab::ProcessManagement).not_to receive(:write_pid)
cli.run(%w(foo))
end
end
end
context 'with --dryrun set' do
let(:sidekiq_exporter_enabled) { true }
it 'does not start the server' do
expect(MetricsServer).not_to receive(:fork)
cli.run(%w(foo --dryrun))
end
end
end
end
context 'supervising the cluster' do
let(:sidekiq_exporter_enabled) { true }
let(:sidekiq_health_checks_port) { '3907' }
let(:metrics_server_pid) { 99 }
let(:sidekiq_worker_pids) { [2, 42] }
before do
allow(Gitlab::SidekiqCluster).to receive(:start).and_return(sidekiq_worker_pids)
end
it 'stops the entire process cluster if one of the workers has been terminated' do
expect(supervisor).to receive(:alive).and_return(true)
expect(supervisor).to receive(:supervise).and_yield([2])
expect(MetricsServer).to receive(:fork).once.and_return(metrics_server_pid)
expect(Gitlab::ProcessManagement).to receive(:signal_processes).with([42, 99], :TERM)
cli.run(%w(foo))
end
context 'when the supervisor is alive' do
it 'restarts the metrics server when it is down' do
expect(supervisor).to receive(:alive).and_return(true)
expect(supervisor).to receive(:supervise).and_yield([metrics_server_pid])
expect(MetricsServer).to receive(:fork).twice.and_return(metrics_server_pid)
cli.run(%w(foo))
end
end
context 'when the supervisor is shutting down' do
it 'does not restart the metrics server' do
expect(supervisor).to receive(:alive).and_return(false)
expect(supervisor).to receive(:supervise).and_yield([metrics_server_pid])
expect(MetricsServer).to receive(:fork).once.and_return(metrics_server_pid)
cli.run(%w(foo))
end
end
end
end
end
| 35.347458 | 147 | 0.581335 |
ed34b89f9ff3162d1d807067a0300be7d826456f | 2,091 | ##########################################################################
# Copyright 2017 ThoughtWorks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##########################################################################
require 'rails_helper'
describe ApiV1::Admin::MergedEnvironments::AgentSummaryRepresenter do
it 'renders an agent summary' do
presenter = ApiV1::Admin::MergedEnvironments::AgentSummaryRepresenter.new({agent: EnvironmentAgentConfig.new('agent-uuid'), environment: get_environment_config})
actual_json = presenter.to_hash(url_builder: UrlBuilder.new)
expect(actual_json).to have_links(:self, :find, :doc)
expect(actual_json).to have_link(:self).with_url('http://test.host/go/api/agents/agent-uuid')
expect(actual_json).to have_link(:find).with_url('http://test.host/go/api/agents/:uuid')
expect(actual_json).to have_link(:doc).with_url('https://api.gocd.org/#agents')
actual_json.delete(:_links)
expect(actual_json).to eq(get_agent_summary)
end
def get_environment_config
env = EnvironmentConfigMother.environment('dev')
env.setOrigins(com.thoughtworks.go.config.remote.FileConfigOrigin.new)
env
end
def get_agent_summary
{
uuid: 'agent-uuid',
origin: {
type: 'local',
file: {
_links: {
self: {
href: 'http://test.host/admin/config_xml'
},
doc: {
href: 'https://api.gocd.org/#get-configuration'
}
},
name: 'cruise-config.xml'
}
}
}
end
end
| 33.725806 | 165 | 0.634146 |
bf94a9a93d714f4b288ce247197bd75439a4b4c0 | 1,117 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module MovieStore
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| 41.37037 | 99 | 0.734109 |
3857ae2684603f78bbf3d4183e1a207fcc20410d | 169 | class TagsController < ApplicationController
def index
@tags = Tag.all
end
def show
@tag = Tag.find(params[:id])
@destinations = @tag.destinations
end
end
| 13 | 44 | 0.704142 |
d59dacbae0b973c380a1e047d378bad5be22fc13 | 1,058 | require File.join(File.dirname(__FILE__), '..', '..', 'spec_helper')
describe "the do_refund paypal payment model" do
it "should set PAYMENTPRODUCTID to '1040' when not provided" do
model = GlobalCollect::RequestModels::DoRefund::PaypalPayment.new(
"ORDERID" => "1234",
"MERCHANTREFERENCE" => "asdf"
)
model["PAYMENTPRODUCTID"].should == "1040"
end
it "should set PAYMENTPRODUCTID to '1040' when it is something invalid" do
model = GlobalCollect::RequestModels::DoRefund::PaypalPayment.new(
"ORDERID" => "1234",
"MERCHANTREFERENCE" => "asdf",
"PAYMENTPRODUCTID" => "a"
)
model["PAYMENTPRODUCTID"].should == "1040"
end
it "should set PAYMENTPRODUCTID to '1040' when it is set to the wrong thing" do
model = GlobalCollect::RequestModels::DoRefund::PaypalPayment.new(
"ORDERID" => "1234",
"MERCHANTREFERENCE" => "asdf",
"PAYMENTPRODUCTID" => "1"
)
model["PAYMENTPRODUCTID"].should == "1040"
end
end | 36.482759 | 81 | 0.619093 |
1dd3ee4f396593650d1f7bc6776e42192e7c279f | 3,416 | require 'spec_helper_acceptance'
describe 'postgresql_psql', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do
it 'should always run SQL' do
pp = <<-EOS
class { 'postgresql::server': } ->
postgresql_psql { 'foobar':
db => 'postgres',
psql_user => 'postgres',
command => 'select 1',
}
EOS
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :expect_changes => true)
end
it 'should run some SQL when the unless query returns no rows' do
pp = <<-EOS
class { 'postgresql::server': } ->
postgresql_psql { 'foobar':
db => 'postgres',
psql_user => 'postgres',
command => 'select 1',
unless => 'select 1 where 1=2',
}
EOS
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :expect_changes => true)
end
it 'should not run SQL when the unless query returns rows' do
pp = <<-EOS
class { 'postgresql::server': } ->
postgresql_psql { 'foobar':
db => 'postgres',
psql_user => 'postgres',
command => 'select * from pg_database limit 1',
unless => 'select 1 where 1=1',
}
EOS
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :catch_changes => true)
end
it 'should not run SQL when refreshed and the unless query returns rows' do
pp = <<-EOS
class { 'postgresql::server': } ->
notify { 'trigger': } ~>
postgresql_psql { 'foobar':
db => 'postgres',
psql_user => 'postgres',
command => 'invalid sql statement',
unless => 'select 1 where 1=1',
}
EOS
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :expect_changes => true)
end
context 'with refreshonly' do
it 'should not run SQL when the unless query returns no rows' do
pp = <<-EOS
class { 'postgresql::server': } ->
postgresql_psql { 'foobar':
db => 'postgres',
psql_user => 'postgres',
command => 'select 1',
unless => 'select 1 where 1=2',
refreshonly => true,
}
EOS
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :catch_changes => true)
end
it 'should run SQL when refreshed and the unless query returns no rows' do
pp = <<-EOS.unindent
class { 'postgresql::server': } ->
notify { 'trigger': } ~>
postgresql_psql { 'foobar':
db => 'postgres',
psql_user => 'postgres',
command => 'select 1',
unless => 'select 1 where 1=2',
refreshonly => true,
}
EOS
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :expect_changes => true)
end
it 'should not run SQL when refreshed and the unless query returns rows' do
pp = <<-EOS.unindent
class { 'postgresql::server': } ->
notify { 'trigger': } ~>
postgresql_psql { 'foobar':
db => 'postgres',
psql_user => 'postgres',
command => 'invalid sql query',
unless => 'select 1 where 1=1',
refreshonly => true,
}
EOS
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :expect_changes => true)
end
end
end
| 29.196581 | 90 | 0.548009 |
186876e454fd8c5b1f1211e2b057e0c0344f80f4 | 1,045 | require 'spec_helper'
feature 'Download buttons in tags page', feature: true do
given(:user) { create(:user) }
given(:role) { :developer }
given(:status) { 'success' }
given(:tag) { 'v1.0.0' }
given(:project) { create(:project) }
given(:pipeline) do
create(:ci_pipeline,
project: project,
sha: project.commit(tag).sha,
ref: tag,
status: status)
end
given!(:build) do
create(:ci_build, :success, :artifacts,
pipeline: pipeline,
status: pipeline.status,
name: 'build')
end
background do
gitlab_sign_in(user)
project.team << [user, role]
end
describe 'when checking tags' do
context 'with artifacts' do
before do
visit project_tags_path(project)
end
scenario 'shows download artifacts button' do
href = latest_succeeded_project_artifacts_path(project, "#{tag}/download", job: 'build')
expect(page).to have_link "Download '#{build.name}'", href: href
end
end
end
end
| 23.75 | 96 | 0.611483 |
18faa134661804a245bcb0bd29fbf156c49196fa | 252 | class Mountain < Cask
version :latest
sha256 :no_check
url 'http://appgineers.de/mountain/files/Mountain.zip'
appcast 'http://appgineers.de/mountain/files/mountaincast.xml'
homepage 'http://appgineers.de/mountain/'
app 'Mountain.app'
end
| 22.909091 | 64 | 0.742063 |
089798a3ce41d44a020308833943acd972b10dd7 | 3,131 | # frozen_string_literal: true
module Audit
class Details
ACTIONS = %i[add remove failed_login change updated_ref custom_message].freeze
def self.humanize(*args)
new(*args).humanize
end
def initialize(details)
@details = details
end
def humanize
if @details[:with]
"Signed in with #{@details[:with].upcase} authentication"
elsif event_created_by_system?
"#{action_text} via system job. Reason: #{@details[:reason]}"
elsif impersonated_event?
"#{action_text} (by #{@details[:impersonated_by]})"
else
action_text
end
end
private
def event_created_by_system?
@details[:system_event]
end
def impersonated_event?
@details[:impersonated_by].present?
end
def action_text
action_name, action_info = @details.slice(*ACTIONS).first
case action_name
when :add
"Added #{target_name}#{@details[:as] ? " as #{@details[:as]}" : ''}"
when :remove
"Removed #{target_name}"
when :failed_login
"Failed to login with #{oauth_label} authentication"
when :updated_ref
target_ref = @details[:updated_ref]
from_sha = @details[:from]
to_sha = @details[:to]
"Updated ref #{target_ref} from #{from_sha} to #{to_sha}"
when :custom_message
action_info
else
text_for_change(target_name)
end
end
def text_for_change(value)
changed = ["Changed #{value}"]
changed << "from #{@details[:from]}" if @details[:from].to_s.present?
changed << "to #{@details[:to]}" if @details[:to].to_s.present?
if access_level_changed?(value) && expiry_details_available?
changed << text_for_expiry_change
end
changed.join(' ')
end
# this check is made in order to not show expiry details for older audit events
# that has been logged *without* these keys.
def expiry_details_available?
@details.has_key?(:expiry_from) && @details.has_key?(:expiry_to)
end
def text_for_expiry_change
old_expiry = @details[:expiry_from].presence || never_expires_text
new_expiry = @details[:expiry_to].presence || never_expires_text
if expiry_changed?(old_expiry, new_expiry)
_('with expiry changing from %{old_expiry} to %{new_expiry}') %
{ old_expiry: old_expiry, new_expiry: new_expiry }
else
_('with expiry remaining unchanged at %{old_expiry}') % { old_expiry: old_expiry }
end
end
def never_expires_text
_('never expires')
end
def expiry_changed?(old_expiry, new_expiry)
new_expiry != old_expiry
end
def access_level_changed?(value)
value == 'access level'
end
def target_name
@details[:target_type] == 'Operations::FeatureFlag' ? detail_value : target_name_with_space
end
def target_name_with_space
detail_value.tr('_', ' ')
end
def detail_value
@details.each_value.first
end
def oauth_label
Gitlab::Auth::OAuth::Provider.label_for(detail_value).upcase
end
end
end
| 26.091667 | 97 | 0.641967 |
08fffc1cc421f88e0036a0254b5e680ee70fc27b | 573 | require 'spec_helper'
describe Scolh::CheckCommand do
before do
@c = Scolh::CommandFactory.new
@ch = Scolh::CheckCommand.new
end
it "should error when only one party" do
list = [@c.parse("party joe has payment address 00100101")]
expect(@ch.run(list)).to eq(false)
expect(@ch.errors).to include("Only one party given")
end
it "should error when some party lacks a payment address" do
list = [@c.parse("party joe")]
expect(@ch.run(list)).to eq(false)
expect(@ch.errors).to include("Party joe needs payment address")
end
end | 28.65 | 68 | 0.677138 |
ac17ba644d3476f524d6981b7935b404d97d7960 | 5,005 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::StorageSync::Mgmt::V2019_02_01
module Models
#
# The parameters used when creating a server endpoint.
#
class ServerEndpointCreateParameters < ProxyResource
include MsRestAzure
# @return [String] Server Local path.
attr_accessor :server_local_path
# @return [Enum] Cloud Tiering. Possible values include: 'on', 'off'
attr_accessor :cloud_tiering
# @return [Integer] Level of free space to be maintained by Cloud Tiering
# if it is enabled.
attr_accessor :volume_free_space_percent
# @return [Integer] Tier files older than days.
attr_accessor :tier_files_older_than_days
# @return [String] Friendly Name
attr_accessor :friendly_name
# @return [String] Server Resource Id.
attr_accessor :server_resource_id
# @return [Enum] Offline data transfer. Possible values include: 'on',
# 'off'
attr_accessor :offline_data_transfer
# @return [String] Offline data transfer share name
attr_accessor :offline_data_transfer_share_name
#
# Mapper for ServerEndpointCreateParameters class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ServerEndpointCreateParameters',
type: {
name: 'Composite',
class_name: 'ServerEndpointCreateParameters',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
server_local_path: {
client_side_validation: true,
required: false,
serialized_name: 'properties.serverLocalPath',
type: {
name: 'String'
}
},
cloud_tiering: {
client_side_validation: true,
required: false,
serialized_name: 'properties.cloudTiering',
type: {
name: 'String'
}
},
volume_free_space_percent: {
client_side_validation: true,
required: false,
serialized_name: 'properties.volumeFreeSpacePercent',
constraints: {
InclusiveMaximum: 100,
InclusiveMinimum: 0
},
type: {
name: 'Number'
}
},
tier_files_older_than_days: {
client_side_validation: true,
required: false,
serialized_name: 'properties.tierFilesOlderThanDays',
constraints: {
InclusiveMaximum: 2147483647,
InclusiveMinimum: 0
},
type: {
name: 'Number'
}
},
friendly_name: {
client_side_validation: true,
required: false,
serialized_name: 'properties.friendlyName',
type: {
name: 'String'
}
},
server_resource_id: {
client_side_validation: true,
required: false,
serialized_name: 'properties.serverResourceId',
type: {
name: 'String'
}
},
offline_data_transfer: {
client_side_validation: true,
required: false,
serialized_name: 'properties.offlineDataTransfer',
type: {
name: 'String'
}
},
offline_data_transfer_share_name: {
client_side_validation: true,
required: false,
serialized_name: 'properties.offlineDataTransferShareName',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 31.28125 | 79 | 0.489111 |
625fb709eb0d6961032c4478b817c52aa5b8a10d | 34,123 | require './test/helper'
require 'aws'
class S3Test < Test::Unit::TestCase
def rails_env(env)
silence_warnings do
Object.const_set(:Rails, stub('Rails', :env => env))
end
end
def setup
AWS.config(:access_key_id => "TESTKEY", :secret_access_key => "TESTSECRET", :stub_requests => true)
end
def teardown
AWS.config(:access_key_id => nil, :secret_access_key => nil, :stub_requests => nil)
end
context "Parsing S3 credentials" do
setup do
@proxy_settings = {:host => "127.0.0.1", :port => 8888, :user => "foo", :password => "bar"}
rebuild_model :storage => :s3,
:bucket => "testing",
:http_proxy => @proxy_settings,
:s3_credentials => {:not => :important}
@dummy = Dummy.new
@avatar = @dummy.avatar
end
should "get the correct credentials when RAILS_ENV is production" do
rails_env("production")
assert_equal({:key => "12345"},
@avatar.parse_credentials('production' => {:key => '12345'},
:development => {:key => "54321"}))
end
should "get the correct credentials when RAILS_ENV is development" do
rails_env("development")
assert_equal({:key => "54321"},
@avatar.parse_credentials('production' => {:key => '12345'},
:development => {:key => "54321"}))
end
should "return the argument if the key does not exist" do
rails_env("not really an env")
assert_equal({:test => "12345"}, @avatar.parse_credentials(:test => "12345"))
end
should "support HTTP proxy settings" do
rails_env("development")
assert_equal(true, @avatar.using_http_proxy?)
assert_equal(@proxy_settings[:host], @avatar.http_proxy_host)
assert_equal(@proxy_settings[:port], @avatar.http_proxy_port)
assert_equal(@proxy_settings[:user], @avatar.http_proxy_user)
assert_equal(@proxy_settings[:password], @avatar.http_proxy_password)
end
end
context ":bucket option via :s3_credentials" do
setup do
rebuild_model :storage => :s3, :s3_credentials => {:bucket => 'testing'}
@dummy = Dummy.new
end
should "populate #bucket_name" do
assert_equal @dummy.avatar.bucket_name, 'testing'
end
end
context ":bucket option" do
setup do
rebuild_model :storage => :s3, :bucket => "testing", :s3_credentials => {}
@dummy = Dummy.new
end
should "populate #bucket_name" do
assert_equal @dummy.avatar.bucket_name, 'testing'
end
end
context "missing :bucket option" do
setup do
rebuild_model :storage => :s3,
#:bucket => "testing", # intentionally left out
:http_proxy => @proxy_settings,
:s3_credentials => {:not => :important}
@dummy = Dummy.new
@dummy.avatar = StringIO.new(".")
end
should "raise an argument error" do
exception = assert_raise(ArgumentError) { @dummy.save }
assert_match /missing required :bucket option/, exception.message
end
end
context "" do
setup do
rebuild_model :storage => :s3,
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:url => ":s3_path_url"
@dummy = Dummy.new
@dummy.avatar = StringIO.new(".")
end
should "return a url based on an S3 path" do
assert_match %r{^http://s3.amazonaws.com/bucket/avatars/stringio.txt}, @dummy.avatar.url
end
should "use the correct bucket" do
assert_equal "bucket", @dummy.avatar.s3_bucket.name
end
should "use the correct key" do
assert_equal "avatars/stringio.txt", @dummy.avatar.s3_object.key
end
end
context "An attachment that uses S3 for storage and has the style in the path" do
setup do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:styles => {
:thumb => "80x80>"
},
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
@dummy = Dummy.new
@dummy.avatar = StringIO.new(".")
@avatar = @dummy.avatar
end
should "use an S3 object based on the correct path for the default style" do
assert_equal("avatars/original/stringio.txt", @dummy.avatar.s3_object.key)
end
should "use an S3 object based on the correct path for the custom style" do
assert_equal("avatars/thumb/stringio.txt", @dummy.avatar.s3_object(:thumb).key)
end
end
context "s3_host_name" do
setup do
rebuild_model :storage => :s3,
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:s3_host_name => "s3-ap-northeast-1.amazonaws.com"
@dummy = Dummy.new
@dummy.avatar = StringIO.new(".")
end
should "return a url based on an :s3_host_name path" do
assert_match %r{^http://s3-ap-northeast-1.amazonaws.com/bucket/avatars/stringio.txt}, @dummy.avatar.url
end
should "use the S3 bucket with the correct host name" do
assert_equal "s3-ap-northeast-1.amazonaws.com", @dummy.avatar.s3_bucket.config.s3_endpoint
end
end
context "An attachment that uses S3 for storage and has styles that return different file types" do
setup do
rebuild_model :styles => { :large => ['500x500#', :jpg] },
:storage => :s3,
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
@dummy = Dummy.new
@dummy.avatar = File.new(fixture_file('5k.png'), 'rb')
end
should "return a url containing the correct original file mime type" do
assert_match /.+\/5k.png/, @dummy.avatar.url
end
should 'use the correct key for the original file mime type' do
assert_match /.+\/5k.png/, @dummy.avatar.s3_object.key
end
should "return a url containing the correct processed file mime type" do
assert_match /.+\/5k.jpg/, @dummy.avatar.url(:large)
end
should "use the correct key for the processed file mime type" do
assert_match /.+\/5k.jpg/, @dummy.avatar.s3_object(:large).key
end
end
context "An attachment that uses S3 for storage and has spaces in file name" do
setup do
rebuild_model :styles => { :large => ['500x500#', :jpg] },
:storage => :s3,
:bucket => "bucket",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
@dummy = Dummy.new
@dummy.avatar = File.new(fixture_file('spaced file.png'), 'rb')
end
should "return a replaced version for path" do
assert_match /.+\/spaced_file\.png/, @dummy.avatar.path
end
should "return a replaced version for url" do
assert_match /.+\/spaced_file\.png/, @dummy.avatar.url
end
end
context "An attachment that uses S3 for storage and has a question mark in file name" do
setup do
rebuild_model :styles => { :large => ['500x500#', :jpg] },
:storage => :s3,
:bucket => "bucket",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
file = StringIO.new(".")
file.original_filename = "question?mark.png"
@dummy = Dummy.new
@dummy.avatar = file
@dummy.save
end
should "return a replaced version for path" do
assert_match /.+\/question_mark\.png/, @dummy.avatar.path
end
should "return a replaced version for url" do
assert_match /.+\/question_mark\.png/, @dummy.avatar.url
end
end
context "" do
setup do
rebuild_model :storage => :s3,
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:url => ":s3_domain_url"
@dummy = Dummy.new
@dummy.avatar = StringIO.new(".")
end
should "return a url based on an S3 subdomain" do
assert_match %r{^http://bucket.s3.amazonaws.com/avatars/stringio.txt}, @dummy.avatar.url
end
end
context "" do
setup do
rebuild_model :storage => :s3,
:s3_credentials => {
:production => { :bucket => "prod_bucket" },
:development => { :bucket => "dev_bucket" }
},
:s3_host_alias => "something.something.com",
:path => ":attachment/:basename.:extension",
:url => ":s3_alias_url"
@dummy = Dummy.new
@dummy.avatar = StringIO.new(".")
end
should "return a url based on the host_alias" do
assert_match %r{^http://something.something.com/avatars/stringio.txt}, @dummy.avatar.url
end
end
context "generating a url with a proc as the host alias" do
setup do
rebuild_model :storage => :s3,
:s3_credentials => { :bucket => "prod_bucket" },
:s3_host_alias => Proc.new{|atch| "cdn#{atch.instance.counter % 4}.example.com"},
:path => ":attachment/:basename.:extension",
:url => ":s3_alias_url"
Dummy.class_eval do
def counter
@counter ||= 0
@counter += 1
@counter
end
end
@dummy = Dummy.new
@dummy.avatar = StringIO.new(".")
end
should "return a url based on the host_alias" do
assert_match %r{^http://cdn1.example.com/avatars/stringio.txt}, @dummy.avatar.url
assert_match %r{^http://cdn2.example.com/avatars/stringio.txt}, @dummy.avatar.url
end
should "still return the bucket name" do
assert_equal "prod_bucket", @dummy.avatar.bucket_name
end
end
context "" do
setup do
rebuild_model :storage => :s3,
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:url => ":asset_host"
@dummy = Dummy.new
@dummy.avatar = StringIO.new(".")
end
should "return a relative URL for Rails to calculate assets host" do
assert_match %r{^avatars/stringio\.txt}, @dummy.avatar.url
end
should "always be rewound when returning from #to_file" do
assert_equal 0, @dummy.avatar.to_file.pos
@dummy.avatar.to_file.seek(10)
assert_equal 0, @dummy.avatar.to_file.pos
end
end
context "Generating a secure url with an expiration" do
setup do
rebuild_model :storage => :s3,
:s3_credentials => {
:production => { :bucket => "prod_bucket" },
:development => { :bucket => "dev_bucket" }
},
:s3_host_alias => "something.something.com",
:s3_permissions => "private",
:path => ":attachment/:basename.:extension",
:url => ":s3_alias_url"
rails_env("production")
@dummy = Dummy.new
@dummy.avatar = StringIO.new(".")
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:url_for).with(:read, :expires => 3600, :secure => true)
@dummy.avatar.expiring_url
end
should "should succeed" do
assert true
end
end
context "Generating a url with an expiration for each style" do
setup do
rebuild_model :storage => :s3,
:s3_credentials => {
:production => { :bucket => "prod_bucket" },
:development => { :bucket => "dev_bucket" }
},
:s3_permissions => :private,
:s3_host_alias => "something.something.com",
:path => ":attachment/:style/:basename.:extension",
:url => ":s3_alias_url"
rails_env("production")
@dummy = Dummy.new
@dummy.avatar = StringIO.new(".")
end
should "should generate a url for the thumb" do
object = stub
@dummy.avatar.stubs(:s3_object).with(:thumb).returns(object)
object.expects(:url_for).with(:read, :expires => 1800, :secure => true)
@dummy.avatar.expiring_url(1800, :thumb)
end
should "should generate a url for the default style" do
object = stub
@dummy.avatar.stubs(:s3_object).with(:original).returns(object)
object.expects(:url_for).with(:read, :expires => 1800, :secure => true)
@dummy.avatar.expiring_url(1800)
end
end
context "Parsing S3 credentials with a bucket in them" do
setup do
rebuild_model :storage => :s3,
:s3_credentials => {
:production => { :bucket => "prod_bucket" },
:development => { :bucket => "dev_bucket" }
}
@dummy = Dummy.new
end
should "get the right bucket in production" do
rails_env("production")
assert_equal "prod_bucket", @dummy.avatar.bucket_name
assert_equal "prod_bucket", @dummy.avatar.s3_bucket.name
end
should "get the right bucket in development" do
rails_env("development")
assert_equal "dev_bucket", @dummy.avatar.bucket_name
assert_equal "dev_bucket", @dummy.avatar.s3_bucket.name
end
end
context "Parsing S3 credentials with a s3_host_name in them" do
setup do
rebuild_model :storage => :s3,
:bucket => 'testing',
:s3_credentials => {
:production => { :s3_host_name => "s3-world-end.amazonaws.com" },
:development => { :s3_host_name => "s3-ap-northeast-1.amazonaws.com" }
}
@dummy = Dummy.new
end
should "get the right s3_host_name in production" do
rails_env("production")
assert_match %r{^s3-world-end.amazonaws.com}, @dummy.avatar.s3_host_name
assert_match %r{^s3-world-end.amazonaws.com}, @dummy.avatar.s3_bucket.config.s3_endpoint
end
should "get the right s3_host_name in development" do
rails_env("development")
assert_match %r{^s3-ap-northeast-1.amazonaws.com}, @dummy.avatar.s3_host_name
assert_match %r{^s3-ap-northeast-1.amazonaws.com}, @dummy.avatar.s3_bucket.config.s3_endpoint
end
should "get the right s3_host_name if the key does not exist" do
rails_env("test")
assert_match %r{^s3.amazonaws.com}, @dummy.avatar.s3_host_name
assert_match %r{^s3.amazonaws.com}, @dummy.avatar.s3_bucket.config.s3_endpoint
end
end
context "An attachment with S3 storage" do
setup do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
end
should "be extended by the S3 module" do
assert Dummy.new.avatar.is_a?(Paperclip::Storage::S3)
end
should "not be extended by the Filesystem module" do
assert ! Dummy.new.avatar.is_a?(Paperclip::Storage::Filesystem)
end
context "when assigned" do
setup do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
should "not get a bucket to get a URL" do
@dummy.avatar.expects(:s3).never
@dummy.avatar.expects(:s3_bucket).never
assert_match %r{^http://s3\.amazonaws\.com/testing/avatars/original/5k\.png}, @dummy.avatar.url
end
context "and saved" do
setup do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => :public_read)
@dummy.save
end
should "succeed" do
assert true
end
end
should "delete tempfiles" do
File.stubs(:exist?).returns(true)
Paperclip::Tempfile.any_instance.expects(:close).at_least_once()
Paperclip::Tempfile.any_instance.expects(:unlink).at_least_once()
@dummy.save!
end
context "and saved without a bucket" do
setup do
AWS::S3::BucketCollection.any_instance.expects(:create).with("testing")
AWS::S3::S3Object.any_instance.stubs(:write).
raises(AWS::S3::Errors::NoSuchBucket.new(stub,
stub(:status => 404,
:body => "<foo/>"))).
then.returns(nil)
@dummy.save
end
should "succeed" do
assert true
end
end
context "and remove" do
setup do
AWS::S3::S3Object.any_instance.stubs(:exists?).returns(true)
AWS::S3::S3Object.any_instance.stubs(:delete)
@dummy.destroy_attached_files
end
should "succeed" do
assert true
end
end
context 'that the file were missing' do
setup do
AWS::S3::S3Object.any_instance.stubs(:exists?).raises(AWS::Errors::Base)
end
should 'return false on exists?' do
assert [email protected]?
end
end
end
end
context "An attachment with S3 storage and bucket defined as a Proc" do
setup do
rebuild_model :storage => :s3,
:bucket => lambda { |attachment| "bucket_#{attachment.instance.other}" },
:s3_credentials => {:not => :important}
end
should "get the right bucket name" do
assert "bucket_a", Dummy.new(:other => 'a').avatar.bucket_name
assert "bucket_a", Dummy.new(:other => 'a').avatar.s3_bucket.name
assert "bucket_b", Dummy.new(:other => 'b').avatar.bucket_name
assert "bucket_b", Dummy.new(:other => 'b').avatar.s3_bucket.name
end
end
context "An attachment with S3 storage and specific s3 headers set" do
setup do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_headers => {'Cache-Control' => 'max-age=31557600'}
end
context "when assigned" do
setup do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
context "and saved" do
setup do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => :public_read,
:cache_control => 'max-age=31557600')
@dummy.save
end
should "succeed" do
assert true
end
end
end
end
context "An attachment with S3 storage and metadata set using header names" do
setup do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_headers => {'x-amz-meta-color' => 'red'}
end
context "when assigned" do
setup do
@file = File.new(File.join(File.dirname(__FILE__), '..', 'fixtures', '5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
context "and saved" do
setup do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => :public_read,
:metadata => { "color" => "red" })
@dummy.save
end
should "succeed" do
assert true
end
end
end
end
context "An attachment with S3 storage and metadata set using the :s3_metadata option" do
setup do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_metadata => { "color" => "red" }
end
context "when assigned" do
setup do
@file = File.new(File.join(File.dirname(__FILE__), '..', 'fixtures', '5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
context "and saved" do
setup do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => :public_read,
:metadata => { "color" => "red" })
@dummy.save
end
should "succeed" do
assert true
end
end
end
end
context "An attachment with S3 storage and storage class set using the header name" do
setup do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_headers => { "x-amz-storage-class" => "reduced_redundancy" }
end
context "when assigned" do
setup do
@file = File.new(File.join(File.dirname(__FILE__), '..', 'fixtures', '5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
context "and saved" do
setup do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => :public_read,
:storage_class => "reduced_redundancy")
@dummy.save
end
should "succeed" do
assert true
end
end
end
end
context "An attachment with S3 storage and using AES256 encryption" do
setup do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_server_side_encryption => :aes256
end
context "when assigned" do
setup do
@file = File.new(File.join(File.dirname(__FILE__), '..', 'fixtures', '5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
context "and saved" do
setup do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => :public_read,
:server_side_encryption => :aes256)
@dummy.save
end
should "succeed" do
assert true
end
end
end
end
context "An attachment with S3 storage and storage class set using the :storage_class option" do
setup do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_storage_class => :reduced_redundancy
end
context "when assigned" do
setup do
@file = File.new(File.join(File.dirname(__FILE__), '..', 'fixtures', '5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
context "and saved" do
setup do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => :public_read,
:storage_class => :reduced_redundancy)
@dummy.save
end
should "succeed" do
assert true
end
end
end
end
context "with S3 credentials supplied as Pathname" do
setup do
ENV['S3_KEY'] = 'pathname_key'
ENV['S3_BUCKET'] = 'pathname_bucket'
ENV['S3_SECRET'] = 'pathname_secret'
rails_env('test')
rebuild_model :storage => :s3,
:s3_credentials => Pathname.new(fixture_file('s3.yml'))
Dummy.delete_all
@dummy = Dummy.new
end
should "parse the credentials" do
assert_equal 'pathname_bucket', @dummy.avatar.bucket_name
assert_equal 'pathname_key', @dummy.avatar.s3_bucket.config.access_key_id
assert_equal 'pathname_secret', @dummy.avatar.s3_bucket.config.secret_access_key
end
end
context "with S3 credentials in a YAML file" do
setup do
ENV['S3_KEY'] = 'env_key'
ENV['S3_BUCKET'] = 'env_bucket'
ENV['S3_SECRET'] = 'env_secret'
rails_env('test')
rebuild_model :storage => :s3,
:s3_credentials => File.new(fixture_file('s3.yml'))
Dummy.delete_all
@dummy = Dummy.new
end
should "run the file through ERB" do
assert_equal 'env_bucket', @dummy.avatar.bucket_name
assert_equal 'env_key', @dummy.avatar.s3_bucket.config.access_key_id
assert_equal 'env_secret', @dummy.avatar.s3_bucket.config.secret_access_key
end
end
context "S3 Permissions" do
context "defaults to :public_read" do
setup do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
end
context "when assigned" do
setup do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
context "and saved" do
setup do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => :public_read)
@dummy.save
end
should "succeed" do
assert true
end
end
end
end
context "string permissions set" do
setup do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_permissions => :private
end
context "when assigned" do
setup do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
context "and saved" do
setup do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => :private)
@dummy.save
end
should "succeed" do
assert true
end
end
end
end
context "hash permissions set" do
setup do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:styles => {
:thumb => "80x80>"
},
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_permissions => {
:original => :private,
:thumb => :public_read
}
end
context "when assigned" do
setup do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
context "and saved" do
setup do
[:thumb, :original].each do |style|
object = stub
@dummy.avatar.stubs(:s3_object).with(style).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => style == :thumb ? :public_read : :private)
end
@dummy.save
end
should "succeed" do
assert true
end
end
end
end
context "proc permission set" do
setup do
rebuild_model(
:storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:styles => {
:thumb => "80x80>"
},
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_permissions => lambda {|attachment, style|
attachment.instance.private_attachment? && style.to_sym != :thumb ? :private : :public_read
}
)
end
context "when assigned" do
setup do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.stubs(:private_attachment? => true)
@dummy.avatar = @file
end
teardown { @file.close }
context "and saved" do
setup do
[:thumb, :original].each do |style|
object = stub
@dummy.avatar.stubs(:s3_object).with(style).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => style == :thumb ? :public_read : :private)
end
@dummy.save
end
should "succeed" do
assert @dummy.avatar.url().include? "https://"
assert @dummy.avatar.url(:thumb).include? "http://"
end
end
end
end
end
context "An attachment with S3 storage and metadata set using a proc as headers" do
setup do
rebuild_model(
:storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:styles => {
:thumb => "80x80>"
},
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_headers => lambda {|attachment|
{'Content-Disposition' => "attachment; filename=\"#{attachment.name}\""}
}
)
end
context "when assigned" do
setup do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.stubs(:name => 'Custom Avatar Name.png')
@dummy.avatar = @file
end
teardown { @file.close }
context "and saved" do
setup do
[:thumb, :original].each do |style|
object = stub
@dummy.avatar.stubs(:s3_object).with(style).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => :public_read,
:content_disposition => 'attachment; filename="Custom Avatar Name.png"')
end
@dummy.save
end
should "succeed" do
assert true
end
end
end
end
end
| 31.771881 | 112 | 0.523166 |
bb6392e0720c8809ecbff95cfacdd7557de4bc57 | 3,195 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe AppleAuth::JWTConditions do
let(:user_identity) { '1234.5678.910' }
let(:jwt_sub) { user_identity }
let(:jwt_iss) { 'https://appleid.apple.com' }
let(:jwt_aud) { 'com.apple_auth' }
let(:jwt_iat) { Time.now.to_i }
let(:jwt_exp) { (jwt_iat + 5.minutes).to_i }
let(:jwt) do
{
iss: jwt_iss,
aud: jwt_aud,
exp: jwt_exp,
iat: jwt_iat,
sub: jwt_sub,
email: '[email protected]',
email_verified: 'true',
is_private_email: 'false'
}
end
let(:decoded_jwt) { ActiveSupport::HashWithIndifferentAccess.new(jwt) }
before do
AppleAuth.config.apple_client_id = 'com.apple_auth'
end
subject(:jwt_conditions_helper) { described_class.new(user_identity, decoded_jwt) }
context '#valid?' do
context 'when decoded jwt attributes are valid and user_identity is valid' do
it 'returns true' do
expect(jwt_conditions_helper.validate!).to eq(true)
end
end
context 'when jwt has incorrect type attributes' do
context 'when exp is not a integer' do
let(:jwt_exp) { Time.now + 5.minutes }
it 'raises an exception' do
expect { jwt_conditions_helper.validate! }.to raise_error(
AppleAuth::Conditions::JWTValidationError
)
end
end
context 'when exp is not a integer' do
let(:jwt_iat) { Time.now }
it 'raises an exception' do
expect { jwt_conditions_helper.validate! }.to raise_error(
AppleAuth::Conditions::JWTValidationError
)
end
end
end
context 'when jwt iss is different to user_identity' do
let(:jwt_sub) { '1234.5678.911' }
it 'raises an exception' do
expect { jwt_conditions_helper.validate! }.to raise_error(
AppleAuth::Conditions::JWTValidationError
)
end
end
context 'when jwt_aud is different to apple_client_id' do
let(:jwt_aud) { 'net.apple_auth' }
it 'raises an exception' do
expect { jwt_conditions_helper.validate! }.to raise_error(
AppleAuth::Conditions::JWTValidationError, 'jwt_aud is different to apple_client_id'
)
end
end
context 'when jwt_iss is different to apple_iss' do
let(:jwt_iss) { 'https://appleid.apple.net' }
it 'raises an exception' do
expect { jwt_conditions_helper.validate! }.to raise_error(
AppleAuth::Conditions::JWTValidationError, 'jwt_iss is different to apple_iss'
)
end
end
context 'when jwt_exp is leasser than now' do
let(:jwt_exp) { Time.now.to_i }
it 'raises an exception' do
expect { jwt_conditions_helper.validate! }.to raise_error(
AppleAuth::Conditions::JWTValidationError, 'Expired jwt_exp'
)
end
end
context 'when jwt_iat is greater than now' do
let(:jwt_iat) { (Time.now + 5.minutes).to_i }
it 'raises an exception' do
expect { jwt_conditions_helper.validate! }.to raise_error(
AppleAuth::Conditions::JWTValidationError, 'jwt_iat is greater than now'
)
end
end
end
end
| 28.274336 | 94 | 0.638811 |
390c23999b9d7b528f278dae3ba0740352fa5fc0 | 162 | # Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
MailmanExampleCode::Application.initialize!
| 27 | 52 | 0.814815 |
7a8a9578094652c98b1b0bb92c697c1a00b3c76c | 1,679 | Rails.application.routes.draw do
get 'home/index'
root 'home#index'
get 'honolulu' => 'honolulu#index'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
| 27.080645 | 84 | 0.646218 |
03803efd77e86defbf479f05d079d86edfe19728 | 877 | class MinefieldPrinter
module STRINGS
CLOSED = "⬜️"
EMPTY = "🔲"
MINE = "💣"
HINTS = {
1 => "1️⃣ ",
2 => "2️⃣ ",
3 => "3️⃣ ",
4 => "4️⃣ ",
5 => "5️⃣ ",
6 => "6️⃣ ",
7 => "7️⃣ ",
8 => "8️⃣ "
}
end
def initialize(minefield)
raise ArgumentError unless minefield.class == Minefield
@minefield = minefield
end
def to_s
field = ""
@minefield.rows.each do |row|
row.each do |cell|
field << character_for_cell(cell)
end
field << "\n"
end
field
end
private
def character_for_cell(cell)
return STRINGS::CLOSED unless cell.revealed?
if cell.mine?
STRINGS::MINE
elsif cell.hint == 0
STRINGS::EMPTY
else
STRINGS::HINTS[cell.hint]
end
end
end
| 18.659574 | 59 | 0.462942 |
1aff4005f4ff98d6b523ddadda4f449c222c63ff | 3,293 | require_relative '../../spec_helper'
describe "Hash#transform_keys" do
before :each do
@hash = { a: 1, b: 2, c: 3 }
end
it "returns new hash" do
ret = @hash.transform_keys(&:succ)
ret.should_not equal(@hash)
ret.should be_an_instance_of(Hash)
end
it "sets the result as transformed keys with the given block" do
@hash.transform_keys(&:succ).should == { b: 1, c: 2, d: 3 }
end
it "keeps last pair if new keys conflict" do
@hash.transform_keys { |_| :a }.should == { a: 3 }
end
it "makes both hashes to share values" do
value = [1, 2, 3]
new_hash = { a: value }.transform_keys(&:upcase)
new_hash[:A].should equal(value)
end
context "when no block is given" do
it "returns a sized Enumerator" do
enumerator = @hash.transform_keys
enumerator.should be_an_instance_of(Enumerator)
enumerator.size.should == @hash.size
enumerator.each(&:succ).should == { b: 1, c: 2, d: 3 }
end
end
it "returns a Hash instance, even on subclasses" do
klass = Class.new(Hash)
h = klass.new
h[:foo] = 42
r = h.transform_keys{|v| :"x#{v}"}
r.keys.should == [:xfoo]
r.class.should == Hash
end
end
describe "Hash#transform_keys!" do
before :each do
@hash = { a: 1, b: 2, c: 3, d: 4 }
@initial_pairs = @hash.dup
end
it "returns self" do
@hash.transform_keys!(&:succ).should equal(@hash)
end
it "updates self as transformed values with the given block" do
@hash.transform_keys!(&:to_s)
@hash.should == { 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4 }
end
# https://bugs.ruby-lang.org/issues/14380
it "prevents conflicts between new keys and old ones" do
@hash.transform_keys!(&:succ)
@hash.should == { b: 1, c: 2, d: 3, e: 4 }
end
ruby_version_is ""..."3.0.2" do # https://bugs.ruby-lang.org/issues/17735
it "returns the processed keys if we break from the block" do
@hash.transform_keys! do |v|
break if v == :c
v.succ
end
@hash.should == { b: 1, c: 2 }
end
end
ruby_version_is "3.0.2" do
it "returns the processed keys and non evaluated keys if we break from the block" do
@hash.transform_keys! do |v|
break if v == :c
v.succ
end
@hash.should == { b: 1, c: 2, d: 4 }
end
end
it "keeps later pair if new keys conflict" do
@hash.transform_keys! { |_| :a }.should == { a: 4 }
end
context "when no block is given" do
it "returns a sized Enumerator" do
enumerator = @hash.transform_keys!
enumerator.should be_an_instance_of(Enumerator)
enumerator.size.should == @hash.size
enumerator.each(&:upcase).should == { A: 1, B: 2, C: 3, D: 4 }
end
end
describe "on frozen instance" do
before :each do
@hash.freeze
end
it "raises a FrozenError on an empty hash" do
->{ {}.freeze.transform_keys!(&:upcase) }.should raise_error(FrozenError)
end
it "keeps pairs and raises a FrozenError" do
->{ @hash.transform_keys!(&:upcase) }.should raise_error(FrozenError)
@hash.should == @initial_pairs
end
context "when no block is given" do
it "does not raise an exception" do
@hash.transform_keys!.should be_an_instance_of(Enumerator)
end
end
end
end
| 26.991803 | 88 | 0.616155 |
019854ab03ef2027fbc4cd5bee199d149a3dba71 | 21 | require "searchlogic" | 21 | 21 | 0.857143 |
620117f51b2697d2aea6392f2947a079e8c499a0 | 476 | module TD::Types
# Represents a part of the text that needs to be formatted in some unusual way.
#
# @attr offset [Integer] Offset of the entity in UTF-16 code points.
# @attr length [Integer] Length of the entity, in UTF-16 code points.
# @attr type [TD::Types::TextEntityType] Type of the entity.
class TextEntity < Base
attribute :offset, TD::Types::Integer
attribute :length, TD::Types::Integer
attribute :type, TD::Types::TextEntityType
end
end
| 36.615385 | 81 | 0.710084 |
abd1467859bf2291a332335da0418f4c862a147d | 1,411 | module Vacuum
module Response
# An Amazon Web Services (AWS) API response.
class Base
# Gets/Sets the String response body.
attr_accessor :body
# Gets/Sets the Integer HTTP response code.
attr_accessor :code
# Initializes a new Response.
#
# body - The String response body.
# code - An HTTP response code that responds to to_i.
def initialize(body, code)
@body, @code = body, code.to_i
end
# Queries the response.
#
# query - String attribute to be queried.
#
# Yields matching nodes to a given block if one is given.
#
# Returns an Array of matching nodes or the return values of the yielded
# block if latter was given.
def find(query)
path = if xml.namespaces.empty?
"//#{query}"
else
"//xmlns:#{query}"
end
xml.xpath(path).map do |node|
hsh = Utils.xml_to_hash node
block_given? ? yield(hsh) : hsh
end
end
alias [] find
# Returns a Hash representation of the response.
def to_hash
Utils.xml_to_hash xml
end
# Returns whether the HTTP response is OK.
def valid?
code == 200
end
# Returns an XML document.
def xml
@xml ||= Nokogiri::XML.parse @body
end
end
end
end
| 24.327586 | 78 | 0.560595 |
e9e2b7a6f0b539e7ce36d5332f21b87b5223adc7 | 639 | # frozen_string_literal: true
class AddUserAccuracyBonusToReviewableScores < ActiveRecord::Migration[6.0]
def up
# Add user_accuracy_bonus to reviewable_scores
add_column :reviewable_scores, :user_accuracy_bonus, :float, default: 0, null: false
# Set user_accuracy_bonus = score - user.trust_level - 1
execute <<~SQL
UPDATE reviewable_scores
SET user_accuracy_bonus = score - users.trust_level - 1
FROM users
WHERE reviewable_scores.user_id = users.id
SQL
end
def down
# Remove user_accuracy_bonus from reviewable_scores
remove_column :reviewable_scores, :user_accuracy_bonus
end
end
| 29.045455 | 88 | 0.757433 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.