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
|
---|---|---|---|---|---|
e85c56a7156486e77e1f478579c166897eb3e397 | 1,728 | require "spec_helper"
describe Endpoints::Heroku::Resources do
include Rack::Test::Methods
def app
Endpoints::Heroku::Resources
end
before do
authorize ENV['HEROKU_USERNAME'], ENV['HEROKU_PASSWORD']
header "Content-Type", "application/json"
end
describe "POST /heroku/resources" do
let(:resource_attributes) { Fabricate.attributes_for(:resource) }
let(:resource) { double(uuid: resource_attributes['uuid']) }
let(:params) do
{
heroku_id: resource_attributes[:heroku_id],
plan: resource_attributes[:plan],
region: resource_attributes[:region],
callback_url: resource_attributes[:callback_url]
}
end
it "calls the mediator" do
expect_any_instance_of(Mediators::Resources::Creator).to receive(:call).and_return(resource)
post "/heroku/resources", MultiJson.encode(params)
expect(last_response.status).to eq(201)
end
end
describe "PUT /heroku/resources/:id" do
let!(:resource) { Fabricate(:resource, plan: 'starter') }
let(:params) do
{
heroku_id: resource.heroku_id,
plan: 'advanced'
}
end
it "calls the mediator" do
expect_any_instance_of(Mediators::Resources::Updater).to receive(:call).and_return(resource)
put "/heroku/resources/#{resource.uuid}", MultiJson.encode(params)
expect(last_response.status).to eq(200)
end
end
describe "DELETE /heroku/resources/:id" do
let!(:resource) { Fabricate(:resource) }
it "calls the mediator" do
expect_any_instance_of(Mediators::Resources::Destroyer).to receive(:call)
delete "/heroku/resources/#{resource.uuid}"
expect(last_response.status).to eq(200)
end
end
end
| 28.8 | 98 | 0.679398 |
7a62df3c823d88a79496d0b267b926c7d9506ac2 | 2,662 | # frozen_string_literal: true
class SeasonHash < BaseHash
class << self
def already_created
Dir.glob(FixtureDataTask::SEASONS_PATH)
.map { |path| YAMLFile.open(path).merge(file_path: path) }
.sort_by(&:fixture_no)
end
def on_air
target_titles = YAMLFile.open(FixtureDataTask::ON_AIR_SEASON_LIST_PATH)
already_created.select { |season| target_titles.include?(season.title) }
end
end
def ==(object)
self.title == object.title
end
def nonexistent_episodes
Scraping::DanimeNicoBranchStore::SEASONS_INCLUDING_NONEXISTENT_EPISODES.find { |season| season == self }&.episodes
end
def different_title_episodes
Scraping::DanimeNicoBranchStore::SEASONS_INCLUDING_DIFFERENT_TITLE_EPISODES
.find { |season| season == self }
&.episodes
end
def has_nonexistent_episode?
Scraping::DanimeNicoBranchStore::SEASONS_INCLUDING_NONEXISTENT_EPISODES.include?(self)
end
def has_different_title_episode?
Scraping::DanimeNicoBranchStore::SEASONS_INCLUDING_DIFFERENT_TITLE_EPISODES.include?(self)
end
def find_different_title_episode(episode)
different_title_episodes&.find { |different_title_episode| different_title_episode.head == episode }
end
def on_air?
return false unless watchable
return true if not_begin_yet?
%r(次話→) === episodes.last.description
end
def add_current_content_id(current_episode, current_overall_number)
if episode_without_episode_no_and_title?(current_episode)
if current_overall_number == 1
season_list = YAMLFile.open(FixtureDataTask::SEASON_LIST_PATH)
target_member = season_list.find { |member| member.title == title }
self.current_content_id = target_member.first_episode_url[%r(so\d+)]
else
self.current_content_id = %r(次話→(so\d+)).match(delete(:before_episode).description)[1]
end
end
end
def add_before_episode(current_episode, current_overall_number)
if episode_without_episode_no_and_title?(current_episode) && current_overall_number < episodes.length
self.before_episode = current_episode
end
end
def not_begin_yet?
watchable && episodes.blank?
end
def different_titles
Scraping::DanimeNicoBranchStore::SEASONS_WITH_DIFFERENT_TITLE.find { |season| season == self }&.differences&.titles
end
def original_or_different_title
nico_episode_title = different_titles&.episode
nico_episode_title.presence || title
end
def fixture_no
file_path.slice(%r(\d+)).to_i
end
private
def episode_without_episode_no_and_title?(episode)
title == episode.title && episode.episode_no.blank?
end
end
| 29.577778 | 119 | 0.74568 |
bf23c7c3857aaaff070801c5b486421c5335bb2c | 5,235 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2018_11_01
module Models
#
# Outbound pool of the load balancer.
#
class OutboundRule < SubResource
include MsRestAzure
# @return [Integer] The number of outbound ports to be used for NAT.
attr_accessor :allocated_outbound_ports
# @return [Array<SubResource>] The Frontend IP addresses of the load
# balancer.
attr_accessor :frontend_ipconfigurations
# @return [SubResource] A reference to a pool of DIPs. Outbound traffic
# is randomly load balanced across IPs in the backend IPs.
attr_accessor :backend_address_pool
# @return [String] Gets the provisioning state of the PublicIP resource.
# Possible values are: 'Updating', 'Deleting', and 'Failed'.
attr_accessor :provisioning_state
# @return [Enum] Protocol - TCP, UDP or All. Possible values include:
# 'Tcp', 'Udp', 'All'
attr_accessor :protocol
# @return [Boolean] Receive bidirectional TCP Reset on TCP flow idle
# timeout or unexpected connection termination. This element is only used
# when the protocol is set to TCP.
attr_accessor :enable_tcp_reset
# @return [Integer] The timeout for the TCP idle connection
attr_accessor :idle_timeout_in_minutes
# @return [String] The name of the resource that is unique within a
# resource group. This name can be used to access the resource.
attr_accessor :name
# @return [String] A unique read-only string that changes whenever the
# resource is updated.
attr_accessor :etag
#
# Mapper for OutboundRule class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'OutboundRule',
type: {
name: 'Composite',
class_name: 'OutboundRule',
model_properties: {
id: {
client_side_validation: true,
required: false,
serialized_name: 'id',
type: {
name: 'String'
}
},
allocated_outbound_ports: {
client_side_validation: true,
required: false,
serialized_name: 'properties.allocatedOutboundPorts',
type: {
name: 'Number'
}
},
frontend_ipconfigurations: {
client_side_validation: true,
required: true,
serialized_name: 'properties.frontendIPConfigurations',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'SubResourceElementType',
type: {
name: 'Composite',
class_name: 'SubResource'
}
}
}
},
backend_address_pool: {
client_side_validation: true,
required: true,
serialized_name: 'properties.backendAddressPool',
type: {
name: 'Composite',
class_name: 'SubResource'
}
},
provisioning_state: {
client_side_validation: true,
required: false,
serialized_name: 'properties.provisioningState',
type: {
name: 'String'
}
},
protocol: {
client_side_validation: true,
required: true,
serialized_name: 'properties.protocol',
type: {
name: 'String'
}
},
enable_tcp_reset: {
client_side_validation: true,
required: false,
serialized_name: 'properties.enableTcpReset',
type: {
name: 'Boolean'
}
},
idle_timeout_in_minutes: {
client_side_validation: true,
required: false,
serialized_name: 'properties.idleTimeoutInMinutes',
type: {
name: 'Number'
}
},
name: {
client_side_validation: true,
required: false,
serialized_name: 'name',
type: {
name: 'String'
}
},
etag: {
client_side_validation: true,
required: false,
serialized_name: 'etag',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 32.515528 | 79 | 0.50277 |
39450ad1eb18470b14cdf42bc2de5d3c26329f07 | 2,159 | require 'spec_helper'
RSpec.describe 'Abucoins integration specs' do
let(:client) { Cryptoexchange::Client.new }
let(:btc_usd_pair) { Cryptoexchange::Models::MarketPair.new(base: 'btc', target: 'usd', market: 'abucoins') }
let(:eth_btc_pair) { Cryptoexchange::Models::MarketPair.new(base: 'ETH', target: 'BTC', market: 'abucoins') }
it 'fetch pairs' do
pairs = client.pairs('abucoins')
expect(pairs).not_to be_empty
pair = pairs.first
expect(pair.base).to_not be nil
expect(pair.target).to_not be nil
expect(pair.market).to eq 'abucoins'
end
it 'fetch ticker' do
ticker = client.ticker(btc_usd_pair)
expect(ticker.base).to eq 'BTC'
expect(ticker.target).to eq 'USD'
expect(ticker.market).to eq 'abucoins'
expect(ticker.last).to be_a Numeric
expect(ticker.ask).to be_a Numeric
expect(ticker.bid).to be_a Numeric
expect(ticker.volume).to be_a Numeric
expect(ticker.timestamp).to be nil
expect(ticker.payload).to_not be nil
end
it 'fetch order book' do
order_book = client.order_book(eth_btc_pair)
expect(order_book.base).to eq 'ETH'
expect(order_book.target).to eq 'BTC'
expect(order_book.market).to eq 'abucoins'
expect(order_book.asks).to_not be_empty
expect(order_book.bids).to_not be_empty
expect(order_book.asks.first.price).to_not be_nil
expect(order_book.bids.first.amount).to_not be_nil
expect(order_book.bids.first.timestamp).to be_nil
expect(order_book.asks.count).to be > 10
expect(order_book.bids.count).to be > 10
expect(order_book.timestamp).to be_a Numeric
expect(order_book.payload).to_not be nil
end
it 'fetch trade' do
trades = client.trades(eth_btc_pair)
trade = trades.sample
expect(trades).to_not be_empty
expect(trade.trade_id).to_not be_nil
expect(trade.base).to eq 'ETH'
expect(trade.target).to eq 'BTC'
expect(['buy', 'sell']).to include trade.type
expect(trade.price).to_not be_nil
expect(trade.amount).to_not be_nil
expect(trade.timestamp).to be_a Numeric
expect(trade.payload).to_not be nil
expect(trade.market).to eq 'abucoins'
end
end
| 32.712121 | 111 | 0.709588 |
0334a40e6bdf3c2a9d094b90e798dff88fc21003 | 1,299 | #
# Be sure to run `pod lib lint ActionClosurable.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "ActionClosurable"
s.version = "1.2.0"
s.summary = "Extensions which helps to convert swifty closure to objc-style target/action."
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.homepage = "https://github.com/takasek/ActionClosurable"
# s.screenshots = "www.example.com/screenshots_1", "www.example.com/screenshots_2"
s.license = 'MIT'
s.author = { "takasek" => "[email protected]" }
s.source = { :git => "https://github.com/takasek/ActionClosurable.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/takasek'
s.ios.deployment_target = '8.0'
s.source_files = 'ActionClosurable/*.swift'
end
| 40.59375 | 108 | 0.676674 |
1d48d23c30828a3e577088997c84c730f1af1479 | 3,553 | class TagsController < ApplicationController
before_action { authorize! }
responders :flash
layout 'assignment_content'
def index
@assignment = Assignment.find_by(id: params[:assignment_id])
respond_to do |format|
format.html
format.json do
parent = @assignment || current_course
tags = parent.tags.includes(:role, :groupings).order(:name)
tag_info = tags.map do |tag|
{
id: tag.id,
name: tag.name,
description: tag.description,
creator: "#{tag.role.first_name} #{tag.role.last_name}",
use: tag.groupings.size
}
end
render json: tag_info
end
end
end
def edit
@tag = record
end
# Creates a new instance of the tag.
def create
tag_params = params.require(:tag).permit(:name, :description)
new_tag = Tag.new(tag_params.merge(role: current_role, assessment: Assessment.find_by(id: params[:assignment_id])))
if new_tag.save && params[:grouping_id]
grouping = Grouping.find(params[:grouping_id])
grouping.tags << new_tag
end
respond_with new_tag, location: -> { request.headers['Referer'] || root_path }
end
def update
tag = record
tag.update(params.require(:tag).permit(:name, :description))
respond_with tag, location: -> { request.headers['Referer'] || root_path }
end
def destroy
record.destroy
head :ok
end
# Dialog to edit a tag.
def edit_tag_dialog
@tag = record
render partial: 'tags/edit_dialog', handlers: [:erb]
end
### Upload/Download Methods ###
def download
parent = Assignment.find_by(id: params[:assignment_id]) || current_course
tags = parent.tags.includes(role: :end_user).order(:name).pluck(:name, :description, 'users.user_name')
case params[:format]
when 'csv'
output = MarkusCsv.generate(tags) do |tag_data|
tag_data
end
format = 'text/csv'
else
# Default to yml download.
output = tags.map do |name, description, user_name|
{
name: name,
description: description,
user: user_name
}
end.to_yaml
format = 'text/yml'
end
send_data output,
type: format,
filename: "tag_list.#{params[:format]}",
disposition: 'attachment'
end
def upload
assignment = Assignment.find_by(id: params[:assignment_id])
begin
data = process_file_upload
rescue Psych::SyntaxError => e
flash_message(:error, t('upload_errors.syntax_error', error: e.to_s))
rescue StandardError => e
flash_message(:error, e.message)
else
if data[:type] == '.csv'
result = Tag.from_csv(data[:file].read, current_course, assignment&.id)
flash_message(:error, result[:invalid_lines]) unless result[:invalid_lines].empty?
flash_message(:success, result[:valid_lines]) unless result[:valid_lines].empty?
elsif data[:type] == '.yml'
result = Tag.from_yml(data[:contents], current_course, assignment&.id)
if result.is_a?(StandardError)
flash_message(:error, result.message)
end
end
end
redirect_to course_tags_path(current_course, assignment_id: assignment&.id)
end
private
# Include assignment_id param in parent_params so that check_record can ensure that
# the assignment is in the same course as the current course
def parent_params
params[:assignment_id].nil? ? super : [*super, :assignment_id]
end
end
| 27.757813 | 119 | 0.639741 |
113664835fa3b8896feebaf2f0ef18ccd1eb6fdc | 665 | require 'rails_helper'
describe 'BiocurationClassifications', type: :feature do
# !! This should act more or less the same as AlternateValue features,
context 'resource routes' do
# before {
# sign_in_user_and_select_project
# }
# The scenario for creating biocuration classifications is in process (it has example usage in accessions/quick/verbatim_material.
# It must handle these three calls for logged in/not logged in users.
# It may be that these features are ultimately tested in a task.
describe 'POST /create' do
end
describe 'PATCH /update' do
end
describe 'DELETE /destroy' do
end
end
end
| 25.576923 | 134 | 0.711278 |
5dfce17609a17c2f10764507abd62bb0f8b5e8d7 | 780 | RSpec.describe ActiveStatus::Configuration do
let(:config) { described_class.new }
describe '#verbose' do
it 'is false by default' do
expect(config.verbose).to be(false)
end
end
describe '#error_code' do
it 'is 503 by default' do
expect(config.error_code).to be(503)
end
end
describe '#success_code' do
it 'is 200 by default' do
expect(config.success_code).to be(200)
end
end
describe '#checks' do
it 'is empty by default' do
expect(config.checks).to be_empty
end
end
describe '#check' do
it 'adds a new check definition' do
expect do
config.check :check_name do
# Some logic to check
end
end.to change { config.checks.size }.from(0).to 1
end
end
end
| 20.526316 | 55 | 0.633333 |
e96251846bab06324f593ee424d019aad98da571 | 1,672 | name 'chef-client'
maintainer 'Chef Software, Inc.'
maintainer_email '[email protected]'
license 'Apache-2.0'
description 'Manages client.rb configuration and chef-client service'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '11.0.5'
recipe 'chef-client', 'Includes the service recipe by default.'
recipe 'chef-client::bsd_service', 'Configures chef-client as a service on *BSD'
recipe 'chef-client::config', 'Configures the client.rb from a template.'
recipe 'chef-client::cron', 'Runs chef-client as a cron job rather than as a service'
recipe 'chef-client::delete_validation', 'Deletes validation.pem after client registers'
recipe 'chef-client::init_service', 'Configures chef-client as a SysVInit service'
recipe 'chef-client::launchd_service', 'Configures chef-client as a launchd service on OS X'
recipe 'chef-client::service', 'Sets up a client daemon to run periodically'
recipe 'chef-client::smf_service', 'Configures chef-client as a service under SMF'
recipe 'chef-client::src_service', 'Configures chef-client as a Service Resource Controller service on AIX'
recipe 'chef-client::task', 'Runs chef-client as a Windows task.'
recipe 'chef-client::upstart_service', 'Configures chef-client as a service under Upstart'
%w( aix amazon centos fedora freebsd debian oracle mac_os_x redhat suse opensuse opensuseleap ubuntu windows zlinux ).each do |os|
supports os
end
depends 'cron', '>= 4.2.0'
depends 'logrotate', '>= 1.9.0'
source_url 'https://github.com/chef-cookbooks/chef-client'
issues_url 'https://github.com/chef-cookbooks/chef-client/issues'
chef_version '>= 13.0'
| 53.935484 | 130 | 0.75 |
d533972fe75f2fda1478674b7f4d0c4a78b57cd2 | 99 | class VisitorsController < ApplicationController
def index
@products = Product.all
end
end
| 16.5 | 48 | 0.767677 |
e238c74a4119fbb9d205efdc0d750cdc6c3b6a33 | 866 | cask "iina-plus" do
version "0.5.25,21121217"
sha256 "ab870d939856f93c8524a8e54c3ae33afa5bb5d696f95e6a6e7a9bdca7648ddc"
url "https://github.com/xjbeta/iina-plus/releases/download/#{version.csv.first}(#{version.csv.second})/iina+.#{version.csv.first}.dmg"
name "IINA+"
desc "Extra danmaku support for iina (iina 弹幕支持)"
homepage "https://github.com/xjbeta/iina-plus"
livecheck do
url "https://github.com/xjbeta/iina-plus/releases/latest"
strategy :page_match do |page|
match = page.match(/(\d+(?:\.\d+)+)\((\d+)\)/i)
next if match.blank?
"#{match[1]},#{match[2]}"
end
end
app "iina+.app"
zap trash: [
"~/Library/Application Support/com.xjbeta.iina-plus",
"~/Library/Caches/com.xjbeta.iina-plus",
"~/Library/Preferences/com.xjbeta.iina-plus.plist",
"~/Library/WebKit/com.xjbeta.iina-plus",
]
end
| 29.862069 | 136 | 0.669746 |
399e14e59d860ea015d9bfc2f11547c2d22ad03b | 282 | require_relative 'node'
class LinkedList
attr_reader :head
def initialize
@head = nil
end
def add_first(value)
end
def get_first
end
def length
return 0
end
def add_last(value)
end
def get_last
end
def get_at_index(index)
end
end
| 8.057143 | 25 | 0.659574 |
e98a929b3abebd37eaa98aaca0e3a6ccba6b90f0 | 1,474 | require 'io/console'
module MovementInDungeon
def movement_loop
# state = `stty -g`
# `stty raw -echo -icanon isig`
while true
c = read_char
@last_pos = @current_pos.clone
unless @current_pos.move( c )
if c == 'k'
kill_monsters
elsif c == 'd'
disarm_traps
else
puts 'Bad order !!!'
end
end
print_dungeon_limited_bmp
end
end
def disarm_traps
@dungeon_content.each_pair do |key, values|
next unless values.include?( 'T' )
trap_pos = Position.from_hash_key( key )
distance = trap_pos.distance( @current_pos )
if distance < Dungeon::WATCH_DISTANCE
@dungeon_content[ key ].delete( 'T' )
end
end
end
def kill_monsters
@dungeon_content.each_pair do |key, values|
next unless values.include?( 'M' )
monster_pos = Position.from_hash_key( key )
distance = monster_pos.distance( @current_pos )
if distance < Dungeon::WATCH_DISTANCE
@dungeon_content[ key ].delete( 'M' )
end
end
end
private
# Reads keypresses from the user including 2 and 3 escape character sequences.
def read_char
STDIN.echo = false
STDIN.raw!
input = STDIN.getc.chr
if input == "\e" then
input << STDIN.read_nonblock(3) rescue nil
input << STDIN.read_nonblock(2) rescue nil
end
ensure
STDIN.echo = true
STDIN.cooked!
return input
end
end | 21.676471 | 80 | 0.616689 |
e95c66156060fa3f2cff204f909c3d073796a520 | 17,582 | #
# File: XmlRuleVisitor.rb
#
# This class is used to visit XML guideline elements
#
#
require 'rexml/document'
require 'rexml/streamlistener'
require 'logger'
require 'xmlutils/xmlvisitor'
require 'xmlutils/gdltemplate'
#################################################
#
# class XmlRuleVisitor
#
#################################################
class XmlRuleVisitor < XmlVisitor
include REXML
attr_accessor :lookupData
attr_accessor :context
attr_accessor :template
#-------------------------------------------------------------------------------------------------------------#
# initialize - Constructor
#
#
#------------------------------------------------------------------------------------------------------------#
def initialize(ctx)
super()
@output = ""
@lookupData = Hash.new
@context = ctx
@template = GdlTemplate.new
#@log = Logger.new(STDOUT)
#@log.level = Logger::DEBUG
end
#-------------------------------------------------------------------------------------------------------------#
# generateMsg - Generate a message
#
# msgTxt - Text of message. Used to lookup message details from context
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def generateMsg(msgTxt)
msgOut = ""
msgData = @context.messages[msgTxt]
if (nil != msgData)
msgOut = @template.msg(msgData)
end
msgOut
end # generateMsg
#-------------------------------------------------------------------------------------------------------------#
# visitRule - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitRule(elem, data)
@@log.debug("XmlRuleVisitor::visitRule")
@@log.debug(elem.inspect)
ruleAlias = elem.attributes['Name']
ruleData = @context.rules[ruleAlias]
raise "Rule data not found: #{ruleAlias}" unless (ruleData.kind_of? Rule)
ruleName = ruleData.name
ruleCond = ""
elem.each_element do |child|
if ("Condition" == child.name)
ruleCond = visit(child, ruleCond)
break
end
end
ifActions = ""
elem.each_element do |child|
if ("IfActions" == child.name)
ifActions = visit(child, ifActions)
break
end
end
elseActions = ""
elem.each_element do |child|
if ("ElseActions" == child.name)
elseActions = visit(child, elseActions)
break
end
end
ifMsgs = "" # Generate 'If' messages
ruleData.ifMsgs.each do |msgTxt|
ifMsgs += generateMsg(msgTxt)
end # ifMsgs.each
elseMsgs = "" # Generate 'Else' messages
ruleData.elseMsgs.each do |msgTxt|
elseMsgs += generateMsg(msgTxt)
end # ifMsgs.each
aliasStmt = "" # Don't create an alias statement if it is not needed.
if (ruleName != ruleAlias)
aliasStmt = <<EOF
alias(rule, #{ruleName}, "#{ruleAlias}");
EOF
end # if rulename...
# Create rule template
output = <<EOF
#{aliasStmt}
// ############################################
// #{ruleName}
rule #{ruleName}()
if(
#{ruleCond}
)
then
#{ifActions}
#{ifMsgs}
EOF
if (elseActions.length > 0)
output += <<EOF
else
#{elseActions}
#{elseMsgs}
EOF
end
output += <<EOF
end
end // rule
EOF
data += output
return data
end # visitRule
#-------------------------------------------------------------------------------------------------------------#
# visitXmlFunction - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitXmlFunction(elem, data)
@@log.debug("XmlRuleVisitor::visitXmlFunction")
@@log.debug(elem.inspect)
funcName = elem.attributes['Name']
funcArgs = ''
elem.each_element do |child|
funcArgs = visit(child, funcArgs)
end
output = "#{funcName}#{funcArgs}"
data += output
return data
end # visitXmlFunction
#-------------------------------------------------------------------------------------------------------------#
# visitArgs - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitArgs(elem, data)
@@log.debug("XmlRuleVisitor::visitArgs")
@@log.debug(elem.inspect)
argsData = ''
elem.each_element do |child|
argsData = visit(child, argsData)
end
output = "( #{argsData} )"
data += output
return data
end # visitArgs
#-------------------------------------------------------------------------------------------------------------#
# visitArg - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitArg(elem, data)
@@log.debug("XmlRuleVisitor::visitArg")
@@log.debug(elem.inspect)
argData = ''
elem.each_element do |child|
argData += ", " if(!data.empty?)
argData = visit(child, argData)
end
data += argData
return data
end # visitArg
#-------------------------------------------------------------------------------------------------------------#
# visitCompute - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitCompute(elem, data)
@@log.debug("XmlRuleVisitor::visitCompute")
@@log.debug(elem.inspect)
if (3 != elem.elements.size)
@@log.error("Compute element did not have the expected number of child elements.")
return data
end
# visit the left side
data = visit(elem.elements[2], data)
# visit the operator
data = visit(elem.elements[1], data)
# visit the right side
data = visit(elem.elements[3], data)
return data
end # visitCompute
#-------------------------------------------------------------------------------------------------------------#
# visitExpression - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitExpression(elem, data)
@@log.debug("XmlRuleVisitor::visitExpression")
@@log.debug(elem.inspect)
elem.each_element do |child|
data = visit(child, data)
end
return data
end # visitExpression
#-------------------------------------------------------------------------------------------------------------#
# visitLeftOperand - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitLeftOperand(elem, data)
@@log.debug("XmlRuleVisitor::visitLeftOperand")
@@log.debug(elem.inspect)
elem.each_element do |child|
data = visit(child, data)
end
return data
end # visitLeftOperand
#-------------------------------------------------------------------------------------------------------------#
# visitRightOperand - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitRightOperand(elem, data)
@@log.debug("XmlRuleVisitor::visitRightOperand")
@@log.debug(elem.inspect)
elem.each_element do |child|
data = visit(child, data)
end
return data
end # visitRightOperand
#-------------------------------------------------------------------------------------------------------------#
# visitOperator - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitOperator(elem, data)
@@log.debug("XmlRuleVisitor::visitOperator")
@@log.debug(elem.inspect)
if (!elem.has_text?)
@@log.error("An OPERATOR element does not have any text.")
return data
end
case elem.text
when '<'
data += ' < '
when '>'
data += ' > '
when '<>', '<>'
data += ' != '
when 'OR'
data += " ||\n\t\t"
when 'AND'
data += " &&\n\t\t"
else
data += " #{elem.text} "
end
return data
end # visitOperator
#-------------------------------------------------------------------------------------------------------------#
# visitBrace - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitBrace(elem, data)
@@log.debug("XmlRuleVisitor::visitBrace")
@@log.debug(elem.inspect)
data += "("
elem.each_element do |child|
data = visit(child, data)
end
data += ")"
return data
end # visitBrace
#-------------------------------------------------------------------------------------------------------------#
# visitConstant - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitConstant(elem, data)
@@log.debug("XmlRuleVisitor::visitConstant")
@@log.debug(elem.inspect)
if (!elem.has_text?)
@@log.error("A CONSTANT element does not have any text.")
return data
end
text = elem.text
num = isNumber(text)
if (nil != num)
data += num.to_s # TODO Fix the fact that numbers are also returned as text.
else
data += "\"#{text}\""
end
return data
end # visitConstant
#-------------------------------------------------------------------------------------------------------------#
# isNumber - Determine if a string is in fact a number
#
# text - string to check
#
# @returns boolean
#
#------------------------------------------------------------------------------------------------------------#
def isNumber(text)
@@log.debug("XmlRuleVisitor::isNumber")
@@log.debug(text.inspect)
if (nil != text.index('.'))
num = text.to_f
if (num.to_s == text)
@@log.debug("isNumber: float: #{num.to_s}")
return num
end # if num
end # if nil
num = text.to_i
if (num.to_s == text)
@@log.debug("isNumber: int: #{num.to_s}")
return num
end # if num
return nil
end # isNumber
#-------------------------------------------------------------------------------------------------------------#
# visitPPM - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitPPM(elem, data)
@@log.debug("XmlRuleVisitor::visitPPM")
@@log.debug(elem.inspect)
varName = @context.ppms[elem.attributes['Name']].name
data += varName
return data
end # visitPPM
#-------------------------------------------------------------------------------------------------------------#
# visitDPM - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitDPM(elem, data)
@@log.debug("XmlRuleVisitor::visitDPM")
@@log.debug(elem.inspect)
varName = @context.dpms[elem.attributes['Name']].name
data += varName
return data
end # visitDPM
#-------------------------------------------------------------------------------------------------------------#
# visitAssign - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitAssign(elem, data)
@@log.debug("XmlRuleVisitor::visitAssign")
@@log.debug(elem.inspect)
if (elem.elements.size < 1)
@@log.error("Assign element has no children.")
end
if (2 != elem.elements.size)
@@log.error("Assign element did not have the expected number of child elements.")
return data
end
# visit the left side
data = visit(elem.elements[1], data)
data += " = " # Add the equals sign.
# visit the assignment
data = visit(elem.elements[2], data)
data += ";\n\t\t" # Terminate the statement.
return data
end # visitAssign
#-------------------------------------------------------------------------------------------------------------#
# visitAssignTo - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitAssignTo(elem, data)
@@log.debug("XmlRuleVisitor::visitAssignTo")
@@log.debug(elem.inspect)
if (elem.elements.size < 1)
@@log.error("AssignTo element has no children.")
end
elem.each_element do |child|
data = visit(child, data)
end
return data
end # visitAssignTo
#-------------------------------------------------------------------------------------------------------------#
# visitAssignValue - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitAssignValue(elem, data)
@@log.debug("XmlRuleVisitor::visitAssignValue")
@@log.debug(elem.inspect)
if (elem.elements.size < 1)
@@log.error("AssignValue element has no children.")
end
elem.each_element do |child|
data = visit(child, data)
end
return data
end # visitAssignValue
#-------------------------------------------------------------------------------------------------------------#
# visitLookup - Handle default parsing
#
# elem - Element to visit
# data - output object to append GDL text to
#
# @returns GDL output
#
#------------------------------------------------------------------------------------------------------------#
def visitLookup(elem, data)
@@log.debug("XmlRuleVisitor::visitLookup")
@@log.debug(elem.inspect)
lkName = elem.attributes['Name']
lkParams = @context.getLookupParamNames(lkName)
data += @template.lookup(lkName, lkParams["xparam"], lkParams["yparam"])
return data
lkup = @context.lookups[lkName]
#puts lkup.inspect
x = nil
y = nil
if (isPpmVar(lkup.xParam))
x = @context.ppms[lkup.xParam.alias]
else
x = @context.dpms[lkup.xParam.alias]
end # if PPM
#puts x.inspect
if (isPpmVar(lkup.yParam))
y = @context.ppms[lkup.yParam.alias]
else
y = @context.dpms[lkup.yParam.alias]
end # if PPM
#puts y.inspect
if (nil == x)
raise "Unable to find xParam (#{lkup.xParam.alias}) in lookup #{lkName}"
end # if nil
if (nil == y)
raise "Unable to find yParam (#{lkup.yParam.alias}) in lookup #{lkName}"
end # if nil
# data += lkup.toGdlRef()
data += @template.lookup(lkName, x.name, y.name)
return data
end # visitLookup
def isPpmVar(var)
isPpm = false
case var.varType
when 'app'
isPpm = true
when 'crd'
isPpm = true
when 'prd'
isPpm = true
end # case
isPpm
end # isPpmVar
end # class XmlRuleVisitor
| 24.939007 | 112 | 0.429985 |
7a7a2ad27bb5adc12c8edd7feb4f19644cb79594 | 48 | class UndergroundLines < ActiveRecord::Base
end
| 16 | 43 | 0.833333 |
331377de5583c6c2422b820725c7687b4012e0a5 | 4,606 | # frozen_string_literal: true
# This file was auto-generated by lib/tasks/web.rake
desc 'AdminUsersSession methods.'
command 'admin_users_session' do |g|
g.desc 'Clear user-specific session settings—the session duration and what happens when the client closes—for a list of users.'
g.long_desc %( Clear user-specific session settings—the session duration and what happens when the client closes—for a list of users. )
g.command 'clearSettings' do |c|
c.flag 'user_ids', desc: "The IDs of users you'd like to clear session settings for."
c.action do |_global_options, options, _args|
puts JSON.dump($client.admin_users_session_clearSettings(options))
end
end
g.desc 'Get user-specific session settings—the session duration and what happens when the client closes—given a list of users.'
g.long_desc %( Get user-specific session settings—the session duration and what happens when the client closes—given a list of users. )
g.command 'getSettings' do |c|
c.flag 'user_ids', desc: "The IDs of users you'd like to fetch session settings for. Note: if a user does not have any active sessions, they will not be returned in the response."
c.action do |_global_options, options, _args|
puts JSON.dump($client.admin_users_session_getSettings(options))
end
end
g.desc 'Revoke a single session for a user. The user will be forced to login to Slack.'
g.long_desc %( Revoke a single session for a user. The user will be forced to login to Slack. )
g.command 'invalidate' do |c|
c.flag 'session_id', desc: 'ID of the session to invalidate.'
c.flag 'team_id', desc: 'ID of the workspace that the session belongs to.'
c.action do |_global_options, options, _args|
puts JSON.dump($client.admin_users_session_invalidate(options))
end
end
g.desc 'List active user sessions for an organization'
g.long_desc %( List active user sessions for an organization )
g.command 'list' do |c|
c.flag 'cursor', desc: 'Set cursor to next_cursor returned by the previous call to list items in the next page.'
c.flag 'limit', desc: 'The maximum number of items to return. Must be between 1 - 1000 both inclusive.'
c.flag 'team_id', desc: "The ID of the workspace you'd like active sessions for. If you pass a team_id, you'll need to pass a user_id as well."
c.flag 'user_id', desc: "The ID of user you'd like active sessions for. If you pass a user_id, you'll need to pass a team_id as well."
c.action do |_global_options, options, _args|
puts JSON.dump($client.admin_users_session_list(options))
end
end
g.desc 'Wipes all valid sessions on all devices for a given user'
g.long_desc %( Wipes all valid sessions on all devices for a given user )
g.command 'reset' do |c|
c.flag 'user_id', desc: 'The ID of the user to wipe sessions for.'
c.flag 'mobile_only', desc: 'Only expire mobile sessions (default: false).'
c.flag 'web_only', desc: 'Only expire web sessions (default: false).'
c.action do |_global_options, options, _args|
puts JSON.dump($client.admin_users_session_reset(options))
end
end
g.desc 'Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users'
g.long_desc %( Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users )
g.command 'resetBulk' do |c|
c.flag 'user_ids', desc: 'The ID of the user to wipe sessions for.'
c.flag 'mobile_only', desc: 'Only expire mobile sessions (default: false).'
c.flag 'web_only', desc: 'Only expire web sessions (default: false).'
c.action do |_global_options, options, _args|
puts JSON.dump($client.admin_users_session_resetBulk(options))
end
end
g.desc 'Configure the user-level session settings—the session duration and what happens when the client closes—for one or more users.'
g.long_desc %( Configure the user-level session settings—the session duration and what happens when the client closes—for one or more users. )
g.command 'setSettings' do |c|
c.flag 'user_ids', desc: 'The list of user IDs to apply the session settings for.'
c.flag 'desktop_app_browser_quit', desc: 'Terminate the session when the client—either the desktop app or a browser window—is closed.'
c.flag 'duration', desc: "The session duration, in seconds. The minimum value is 28800, which represents 8 hours; the max value is 315569520 or 10 years (that's a long Slack session)."
c.action do |_global_options, options, _args|
puts JSON.dump($client.admin_users_session_setSettings(options))
end
end
end
| 58.303797 | 188 | 0.732523 |
622dd203dc7dfb7fceb7ef587c7e2751ed7a6d53 | 812 | # frozen_string_literal: true
##
# Componentizes cards.
class CardComponent < ViewComponent::Base
include Mixins::UtilityMixins
CARD_CLASS_LIST = 'p-0 max-w-lg mx-auto my-4 bg-white dark:bg-gray-700 rounded-xl shadow-md items-center'
CARD_HEADER_CLASS_LIST = 'flex justify-between flex-row flex-wrap text-sm px-2 pt-4'
CARD_BODY_CLASS_LIST = 'm-0 px-3 py-6'
renders_one :header, lambda { |options: {}, &block|
tag.div class: merge_classes([CARD_HEADER_CLASS_LIST, options[:classes]]) do
block.call
end
}
renders_one :body, lambda { |options: {}, &block|
tag.div class: merge_classes([CARD_BODY_CLASS_LIST, options[:classes]]) do
block.call
end
}
def initialize(options: {})
super
@classes = merge_classes([CARD_CLASS_LIST, options[:classes]])
end
end
| 28 | 107 | 0.705665 |
ab365e7f3e8f3634353fc6f4803afb429555477a | 552 | module Notifications
class NotificationsController < Notifications::ApplicationController
def index
@notifications = current_user.notifications.includes(:actor).order('id desc').page(params[:page])
unread_ids = []
@notifications.each do |n|
unread_ids << n.id unless n.read?
end
Notification.read!(unread_ids)
Notification.realtime_push_to_client(current_user)
end
def clean
Notification.where(user_id: current_user.id).delete_all
redirect_to notifications_path
end
end
end
| 27.6 | 103 | 0.710145 |
21293679a7446ceab80f1a32a0273294b8e25a07 | 443 | require './config/environment'
class ApplicationController < Sinatra::Base
configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
set :session_secret, "fwitter_secret"
end
get '/' do
erb :index
end
helpers do
def logged_in?
!!current_user
end
def current_user
@current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
end
end
end
| 16.407407 | 80 | 0.65237 |
01b8036b8fbec9cd054fa72d1bf0a26902888c2f | 4,899 | require 'faker'
require 'factory_bot'
require 'csv'
namespace :drafts do
desc 'Load full draft into database'
task load_full: :environment do
draft = FactoryBot.build(:full_collection_draft)
found_draft = Draft.where(native_id: draft.native_id)
if found_draft.empty?
new_draft = FactoryBot.create(:full_collection_draft,
user: User.first,
provider_id: User.first.provider_id,
short_name: draft.draft['ShortName'],
entry_title: draft.draft['EntryTitle']
)
puts "Loaded full draft, ID: #{new_draft.id}"
else
puts "Did not load full draft, it was already loaded, ID: #{found_draft.first.id}"
end
end
desc 'Load full draft into database'
task load_full_variable: :environment do
draft = FactoryBot.build(:full_variable_draft)
found_draft = Draft.where(native_id: draft.native_id)
if found_draft.empty?
new_draft = FactoryBot.create(:full_variable_draft,
user: User.first,
provider_id: User.first.provider_id,
short_name: draft.draft['Name'],
entry_title: draft.draft['LongName']
)
puts "Loaded full draft, ID: #{new_draft.id}"
else
puts "Did not load full draft, it was already loaded, ID: #{found_draft.first.id}"
end
end
desc 'Load full draft into database'
task load_full_service: :environment do
draft = FactoryBot.build(:full_service_draft)
found_draft = Draft.where(native_id: draft.native_id)
if found_draft.empty?
new_draft = FactoryBot.create(:full_service_draft,
user: User.first,
provider_id: User.first.provider_id,
short_name: draft.draft['Name'],
entry_title: draft.draft['LongName']
)
puts "Loaded full draft, ID: #{new_draft.id}"
else
puts "Did not load full draft, it was already loaded, ID: #{found_draft.first.id}"
end
end
desc 'Load required fields only draft into database'
task load_required: :environment do
draft = FactoryBot.build(:collection_draft_all_required_fields)
found_draft = Draft.where(native_id: draft.native_id)
if found_draft.empty?
new_draft = FactoryBot.create(:collection_draft_all_required_fields,
user: User.first,
provider_id: User.first.provider_id,
short_name: draft.draft['ShortName'],
entry_title: draft.draft['EntryTitle']
)
puts "Loaded required fields only draft, ID: #{new_draft.id}"
else
puts "Did not load required fields only draft, it was already loaded, ID: #{found_draft.first.id}"
end
end
desc 'Load draft with invalid picklists into database'
task load_invalid_picklists: :environment do
draft = FactoryBot.build(:collection_draft_invalid_picklists)
found_draft = Draft.where(native_id: draft.native_id)
if found_draft.empty?
new_draft = FactoryBot.create(:collection_draft_invalid_picklists,
user: User.first,
provider_id: User.first.provider_id,
short_name: draft.draft['ShortName'],
entry_title: draft.draft['EntryTitle']
)
puts "Loaded draft with invalid picklists, ID: #{new_draft.id}"
else
puts "Did not load draft with invalid picklists, it was already loaded, ID: #{found_draft.first.id}"
end
end
desc 'Load draft dump for debugging'
task load_drafts_dump: :environment do
Draft.destroy_all
filename = File.join(Rails.root, 'tmp', 'drafts_dump.csv')
if File.file?(filename)
CSV.foreach(filename) do |row|
draft = Draft.new do |d|
# Draft(id: integer, user_id: integer, draft: text, created_at: datetime, updated_at: datetime, short_name: string, entry_title: string, provider_id: string, native_id: string)
d.id = row[0]
d.user_id = row[1]
d.draft = eval(row[2])
d.created_at = row[3]
d.updated_at = row[4]
d.short_name = row[5]
d.entry_title = row[6]
d.provider_id = row[7]
d.native_id = row[8]
end
draft.save
end
else
puts "You are missing the drafts dump CSV file (#{Rails.root}/tmp/drafts_dump.csv)"
end
end
end
| 40.487603 | 186 | 0.571137 |
b9bc3e10820501dbdf39ce94bf4e3c73ed91548b | 3,814 | class Libmodplug < Formula
desc "Library from the Modplug-XMMS project"
homepage "https://modplug-xmms.sourceforge.io/"
url "https://downloads.sourceforge.net/project/modplug-xmms/libmodplug/0.8.9.0/libmodplug-0.8.9.0.tar.gz"
sha256 "457ca5a6c179656d66c01505c0d95fafaead4329b9dbaa0f997d00a3508ad9de"
livecheck do
url :stable
regex(%r{url=.*?/libmodplug[._-]v?(\d+(?:\.\d+)+)\.t}i)
end
bottle do
rebuild 1
sha256 cellar: :any, arm64_monterey: "ae975c5a64bbb689329dc579f6997f2bd471b712a1d36e2055b1f94cf5bb927c"
sha256 cellar: :any, arm64_big_sur: "c3776d593085eda8a8fcf65c3ddb1419983a189381dfff047fe2a0ac2f7016e7"
sha256 cellar: :any, monterey: "f3ade438922dd6467216e1153ac89e017f3e665e96423d9d5fb7c9297f796202"
sha256 cellar: :any, big_sur: "64f182f657535f24a6f6a9fe6a351eced9f56a99bc0c0aef2f494079de6c2211"
sha256 cellar: :any, catalina: "62cb39e81cea4111f72a3f594ac78557f6f6992ae964321632fda16a16c97bd2"
sha256 cellar: :any, mojave: "67ea2db6931cc6f60ed71f09cfab02cb22d2781d2e5bbb96ff0ef6a22ebb1c83"
sha256 cellar: :any, high_sierra: "3f46eca3704d441ba8133d71bd283e8d24cff61e8b903fff720b78932185f9bf"
sha256 cellar: :any, sierra: "fc88a11e82b19a1a0aa4ada0ed3468147464d3414c3e9dffda9cea139b195c9d"
sha256 cellar: :any, el_capitan: "968a0bdc082725f136ab94f3a7eaf5a6a376eb94ec03b45f49ab275bd9193318"
sha256 cellar: :any_skip_relocation, x86_64_linux: "35918d9e7c950037e5184f85cd91d89ed308e478355dd9ad0ec8a312c69289d9"
end
resource "testmod" do
# Most favourited song on modarchive:
# https://modarchive.org/index.php?request=view_by_moduleid&query=60395
url "https://api.modarchive.org/downloads.php?moduleid=60395#2ND_PM.S3M"
sha256 "f80735b77123cc7e02c4dad6ce8197bfefcb8748b164a66ffecd206cc4b63d97"
end
# Fix -flat_namespace being used on Big Sur and later.
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/03cf8088210822aa2c1ab544ed58ea04c897d9c4/libtool/configure-big_sur.diff"
sha256 "35acd6aebc19843f1a2b3a63e880baceb0f5278ab1ace661e57a502d9d78c93c"
end
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make", "install"
end
test do
# First a basic test just that we can link on the library
# and call an initialization method.
(testpath/"test_null.cpp").write <<~EOS
#include "libmodplug/modplug.h"
int main() {
ModPlugFile* f = ModPlug_Load((void*)0, 0);
if (!f) {
// Expecting a null pointer, as no data supplied.
return 0;
} else {
return -1;
}
}
EOS
system ENV.cc, "test_null.cpp", "-L#{lib}", "-lmodplug", "-o", "test_null"
system "./test_null"
# Second, acquire an actual music file from a popular internet
# source and attempt to parse it.
resource("testmod").stage testpath
(testpath/"test_mod.cpp").write <<~EOS
#include "libmodplug/modplug.h"
#include <fstream>
#include <sstream>
int main() {
std::ifstream in("2ND_PM.S3M");
std::stringstream buffer;
buffer << in.rdbuf();
int length = buffer.tellp();
ModPlugFile* f = ModPlug_Load(buffer.str().c_str(), length);
if (f) {
// Expecting success
return 0;
} else {
return -1;
}
}
EOS
system ENV.cxx, "test_mod.cpp", "-L#{lib}", "-lmodplug", "-o", "test_mod"
system "./test_mod"
end
end
| 41.456522 | 140 | 0.658102 |
1cd1e112a69735ec9c95061c9b8963636b5ac1e9 | 749 | require 'logger'
module CfnVpn
module Log
def self.colors
@colors ||= {
ERROR: 31, # red
WARN: 33, # yellow
INFO: 0,
DEBUG: 32 # grenn
}
end
def self.logger
if @logger.nil?
@logger = Logger.new(STDOUT)
@logger.level = Logger::INFO
@logger.formatter = proc do |severity, datetime, progname, msg|
"\e[#{colors[severity.to_sym]}m#{severity}: - #{msg}\e[0m\n"
end
end
@logger
end
def self.logger=(logger)
@logger = logger
end
levels = %w(debug info warn error fatal)
levels.each do |level|
define_method("#{level.to_sym}") do |msg|
self.logger.send(level, msg)
end
end
end
end
| 19.205128 | 71 | 0.540721 |
f7ec86ad19bd18e196a8e3cd90af7793841ec8c5 | 464 | cask 'natron' do
version '2.3.15'
sha256 '9ac24bb154aea1d65813c2a8451237f02b77dd68a39619c91a671ab897eebde9'
# github.com/NatronGitHub/Natron/ was verified as official when first introduced to the cask
url "https://github.com/NatronGitHub/Natron/releases/download/v#{version}/Natron-#{version}-OSX-64.dmg"
appcast 'https://github.com/NatronGitHub/Natron/releases.atom'
name 'Natron'
homepage 'https://NatronGitHub.github.io/'
app 'Natron.app'
end
| 35.692308 | 105 | 0.771552 |
0820da148e9693b7662c74478516bf408518c409 | 291 | FactoryBot.define do
# Define your Spree extensions Factories within this file to enable applications, and other extensions to use and override them.
#
# Example adding this to your spec_helper will load these Factories for use:
# require 'spree_stalnoy_import_export/factories'
end
| 41.571429 | 130 | 0.797251 |
7a71c64472707cf4f915a158a981e74df391bf3b | 86 | RSpec.describe "13" do
it do
sleep 13 / 100.0
expect(13).to eq 13
end
end
| 12.285714 | 23 | 0.604651 |
4a991d0c71056b89fd6bbc64efc3a93ccb50736c | 1,058 | # 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: 20200111161219) do
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.index ["email"], name: "index_users_on_email", unique: true
end
end
| 42.32 | 86 | 0.759924 |
b9947954290c3c45499cddaa2ee846b48b7dfd7e | 5,126 | #! /usr/bin/env ruby -S rspec
require 'spec_helper'
describe Puppet::Parser::AST::CaseStatement do
before :each do
@scope = Puppet::Parser::Scope.new
end
describe "when evaluating" do
before :each do
@test = stub 'test'
@test.stubs(:safeevaluate).with(@scope).returns("value")
@option1 = Puppet::Parser::AST::CaseOpt.new({})
@option1.stubs(:eachopt)
@option1.stubs(:default?).returns false
@option2 = Puppet::Parser::AST::CaseOpt.new({})
@option2.stubs(:eachopt)
@option2.stubs(:default?).returns false
@options = Puppet::Parser::AST::ASTArray.new(:children => [@option1, @option2])
@casestmt = Puppet::Parser::AST::CaseStatement.new :test => @test, :options => @options
end
it "should evaluate test" do
@test.expects(:safeevaluate).with(@scope)
@casestmt.evaluate(@scope)
end
it "should scan each option" do
@casestmt.evaluate(@scope)
end
describe "when scanning options" do
before :each do
@opval1 = stub_everything 'opval1'
@option1.stubs(:eachopt).yields(@opval1)
@opval2 = stub_everything 'opval2'
@option2.stubs(:eachopt).yields(@opval2)
end
it "should evaluate each sub-option" do
@option1.expects(:eachopt)
@option2.expects(:eachopt)
@casestmt.evaluate(@scope)
end
it "should evaluate first matching option" do
@opval2.stubs(:evaluate_match).with { |*arg| arg[0] == "value" }.returns(true)
@option2.expects(:safeevaluate).with(@scope)
@casestmt.evaluate(@scope)
end
it "should return the first matching evaluated option" do
@opval2.stubs(:evaluate_match).with { |*arg| arg[0] == "value" }.returns(true)
@option2.stubs(:safeevaluate).with(@scope).returns(:result)
@casestmt.evaluate(@scope).should == :result
end
it "should evaluate the default option if none matched" do
@option1.stubs(:default?).returns(true)
@option1.expects(:safeevaluate).with(@scope)
@casestmt.evaluate(@scope)
end
it "should return the default evaluated option if none matched" do
@option1.stubs(:default?).returns(true)
@option1.stubs(:safeevaluate).with(@scope).returns(:result)
@casestmt.evaluate(@scope).should == :result
end
it "should return nil if nothing matched" do
@casestmt.evaluate(@scope).should be_nil
end
it "should match and set scope ephemeral variables" do
@opval1.expects(:evaluate_match).with { |*arg| arg[0] == "value" and arg[1] == @scope }
@casestmt.evaluate(@scope)
end
it "should evaluate this regex option if it matches" do
@opval1.stubs(:evaluate_match).with { |*arg| arg[0] == "value" and arg[1] == @scope }.returns(true)
@option1.expects(:safeevaluate).with(@scope)
@casestmt.evaluate(@scope)
end
it "should return this evaluated regex option if it matches" do
@opval1.stubs(:evaluate_match).with { |*arg| arg[0] == "value" and arg[1] == @scope }.returns(true)
@option1.stubs(:safeevaluate).with(@scope).returns(:result)
@casestmt.evaluate(@scope).should == :result
end
it "should unset scope ephemeral variables after option evaluation" do
@scope.stubs(:ephemeral_level).returns(:level)
@opval1.stubs(:evaluate_match).with { |*arg| arg[0] == "value" and arg[1] == @scope }.returns(true)
@option1.stubs(:safeevaluate).with(@scope).returns(:result)
@scope.expects(:unset_ephemeral_var).with(:level)
@casestmt.evaluate(@scope)
end
it "should not leak ephemeral variables even if evaluation fails" do
@scope.stubs(:ephemeral_level).returns(:level)
@opval1.stubs(:evaluate_match).with { |*arg| arg[0] == "value" and arg[1] == @scope }.returns(true)
@option1.stubs(:safeevaluate).with(@scope).raises
@scope.expects(:unset_ephemeral_var).with(:level)
lambda { @casestmt.evaluate(@scope) }.should raise_error
end
end
end
it "should match if any of the provided options evaluate as true" do
ast = nil
AST = Puppet::Parser::AST
tests = {
"one" => %w{a b c},
"two" => %w{e f g}
}
options = tests.collect do |result, values|
values = values.collect { |v| AST::Leaf.new :value => v }
AST::CaseOpt.new(
:value => AST::ASTArray.new(:children => values),
:statements => AST::Leaf.new(:value => result)
)
end
options << AST::CaseOpt.new(
:value => AST::Default.new(:value => "default"),
:statements => AST::Leaf.new(:value => "default")
)
ast = nil
param = AST::Variable.new(:value => "testparam")
ast = AST::CaseStatement.new(:test => param, :options => options)
tests.each do |should, values|
values.each do |value|
@scope = Puppet::Parser::Scope.new
@scope['testparam'] = value
result = ast.evaluate(@scope)
result.should == should
end
end
end
end
| 31.066667 | 107 | 0.617831 |
4aff75b3009c3c2be3117589fb31e44234ee7d57 | 164 | class CreateFreckles < ActiveRecord::Migration[6.0]
def change
create_table :freckles do |t|
t.integer :marker_id
t.timestamps
end
end
end
| 16.4 | 51 | 0.676829 |
91a404f7585a2bde9e7a728a42871052f2f3b3c6 | 773 | require "json"
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
Pod::Spec.new do |s|
s.name = "SnapchatLogin"
s.version = package["version"]
s.summary = package["description"]
s.description = <<-DESC
SnapchatLogin
DESC
s.homepage = "https://github.com/author/SnapchatLogin"
s.license = package["license"]
s.author = { "author" => package["author"]["email"], "name" => package["author"]["name"] }
s.platform = :ios, "10.0"
s.source = { :git => "https://github.com/author/SnapchatLogin.git", :tag => "#{s.version}" }
s.source_files = "ios/**/*.{h,m}"
s.requires_arc = true
s.dependency "React"
s.dependency "SnapSDK/SCSDKLoginKit", "1.6.7"
end
| 30.92 | 100 | 0.580854 |
f7a9285575f5fd1786d4bb9654fe7fce0136133d | 12,782 | # encoding: UTF-8
require 'csv'
module Sources
module Strategies
class Pixiv < Base
attr_reader :zip_url, :ugoira_frame_data, :ugoira_content_type
MONIKER = '(?:[a-zA-Z0-9_-]+)'
TIMESTAMP = '(?:[0-9]{4}/[0-9]{2}/[0-9]{2}/[0-9]{2}/[0-9]{2}/[0-9]{2})'
EXT = "(?:jpg|jpeg|png|gif)"
WEB = "^(?:https?://)?www\\.pixiv\\.net"
I12 = "^(?:https?://)?i[0-9]+\\.pixiv\\.net"
IMG = "^(?:https?://)?img[0-9]*\\.pixiv\\.net"
TOUCH = "^(?:https?://)?touch\\.pixiv\\.net"
def self.url_match?(url)
url =~ /#{WEB}|#{IMG}|#{I12}|#{TOUCH}/i
end
def referer_url
if @referer_url =~ /pixiv\.net\/member_illust.+mode=medium/ && @url =~ /#{IMG}|#{I12}/
@referer_url
else
@url
end
end
def site_name
"Pixiv"
end
def unique_id
@pixiv_moniker
end
def fake_referer
"http://www.pixiv.net"
end
def has_artist_commentary?
@artist_commentary_desc.present?
end
def normalized_for_artist_finder?
url =~ %r!https?://img\.pixiv\.net/img/#{MONIKER}/?$!i
end
def normalizable_for_artist_finder?
has_moniker? || sample_image? || full_image? || work_page?
end
def normalize_for_artist_finder!
if has_moniker?
moniker = get_moniker_from_url
else
@illust_id = illust_id_from_url!
@metadata = get_metadata_from_papi(@illust_id)
moniker = @metadata.moniker
end
"http://img.pixiv.net/img/#{moniker}/"
end
def get
return unless illust_id_from_url
@illust_id = illust_id_from_url
@metadata = get_metadata_from_papi(@illust_id)
page = agent.get(URI.parse(normalized_url))
if page.search("body.not-logged-in").any?
# Session cache is invalid, clear it and log in normally.
Cache.delete("pixiv-phpsessid")
@agent = nil
page = agent.get(URI.parse(normalized_url))
end
@artist_name, @profile_url = get_profile_from_page(page)
@pixiv_moniker = get_moniker_from_page(page)
@zip_url, @ugoira_frame_data, @ugoira_content_type = get_zip_url_from_page(page)
@tags = get_tags_from_page(page)
@page_count = get_page_count_from_page(page)
@artist_commentary_title = @metadata.artist_commentary_title
@artist_commentary_desc = @metadata.artist_commentary_desc
is_manga = @page_count > 1
if !@zip_url
@image_url = get_image_url_from_page(page, is_manga)
end
end
def rewrite_thumbnails(thumbnail_url, is_manga=nil)
thumbnail_url = rewrite_new_medium_images(thumbnail_url)
thumbnail_url = rewrite_medium_ugoiras(thumbnail_url)
thumbnail_url = rewrite_old_small_and_medium_images(thumbnail_url, is_manga)
return thumbnail_url
end
def agent
@agent ||= PixivWebAgent.build
end
def file_url
image_url || zip_url
end
def image_urls
@metadata.pages
end
def illust_id_from_url
if sample_image? || full_image? || work_page?
illust_id_from_url!
else
nil
end
rescue Sources::Error
nil
end
def illust_id_from_url!
# http://img18.pixiv.net/img/evazion/14901720.png
#
# http://i2.pixiv.net/img18/img/evazion/14901720.png
# http://i2.pixiv.net/img18/img/evazion/14901720_m.png
# http://i2.pixiv.net/img18/img/evazion/14901720_s.png
# http://i1.pixiv.net/img07/img/pasirism/18557054_p1.png
# http://i1.pixiv.net/img07/img/pasirism/18557054_big_p1.png
#
# http://i1.pixiv.net/img-inf/img/2011/05/01/23/28/04/18557054_64x64.jpg
# http://i1.pixiv.net/img-inf/img/2011/05/01/23/28/04/18557054_s.png
#
# http://i1.pixiv.net/c/600x600/img-master/img/2014/10/02/13/51/23/46304396_p0_master1200.jpg
# http://i1.pixiv.net/img-original/img/2014/10/02/13/51/23/46304396_p0.png
#
# http://i1.pixiv.net/img-zip-ugoira/img/2014/10/03/17/29/16/46323924_ugoira1920x1080.zip
if url =~ %r!/(\d+)(?:_\w+)?\.(?:jpg|jpeg|png|gif|zip)!i
$1
# http://www.pixiv.net/member_illust.php?mode=medium&illust_id=18557054
# http://www.pixiv.net/member_illust.php?mode=big&illust_id=18557054
# http://www.pixiv.net/member_illust.php?mode=manga&illust_id=18557054
# http://www.pixiv.net/member_illust.php?mode=manga_big&illust_id=18557054&page=1
elsif url =~ /illust_id=(\d+)/i
$1
# http://www.pixiv.net/i/18557054
elsif url =~ %r!pixiv\.net/i/(\d+)!i
$1
else
raise Sources::Error.new("Couldn't get illust ID from URL: #{url}")
end
end
# http://i1.pixiv.net/c/600x600/img-master/img/2014/10/02/13/51/23/46304396_p1_master1200.jpg
# => http://i1.pixiv.net/img-original/img/2014/10/02/13/51/23/46304396_p1.png
def rewrite_new_medium_images(thumbnail_url)
if thumbnail_url =~ %r!/c/\d+x\d+/img-master/img/#{TIMESTAMP}/\d+_p\d+_\w+\.jpg!i
page = manga_page_from_url(@url).to_i
thumbnail_url = @metadata.pages[page]
end
thumbnail_url
end
# http://i3.pixiv.net/img-zip-ugoira/img/2014/12/03/04/58/24/47378698_ugoira600x600.zip
# => http://i3.pixiv.net/img-zip-ugoira/img/2014/12/03/04/58/24/47378698_ugoira1920x1080.zip
def rewrite_medium_ugoiras(thumbnail_url)
if thumbnail_url =~ %r!/img-zip-ugoira/img/.*/\d+_ugoira600x600.zip!i
thumbnail_url = thumbnail_url.sub("_ugoira600x600.zip", "_ugoira1920x1080.zip")
end
thumbnail_url
end
# If the thumbnail is for a manga gallery, it needs to be rewritten like this:
#
# http://i2.pixiv.net/img18/img/evazion/14901720_m.png
# => http://i2.pixiv.net/img18/img/evazion/14901720_big_p0.png
#
# Otherwise, it needs to be rewritten like this:
#
# http://i2.pixiv.net/img18/img/evazion/14901720_m.png
# => http://i2.pixiv.net/img18/img/evazion/14901720.png
#
def rewrite_old_small_and_medium_images(thumbnail_url, is_manga)
if thumbnail_url =~ %r!/img/#{MONIKER}/\d+_[ms]\.#{EXT}!i
if is_manga.nil?
page_count = @metadata.page_count
is_manga = page_count > 1
end
if is_manga
page = manga_page_from_url(@url)
return thumbnail_url.sub(/_[ms]\./, "_big_p#{page}.")
else
return thumbnail_url.sub(/_[ms]\./, ".")
end
end
return thumbnail_url
end
def manga_page_from_url(url)
# http://i2.pixiv.net/img04/img/syounen_no_uta/46170939_p0.jpg
# http://i1.pixiv.net/c/600x600/img-master/img/2014/09/24/23/25/08/46168376_p0_master1200.jpg
# http://i1.pixiv.net/img-original/img/2014/09/25/23/09/29/46183440_p0.jpg
if url =~ %r!/\d+_p(\d+)(?:_\w+)?\.#{EXT}!i
$1
# http://www.pixiv.net/member_illust.php?mode=manga_big&illust_id=46170939&page=0
elsif url =~ /page=(\d+)/i
$1
else
0
end
end
def get_profile_from_page(page)
profile_url = page.search("a.user-link").first
if profile_url
profile_url = "http://www.pixiv.net" + profile_url["href"]
end
artist_name = page.search("h1.user").first
if artist_name
artist_name = artist_name.inner_text
end
return [artist_name, profile_url]
end
def get_moniker_from_page(page)
# <a class="tab-feed" href="/stacc/gennmai-226">Feed</a>
stacc_link = page.search("a.tab-feed").first
if not stacc_link.nil?
stacc_link.attr("href").sub(%r!^/stacc/!i, '')
end
end
def get_moniker_from_url
case url
when %r!#{IMG}/img/(#{MONIKER})!i
$1
when %r!#{I12}/img[0-9]+/img/(#{MONIKER})!i
$1
when %r!#{WEB}/stacc/(#{MONIKER})/?$!i
$1
else
false
end
end
def has_moniker?
get_moniker_from_url != false
end
def get_image_url_from_page(page, is_manga)
if is_manga
elements = page.search("div.works_display a img").find_all do |node|
node["src"] !~ /source\.pixiv\.net/
end
else
elements = page.search("div.works_display div img.big")
elements = page.search("div.works_display div img") if elements.empty?
end
if elements.any?
element = elements.first
thumbnail_url = element.attr("src") || element.attr("data-src")
return rewrite_thumbnails(thumbnail_url, is_manga)
end
end
def get_zip_url_from_page(page)
scripts = page.search("body script").find_all do |node|
node.text =~ /_ugoira600x600\.zip/
end
if scripts.any?
javascript = scripts.first.text
json = javascript.match(/;pixiv\.context\.ugokuIllustData\s+=\s+(\{.+?\});(?:$|pixiv\.context)/)[1]
data = JSON.parse(json)
zip_url = data["src"].sub("_ugoira600x600.zip", "_ugoira1920x1080.zip")
frame_data = data["frames"]
content_type = data["mime_type"]
return [zip_url, frame_data, content_type]
end
end
def get_tags_from_page(page)
# puts page.root.to_xhtml
links = page.search("ul.tags a.text").find_all do |node|
node["href"] =~ /search\.php/
end
original_flag = page.search("a.original-works")
if links.any?
links.map! do |node|
[node.inner_text, "http://www.pixiv.net" + node.attr("href")]
end
if original_flag.any?
links << ["オリジナル", "http://www.pixiv.net/search.php?s_mode=s_tag_full&word=%E3%82%AA%E3%83%AA%E3%82%B8%E3%83%8A%E3%83%AB"]
end
links
else
[]
end
end
def get_page_count_from_page(page)
elements = page.search("ul.meta li").find_all do |node|
node.text =~ /Manga|漫画|複数枚投稿|Multiple images/
end
if elements.any?
elements[0].text =~ /(?:Manga|漫画|複数枚投稿|Multiple images):? (\d+)P/
$1.to_i
else
1
end
end
def normalized_url
"http://www.pixiv.net/member_illust.php?mode=medium&illust_id=#{@illust_id}"
end
def get_metadata_from_papi(illust_id)
@metadata ||= PixivApiClient.new.works(illust_id)
end
def work_page?
return true if url =~ %r!(?:#{WEB}|#{TOUCH})/member_illust\.php\?mode=(?:medium|big|manga|manga_big)&illust_id=\d+!i
return true if url =~ %r!(?:#{WEB}|#{TOUCH})/i/\d+$!i
return false
end
def full_image?
# http://img18.pixiv.net/img/evazion/14901720.png?1234
return true if url =~ %r!#{IMG}/img/#{MONIKER}/\d+(?:_big_p\d+)?\.#{EXT}!i
# http://i2.pixiv.net/img18/img/evazion/14901720.png
# http://i1.pixiv.net/img07/img/pasirism/18557054_big_p1.png
return true if url =~ %r!#{I12}/img\d+/img/#{MONIKER}/\d+(?:_big_p\d+)?\.#{EXT}!i
# http://i1.pixiv.net/img-original/img/2014/10/02/13/51/23/46304396_p0.png
return true if url =~ %r!#{I12}/img-original/img/#{TIMESTAMP}/\d+_p\d+\.#{EXT}$!i
# http://i1.pixiv.net/img-zip-ugoira/img/2014/10/03/17/29/16/46323924_ugoira1920x1080.zip
return true if url =~ %r!#{I12}/img-zip-ugoira/img/#{TIMESTAMP}/\d+_ugoira\d+x\d+\.zip$!i
return false
end
def sample_image?
# http://img18.pixiv.net/img/evazion/14901720_m.png
return true if url =~ %r!#{IMG}/img/#{MONIKER}/\d+_(?:[sm]|p\d+)\.#{EXT}!i
# http://i2.pixiv.net/img18/img/evazion/14901720_m.png
# http://i1.pixiv.net/img07/img/pasirism/18557054_p1.png
return true if url =~ %r!#{I12}/img\d+/img/#{MONIKER}/\d+_(?:[sm]|p\d+)\.#{EXT}!i
# http://i1.pixiv.net/c/600x600/img-master/img/2014/10/02/13/51/23/46304396_p0_master1200.jpg
# http://i2.pixiv.net/c/64x64/img-master/img/2014/10/09/12/59/50/46441917_square1200.jpg
return true if url =~ %r!#{I12}/c/\d+x\d+/img-master/img/#{TIMESTAMP}/\d+_\w+\.#{EXT}$!i
# http://i1.pixiv.net/img-inf/img/2011/05/01/23/28/04/18557054_s.png
# http://i2.pixiv.net/img-inf/img/2010/11/30/08/54/06/14901765_64x64.jpg
return true if url =~ %r!#{I12}/img-inf/img/#{TIMESTAMP}/\d+_\w+\.#{EXT}!i
return false
end
end
end
end
| 32.858612 | 134 | 0.588171 |
03140dee52fb806623e7cb196903803aa8b0d5de | 414 | require 'spec_helper'
# docker package should be installed when a repository is enabled
describe package('docker-engine') do
it { should be_installed }
end
# docker package should be installed from the docker-experimental repo
describe command('apt-cache madison docker-engine') do
its(:stdout) { should contain('https://apt.dockerproject.org/repo/') }
its(:stdout) { should contain('/experimental') }
end
| 31.846154 | 72 | 0.758454 |
39a4911b443804c4cba5806bfaad8b284a0fc6f1 | 378 | T1, T2 = gets.chomp.split(" ").map(&:to_i)
A1, A2 = gets.chomp.split(" ").map(&:to_i)
B1, B2 = gets.chomp.split(" ").map(&:to_i)
R1 = A1 - B1
R2 = A2 - B2
DR1 = R1 * T1
DR2 = R2 * T2
DR = DR1 + DR2
if DR.zero?
puts "infinity"
exit
end
if DR1 * DR > 0
puts 0
exit
end
n, m = DR1.divmod(DR)
if m.zero?
puts 1 + (n.abs - 1) * 2 + 1
else
puts 1 + (n.abs - 1) * 2
end
| 14.538462 | 42 | 0.544974 |
7a5c7a61ed31f6f2bac080d65be7eb741d62470f | 9,981 | # encoding: UTF-8
#
# Copyright (c) 2010-2017 GoodData Corporation. All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
require_relative '../metadata'
require_relative 'metadata'
module GoodData
class Report < GoodData::MdObject
include Mixin::Lockable
class << self
# Method intended to get all objects of that type in a specified project
#
# @param options [Hash] the options hash
# @option options [Boolean] :full if passed true the subclass can decide
# to pull in full objects. This is desirable from the usability POV
# but unfortunately has negative impact on performance so it is not
# the default.
# @return [Array<GoodData::MdObject> | Array<Hash>] Return the appropriate metadata objects or their representation
def all(options = { :client => GoodData.connection, :project => GoodData.project })
query('report', Report, options)
end
def create(options = { :client => GoodData.connection, :project => GoodData.project })
client, project = GoodData.get_client_and_project(options)
title = options[:title]
fail 'Report needs a title specified' unless title
summary = options[:summary] || ''
options_rd = options.dup
options_rd.delete(:identifier)
rd = options[:rd] || ReportDefinition.create(options_rd)
rd.save
report = {
'report' => {
'content' => {
'domains' => [],
'definitions' => [rd.uri]
},
'meta' => {
'tags' => '',
'deprecated' => '0',
'summary' => summary,
'title' => title
}
}
}
# TODO: write test for report definitions with explicit identifiers
report['report']['meta']['identifier'] = options[:identifier] if options[:identifier]
client.create(Report, report, :project => project)
end
def data_result(result, options = {})
client = options[:client]
data_result_uri = result['execResult']['dataResult']
begin
result = client.poll_on_response(data_result_uri, options) do |body|
body && body['taskState'] && body['taskState']['status'] == 'WAIT'
end
rescue RestClient::BadRequest => e
resp = JSON.parse(e.response)
if GoodData::Helpers.get_path(resp, %w(error component)) == 'MD::DataResult'
raise GoodData::UncomputableReport
else
raise e
end
end
if result.to_s.empty?
ReportDataResult.new(data: [], top: 0, left: 0)
else
ReportDataResult.from_xtab(result)
end
end
end
# Add a report definition to a report. This will show on a UI as a new version.
#
# @param report_definition [GoodData::ReportDefinition | String] Report definition to add. Either it can be a URI of a report definition or an actual report definition object.
# @return [GoodData::Report] Return self
def add_definition(report_definition)
rep_def = project.report_definitions(report_definition)
content['definitions'] = definition_uris << rep_def.uri
self
end
# Add a report definition to a report. This will show on a UI as a new version.
#
# @param report_definition [GoodData::ReportDefinition | String] Report definition to add. Either it can be a URI of a report definition or an actual report definition object.
# @return [GoodData::Report] Return self
def add_definition!(report_definition)
res = add_definition(report_definition)
res.save
end
# Returns the newest (current version) report definition as an object
#
# @return [GoodData::ReportDefinition] Returns the newest report defintion
def definition
project.report_definitions(latest_report_definition_uri)
end
alias_method :latest_report_definition, :definition
# Returns the newest (current version) report definition uri
#
# @return [String] Returns uri of the newest report defintion
def definition_uri
definition_uris.last
end
alias_method :latest_report_definition_uri, :definition_uri
# Gets a report definitions (versions) of this report as objects.
#
# @return [Array<GoodData::ReportDefinition>] Returns list of report definitions. Oldest comes first
def definitions
content['definitions'].pmap { |uri| project.report_definitions(uri) }
end
alias_method :report_definitions, :definitions
# Gets list of uris of report definitions (versions) of this report.
#
# @return [Array<String>] Returns list of report definitions' uris. Oldest comes first
def definition_uris
content['definitions']
end
# Deletes report along with its report definitions.
#
# @return [GoodData::Report] Returns self
def delete
defs = definitions
super
defs.peach(&:delete)
self
end
# Computes the report and returns the result. If it is not computable returns nil.
#
# @option options [Time] :time Force the platform to simutale the result at this time
# @return [GoodData::DataResult] Returns the result
def execute(options = {})
time = options[:time]
report_req = { 'report' => uri }
report_req['timestamp'] = time.to_i if time
fail 'You have to save the report before executing. If you do not want to do that please use GoodData::ReportDefinition' unless saved?
result = client.post "/gdc/projects/#{project.pid}/execute", 'report_req' => report_req
GoodData::Report.data_result(result, options.merge(client: client))
end
# Returns true if you can export and object
#
# @return [Boolean] Returns whether the report is exportable
def exportable?
true
end
# Returns binary data of the exported report in a given format. The format can be
# either 'csv', 'xls', 'xlsx' or 'pdf'.
#
# @return [String] Returns data
def export(format, options = {})
result = client.post("/gdc/projects/#{project.pid}/execute", 'report_req' => { 'report' => uri })
result1 = client.post('/gdc/exporter/executor', :result_req => { :format => format, :result => result })
client.poll_on_code(result1['uri'], options.merge(process: false))
end
# Exports a report too large to be computed on the UI. It executes in raw form.
# Saves the result into file.
#
# @param filename [String] Filename to save into
# @return [Net::HTTPResponse] Returns HTTP status
def export_raw(filename)
result = client.post("/gdc/app/projects/#{project.pid}/execute/raw", 'report_req' => { 'report' => uri })
client.download(result['uri'], filename, url_encode: false)
end
# Returns the newest (current version) report definition uri
#
# @return [String] Returns uri of the newest report defintion
def purge_report_of_unused_definitions!
full_list = definition_uris
remove_definition_but_latest
purged_list = definition_uris
to_remove = full_list - purged_list
save
to_remove.each { |uri| client.delete(uri) }
self
end
# Removes definition from the report. The definition to remove can be passed in any form that is accepted by
# GoodData::ReportDefintion[]
#
# @param definition [String | GoodData::ReportDefinition] Report defintion to remove
# @return [GoodData::Report] Returns report with removed definition
def remove_definition(definition)
a_def = GoodData::ReportDefinition[definition, project: project, client: client]
def_uri = a_def.uri
content['definitions'] = definition_uris.reject { |x| x == def_uri }
self
end
# TODO: Cover with test. You would probably need something that will be able to create a report easily from a definition
# Removes all definitions but the latest from the report. This is useful for cleaning up before you create
# a template out of a project.
#
# @return [GoodData::Report] Returns report with removed definitions
def remove_definition_but_latest
to_remove = definition_uris - [latest_report_definition_uri]
to_remove.each do |uri|
remove_definition(uri)
end
self
end
# Method used for replacing values in their state according to mapping.
# Can be used to replace any values but it is typically used to replace
# the URIs. Returns a new object of the same type.
#
# @param [Array<Array>]Mapping specifying what should be exchanged for what. As mapping should be used output of GoodData::Helpers.prepare_mapping.
# @return [GoodData::Report]
def replace(mapping)
new_defs = definitions.map do |rep_def|
rep_def.replace(mapping)
end
new_defs.pmap(&:save)
self
end
## Update report definition and reflect the change in report
#
# @param [Hash] opts Options
# @option opts [Boolean] :new_definition (true) If true then new definition will be created
# @return [GoodData::ReportDefinition] Updated and saved report definition
def update_definition(opts = { :new_definition => true }, &block)
# TODO: Cache the latest report definition somehow
repdef = definition.dup
block.call(repdef, self) if block_given?
if opts[:new_definition]
new_def = GoodData::ReportDefinition.create(:client => client, :project => project)
rd = repdef.json['reportDefinition']
rd.delete('links')
%w(author uri created identifier updated contributor).each { |k| rd['meta'].delete(k) }
new_def.json['reportDefinition'] = rd
new_def.save
add_definition!(new_def)
return new_def
else
repdef.save
end
repdef
end
end
end
| 37.104089 | 179 | 0.661156 |
5defe0375c60302fbaf178436e39a41b375c612a | 1,316 | # -*- encoding: utf-8 -*-
# stub: formatador 0.2.5 ruby lib
Gem::Specification.new do |s|
s.name = "formatador".freeze
s.version = "0.2.5"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["geemus (Wesley Beary)".freeze]
s.date = "2014-05-23"
s.description = "STDOUT text formatting".freeze
s.email = "[email protected]".freeze
s.extra_rdoc_files = ["README.rdoc".freeze]
s.files = ["README.rdoc".freeze]
s.homepage = "http://github.com/geemus/formatador".freeze
s.rdoc_options = ["--charset=UTF-8".freeze]
s.rubygems_version = "3.0.2".freeze
s.summary = "Ruby STDOUT text formatting".freeze
s.installed_by_version = "3.0.2" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 2
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<rake>.freeze, [">= 0"])
s.add_development_dependency(%q<shindo>.freeze, [">= 0"])
else
s.add_dependency(%q<rake>.freeze, [">= 0"])
s.add_dependency(%q<shindo>.freeze, [">= 0"])
end
else
s.add_dependency(%q<rake>.freeze, [">= 0"])
s.add_dependency(%q<shindo>.freeze, [">= 0"])
end
end
| 34.631579 | 112 | 0.664134 |
d53126a0f5a54f6888e9e32f5cd74993a388f6a3 | 16,396 | Pod::Spec.new do |s|
s.name = "QMUIKit"
s.version = "4.4.2"
s.summary = "致力于提高项目 UI 开发效率的解决方案"
s.description = <<-DESC
QMUI iOS 是一个致力于提高项目 UI 开发效率的解决方案,其设计目的是用于辅助快速搭建一个具备基本设计还原效果的 iOS 项目,同时利用自身提供的丰富控件及兼容处理, 让开发者能专注于业务需求而无需耗费精力在基础代码的设计上。不管是新项目的创建,或是已有项目的维护,均可使开发效率和项目质量得到大幅度提升。
DESC
s.homepage = "https://qmuiteam.com/ios"
s.license = 'MIT'
s.author = {"qmuiteam" => "[email protected]"}
s.source = {:git => "https://github.com/Tencent/QMUI_iOS.git", :tag => s.version.to_s}
#s.source = {:git => "https://github.com/Tencent/QMUI_iOS.git", :branch => 'master'}
s.social_media_url = 'https://github.com/Tencent/QMUI_iOS'
s.requires_arc = true
s.documentation_url = 'https://qmuiteam.com/ios/page/document.html'
s.screenshot = 'https://cloud.githubusercontent.com/assets/1190261/26751376/63f96538-486a-11e7-81cf-5bc83a945207.png'
s.platform = :ios, '11.0'
s.frameworks = 'Foundation', 'UIKit', 'CoreGraphics'
s.preserve_paths = 'QMUIConfigurationTemplate/*'
s.source_files = 'QMUIKit/QMUIKit.h'
s.pod_target_xcconfig = { 'SWIFT_COMPILATION_MODE' => 'wholemodule' }
s.subspec 'QMUICore' do |ss|
ss.source_files = 'QMUIKit/QMUIKit.h', 'QMUIKit/QMUICore', 'QMUIKit/UIKitExtensions'
ss.frameworks = 'CoreImage', 'ImageIO'
ss.dependency 'QMUIKit/QMUIWeakObjectContainer'
ss.dependency 'QMUIKit/QMUILog'
end
s.subspec 'QMUIMainFrame' do |ss|
ss.source_files = 'QMUIKit/QMUIMainFrame'
ss.dependency 'QMUIKit/QMUICore'
ss.dependency 'QMUIKit/QMUIComponents/QMUINavigationTitleView'
ss.dependency 'QMUIKit/QMUIComponents/QMUITableView'
ss.dependency 'QMUIKit/QMUIComponents/QMUITableViewHeaderFooterView'
ss.dependency 'QMUIKit/QMUIComponents/QMUIEmptyView'
ss.dependency 'QMUIKit/QMUIComponents/QMUIKeyboardManager'
ss.dependency 'QMUIKit/QMUILog'
ss.dependency 'QMUIKit/QMUIComponents/QMUIMultipleDelegates'
end
s.subspec 'QMUIResources' do |ss|
ss.resource_bundles = {'QMUIResources' => ['QMUIKit/QMUIResources/*.*']}
end
s.subspec 'QMUIWeakObjectContainer' do |ss|
ss.source_files = 'QMUIKit/QMUIComponents/QMUIWeakObjectContainer.{h,m}'
end
s.subspec 'QMUILog' do |ss|
ss.source_files = 'QMUIKit/QMUIComponents/QMUILog/*.{h,m}'
end
s.subspec 'QMUIComponents' do |ss|
ss.dependency 'QMUIKit/QMUICore'
ss.subspec 'QMUICAAnimationExtension' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/CAAnimation+QMUI.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIMultipleDelegates'
end
ss.subspec 'QMUICALayerExtension' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/CALayer+QMUIViewAnimation.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIMultipleDelegates'
end
ss.subspec 'QMUIAnimation' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIAnimation'
end
ss.subspec 'QMUINavigationTitleView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUINavigationTitleView.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAppearance'
end
ss.subspec 'QMUIButton' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIButton/QMUIButton.{h,m}'
end
ss.subspec 'QMUINavigationButton' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIButton/QMUINavigationButton.{h,m}'
sss.dependency 'QMUIKit/QMUIMainFrame'
end
ss.subspec 'QMUIToolbarButton' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIButton/QMUIToolbarButton.{h,m}'
end
ss.subspec 'QMUITableView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUITableView.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUITableViewProtocols'
end
ss.subspec 'QMUITableViewProtocols' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUITableViewProtocols.{h,m}'
end
ss.subspec 'QMUIEmptyView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIEmptyView.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAppearance'
end
ss.subspec 'QMUILabel' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUILabel.{h,m}'
end
ss.subspec 'QMUIKeyboardManager' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIKeyboardManager.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAppearance'
sss.dependency 'QMUIKit/QMUIComponents/QMUIMultipleDelegates'
end
# 从这里开始就是非必须的组件
ss.subspec 'QMUIMultipleDelegates' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIMultipleDelegates/*.{h,m}'
end
ss.subspec 'QMUIAlertController' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIAlertController.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIModalPresentationViewController'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
sss.dependency 'QMUIKit/QMUIComponents/QMUITextField'
sss.dependency 'QMUIKit/QMUIComponents/QMUIKeyboardManager'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAppearance'
sss.dependency 'QMUIKit/QMUIComponents/QMUILabel'
end
ss.subspec 'QMUIAppearance' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIAppearance.{h,m}'
end
ss.subspec 'QMUICellHeightCache' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUICellHeightCache.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUITableViewProtocols'
end
ss.subspec 'QMUICellHeightKeyCache' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUICellHeightKeyCache/*.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUITableViewProtocols'
sss.dependency 'QMUIKit/QMUIComponents/QMUIMultipleDelegates'
end
ss.subspec 'QMUICellSizeKeyCache' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUICellSizeKeyCache/*.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIMultipleDelegates'
end
ss.subspec 'QMUIConsole' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIConsole/*.{h,m}'
sss.dependency 'QMUIKit/QMUIResources'
sss.dependency 'QMUIKit/QMUIComponents/QMUITextView'
sss.dependency 'QMUIKit/QMUIComponents/QMUITextField'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
sss.dependency 'QMUIKit/QMUIComponents/QMUITableView'
sss.dependency 'QMUIKit/QMUIComponents/QMUITableViewCell'
sss.dependency 'QMUIKit/QMUIComponents/QMUICellHeightKeyCache'
sss.dependency 'QMUIKit/QMUIComponents/QMUIPopupMenuView'
sss.dependency 'QMUIKit/QMUIComponents/QMUICAAnimationExtension'
end
ss.subspec 'QMUICollectionViewPagingLayout' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUICollectionViewPagingLayout.{h,m}'
end
ss.subspec 'QMUIDialogViewController' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIDialogViewController.{h,m}'
sss.dependency 'QMUIKit/QMUIMainFrame'
sss.dependency 'QMUIKit/QMUIComponents/QMUILabel'
sss.dependency 'QMUIKit/QMUIComponents/QMUIModalPresentationViewController'
sss.dependency 'QMUIKit/QMUIComponents/QMUITableView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
sss.dependency 'QMUIKit/QMUIComponents/QMUITextField'
sss.dependency 'QMUIKit/QMUIComponents/QMUITableViewCell'
sss.dependency 'QMUIKit/QMUIComponents/QMUINavigationTitleView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAppearance'
end
ss.subspec 'QMUIEmotionView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIEmotionView.{h,m}'
sss.dependency 'QMUIKit/QMUIResources'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
end
ss.subspec 'QMUIFloatLayoutView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIFloatLayoutView.{h,m}'
end
ss.subspec 'QMUIGridView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIGridView.{h,m}'
end
ss.subspec 'QMUIImagePreviewView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIImagePreviewView/*.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIZoomImageView'
sss.dependency 'QMUIKit/QMUIComponents/QMUICollectionViewPagingLayout'
sss.dependency 'QMUIKit/QMUIComponents/QMUIEmptyView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIPieProgressView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAppearance'
sss.dependency 'QMUIKit/QMUIMainFrame'
end
ss.subspec 'QMUIMarqueeLabel' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIMarqueeLabel.{h,m}'
end
ss.subspec 'QMUIModalPresentationViewController' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIModalPresentationViewController.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIKeyboardManager'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAppearance'
end
ss.subspec 'QMUIMoreOperationController' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIMoreOperationController.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIModalPresentationViewController'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAppearance'
end
ss.subspec 'QMUIOrderedDictionary' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIOrderedDictionary.{h,m}'
end
ss.subspec 'QMUIPieProgressView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIPieProgressView.{h,m}'
end
ss.subspec 'QMUIPopupContainerView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIPopupContainerView.{h,m}'
sss.dependency 'QMUIKit/QMUIMainFrame'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAppearance'
end
ss.subspec 'QMUIPopupMenuView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIPopupMenuView/*.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
sss.dependency 'QMUIKit/QMUIComponents/QMUIPopupContainerView'
end
ss.subspec 'QMUIScrollAnimator' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIScrollAnimator/*.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIMultipleDelegates'
end
ss.subspec 'QMUIEmotionInputManager' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIEmotionInputManager.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIEmotionView'
end
ss.subspec 'QMUISearchBar' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUISearchBar.{h,m}'
end
ss.subspec 'QMUISearchController' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUISearchController.{h,m}'
sss.dependency 'QMUIKit/QMUIMainFrame'
sss.dependency 'QMUIKit/QMUIComponents/QMUISearchBar'
sss.dependency 'QMUIKit/QMUIComponents/QMUIEmptyView'
end
ss.subspec 'QMUISegmentedControl' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUISegmentedControl.{h,m}'
end
ss.subspec 'QMUITableViewCell' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUITableViewCell.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
end
ss.subspec 'QMUITableViewHeaderFooterView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUITableViewHeaderFooterView.{h,m}'
end
ss.subspec 'QMUITestView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUITestView.{h,m}'
end
ss.subspec 'QMUITextField' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUITextField.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIMultipleDelegates'
end
ss.subspec 'QMUITextView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUITextView.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUILabel'
sss.dependency 'QMUIKit/QMUIComponents/QMUIMultipleDelegates'
end
ss.subspec 'QMUITheme' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUITheme/*.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIImagePickerLibrary'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAlertController'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
sss.dependency 'QMUIKit/QMUIComponents/QMUIConsole'
sss.dependency 'QMUIKit/QMUIComponents/QMUIEmotionView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIEmptyView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIGridView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIImagePreviewView'
sss.dependency 'QMUIKit/QMUIComponents/QMUILabel'
sss.dependency 'QMUIKit/QMUIComponents/QMUIPopupContainerView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIPopupMenuView'
sss.dependency 'QMUIKit/QMUIComponents/QMUITextField'
sss.dependency 'QMUIKit/QMUIComponents/QMUITextView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIToastView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIModalPresentationViewController'
sss.dependency 'QMUIKit/QMUIComponents/QMUIBadge'
end
ss.subspec 'QMUITips' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUITips.{h,m}'
sss.dependency 'QMUIKit/QMUIResources'
sss.dependency 'QMUIKit/QMUIComponents/QMUIToastView'
end
ss.subspec 'QMUIWindowSizeMonitor' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIWindowSizeMonitor.{h,m}'
end
ss.subspec 'QMUIZoomImageView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIZoomImageView.{h,m}'
sss.frameworks = 'PhotosUI', 'CoreMedia', 'AVFoundation', 'QuartzCore'
sss.dependency 'QMUIKit/QMUIResources'
sss.dependency 'QMUIKit/QMUIComponents/QMUIEmptyView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
sss.dependency 'QMUIKit/QMUIComponents/QMUIPieProgressView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAssetLibrary'
end
ss.subspec 'QMUIAssetLibrary' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/AssetLibrary/*.{h,m}'
sss.frameworks = 'Photos', 'CoreServices'
end
ss.subspec 'QMUIImagePickerLibrary' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/ImagePickerLibrary/*.{h,m}'
sss.dependency 'QMUIKit/QMUIMainFrame'
sss.dependency 'QMUIKit/QMUIResources'
sss.dependency 'QMUIKit/QMUIComponents/QMUIImagePreviewView'
sss.dependency 'QMUIKit/QMUIComponents/QMUITableViewCell'
sss.dependency 'QMUIKit/QMUIComponents/QMUIButton'
sss.dependency 'QMUIKit/QMUIComponents/QMUINavigationButton'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAssetLibrary'
sss.dependency 'QMUIKit/QMUIComponents/QMUIZoomImageView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAlertController'
sss.dependency 'QMUIKit/QMUIComponents/QMUIEmptyView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIAppearance'
end
ss.subspec 'QMUILogManagerViewController' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUILogManagerViewController.{h,m}'
sss.dependency 'QMUIKit/QMUIMainFrame'
sss.dependency 'QMUIKit/QMUIComponents/QMUIStaticTableView'
sss.dependency 'QMUIKit/QMUIComponents/QMUITableView'
sss.dependency 'QMUIKit/QMUIComponents/QMUIPopupMenuView'
sss.dependency 'QMUIKit/QMUIComponents/QMUISearchController'
end
ss.subspec 'QMUILogWithConfigurationSupported' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUILogger+QMUIConfigurationTemplate.{h,m}'
end
ss.subspec 'NavigationBarTransition' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/NavigationBarTransition/*.{h,m}'
sss.dependency 'QMUIKit/QMUIMainFrame'
sss.dependency 'QMUIKit/QMUIComponents/QMUINavigationTitleView'
end
ss.subspec 'QMUIBadge' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/QMUIBadge/*.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUILabel'
end
ss.subspec 'QMUIToastView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/ToastView/*.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUIKeyboardManager'
end
ss.subspec 'QMUIStaticTableView' do |sss|
sss.source_files = 'QMUIKit/QMUIComponents/StaticTableView/*.{h,m}'
sss.dependency 'QMUIKit/QMUIComponents/QMUITableViewCell'
sss.dependency 'QMUIKit/QMUIComponents/QMUIMultipleDelegates'
end
end
end
| 41.720102 | 180 | 0.738778 |
abe39e82d058cf814e259130eeb2d6b70e4c7354 | 9,522 | require 'rexml/document'
module ActiveMerchant #:nodoc:
module Billing #:nodoc:
class VerifiGateway < Gateway
class VerifiPostData < PostData
# Fields that will be sent even if they are blank
self.required_fields = [ :amount, :type, :ccnumber, :ccexp, :firstname, :lastname,
:company, :address1, :address2, :city, :state, :zip, :country, :phone ]
end
URL = 'https://secure.verifi.com/gw/api/transact.php'
RESPONSE_CODE_MESSAGES = {
"100" => "Transaction was Approved",
"200" => "Transaction was Declined by Processor",
"201" => "Do Not Honor",
"202" => "Insufficient Funds",
"203" => "Over Limit",
"204" => "Transaction not allowed",
"220" => "Incorrect payment Data",
"221" => "No Such Card Issuer",
"222" => "No Card Number on file with Issuer",
"223" => "Expired Card",
"224" => "Invalid Expiration Date",
"225" => "Invalid Card Security Code",
"240" => "Call Issuer for Further Information",
"250" => "Pick Up Card",
"251" => "Lost Card",
"252" => "Stolen Card",
"253" => "Fraudulent Card",
"260" => "Declined With further Instructions Available (see response text)",
"261" => "Declined - Stop All Recurring Payments",
"262" => "Declined - Stop this Recurring Program",
"263" => "Declined - Update Cardholder Data Available",
"264" => "Declined - Retry in a few days",
"300" => "Transaction was Rejected by Gateway",
"400" => "Transaction Error Returned by Processor",
"410" => "Invalid Merchant Configuration",
"411" => "Merchant Account is Inactive",
"420" => "Communication Error",
"421" => "Communication Error with Issuer",
"430" => "Duplicate Transaction at Processor",
"440" => "Processor Format Error",
"441" => "Invalid Transaction Information",
"460" => "Processor Feature Not Available",
"461" => "Unsupported Card Type"
}
SUCCESS = 1
TRANSACTIONS = {
:authorization => 'auth',
:purchase => 'sale',
:capture => 'capture',
:void => 'void',
:credit => 'credit',
:refund => 'refund'
}
self.supported_countries = ['US']
self.supported_cardtypes = [:visa, :master, :american_express, :discover]
self.homepage_url = 'http://www.verifi.com/'
self.display_name = 'Verifi'
def initialize(options = {})
requires!(options, :login, :password)
@options = options
super
end
def purchase(money, credit_card, options = {})
sale_authorization_or_credit_template(:purchase, money, credit_card, options)
end
def authorize(money, credit_card, options = {})
sale_authorization_or_credit_template(:authorization, money, credit_card, options)
end
def capture(money, authorization, options = {})
capture_void_or_refund_template(:capture, money, authorization, options)
end
def void(authorization, options = {})
capture_void_or_refund_template(:void, 0, authorization, options)
end
def credit(money, credit_card_or_authorization, options = {})
if credit_card_or_authorization.is_a?(String)
capture_void_or_refund_template(:refund, money, credit_card_or_authorization, options)
else
sale_authorization_or_credit_template(:credit, money, credit_card_or_authorization, options)
end
end
private
def sale_authorization_or_credit_template(trx_type, money, credit_card, options = {})
post = VerifiPostData.new
add_security_key_data(post, options, money)
add_credit_card(post, credit_card)
add_addresses(post, options)
add_customer_data(post, options)
add_invoice_data(post, options)
add_optional_data(post, options)
add_merchant_defined_data(post, options)
commit(trx_type, money, post)
end
def capture_void_or_refund_template(trx_type, money, authorization, options)
post = VerifiPostData.new
post[:transactionid] = authorization
commit(trx_type, money, post)
end
def add_credit_card(post, credit_card)
post[:ccnumber] = credit_card.number
post[:ccexp] = expdate(credit_card)
post[:firstname] = credit_card.first_name
post[:lastname] = credit_card.last_name
post[:cvv] = credit_card.verification_value
end
def expdate(credit_card)
year = sprintf("%.4i", credit_card.year)
month = sprintf("%.2i", credit_card.month)
"#{month}#{year[-2..-1]}"
end
def add_addresses(post, options)
if billing_address = options[:billing_address] || options[:address]
post[:company] = billing_address[:company]
post[:address1] = billing_address[:address1]
post[:address2] = billing_address[:address2]
post[:city] = billing_address[:city]
post[:state] = billing_address[:state]
post[:zip] = billing_address[:zip]
post[:country] = billing_address[:country]
post[:phone] = billing_address[:phone]
post[:fax] = billing_address[:fax]
end
if shipping_address = options[:shipping_address]
post[:shipping_firstname] = shipping_address[:first_name]
post[:shipping_lastname] = shipping_address[:last_name]
post[:shipping_company] = shipping_address[:company]
post[:shipping_address1] = shipping_address[:address1]
post[:shipping_address2] = shipping_address[:address2]
post[:shipping_city] = shipping_address[:city]
post[:shipping_state] = shipping_address[:state]
post[:shipping_zip] = shipping_address[:zip]
post[:shipping_country] = shipping_address[:country]
post[:shipping_email] = shipping_address[:email]
end
end
def add_customer_data(post, options)
post[:email] = options[:email]
post[:ipaddress] = options[:ip]
end
def add_invoice_data(post, options)
post[:orderid] = options[:order_id]
post[:ponumber] = options[:invoice]
post[:orderdescription] = options[:description]
post[:tax] = options[:tax]
post[:shipping] = options[:shipping]
end
def add_optional_data(post, options)
post[:billing_method] = options[:billing_method]
post[:website] = options[:website]
post[:descriptor] = options[:descriptor]
post[:descriptor_phone] = options[:descriptor_phone]
post[:cardholder_auth] = options[:cardholder_auth]
post[:cavv] = options[:cavv]
post[:xid] = options[:xid]
post[:customer_receipt] = options[:customer_receipt]
end
def add_merchant_defined_data(post, options)
# add the mercant_defined_fields
(1..20).each do |num|
unless options[('merchant_defined_field_' + num.to_s).to_sym].nil?
post[('merchant_defined_field_' + num.to_s).to_sym] = options[('merchant_defined_field_' + num.to_s).to_sym]
end
end
end
def add_security_key_data(post, options, money)
# MD5(username|password|orderid|amount|time)
now = Time.now.to_i.to_s
md5 = Digest::MD5.new
md5 << @options[:login].to_s + "|"
md5 << @options[:password].to_s + "|"
md5 << options[:order_id].to_s + "|"
md5 << amount(money).to_s + "|"
md5 << now
post[:key] = md5.hexdigest
post[:time] = now
end
def commit(trx_type, money, post)
post[:amount] = amount(money)
response = parse( ssl_post(URL, post_data(trx_type, post)) )
Response.new(response[:response].to_i == SUCCESS, message_from(response), response,
:test => test?,
:authorization => response[:transactionid],
:avs_result => { :code => response[:avsresponse] },
:cvv_result => response[:cvvresponse]
)
end
def message_from(response)
response[:response_code_message] ? response[:response_code_message] : ""
end
def parse(body)
results = {}
CGI.parse(body).each { |key, value| results[key.intern] = value[0] }
results[:response_code_message] = RESPONSE_CODE_MESSAGES[results[:response_code]] if results[:response_code]
results
end
def post_data(trx_type, post)
post[:username] = @options[:login]
post[:password] = @options[:password]
post[:type] = TRANSACTIONS[trx_type]
post.to_s
end
end
end
end
| 39.841004 | 120 | 0.564377 |
f7f48ea7b292ef18366a18ee20979cbb16d5e731 | 23,096 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
# require "google/ads/google_ads/error"
require "google/ads/google_ads/v5/services/feed_mapping_service_pb"
module Google
module Ads
module GoogleAds
module V5
module Services
module FeedMappingService
##
# Client for the FeedMappingService service.
#
# Service to manage feed mappings.
#
class Client
include Paths
# @private
attr_reader :feed_mapping_service_stub
##
# Configure the FeedMappingService Client class.
#
# See {::Google::Ads::GoogleAds::V5::Services::FeedMappingService::Client::Configuration}
# for a description of the configuration fields.
#
# ## Example
#
# To modify the configuration for all FeedMappingService clients:
#
# ::Google::Ads::GoogleAds::V5::Services::FeedMappingService::Client.configure do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def self.configure
@configure ||= begin
default_config = Client::Configuration.new
default_config.timeout = 3600.0
default_config.retry_policy = {
initial_delay: 5.0,
max_delay: 60.0,
multiplier: 1.3,
retry_codes: [14, 4]
}
default_config
end
yield @configure if block_given?
@configure
end
##
# Configure the FeedMappingService Client instance.
#
# The configuration is set to the derived mode, meaning that values can be changed,
# but structural changes (adding new fields, etc.) are not allowed. Structural changes
# should be made on {Client.configure}.
#
# See {::Google::Ads::GoogleAds::V5::Services::FeedMappingService::Client::Configuration}
# for a description of the configuration fields.
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def configure
yield @config if block_given?
@config
end
##
# Create a new FeedMappingService client object.
#
# ## Examples
#
# To create a new FeedMappingService client with the default
# configuration:
#
# client = ::Google::Ads::GoogleAds::V5::Services::FeedMappingService::Client.new
#
# To create a new FeedMappingService client with a custom
# configuration:
#
# client = ::Google::Ads::GoogleAds::V5::Services::FeedMappingService::Client.new do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the FeedMappingService client.
# @yieldparam config [Client::Configuration]
#
def initialize
# These require statements are intentionally placed here to initialize
# the gRPC module only when it's required.
# See https://github.com/googleapis/toolkit/issues/446
require "gapic/grpc"
require "google/ads/google_ads/v5/services/feed_mapping_service_services_pb"
# Create the configuration object
@config = Configuration.new Client.configure
# Yield the configuration if needed
yield @config if block_given?
# Create credentials
credentials = @config.credentials
credentials ||= Credentials.default scope: @config.scope
if credentials.is_a?(String) || credentials.is_a?(Hash)
credentials = Credentials.new credentials, scope: @config.scope
end
@quota_project_id = @config.quota_project
@quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id
@feed_mapping_service_stub = ::Gapic::ServiceStub.new(
::Google::Ads::GoogleAds::V5::Services::FeedMappingService::Stub,
credentials: credentials,
endpoint: @config.endpoint,
channel_args: @config.channel_args,
interceptors: @config.interceptors
)
end
# Service calls
##
# Returns the requested feed mapping in full detail.
#
# @overload get_feed_mapping(request, options = nil)
# Pass arguments to `get_feed_mapping` via a request object, either of type
# {::Google::Ads::GoogleAds::V5::Services::GetFeedMappingRequest} or an equivalent Hash.
#
# @param request [::Google::Ads::GoogleAds::V5::Services::GetFeedMappingRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload get_feed_mapping(resource_name: nil)
# Pass arguments to `get_feed_mapping` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param resource_name [::String]
# Required. The resource name of the feed mapping to fetch.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Google::Ads::GoogleAds::V5::Resources::FeedMapping]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Google::Ads::GoogleAds::V5::Resources::FeedMapping]
#
# @raise [Google::Ads::GoogleAds::Error] if the RPC is aborted.
#
def get_feed_mapping request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Ads::GoogleAds::V5::Services::GetFeedMappingRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.get_feed_mapping.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Ads::GoogleAds::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"resource_name" => request.resource_name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.get_feed_mapping.timeout,
metadata: metadata,
retry_policy: @config.rpcs.get_feed_mapping.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@feed_mapping_service_stub.call_rpc :get_feed_mapping, request, options: options do |response, operation|
yield response, operation if block_given?
return response
end
# rescue GRPC::BadStatus => grpc_error
# raise Google::Ads::GoogleAds::Error.new grpc_error.message
end
##
# Creates or removes feed mappings. Operation statuses are
# returned.
#
# @overload mutate_feed_mappings(request, options = nil)
# Pass arguments to `mutate_feed_mappings` via a request object, either of type
# {::Google::Ads::GoogleAds::V5::Services::MutateFeedMappingsRequest} or an equivalent Hash.
#
# @param request [::Google::Ads::GoogleAds::V5::Services::MutateFeedMappingsRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload mutate_feed_mappings(customer_id: nil, operations: nil, partial_failure: nil, validate_only: nil)
# Pass arguments to `mutate_feed_mappings` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param customer_id [::String]
# Required. The ID of the customer whose feed mappings are being modified.
# @param operations [::Array<::Google::Ads::GoogleAds::V5::Services::FeedMappingOperation, ::Hash>]
# Required. The list of operations to perform on individual feed mappings.
# @param partial_failure [::Boolean]
# If true, successful operations will be carried out and invalid
# operations will return errors. If false, all operations will be carried
# out in one transaction if and only if they are all valid.
# Default is false.
# @param validate_only [::Boolean]
# If true, the request is validated but not executed. Only errors are
# returned, not results.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Google::Ads::GoogleAds::V5::Services::MutateFeedMappingsResponse]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Google::Ads::GoogleAds::V5::Services::MutateFeedMappingsResponse]
#
# @raise [Google::Ads::GoogleAds::Error] if the RPC is aborted.
#
def mutate_feed_mappings request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Ads::GoogleAds::V5::Services::MutateFeedMappingsRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.mutate_feed_mappings.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Ads::GoogleAds::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"customer_id" => request.customer_id
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.mutate_feed_mappings.timeout,
metadata: metadata,
retry_policy: @config.rpcs.mutate_feed_mappings.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@feed_mapping_service_stub.call_rpc :mutate_feed_mappings, request, options: options do |response, operation|
yield response, operation if block_given?
return response
end
# rescue GRPC::BadStatus => grpc_error
# raise Google::Ads::GoogleAds::Error.new grpc_error.message
end
##
# Configuration class for the FeedMappingService API.
#
# This class represents the configuration for FeedMappingService,
# providing control over timeouts, retry behavior, logging, transport
# parameters, and other low-level controls. Certain parameters can also be
# applied individually to specific RPCs. See
# {::Google::Ads::GoogleAds::V5::Services::FeedMappingService::Client::Configuration::Rpcs}
# for a list of RPCs that can be configured independently.
#
# Configuration can be applied globally to all clients, or to a single client
# on construction.
#
# # Examples
#
# To modify the global config, setting the timeout for get_feed_mapping
# to 20 seconds, and all remaining timeouts to 10 seconds:
#
# ::Google::Ads::GoogleAds::V5::Services::FeedMappingService::Client.configure do |config|
# config.timeout = 10.0
# config.rpcs.get_feed_mapping.timeout = 20.0
# end
#
# To apply the above configuration only to a new client:
#
# client = ::Google::Ads::GoogleAds::V5::Services::FeedMappingService::Client.new do |config|
# config.timeout = 10.0
# config.rpcs.get_feed_mapping.timeout = 20.0
# end
#
# @!attribute [rw] endpoint
# The hostname or hostname:port of the service endpoint.
# Defaults to `"googleads.googleapis.com"`.
# @return [::String]
# @!attribute [rw] credentials
# Credentials to send with calls. You may provide any of the following types:
# * (`String`) The path to a service account key file in JSON format
# * (`Hash`) A service account key as a Hash
# * (`Google::Auth::Credentials`) A googleauth credentials object
# (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html))
# * (`Signet::OAuth2::Client`) A signet oauth2 client object
# (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html))
# * (`GRPC::Core::Channel`) a gRPC channel with included credentials
# * (`GRPC::Core::ChannelCredentials`) a gRPC credentails object
# * (`nil`) indicating no credentials
# @return [::Object]
# @!attribute [rw] scope
# The OAuth scopes
# @return [::Array<::String>]
# @!attribute [rw] lib_name
# The library name as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] lib_version
# The library version as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] channel_args
# Extra parameters passed to the gRPC channel. Note: this is ignored if a
# `GRPC::Core::Channel` object is provided as the credential.
# @return [::Hash]
# @!attribute [rw] interceptors
# An array of interceptors that are run before calls are executed.
# @return [::Array<::GRPC::ClientInterceptor>]
# @!attribute [rw] timeout
# The call timeout in seconds.
# @return [::Numeric]
# @!attribute [rw] metadata
# Additional gRPC headers to be sent with the call.
# @return [::Hash{::Symbol=>::String}]
# @!attribute [rw] retry_policy
# The retry policy. The value is a hash with the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
# @return [::Hash]
# @!attribute [rw] quota_project
# A separate project against which to charge quota.
# @return [::String]
#
class Configuration
extend ::Gapic::Config
config_attr :endpoint, "googleads.googleapis.com", ::String
config_attr :credentials, nil do |value|
allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil]
allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC
allowed.any? { |klass| klass === value }
end
config_attr :scope, nil, ::String, ::Array, nil
config_attr :lib_name, nil, ::String, nil
config_attr :lib_version, nil, ::String, nil
config_attr(:channel_args, { "grpc.service_config_disable_resolution"=>1 }, ::Hash, nil)
config_attr :interceptors, nil, ::Array, nil
config_attr :timeout, nil, ::Numeric, nil
config_attr :metadata, nil, ::Hash, nil
config_attr :retry_policy, nil, ::Hash, ::Proc, nil
config_attr :quota_project, nil, ::String, nil
# @private
def initialize parent_config = nil
@parent_config = parent_config unless parent_config.nil?
yield self if block_given?
end
##
# Configurations for individual RPCs
# @return [Rpcs]
#
def rpcs
@rpcs ||= begin
parent_rpcs = nil
parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config&.respond_to?(:rpcs)
Rpcs.new parent_rpcs
end
end
##
# Configuration RPC class for the FeedMappingService API.
#
# Includes fields providing the configuration for each RPC in this service.
# Each configuration object is of type `Gapic::Config::Method` and includes
# the following configuration fields:
#
# * `timeout` (*type:* `Numeric`) - The call timeout in milliseconds
# * `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers
# * `retry_policy (*type:* `Hash`) - The retry policy. The policy fields
# include the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
#
class Rpcs
##
# RPC-specific configuration for `get_feed_mapping`
# @return [::Gapic::Config::Method]
#
attr_reader :get_feed_mapping
##
# RPC-specific configuration for `mutate_feed_mappings`
# @return [::Gapic::Config::Method]
#
attr_reader :mutate_feed_mappings
# @private
def initialize parent_rpcs = nil
get_feed_mapping_config = parent_rpcs&.get_feed_mapping if parent_rpcs&.respond_to? :get_feed_mapping
@get_feed_mapping = ::Gapic::Config::Method.new get_feed_mapping_config
mutate_feed_mappings_config = parent_rpcs&.mutate_feed_mappings if parent_rpcs&.respond_to? :mutate_feed_mappings
@mutate_feed_mappings = ::Gapic::Config::Method.new mutate_feed_mappings_config
yield self if block_given?
end
end
end
end
end
end
end
end
end
end
| 50.538293 | 133 | 0.545419 |
d53fc48fb27457378d7bf3f4e4096d67b44bd66f | 109 | # frozen_string_literal: true
require_relative './config/boot'
require_relative './web_app'
run WebApp.new
| 15.571429 | 32 | 0.788991 |
bb9540abbb9dd565024757703206c155952792bb | 1,051 | Pod::Spec.new do |s|
s.name = 'qr_mobile_vision'
s.version = '0.0.1'
s.summary = 'Plugin for reading QR codes using Firebase's Mobile Vision API.'
s.description = <<-DESC
Plugin for reading QR codes using Google's Mobile Vision API.
DESC
s.homepage = 'https://github.com/rmtmckenzie/flutter_qr_mobile_vision'
s.license = { :file => '../LICENSE' }
s.author = { 'Morgan McKenzie' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.public_header_files = 'Classes/**/*.h'
s.dependency 'Flutter'
s.platform = :ios, '8.0'
# Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
s.swift_version = '5.0'
s.dependency 'Firebase/MLVision'
s.dependency 'Firebase/MLVisionBarcodeModel'
s.static_framework = true
end
| 40.423077 | 105 | 0.607992 |
01b44263996fdbe68d65e89496469181598b0777 | 1,027 | class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates :name, presence: true, length: { maximum: 20 }
has_many :posts
has_many :comments, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :friendships
has_many :confirmed_friendships, -> { where confirmed: true }, class_name: 'Friendship'
has_many :friends, through: :confirmed_friendships
has_many :pending_friendships, -> { where confirmed: nil }, class_name: 'Friendship', foreign_key: 'user_id'
has_many :pending_friends, through: :pending_friendships, source: :friend
has_many :inverted_friendships, -> { where confirmed: nil }, class_name: 'Friendship', foreign_key: 'friend_id'
has_many :friend_requests, through: :inverted_friendships, source: :user
def friend?(user)
friends.include?(user)
end
end
| 38.037037 | 113 | 0.748783 |
ed563402c146b5e32d788ee81ed06c0ec63e67e5 | 385 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2020_08_01
module Models
#
# Defines values for ConnectionMonitorEndpointFilterType
#
module ConnectionMonitorEndpointFilterType
Include = "Include"
end
end
end
| 24.0625 | 70 | 0.74026 |
ac04de0962f63f8f4adfe6c16d3eb04370fe834a | 398 | name 'meniscus-configdb'
maintainer 'Steven Gonzales'
maintainer_email '[email protected]'
license 'Apache 2.0'
description 'Installs/Configures meniscus-configdb'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.2.0'
supports 'ubuntu'
depends 'base-template'
depends 'mmongo'
depends 'meetme-newrelic-plugin' | 33.166667 | 72 | 0.718593 |
03ccc80cf3e2f0d897b0d34e8f00694f71e033e6 | 4,711 | require_relative '../fixtures/classes'
require_relative '../fixtures/encoded_strings'
describe :array_inspect, shared: true do
it "returns a string" do
@subject.new([1, 2, 3]).send(@method).should be_an_instance_of(String)
end
it "returns '[]' for an empty Array" do
@subject.new([]).send(@method).should == "[]"
end
it "calls inspect on its elements and joins the results with commas" do
items = @subject.new(3) do |i|
obj = mock(i.to_s)
obj.should_receive(:inspect).and_return(i.to_s)
obj
end
items.send(@method).should == "[0, 1, 2]"
end
it "does not call #to_s on a String returned from #inspect" do
str = "abc"
str.should_not_receive(:to_s)
@subject.new([str]).send(@method).should == '["abc"]'
end
it "calls #to_s on the object returned from #inspect if the Object isn't a String" do
obj = mock("Array#inspect/to_s calls #to_s")
obj.should_receive(:inspect).and_return(obj)
obj.should_receive(:to_s).and_return("abc")
@subject.new([obj]).send(@method).should == "[abc]"
end
it "does not call #to_str on the object returned from #inspect when it is not a String" do
obj = mock("Array#inspect/to_s does not call #to_str")
obj.should_receive(:inspect).and_return(obj)
obj.should_not_receive(:to_str)
@subject.new([obj]).send(@method).should =~ /^\[#<MockObject:0x[0-9a-f]+>\]$/
end
it "does not call #to_str on the object returned from #to_s when it is not a String" do
obj = mock("Array#inspect/to_s does not call #to_str on #to_s result")
obj.should_receive(:inspect).and_return(obj)
obj.should_receive(:to_s).and_return(obj)
obj.should_not_receive(:to_str)
@subject.new([obj]).send(@method).should =~ /^\[#<MockObject:0x[0-9a-f]+>\]$/
end
it "does not swallow exceptions raised by #to_s" do
obj = mock("Array#inspect/to_s does not swallow #to_s exceptions")
obj.should_receive(:inspect).and_return(obj)
obj.should_receive(:to_s).and_raise(Exception)
-> { @subject.new([obj]).send(@method) }.should raise_error(Exception)
end
it "represents a recursive element with '[...]'" do
CollectionSpecs.recursive_array(@subject).send(@method).should == "[1, \"two\", 3.0, [...], [...], [...], [...], [...]]"
CollectionSpecs.head_recursive_array(@subject).send(@method).should == "[[...], [...], [...], [...], [...], 1, \"two\", 3.0]"
CollectionSpecs.empty_recursive_array(@subject).send(@method).should == "[[...]]"
end
ruby_version_is ''...'2.7' do
it "taints the result if the Array is non-empty and tainted" do
@subject.new([1, 2]).taint.send(@method).tainted?.should be_true
end
it "does not taint the result if the Array is tainted but empty" do
@subject.new([]).taint.send(@method).tainted?.should be_false
end
it "taints the result if an element is tainted" do
@subject.new(["str".taint]).send(@method).tainted?.should be_true
end
it "untrusts the result if the Array is untrusted" do
@subject.new([1, 2]).untrust.send(@method).untrusted?.should be_true
end
it "does not untrust the result if the Array is untrusted but empty" do
@subject.new([]).untrust.send(@method).untrusted?.should be_false
end
it "untrusts the result if an element is untrusted" do
@subject.new(["str".untrust]).send(@method).untrusted?.should be_true
end
end
describe "with encoding" do
before :each do
@default_external_encoding = Encoding.default_external
end
after :each do
Encoding.default_external = @default_external_encoding
end
it "returns a US-ASCII string for an empty Array" do
@subject.new([]).send(@method).encoding.should == Encoding::US_ASCII
end
it "use the default external encoding if it is ascii compatible" do
Encoding.default_external = Encoding.find('UTF-8')
utf8 = "utf8".encode("UTF-8")
jp = "jp".encode("EUC-JP")
array = [jp, utf8]
@subject.new(array).send(@method).encoding.name.should == "UTF-8"
end
it "use US-ASCII encoding if the default external encoding is not ascii compatible" do
Encoding.default_external = Encoding.find('UTF-32')
utf8 = "utf8".encode("UTF-8")
jp = "jp".encode("EUC-JP")
array = [jp, utf8]
@subject.new(array).send(@method).encoding.name.should == "US-ASCII"
end
it "does not raise if inspected result is not default external encoding" do
utf_16be = mock("utf_16be")
utf_16be.should_receive(:inspect).and_return(%<"utf_16be \u3042">.encode!(Encoding::UTF_16BE))
@subject.new([utf_16be]).send(@method).should == '["utf_16be \u3042"]'
end
end
end
| 34.896296 | 129 | 0.656973 |
2615f9fa1ca8057c5addc552536de5acca060937 | 429 | require 'r'
class Main
def init
@instance = TestDir.new()
@instance.init
end
def match
if @instance != nil
@instance.match("1.1.1.1 abc")
else
puts "initial config not loaded"
end
end
end
puts "push to load read and load configuration"
char = STDIN.gets
instance = Main.new()
instance.init
puts "init process complete"
while true do
puts "push to perform match"
char = STDIN.getc
instance.match
end
| 13.40625 | 47 | 0.699301 |
1152a9d261cb9b817554082e2503e7f4b50e0909 | 1,190 | # -*- encoding: utf-8 -*-
=begin
#Accounting API
#No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 2.0.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.0.3
=end
$:.push File.expand_path("../lib", __FILE__)
require "xero-ruby/version"
Gem::Specification.new do |s|
s.name = "xero-ruby"
s.version = XeroRuby::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Xero Developer Evangelist Team"]
s.email = ["[email protected]"]
s.homepage = "https://developer.xero.com"
s.summary = "Accounting API Ruby Gem"
s.description = "Official Ruby SDK for Xero API with OAuth 2.0 support."
s.license = "MIT"
s.required_ruby_version = ">= 1.9"
s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1'
s.add_runtime_dependency 'json', '~> 2.1', '>= 2.1.0'
s.add_development_dependency 'rspec', '~> 3.6', '>= 3.6.0'
s.files = `find *`.split("\n").uniq.sort.select { |f| !f.empty? }
s.test_files = `find spec/*`.split("\n")
s.executables = []
s.require_paths = ["lib"]
end
| 29.75 | 107 | 0.644538 |
08597f1cb04b8897834f81f7c17d910f5ed66b80 | 2,613 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'example.com',
user_name: 'defoe.brand',
password: 'cpkrhqcuvyimtcln',
authentication: 'plain',
enable_starttls_auto: true
}
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| 34.381579 | 87 | 0.753923 |
18b55cd52be59b4d7792df70737d50859cfbe1da | 1,261 | # -*- encoding: utf-8 -*-
=begin
#OpenAPI Petstore
#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.0.0-SNAPSHOT
=end
$:.push File.expand_path("../lib", __FILE__)
require "petstore/version"
Gem::Specification.new do |s|
s.name = "petstore"
s.version = Petstore::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["OpenAPI-Generator"]
s.email = [""]
s.homepage = "https://openapi-generator.tech"
s.summary = "OpenAPI Petstore Ruby Gem"
s.description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\"
s.license = "Unlicense"
s.required_ruby_version = ">= 2.4"
s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1'
s.add_development_dependency 'rspec', '~> 3.6', '>= 3.6.0'
s.files = `find *`.split("\n").uniq.sort.select { |f| !f.empty? }
s.test_files = `find spec/*`.split("\n")
s.executables = []
s.require_paths = ["lib"]
end
| 32.333333 | 176 | 0.659794 |
08b7033f0e219758fa2c0d6900846015912ba8fe | 356 | class FontNotoSansHatran < Formula
head "https://github.com/google/fonts/raw/main/ofl/notosanshatran/NotoSansHatran-Regular.ttf", verified: "github.com/google/fonts/"
desc "Noto Sans Hatran"
homepage "https://fonts.google.com/specimen/Noto+Sans+Hatran"
def install
(share/"fonts").install "NotoSansHatran-Regular.ttf"
end
test do
end
end
| 32.363636 | 133 | 0.752809 |
f8bb70e882e268cae2dd13a5c4d27eed7c5f49a2 | 249 | class CreateTableCriteriakeys < ActiveRecord::Migration
def up
create_table :criteriakeys do |t|
t.string :criterianame
t.integer :scalevalue
t.text :textvalue
end
end
def down
drop_table :criteriakeys
end
end
| 17.785714 | 55 | 0.694779 |
28af3b387ec3bca7d929e07796861b1c969ea7df | 916 | module Coconductor
module Projects
module Project
DIRS = ['./', './docs/', './.github/'].freeze
def code_of_conduct
code_of_conduct_file.code_of_conduct if code_of_conduct_file
end
def code_of_conduct_file
return @code_of_conduct_file if defined? @code_of_conduct_file
return if files.nil? || files.empty?
file = find_files do |filename|
ProjectFiles::CodeOfConductFile.name_score(filename)
end.first
return unless file
content = load_file(file)
@code_of_conduct_file = begin
ProjectFiles::CodeOfConductFile.new(content, file)
end
end
private
def path_relative_to_root(path)
return path if is_a?(GitProject) || path.nil?
root = Pathname.new(@dir)
path = Pathname.new(path)
path.relative_path_from(root).to_s
end
end
end
end
| 24.105263 | 70 | 0.635371 |
ab2272dd66b2014df7926059af59b1a4b6794bca | 1,918 | describe :hash_store, :shared => true do
it "associates the key with the value and return the value" do
h = new_hash(:a => 1)
h.send(@method, :b, 2).should == 2
h.should == new_hash(:b=>2, :a=>1)
end
it "duplicates string keys using dup semantics" do
# dup doesn't copy singleton methods
key = "foo"
def key.reverse() "bar" end
h = new_hash
h.send(@method, key, 0)
h.keys[0].reverse.should == "oof"
end
it "stores unequal keys that hash to the same value" do
h = new_hash
k1 = ["x"]
k2 = ["y"]
# So they end up in the same bucket
k1.should_receive(:hash).and_return(0)
k2.should_receive(:hash).and_return(0)
h[k1] = 1
h[k2] = 2
h.size.should == 2
end
it "accepts keys with private #hash method" do
key = HashSpecs::KeyWithPrivateHash.new
h = new_hash
h[key] = "foo"
h[key].should == "foo"
end
it "duplicates and freezes string keys" do
key = "foo"
h = new_hash
h.send(@method, key, 0)
key << "bar"
h.should == new_hash("foo" => 0)
h.keys[0].frozen?.should == true
end
it "doesn't duplicate and freeze already frozen string keys" do
key = "foo".freeze
h = new_hash
h.send(@method, key, 0)
h.keys[0].should equal(key)
end
ruby_version_is ""..."1.9" do
it "raises a TypeError if called on a frozen instance" do
lambda { HashSpecs.frozen_hash.send(@method, 1, 2) }.should raise_error(TypeError)
end
end
ruby_version_is "1.9" do
it "raises a RuntimeError if called on a frozen instance" do
lambda { HashSpecs.frozen_hash.send(@method, 1, 2) }.should raise_error(RuntimeError)
end
end
it "does not raise an exception if changing the value of an existing key during iteration" do
hash = {1 => 2, 3 => 4, 5 => 6}
hash.each { hash.send(@method, 1, :foo) }
hash.should == {1 => :foo, 3 => 4, 5 => 6}
end
end
| 26.638889 | 95 | 0.614703 |
b9158b1b35d7c935c4dc87d3cf94217cfd894727 | 627 | require 'spec_helper'
describe "uploader_files" do
subject(:site) { cms_site }
subject(:node) { create_once :uploader_node_file, name: "uploader" }
subject(:item) { Uploader::File.last }
subject(:index_path) { uploader_files_path site.host, node }
it "without login" do
visit index_path
expect(current_path).to eq sns_login_path
end
it "without auth" do
login_ss_user
visit index_path
expect(status_code).to eq 403
end
context "with auth" do
before { login_cms_user }
it "#index" do
visit index_path
expect(current_path).not_to eq sns_login_path
end
end
end
| 21.62069 | 70 | 0.698565 |
2608b240f7e45db561149f556c6560401ff7b833 | 237 | class CollectionsController < ApplicationController
include CurationConcerns::CollectionsControllerBehavior
include CurationConcerns::CollectionsControllerBehaviorEnhancements
def presenter_class
CollectionPresenter
end
end
| 26.333333 | 69 | 0.869198 |
8727baa4f09c57651ffa2bebfe8c82141b71780e | 8,587 | class CamaleonCms::SiteDecorator < CamaleonCms::TermTaxonomyDecorator
delegate_all
def the_description
the_content
end
# return logo url for this site
# default: this url will be returned if logo is not present.
def the_logo(default = nil)
object.get_option("logo") || (default || "#{h.asset_url("camaleon_cms/theturtlefoundation-logo.png")}")
end
def the_icon
object.get_option("icon") || h.asset_url('camaleon_cms/favicon.ico')
end
# return all contents from this site registered for post_type = slug (filter visibility, hidden, expired, ...)
# slug_or_id: slug or id of the post_type or array of slugs of post_types, default 'post'
def the_contents(slug_or_id = "post")
return h.verify_front_visibility(object.posts.where("#{CamaleonCms::TermTaxonomy.table_name}.id = ?", slug_or_id)) if slug_or_id.is_a?(Integer)
return h.verify_front_visibility(object.posts.where("#{CamaleonCms::TermTaxonomy.table_name}.slug = ?", slug_or_id)) if slug_or_id.is_a?(String)
return h.verify_front_visibility(object.posts.where("#{CamaleonCms::TermTaxonomy.table_name}.slug in (?)", slug_or_id)) if slug_or_id.is_a?(Array)
end
# return all contents for this site filteredby (visibility, hidden, expired, ...)
# slug_or_id: (slug of the post_type) possible values:
# empty: return all posts of the current site
# string: return all posts of post_type with slug = slug_or_id
# integer: return all posts of post_type with id = slug_or_id
# array: return all posts of post_types with slug in slug_or_id
def the_posts(slug_or_id = nil)
if slug_or_id.present?
the_contents(slug_or_id)
else
h.verify_front_visibility(object.posts)
end
end
# return the post with id or slug equal to slug_or_id
# slug_or_id: (String) for post slug
# slug_or_id: (Integer) for post id
# slug_or_id: (Array) array of post ids, return multiple posts
# return post model or nil
def the_post(slug_or_id)
post = self.the_posts.find(slug_or_id) rescue nil if slug_or_id.is_a?(Integer) # id
post = self.the_posts.find(slug_or_id) rescue nil if slug_or_id.is_a?(Array) # id
post = self.the_posts.find_by_slug(slug_or_id) if slug_or_id.is_a?(String) # id
post.present? ? post.decorate : nil
end
# return a collection of categories
# Arguments:
# slug_or_id: string or integer
# return:
# slug_or_id: nil => return all main_categories for this site
# slug_or_id: integer => return all main categories of the post_type with id = slug_or_id
# slug_or_id: string => return all main categories of the post_type with slug = slug_or_id
def the_categories(slug_or_id = nil)
return the_post_type(slug_or_id).the_categories if slug_or_id.present?
return object.categories unless slug_or_id.present?
end
# return the category object with id or slug = slug_or_id from this site
def the_category(slug_or_id)
return the_full_categories.where(id: slug_or_id).first.decorate rescue nil if slug_or_id.is_a?(Integer)
return the_full_categories.find_by_slug(slug_or_id).decorate rescue nil if slug_or_id.is_a?(String)
end
# return all categories for ths site (include all children categories)
def the_full_categories
object.full_categories
end
# return all post tags for ths site
def the_tags
object.post_tags
end
# return the post_tag object with id or slug = slug_or_id from this site
# sample: current_site.the_tag('test').the_url
# sample2: current_site.the_tag('test').the_posts
def the_tag(slug_or_id)
return object.post_tags.where(id: slug_or_id).first.decorate rescue nil if slug_or_id.is_a?(Integer)
return object.post_tags.find_by_slug(slug_or_id).decorate rescue nil if slug_or_id.is_a?(String)
end
# return the user object with id or username = id_or_username from this site
def the_user(id_or_username)
return object.users.where(id: id_or_username).first.decorate rescue nil if id_or_username.is_a?(Integer)
return object.users.find_by_username(id_or_username).decorate rescue nil if id_or_username.is_a?(String)
end
# return all post types for this site
def the_post_types
object.post_types
end
# return a post_type object with id or slug = slug_or_id
# Arguments:
# slug_or_id: string or integer
# return:
# slug_or_id: integer => return the post type with id = slug_or_id
# slug_or_id: string => return the post type with slug = slug_or_id
# slug_or_id: array => return all post types with slugs in the array of this site
def the_post_type(slug_or_id)
return object.post_types.find_by_slug(slug_or_id).decorate rescue nil if slug_or_id.is_a?(String)
return object.post_types.find_by_slug(slug_or_id).decorate rescue nil if slug_or_id.is_a?(Array)
return object.post_types.find(slug_or_id).decorate rescue nil if slug_or_id.is_a?(Integer)
end
# draw languages configured for this site
# list_class: (String) Custom css classes for ul list
# current_page: (boolean) true: link with translation to current url, false: link with translation to root url
# block permit to render custom link label, default: flag icon
def draw_languages(list_class = "language_list list-inline pull-right", current_page = false, current_class = "current_l", &block)
lan = object.get_languages
return if lan.size < 2
res = ["<ul class='#{list_class}'>"]
lan.each do |lang|
path = lang.to_s+'.png'
label = (block ? h.capture(lang, I18n.locale.to_s == lang.to_s, &block) : "<img src='#{h.asset_path("camaleon_cms/language/#{path}")}'/>")
res << "<li class='#{ current_class if I18n.locale.to_s == lang.to_s}'> <a href='#{h.cama_url_to_fixed(current_page ? "url_for" : "cama_root_url", {locale: lang, cama_set_language: lang})}'>#{label}</a> </li>"
end
res << "</ul>"
res.join("").html_safe
end
# return Array of frontend languages configured for this site
def the_languages
object.get_languages
end
# return the role_id of current visitor for this site
# if the visitor was not logged in, then return -1
def visitor_role
h.signin? ? h.cama_current_user.role : '-1'
end
# check if plugin_key is already installed for this site
def plugin_installed?(plugin_key)
res = false
PluginRoutes.enabled_plugins(object).each{|plugin| res = true if plugin["key"] == plugin_key }
res
end
# return root url for this site
# args = {skip_relative_url_root: true/false(default), as_path: true/false(default)}
def the_url(*args)
args = args.extract_options!
args[:site] = self
args[:host], args[:port] = object.get_domain.to_s.split(':') if !args[:as_path] && (h.current_site rescue false) != self # fix for different site of current visited site
h.cama_current_site_host_port(args) unless args[:as_path]
args[:locale] = @_deco_locale unless args.include?(:locale)
postfix = 'url'
postfix = 'path' if args.delete(:as_path)
skip_relative_url_root = args.delete(:skip_relative_url_root)
h.cama_current_site_host_port(args) unless args.keys.include?(:host)
res = h.cama_url_to_fixed("cama_root_#{postfix}", args)
res = res.sub("/#{PluginRoutes.static_system_info['relative_url_root']}", '') if skip_relative_url_root && PluginRoutes.static_system_info['relative_url_root'].present?
res
end
# return the path for this site
def the_path(*args)
args = args.extract_options!
args[:as_path] = true
the_url(args)
end
# draw bread crumb for current site
def generate_breadcrumb(add_post_type = true)
h.breadcrumb_add(self.the_title)
end
# =============================== ADMIN =======================
# admin root url for this site
def the_admin_url
host = object.main_site? ? object.slug : (object.slug.include?(".") ? object.slug : "#{object.slug}.#{Cama::Site.main_site.slug}")
port = (host.split(":")[1] rescue nil)
h.cama_url_to_fixed("cama_admin_dashboard_url", host: host, port: port, locale: nil)
end
# check if current user can manage sites
def manage_sites?
self.main_site? && h.cama_current_user.admin?
end
# return the text status of current site
def the_status
I18n.t("camaleon_cms.models.site.status_options.#{object.status || 'active'}", default: (object.status || 'active').titleize)
end
# return an array for select options of all status for this site
def the_status_options
['active', 'inactive', 'maintenance'].map do |o|
[I18n.t("camaleon_cms.models.site.status_options.#{o}", default: o.titleize), o == 'active' ? '': o]
end
end
end
| 42.721393 | 215 | 0.72109 |
ed2e16d3ace6b624f2cc599548434a6fc4538fb5 | 100 | FactoryGirl.define do
factory :repo do
sequence(:name) { |n| "SomeUser/repo_#{n}" }
end
end
| 16.666667 | 48 | 0.65 |
bb7202ec6bf147c1795a8772d1b9f6c8147b88b1 | 183 | Merb::Config[:framework] = {
application: Merb.root / "application.rb",
config: [Merb.root / "config", nil],
public: [Merb.root / "public", nil],
view: Merb.root / "views"
}
| 22.875 | 44 | 0.622951 |
ede8eeeb0a5edb24a77d5ce5ac1b6da92115aeaf | 397 | name "sys_krb5_test"
description "Use to test the [sys::krb5] recipe."
run_list( "recipe[sys::krb5]" )
default_attributes(
"sys" => {
"krb5" => {
# this is upcased in the recipe
"realm" => "example.com",
"admin_server" => "kdc1.h5l.example.com",
"master" => "kdc1.h5l.example.com",
"slave" => "kdc2.h5l.example.com",
"domain" => "example.com"
}
}
)
| 24.8125 | 49 | 0.574307 |
d5da858ee8264e45cc7ebc8a91c6ae487e04e2ea | 299 | class CreateProjections < ActiveRecord::Migration[5.0]
def change
create_table :projections do |t|
t.date :due_date
t.decimal :amount, :precision => 8, :scale => 2
t.integer :user_id
t.string :description
t.boolean :cash
t.timestamps
end
end
end
| 21.357143 | 54 | 0.628763 |
11530d86c7b0b143f3fd793d842e84c946f08e22 | 3,239 | # -*- ruby encoding: utf-8 -*-
require 'color'
require 'minitest_helper'
module TestColor
class TestGrayScale < Minitest::Test
def setup
@gs = Color::GrayScale.from_percent(33)
end
def test_brightness
assert_in_delta(0.33, @gs.brightness, Color::COLOR_TOLERANCE)
end
def test_darken_by
assert_in_delta(29.7, @gs.darken_by(10).gray, Color::COLOR_TOLERANCE)
end
def test_g
assert_in_delta(0.33, @gs.g, Color::COLOR_TOLERANCE)
assert_in_delta(33, @gs.grey, Color::COLOR_TOLERANCE)
@gs.gray = 40
assert_in_delta(0.4, @gs.g, Color::COLOR_TOLERANCE)
@gs.g = 2.0
assert_in_delta(100, @gs.gray, Color::COLOR_TOLERANCE)
@gs.grey = -2.0
assert_in_delta(0.0, @gs.g, Color::COLOR_TOLERANCE)
end
def test_html_css
assert_equal("#545454", @gs.html)
assert_equal("rgb(33.00%, 33.00%, 33.00%)", @gs.css_rgb)
assert_equal("rgba(33.00%, 33.00%, 33.00%, 1.00)", @gs.css_rgba)
assert_equal("rgba(33.00%, 33.00%, 33.00%, 0.20)", @gs.css_rgba(0.2))
end
def test_lighten_by
assert_in_delta(0.363, @gs.lighten_by(10).g, Color::COLOR_TOLERANCE)
end
def test_pdf_fill
assert_equal("0.330 g", @gs.pdf_fill)
assert_equal("0.330 G", @gs.pdf_stroke)
end
def test_to_cmyk
cmyk = @gs.to_cmyk
assert_kind_of(Color::CMYK, cmyk)
assert_in_delta(0.0, cmyk.c, Color::COLOR_TOLERANCE)
assert_in_delta(0.0, cmyk.m, Color::COLOR_TOLERANCE)
assert_in_delta(0.0, cmyk.y, Color::COLOR_TOLERANCE)
assert_in_delta(0.67, cmyk.k, Color::COLOR_TOLERANCE)
end
def test_to_grayscale
assert_equal(@gs, @gs.to_grayscale)
assert_equal(@gs, @gs.to_greyscale)
end
def test_to_hsl
hsl = @gs.to_hsl
assert_kind_of(Color::HSL, hsl)
assert_in_delta(0.0, hsl.h, Color::COLOR_TOLERANCE)
assert_in_delta(0.0, hsl.s, Color::COLOR_TOLERANCE)
assert_in_delta(0.33, hsl.l, Color::COLOR_TOLERANCE)
assert_equal("hsl(0.00, 0.00%, 33.00%)", @gs.css_hsl)
assert_equal("hsla(0.00, 0.00%, 33.00%, 1.00)", @gs.css_hsla)
end
def test_to_rgb
rgb = @gs.to_rgb
assert_kind_of(Color::RGB, rgb)
assert_in_delta(0.33, rgb.r, Color::COLOR_TOLERANCE)
assert_in_delta(0.33, rgb.g, Color::COLOR_TOLERANCE)
assert_in_delta(0.33, rgb.b, Color::COLOR_TOLERANCE)
end
def test_to_yiq
yiq = @gs.to_yiq
assert_kind_of(Color::YIQ, yiq)
assert_in_delta(0.33, yiq.y, Color::COLOR_TOLERANCE)
assert_in_delta(0.0, yiq.i, Color::COLOR_TOLERANCE)
assert_in_delta(0.0, yiq.q, Color::COLOR_TOLERANCE)
end
def test_add
delta = @gs + Color::GrayScale.new(20)
max = @gs + Color::GrayScale.new(80)
assert_in_delta(1.0, max.g, Color::COLOR_TOLERANCE)
assert_in_delta(0.53, delta.g, Color::COLOR_TOLERANCE)
end
def test_subtract
delta = @gs - Color::GrayScale.new(20)
max = @gs - Color::GrayScale.new(80)
assert_in_delta(0.0, max.g, Color::COLOR_TOLERANCE)
assert_in_delta(0.13, delta.g, Color::COLOR_TOLERANCE)
end
def test_inspect
assert_equal("Gray [33.00%]", @gs.inspect)
end
end
end
| 30.271028 | 75 | 0.649583 |
0138852c0a0647b93ba861b83a3184a48316e4d9 | 2,614 | # "File" is a reserved class name
class FileFormula < Formula
desc "Utility to determine file types"
homepage "https://darwinsys.com/file/"
url "https://astron.com/pub/file/file-5.41.tar.gz"
sha256 "13e532c7b364f7d57e23dfeea3147103150cb90593a57af86c10e4f6e411603f"
# file-formula has a BSD-2-Clause-like license
license :cannot_represent
head "https://github.com/file/file.git"
livecheck do
url "https://astron.com/pub/file/"
regex(/href=.*?file[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
sha256 cellar: :any, arm64_monterey: "62330e525abefef9b0ee14c3c68eda5b3929885d40047ed3ff986a55530c1291"
sha256 cellar: :any, arm64_big_sur: "15e4b048fc9187617a94167c6a380334ba6b007f10c0b2e053f7eb819a07f487"
sha256 cellar: :any, monterey: "c7e02240e32e51a7864951464452210f93ab0d69b1db271620bdbca05c10664b"
sha256 cellar: :any, big_sur: "23a026b284b4a3b4d35bd2523dd2ff29e7067ba1a9398237f22187ff4b03ea99"
sha256 cellar: :any, catalina: "42b22fa1942a019e33f96f30af4e58bbffd586a14d9fba7318973b9d519aa264"
sha256 cellar: :any, mojave: "5b11f9096a34a2d37b3fdfc89836936d539b3db6da1e5468fc4d21e25d76160c"
sha256 cellar: :any_skip_relocation, x86_64_linux: "0a7e755b89c571f80b085d72602f34faefdaab64f7d879c3bb876c46480e8c69"
end
keg_only :provided_by_macos
depends_on "libmagic"
patch :DATA
def install
ENV.prepend "LDFLAGS", "-L#{Formula["libmagic"].opt_lib} -lmagic"
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install-exec"
system "make", "-C", "doc", "install-man1"
rm_r lib
end
test do
system "#{bin}/file", test_fixtures("test.mp3")
end
end
__END__
diff --git a/src/Makefile.in b/src/Makefile.in
index c096c71..583a0ba 100644
--- a/src/Makefile.in
+++ b/src/Makefile.in
@@ -115,7 +115,6 @@ libmagic_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
PROGRAMS = $(bin_PROGRAMS)
am_file_OBJECTS = file.$(OBJEXT) seccomp.$(OBJEXT)
file_OBJECTS = $(am_file_OBJECTS)
-file_DEPENDENCIES = libmagic.la
AM_V_P = $(am__v_P_@AM_V@)
am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
am__v_P_0 = false
@@ -311,7 +310,7 @@ libmagic_la_LDFLAGS = -no-undefined -version-info 1:0:0
@MINGW_TRUE@MINGWLIBS = -lgnurx -lshlwapi
libmagic_la_LIBADD = $(LTLIBOBJS) $(MINGWLIBS)
file_SOURCES = file.c seccomp.c
-file_LDADD = libmagic.la
+file_LDADD = $(LDADD)
CLEANFILES = magic.h
EXTRA_DIST = magic.h.in
HDR = $(top_srcdir)/src/magic.h.in
| 37.884058 | 123 | 0.700459 |
abb6dbbfa76e9c9e1ac8fb589ccb95f4d4976cdb | 628 | class ApiController < ApplicationController
before_action :check_sign_in
protect_from_forgery except: []
rescue_from CanCan::AccessDenied, with: :not_authorized
def not_authorized
render status: 401, json: { error: 'Not authorized.' }
end
def check_sign_in
not_authorized unless user_signed_in?
end
def ensure_patient
check_sign_in || not_authorized unless Patient === current_user.identity
end
def ensure_doctor
check_sign_in || not_authorized unless Doctor === current_user.identity
end
def use_case(klass)
UseCaseAdapter.new(klass, params, current_user, self).run
end
end
| 22.428571 | 76 | 0.756369 |
bf2d0a6afd3875089d4c4711e8a095f7c9658a5d | 150 | default['one_password']['version'] = '3.5.7'
default['one_password']['checksum'] = "fecb10ad40af614d15be2bac4e7a9ea35e57724dc608c34f8b95f464dc6c3224"
| 50 | 104 | 0.8 |
79b8d303af01f9c2846d03a03d48010a4e013fb3 | 89 | # frozen_string_literal: true
module Pico
module Case
VERSION = "0.1.0"
end
end
| 11.125 | 29 | 0.685393 |
7a29055f5ece8291708410b839393aa910da85c9 | 1,823 | ##
# This part of the module defines classes and methods
# related to variables.
module Cobaya::Combinators
##
# This abstract class defines the common parts
# of the variables combinators.
class Var < Combinator
def initialize(context, vars)
super context
@vars = vars
end
def generate
new_var = name
@vars.add new_var
new_var
end
end
##
# Defines how the local variables are going to be generated.
#
# :reek:UtilityFunction
class LVar < Var
def name
"var#{Cobaya::Generators::NumGen.new(10_000, false).generate}".to_sym
end
end
##
# Defines how the instance variables are going to be generated.
#
# :reek:UtilityFunction
class IVar < Var
def name
"@var#{Cobaya::Generators::NumGen.new(10_000, false).generate}".to_sym
end
end
##
# Defines how the class variables are going to be generated.
#
# :reek:UtilityFunction
class CVar < Var
def name
"@@var#{Cobaya::Generators::NumGen.new(10_000, false).generate}".to_sym
end
end
##
# Defines how the global variables are going to be generated.
#
# :reek:UtilityFunction
class GVar < Var
def name
"$var#{Cobaya::Generators::NumGen.new(10_000, false).generate}".to_sym
end
end
##
# Defines how the constants are going to be generated.
#
# :reek:UtilityFunction
class Const < Var
def name
"Const#{Cobaya::Generators::NumGen.new(10_000, false).generate}".to_sym
end
end
def lvar(locals)
LVar.new @context, locals
end
def ivar(instance_vars)
IVar.new @context, instance_vars
end
def cvar(class_vars)
CVar.new @context, class_vars
end
def gvar(globals)
GVar.new @context, globals
end
def const(consts)
Const.new @context, consts
end
end
| 19.602151 | 77 | 0.65661 |
1108334ffec7a61c272464db3bb93f023c1f48ca | 839 | =begin
#Tatum API
## Authentication <!-- ReDoc-Inject: <security-definitions> -->
OpenAPI spec version: 3.9.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 3.0.31
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Tatum::OneOfv3SubscriptionBody
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'OneOfv3SubscriptionBody' do
before do
# run before each test
@instance = Tatum::OneOfv3SubscriptionBody.new
end
after do
# run after each test
end
describe 'test an instance of OneOfv3SubscriptionBody' do
it 'should create an instance of OneOfv3SubscriptionBody' do
expect(@instance).to be_instance_of(Tatum::OneOfv3SubscriptionBody)
end
end
end
| 23.971429 | 85 | 0.75447 |
9168e3d79ba7b274f1e031a0f94f5222cb2e35ec | 1,034 | require File.expand_path("../../Abstract/abstract-php-extension", __FILE__)
class Php54MysqlndMs < AbstractPhp54Extension
init
homepage "http://pecl.php.net/package/mysqlnd_ms"
url "http://pecl.php.net/get/mysqlnd_ms-1.5.2.tgz"
sha1 "b7b3ddd1f40ffec75a48456edf053c28fc5aad83"
head "https://svn.php.net/repository/pecl/mysqlnd_ms/trunk/"
bottle do
sha256 "70582aaf75d9bc6dcd9aa9c93c370c1a9da08c631c75317014fc6e9a90c90efc" => :yosemite
sha256 "c34882192c7f22823d0e3f3ade9c75f634e91d48b586464700cac34432788386" => :mavericks
sha256 "caff6467525dfdaa5c2f2394101ed9f146bf85553143edf09aefb6ff9cebca56" => :mountain_lion
end
def extension
"mysqlnd_ms"
end
def install
Dir.chdir extension + "-#{version}" unless build.head?
ENV.universal_binary if build.universal?
safe_phpize
system "./configure", "--prefix=#{prefix}", phpconfig, "--enable-mysqlnd-ms"
system "make"
prefix.install "modules/" + extension + ".so"
write_config_file if build.with? "config-file"
end
end
| 31.333333 | 95 | 0.750484 |
33954f810810465ac83dba6ba29142477bba9279 | 1,202 | require 'spec_helper'
describe ProtectedController do
describe 'get :index' do
with :client
with :user
before do
@token = Devise::Oauth2Providable::AccessToken.create! :client => client, :user => user
end
context 'with valid bearer token in header' do
before do
@request.env['HTTP_AUTHORIZATION'] = "Bearer #{@token.token}"
get :index, :format => 'json'
end
it { should respond_with :ok }
end
context 'with valid bearer token in query string' do
before do
get :index, :access_token => @token.token, :format => 'json'
end
it { should respond_with :ok }
end
context 'with invalid bearer token in query param' do
before do
get :index, :access_token => 'invalid', :format => 'json'
end
it { should respond_with :unauthorized }
end
context 'with valid bearer token in header and query string' do
before do
end
it 'raises error' do
lambda {
@request.env['HTTP_AUTHORIZATION'] = "Bearer #{@token.token}"
get :index, :access_token => @token.token, :format => 'json'
}.should raise_error
end
end
end
end
| 27.953488 | 93 | 0.609817 |
798ddde58767bc0ac91652a99ba1062809cb6e0b | 3,617 | module HealthSeven::V2_7
class PglPc6 < ::HealthSeven::Message
attribute :msh, Msh, position: "MSH", require: true
attribute :sfts, Array[Sft], position: "SFT", multiple: true
attribute :uac, Uac, position: "UAC"
attribute :pid, Pid, position: "PID", require: true
class PatientVisit < ::HealthSeven::SegmentGroup
attribute :pv1, Pv1, position: "PV1", require: true
attribute :pv2, Pv2, position: "PV2"
end
attribute :patient_visit, PatientVisit, position: "PGL_PC6.PATIENT_VISIT"
class Goal < ::HealthSeven::SegmentGroup
attribute :gol, Gol, position: "GOL", require: true
attribute :ntes, Array[Nte], position: "NTE", multiple: true
attribute :vars, Array[Var], position: "VAR", multiple: true
class GoalRole < ::HealthSeven::SegmentGroup
attribute :rol, Rol, position: "ROL", require: true
attribute :vars, Array[Var], position: "VAR", multiple: true
end
attribute :goal_roles, Array[GoalRole], position: "PGL_PC6.GOAL_ROLE", multiple: true
class Pathway < ::HealthSeven::SegmentGroup
attribute :pth, Pth, position: "PTH", require: true
attribute :vars, Array[Var], position: "VAR", multiple: true
end
attribute :pathways, Array[Pathway], position: "PGL_PC6.PATHWAY", multiple: true
class Observation < ::HealthSeven::SegmentGroup
attribute :obx, Obx, position: "OBX", require: true
attribute :ntes, Array[Nte], position: "NTE", multiple: true
end
attribute :observations, Array[Observation], position: "PGL_PC6.OBSERVATION", multiple: true
class Problem < ::HealthSeven::SegmentGroup
attribute :prb, Prb, position: "PRB", require: true
attribute :ntes, Array[Nte], position: "NTE", multiple: true
attribute :vars, Array[Var], position: "VAR", multiple: true
class ProblemRole < ::HealthSeven::SegmentGroup
attribute :rol, Rol, position: "ROL", require: true
attribute :vars, Array[Var], position: "VAR", multiple: true
end
attribute :problem_roles, Array[ProblemRole], position: "PGL_PC6.PROBLEM_ROLE", multiple: true
class ProblemObservation < ::HealthSeven::SegmentGroup
attribute :obx, Obx, position: "OBX", require: true
attribute :ntes, Array[Nte], position: "NTE", multiple: true
end
attribute :problem_observations, Array[ProblemObservation], position: "PGL_PC6.PROBLEM_OBSERVATION", multiple: true
end
attribute :problems, Array[Problem], position: "PGL_PC6.PROBLEM", multiple: true
class Order < ::HealthSeven::SegmentGroup
attribute :orc, Orc, position: "ORC", require: true
class OrderDetail < ::HealthSeven::SegmentGroup
class Choice < ::HealthSeven::SegmentGroup
end
attribute :choice, Choice, position: "PGL_PC6.CHOICE", require: true
attribute :ntes, Array[Nte], position: "NTE", multiple: true
attribute :vars, Array[Var], position: "VAR", multiple: true
class OrderObservation < ::HealthSeven::SegmentGroup
attribute :obx, Obx, position: "OBX", require: true
attribute :ntes, Array[Nte], position: "NTE", multiple: true
attribute :vars, Array[Var], position: "VAR", multiple: true
end
attribute :order_observations, Array[OrderObservation], position: "PGL_PC6.ORDER_OBSERVATION", multiple: true
end
attribute :order_detail, OrderDetail, position: "PGL_PC6.ORDER_DETAIL"
end
attribute :orders, Array[Order], position: "PGL_PC6.ORDER", multiple: true
end
attribute :goals, Array[Goal], position: "PGL_PC6.GOAL", require: true, multiple: true
end
end | 52.42029 | 121 | 0.687863 |
01b5cb1edd9a4214a11847df5110aea6183d5d17 | 901 | # frozen_string_literal: true
require "test_helper"
class ConfigTest < ActiveSupport::TestCase
def setup
@klass = Class.new {
extend Authlogic::Config
def self.foobar(value = nil)
rw_config(:foobar_field, value, "default_foobar")
end
}
@subklass = Class.new(@klass)
end
def test_config
assert_equal({}, @klass.acts_as_authentic_config)
end
def test_rw_config_read_with_default
assert "default_foobar", @klass.foobar
end
def test_rw_config_write
assert_equal "my_foobar", @klass.foobar("my_foobar")
assert_equal "my_foobar", @klass.foobar
assert_equal "my_new_foobar", @klass.foobar("my_new_foobar")
assert_equal "my_new_foobar", @klass.foobar
end
def test_subclass_rw_config_write
assert_equal "subklass_foobar", @subklass.foobar("subklass_foobar")
assert_equal "default_foobar", @klass.foobar
end
end
| 23.102564 | 71 | 0.722531 |
acf6eac1bd19041a7bbcbf4ad7f685ecfcc67101 | 1,396 | module SessionsHelper
# 渡されたユーザーでログインする
def log_in(user)
session[:user_id] = user.id
end
# ユーザーのセッションを永続的にする
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
# 渡されたユーザーがログイン済みユーザーであればtrueを返す
def current_user?(user)
user == current_user
end
# 記憶トークンcookieに対応するユーザーを返す
# 現在ログイン中のユーザーを返す (いる場合)
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, cookies[:remember_token])
log_in user
@current_user = user
end
end
end
# ユーザーがログインしていればtrue、その他ならfalseを返す
def logged_in?
!current_user.nil?
end
# 永続的セッションを破棄する
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
# 現在のユーザーをログアウトする
def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
# 記憶したURL (もしくはデフォルト値) にリダイレクト
def redirect_back_or(default)
redirect_to(session[:forwarding_url] || default)
session.delete(:forwarding_url)
end
# アクセスしようとしたURLを覚えておく
def store_location
session[:forwarding_url] = request.original_url if request.get?
end
end
| 21.476923 | 75 | 0.691977 |
1d27b5995dac9f61240e3b39250b5d41c3b0e360 | 2,446 | =begin
This file is part of Viewpoint; the Ruby library for Microsoft Exchange Web Services.
Copyright © 2011 Dan Wanek <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
module Viewpoint
class StringFormatException < ::Exception; end
# Collection of utility methods for working with Strings
module StringUtils
DURATION_RE = /
(?<start>P)
((?<weeks>\d+)W)?
((?<days>\d+)D)?
(?<time>T
((?<hours>\d+)H)?
((?<minutes>\d+)M)?
((?<seconds>\d+)S)?
)?
/x
def self.included(klass)
klass.extend StringUtils
end
private
# Change CamelCased strings to ruby_cased strings
# It uses the lookahead assertion ?= In this case it basically says match
# anything followed by a capital letter, but not the capital letter itself.
# @see http://www.pcre.org/pcre.txt The PCRE guide for more details
def ruby_case(input)
input.to_s.split(/(?=[A-Z])/).join('_').downcase
end
# Change a ruby_cased string to CamelCased
def camel_case(input)
input.to_s.split(/_/).map { |i|
i.sub(/^./) { |s| s.upcase }
}.join
end
# Convert an ISO8601 Duration format to seconds
# @see http://tools.ietf.org/html/rfc2445#section-4.3.6
# @param [String] input
# @return [nil,Fixnum] the number of seconds in this duration
# nil if there is no known duration
def iso8601_duration_to_seconds(input)
return nil if input.nil? || input.empty?
match_data = DURATION_RE.match(input)
raise(StringFormatException, "Invalid duration given") if match_data.nil?
duration = 0
duration += match_data[:weeks].to_i * 604800
duration += match_data[:days].to_i * 86400
duration += match_data[:hours].to_i * 3600
duration += match_data[:minutes].to_i * 60
duration += match_data[:seconds].to_i
end
end # StringUtils
end # Viewpoint
| 31.766234 | 87 | 0.665576 |
d520ad9a3c4732a5e4b38815c829dbd3343f2010 | 866 | # frozen_string_literal: true
require 'rails_helper'
include Warden::Test::Helpers
RSpec.describe 'Password protect non production instances', type: :system do
let(:login) { 'admin' }
let(:password) { 'whatever' }
before do
ENV['HTTP_USERNAME'] = login
ENV['HTTP_PASSWORD'] = password
end
context 'visiting an instance without HTTP_PASSWORD_PROTECT set' do
it 'does not prompt the user for a password' do
visit('/')
expect(page).to have_content('Emory')
end
end
context 'visiting an instance with HTTP_PASSWORD_PROTECT set' do
before do
ENV['HTTP_PASSWORD_PROTECT'] = 'true'
end
after do
ENV['HTTP_PASSWORD_PROTECT'] = 'false'
end
it 'prompts the user for a password' do
visit('/')
expect(page.find(:xpath, '//body').text).to eq "HTTP Basic: Access denied."
end
end
end
| 25.470588 | 81 | 0.670901 |
e23d8c5686be5209cdecfd4e90c603c260f90a0f | 819 | class TalksController < ApplicationController
before_filter :login_required, :except => :index
def index
@talks = Talk.all
respond_to do |format|
format.json {}
end
end
def new
@talk = Talk.new
end
def create
@talk = Talk.create(params[:talk])
if @talk.save
flash[:notice] = "Talk created"
redirect_to root_path
else
render :action => "new"
end
end
def edit
@talk = Talk.find(params[:id])
end
def update
@talk = Talk.find(params[:id])
@talk.update_attributes(params[:talk])
if @talk.save
flash[:notice] = "Talk updated"
redirect_to root_path
else
render :action => "edit"
end
end
def destroy
Talk.destroy(params[:id])
redirect_to root_path
end
end | 17.804348 | 50 | 0.593407 |
18375e5ec74a13728234a68000e9fd867a54ef34 | 4,546 | module Strongspace::Command
class Auth < Base
attr_accessor :credentials
def client
@client ||= init_strongspace
end
def init_strongspace
client = Strongspace::Client.new(user, password, host)
client
end
# just a stub; will raise if not authenticated
def check
client.spaces
end
def host
ENV['STRONGSPACE_HOST'] || 'https://www.strongspace.com'
end
def reauthorize_interactve
@credentials = ask_for_credentials
write_credentials
end
def authorize!
@credentials = [args.first, args[1]]
r = Strongspace::Client.auth(@credentials[0], @credentials[1], host)
if r
@credentials[0] = r['username']
@credentials[1] = r['api_token']
write_credentials
return true
end
return false
end
def authenticated_login
if args.blank?
url = "#{host}/login/#{client.login_token['login_token']}"
else
to = URI.escape(args[0][0..1]) + URI.escape(URI.escape(args[0][2..-1])).gsub('&', '%26')
url = "#{host}/login/#{client.login_token['login_token']}?to=#{to}"
end
if running_on_a_mac?
`open "#{url}"`
elsif running_on_windows?
require 'win32ole'
shell = WIN32OLE.new('Shell.Application')
shell.shellExecute(url, '', '', 'open', 3)
end
end
def user # :nodoc:
get_credentials
@credentials[0]
end
def password # :nodoc:
get_credentials
@credentials[1]
end
def get_credentials # :nodoc:
return if @credentials
unless @credentials = read_credentials
@credentials = ask_for_credentials
save_credentials
end
@credentials
end
def read_credentials
File.exists?(credentials_file) and File.read(credentials_file).split("\n")
end
def echo_off
system "stty -echo"
end
def echo_on
system "stty echo"
end
def ask_for_credentials
if ENV["STRONGSPACE_DISPLAY"] == "silent"
return [nil, nil]
end
puts "Enter your Strongspace credentials."
print "Username or Email: "
user = ask
print "Password: "
password = running_on_windows? ? ask_for_password_on_windows : ask_for_password
r = Strongspace::Client.auth(user, password, host)
[r['username'], r['api_token']]
end
def valid_saved_credentials?
if File.exists?(credentials_file)
credentials = read_credentials
r = Strongspace::Client.auth(credentials[0], credentials[1], host)
return !r.blank?
end
return false
end
def ask_for_password_on_windows
require "Win32API"
char = nil
password = ''
while char = Win32API.new("crtdll", "_getch", [ ], "L").Call do
break if char == 10 || char == 13 # received carriage return or newline
if char == 127 || char == 8 # backspace and delete
password.slice!(-1, 1)
else
# windows might throw a -1 at us so make sure to handle RangeError
(password << char.chr) rescue RangeError
end
end
puts
return password
end
def ask_for_password
echo_off
password = ask
puts
echo_on
return password
end
def save_credentials
if args[0] and args[1]
@credentials = []
@credentials[0] = args[0]
@credentials[1] = args[1]
end
begin
write_credentials
command = 'auth:check'
Strongspace::Command.run_internal(command, args)
rescue RestClient::Unauthorized => e
delete_credentials
raise e unless retry_login?
display "\nAuthentication failed"
@credentials = ask_for_credentials
@client = init_strongspace
retry
rescue Exception => e
delete_credentials
raise e
end
end
def retry_login?
@login_attempts ||= 0
@login_attempts += 1
@login_attempts < 3
end
def write_credentials
begin
FileUtils.mkdir_p(credentials_folder)
rescue Errno::EEXIST => e
end
File.open(credentials_file, 'w') do |f|
f.puts self.credentials
end
set_credentials_permissions
end
def set_credentials_permissions
FileUtils.chmod 0700, File.dirname(credentials_file)
FileUtils.chmod 0600, credentials_file
end
def delete_credentials
FileUtils.rm_f(credentials_file)
end
end
end
| 23.193878 | 96 | 0.604927 |
e2ef8aa4827036de6361a59290232ad7bfeca0f5 | 2,592 |
require 'cuba'
require 'da99_rack_protect'
require 'multi_json'
require 'www_app'
PATH = File.expand_path(File.dirname(__FILE__) + '../../..')
Rack::Mime::MIME_TYPES.merge!({".map" => "application/json"})
Cuba.use Da99_Rack_Protect do |c|
c.config :host, :localhost if ENV['IS_DEV']
end
Cuba.use Rack::ShowExceptions
# Cuba.use(Class.new {
# def initialize app
# @app = app
# end
# def call env
# results = @app.call(env)
# if results.first == 404
# if env['PATH_INFO'] == '/old'
# return [
# 200,
# {"Content-Type" => "text/html"},
# [File.read("./specs/client-side/index.html").gsub("{token}", env['rack.session']['csrf'])]
# ]
# end
# [
# Rack::Directory.new(File.expand_path('./specs/lib')),
# Rack::Directory.new(File.expand_path('./specs/client-side')),
# Rack::Directory.new(File.expand_path('./lib/public'))
# ].detect { |r|
# status, headers, body = r.call(env)
# return [status, headers, body] if status != 404
# false
# }
# end
# results
# end
# })
PAGES = {
:root => WWW_App.new {
title { 'hello' }
div {
_.^(:happy) {
border '1px dashed red'
}
on(:click) {
add_class :happy
}
"Almost done."
}
}
}
Cuba.use Rack::Static, :urls=>["/www_app-#{File.read(PATH + '/VERSION').strip}"], :root=>'Public'
Cuba.define do
on get do
on root do
res.write PAGES[:root].to_html
end
end
on post do
data = (req.env["rack.request.form_hash"]).dup
data.delete('authenticity_token')
res['Content-Type'] = 'application/json';
on "repeat/error_msg" do
res.write MultiJson.dump({
'data' => data,
'clean_html' => {
'error_msg' => "<span>#{data['error_msg'] || 'Unknown error.'}</span>"
}
})
end
on "repeat/success_msg" do
res.write MultiJson.dump({
'data' => data,
'clean_html' => {
'success_msg' => "<span>#{ data['success_msg'] || 'Unknown success'}</span>"
}
})
end
on "repeat/vals" do
res.write MultiJson.dump({
'data' => data.select { |k,v| k['val'] },
'clean_html' => {
'success_msg' => 'Success in repeating vals.'
}
})
end
on(default) {
res.status = 404
res.write 'Missing'
}
end
on get do
on(default) {
res.status = 404
res.write 'Missing'
}
end # === on get
end # === Cuba.define
run Cuba
| 20.571429 | 102 | 0.524691 |
218421b3a381bd9b561b4b0e10f79c0d432668e1 | 33 | module FantasyManagersHelper
end
| 11 | 28 | 0.909091 |
ffd57718a69ca1fc542867597fb75d311c90b936 | 3,755 | # encoding: UTF-8
# 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: 20160222172108) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "assignments", force: :cascade do |t|
t.datetime "date"
t.integer "user_id"
t.integer "project_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "assignments", ["project_id"], name: "index_assignments_on_project_id", using: :btree
add_index "assignments", ["user_id"], name: "index_assignments_on_user_id", using: :btree
create_table "customers", force: :cascade do |t|
t.string "title"
t.string "comment"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "projects", force: :cascade do |t|
t.string "location"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "customer_id"
t.string "title"
t.integer "status_id"
end
add_index "projects", ["customer_id"], name: "index_projects_on_customer_id", using: :btree
add_index "projects", ["status_id"], name: "index_projects_on_status_id", using: :btree
create_table "statuses", force: :cascade do |t|
t.string "text"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "table_entries", force: :cascade do |t|
t.string "comment"
t.float "duration"
t.datetime "date"
t.integer "user_id"
t.integer "project_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "table_entries", ["project_id"], name: "index_table_entries_on_project_id", using: :btree
add_index "table_entries", ["user_id"], name: "index_table_entries_on_user_id", using: :btree
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "position"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
add_foreign_key "assignments", "projects"
add_foreign_key "assignments", "users"
add_foreign_key "projects", "customers"
add_foreign_key "projects", "statuses"
add_foreign_key "table_entries", "projects"
add_foreign_key "table_entries", "users"
end
| 39.114583 | 119 | 0.701198 |
aba60a118e80752d6782d0c81b1a6abd4a7c8061 | 3,493 | class Libgxps < Formula
desc "GObject based library for handling and rendering XPS documents"
homepage "https://wiki.gnome.org/Projects/libgxps"
url "https://download.gnome.org/sources/libgxps/0.3/libgxps-0.3.2.tar.xz"
sha256 "6d27867256a35ccf9b69253eb2a88a32baca3b97d5f4ef7f82e3667fa435251c"
license "LGPL-2.1-or-later"
revision 1
head "https://gitlab.gnome.org/GNOME/libgxps.git", branch: "master"
livecheck do
url :stable
regex(/libgxps[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
sha256 cellar: :any, arm64_monterey: "2e78b1e36e2e6095af5cbf6f86e1d544d3225402474164aa1d667fbeb97a6e91"
sha256 cellar: :any, arm64_big_sur: "0243fa2f8e5b1559b417e47e5aea3b6ab8745164f397963c2ac94952c3915324"
sha256 cellar: :any, monterey: "acb2b38e9fa9925dc00c2b8497e9e0c98e38a279d81dd3b2ca6946017bff8367"
sha256 cellar: :any, big_sur: "6ad3b9179f42d68083b2b8bf54fe2d36433ed45d51e8ee13af392638e1b07174"
sha256 cellar: :any, catalina: "52dc9223c583d315cc9b6edd29e696ac4e8dab1fe5d4d452c9ac3f20af185412"
sha256 cellar: :any, mojave: "e113e3685b5f6a000d1e23f2bf67cb78e67c5bba58562156d5a78311ee28c05c"
sha256 x86_64_linux: "5c4da3716214bcc70b6a4cfe2b3dd0c5b624e74a34cc2f72f2e3ac00f7211258"
end
keg_only "it conflicts with `ghostscript`"
depends_on "gobject-introspection" => :build
depends_on "meson" => :build
depends_on "ninja" => :build
depends_on "pkg-config" => :build
depends_on "glib"
depends_on "gtk+3"
depends_on "libarchive"
depends_on "little-cms2"
uses_from_macos "zip" => :test
uses_from_macos "zlib"
def install
# Tell meson to search for brewed zlib before host zlib on Linux.
# This is not the same variable as setting LD_LIBRARY_PATH!
ENV.append "LIBRARY_PATH", Formula["zlib"].opt_lib unless OS.mac?
mkdir "build" do
system "meson", *std_meson_args, ".."
system "ninja", "-v"
system "ninja", "install", "-v"
end
end
def caveats
<<~EOS
`ghostscript` now installs a conflicting #{shared_library("libgxps")}.
You may need to `brew unlink libgxps` if you have both installed.
EOS
end
test do
mkdir_p [
(testpath/"Documents/1/Pages/_rels/"),
(testpath/"_rels/"),
]
(testpath/"FixedDocumentSequence.fdseq").write <<~EOS
<FixedDocumentSequence>
<DocumentReference Source="/Documents/1/FixedDocument.fdoc"/>
</FixedDocumentSequence>
EOS
(testpath/"Documents/1/FixedDocument.fdoc").write <<~EOS
<FixedDocument>
<PageContent Source="/Documents/1/Pages/1.fpage"/>
</FixedDocument>
EOS
(testpath/"Documents/1/Pages/1.fpage").write <<~EOS
<FixedPage Width="1" Height="1" xml:lang="und" />
EOS
(testpath/"_rels/.rels").write <<~EOS
<Relationships>
<Relationship Target="/FixedDocumentSequence.fdseq" Type="http://schemas.microsoft.com/xps/2005/06/fixedrepresentation"/>
</Relationships>
EOS
[
"_rels/FixedDocumentSequence.fdseq.rels",
"Documents/1/_rels/FixedDocument.fdoc.rels",
"Documents/1/Pages/_rels/1.fpage.rels",
].each do |f|
(testpath/f).write <<~EOS
<Relationships />
EOS
end
zip = OS.mac? ? "/usr/bin/zip" : Formula["zip"].opt_bin/"zip"
Dir.chdir(testpath) do
system zip, "-qr", (testpath/"test.xps"), "_rels", "Documents", "FixedDocumentSequence.fdseq"
end
system "#{bin}/xpstopdf", (testpath/"test.xps")
end
end
| 35.642857 | 127 | 0.691955 |
bbcd055fc6cabc5b6cb77a02d136760de7625f16 | 59 | module GEPUB
# GEPUB gem version
VERSION = "1.0.4"
end
| 11.8 | 21 | 0.661017 |
1c4a07274abeb0e83b7aea7bd60ad4b2cf1f1fc5 | 682 | class API::V1::PartnerApprovalsController < ApplicationController
skip_before_action :verify_authenticity_token
skip_before_action :authenticate_user!
skip_before_action :authorize_user
respond_to :json
def create
return head :forbidden unless api_key_valid?
@partner = Partner.find(approval_params[:diaper_partner_id])
@partner.awaiting_review!
render json: { message: "Status changed to awaiting review." }, status: :ok
end
private
def approval_params
params.require(:partner).permit(:diaper_partner_id)
end
def api_key_valid?
return true if Rails.env.development?
request.headers["X-Api-Key"] == ENV["PARTNER_KEY"]
end
end
| 25.259259 | 79 | 0.756598 |
ff8d30258c3b5ee272c79c763f0d4f9a977e8bea | 239 | # frozen_string_literal: true
require 'spec_helper'
require_relative '../../app/models/test'
RSpec.describe Test do
let(:object) { described_class.new }
describe '#call' do
it 'processes' do
object.call
end
end
end
| 14.9375 | 40 | 0.686192 |
3945939bcd029103bbdb75d8f64f41c269849a09 | 883 | Rails.application.routes.draw do
devise_for :admin_users
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
root 'static_pages#home'
get '/about', to: 'static_pages#about'
get '/signup', to: 'users#new'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
resources :users do
member do
end
end
resources :account_activations, only: [:edit]
#ルーティングを作成(入れ子のルーティングの書き方を調査)
resources :attendances do
collection do
get '/month_edit', to: 'attendances#month_edit'
post '/month_update', to: 'attendances#month_update'
end
end
resources :password_resets, only: [:new, :create, :edit, :update]
resources :relationships, only: [:create, :destroy]
end | 27.59375 | 71 | 0.661382 |
d5149defa2edd483e5b40a06ec6aecb6e6befcf5 | 307 | require 'securerandom'
Fabricator(:workflow_task_metadata, from: :open_struct) do
namespace 'test-namespace'
id { sequence(:workflow_task_id) }
task_token { SecureRandom.uuid }
attempt 1
workflow_run_id { SecureRandom.uuid }
workflow_id { SecureRandom.uuid }
workflow_name 'TestWorkflow'
end
| 25.583333 | 58 | 0.76873 |
188dd7a0a76901f6fcd58d3aa5f55e9025678fe9 | 460 | class AddRequiredInformation < ActiveRecord::Migration
def change
add_column :checkins, :full_name, :string
add_column :checkins, :address, :text
add_column :checkins, :interview_location, :string
add_column :checkins, :interview_date, :string
add_column :checkins, :interview_time, :string
add_column :checkins, :primary_contact_name, :string
add_column :checkins, :primary_contact_mobile_phone, :string
end
end
| 28.75 | 66 | 0.736957 |
f8ad10abe64f3966c1638ff74f0cd9ddf64504ba | 290 | require './config/environment.rb'
class Student < ActiveRecord::Base
has_many :lessons
has_many :notes
has_many :topics, through: :lessons
# returns an array of instances of the Note class that belong to a student
def get_all_notes
Note.where(student_id: self.id)
end
end
| 22.307692 | 76 | 0.744828 |
18983245a4ba4d7a46d230a8543bd424ef8c3c0a | 8,141 | require "spec_helper"
class PageAttachment < ActiveRecord::Base
end
describe Irwi::Helpers::WikiPagesHelper do
it { is_expected.not_to be_nil }
context "included in class" do
subject do
ActionView::Base.new.tap do |v|
v.send :extend, ERB::Util
v.send :extend, described_class
end
end
it { is_expected.to respond_to(:wiki_page_form) }
it { is_expected.to respond_to(:wiki_page_new_path) }
it { is_expected.to respond_to(:wiki_page_edit_path) }
it { is_expected.to respond_to(:wiki_page_history_path) }
it { is_expected.to respond_to(:wiki_page_compare_path) }
it { is_expected.to respond_to(:wiki_page_path) }
specify "builds url_for params by wiki_page_new_path" do
allow(subject).to receive(:params).and_return(path: 'newpath')
expect(subject).to receive(:url_for).with(action: :new, path: 'newpath').and_return('newpath')
expect(subject.wiki_page_new_path).to eq 'newpath'
end
specify "builds url_for params by wiki_page_new_path if path left blank" do
allow(subject).to receive(:params).and_return(nil)
expect(subject).to receive(:url_for).with(action: :new).and_return('blank_path')
expect(subject.wiki_page_new_path).to eq('blank_path')
end
specify "builds url_for params by wiki_page_edit_path" do
expect(subject).to receive(:url_for).with(action: :edit).and_return('epath')
expect(subject.wiki_page_edit_path).to eq('epath')
end
specify "builds url_for params by wiki_page_edit_path with path" do
expect(subject).to receive(:url_for).with(action: :edit, path: 'qwerty').and_return('epath')
expect(subject.wiki_page_edit_path('qwerty')).to eq('epath')
end
specify "builds url_for params by wiki_page_history_path" do
expect(subject).to receive(:url_for).with(action: :history).and_return('hpath')
expect(subject.wiki_page_history_path).to eq('hpath')
end
specify "builds url_for params by wiki_page_compare_path" do
expect(subject).to receive(:url_for).with(action: :compare).and_return('cpath')
expect(subject.wiki_page_compare_path).to eq('cpath')
end
specify "builds url_for params by wiki_page_path" do
expect(subject).to receive(:url_for).with(action: :show).and_return('spath')
expect(subject.wiki_page_path).to eq('spath')
end
specify "builds url_for params by wiki_page_path with path" do
expect(subject).to receive(:url_for).with(action: :show, path: '123').and_return('spath')
expect(subject.wiki_page_path('123')).to eq('spath')
end
it { expect(subject).to respond_to(:wiki_content) }
it { expect(subject).to respond_to(:wiki_diff) }
it { expect(subject).to respond_to(:wiki_user) }
it { expect(subject).to respond_to(:wiki_page_info) }
it { expect(subject).to respond_to(:wiki_page_actions) }
it { expect(subject).to respond_to(:wiki_page_history) }
it { expect(subject).to respond_to(:wiki_page_style) }
it { expect(subject).to respond_to(:wiki_link) }
it { expect(subject).to respond_to(:wiki_linkify) }
it { expect(subject).to respond_to(:wt) }
specify "formats and sanitizes content with current formatter and #sanitize" do
Irwi.config.formatter = double 'Formatter'
expect(Irwi.config.formatter).to receive(:format).with('Page content').and_return('Formatted content')
expect(subject).to receive(:auto_link).with('Formatted content').and_return('Formatted content with links')
expect(subject).to receive(:sanitize).with('Formatted content with links').and_return('Formatted and sanitized content with links')
expect(subject.wiki_content('Page content')).to eq('Formatted and sanitized content with links')
end
specify "renders wiki_page_info partial" do
expect(subject).to receive(:template_dir).and_return('partial_dir')
expect(subject).to receive(:render).with(partial: "partial_dir/wiki_page_info", locals: { page: 'MyPage' }).and_return('partial_body')
expect(subject.wiki_page_info('MyPage')).to eq('partial_body')
end
specify "renders wiki_page_actions partial" do
expect(subject).to receive(:template_dir).and_return('partial_dir')
expect(subject).to receive(:render).with(partial: "partial_dir/wiki_page_actions", locals: { page: 'MyPage' }).and_return('partial_body')
expect(subject.wiki_page_actions('MyPage')).to eq('partial_body')
end
specify "renders wiki_page_history partial" do
expect(subject).to receive(:template_dir).and_return('partial_dir')
expect(subject).to receive(:render).with(partial: "partial_dir/wiki_page_history", locals: { page: 'MyPage', versions: [1, 2], with_form: true }).and_return('partial_body')
expect(subject.wiki_page_history('MyPage', [1, 2])).to eq('partial_body')
end
specify "renders wiki_page_history partial (with default versions)" do
page = double 'MyPage'
expect(page).to receive(:versions).and_return([1])
expect(subject).to receive(:template_dir).and_return('partial_dir')
expect(subject).to receive(:render).with(partial: "partial_dir/wiki_page_history", locals: { page: page, versions: [1], with_form: false }).and_return('partial_body')
expect(subject.wiki_page_history(page)).to eq('partial_body')
end
specify "linkifies string" do
expect(subject).to receive(:wiki_link).exactly(3).times.with('Some other page').and_return('url')
expect(subject.wiki_linkify('[[Some other page]] - link')).to eq('<a href="url">Some other page</a> - link')
expect(subject.wiki_linkify('[[Some other page|Go other page]] - link')).to eq('<a href="url">Go other page</a> - link')
expect(subject.wiki_linkify('[[Some other page]]s are there')).to eq('<a href="url">Some other pages</a> are there')
end
specify "linkifies with anchors" do
expect(subject).to receive(:wiki_link).once.with('Some other page').and_return('url')
expect(subject.wiki_linkify('And [[Some other page#other|other page]]')).to eq('And <a href="url#other">other page</a>')
end
specify "generates link for non-existent page" do
page_class = double "WikiPageClass"
expect(page_class).to receive(:find_by_title).with('Page_title').and_return(nil)
expect(Irwi.config).to receive(:page_class).and_return(page_class)
expect(subject).to receive(:url_for).with(controller: 'wiki_pages', action: :show, path: 'Page_title').and_return('url')
expect(subject.wiki_link('Page_title')).to eq('url')
end
specify "generates link for existent page" do
page = double "WikiPage"
expect(page).to receive(:path).and_return('page_path')
page_class = double "WikiPageClass"
expect(page_class).to receive(:find_by_title).with('Page title').and_return(page)
expect(Irwi.config).to receive(:page_class).and_return(page_class)
expect(subject).to receive(:url_for).with(controller: 'wiki_pages', action: :show, path: 'page_path').and_return('url')
expect(subject.wiki_link('Page title')).to eq('url')
end
specify "not be vulnerable to XSS when showing a diff" do
xss = '<script>alert("exploit")</script>'
expect(subject.wiki_diff('foo bar', "foo #{xss} bar")).not_to include(xss)
end
it "renders wiki_page_form" do
allow(subject).to receive(:url_for).and_return("some_url")
allow(subject).to receive(:protect_against_forgery?).and_return(false)
subject.instance_variable_set(:@page, double(id: 11, title: 'Some value'))
code = subject.wiki_page_form do |f|
f.text_field :title
end
expect(code).to include('<form')
end
it "renders wiki_page_attachments" do
Irwi.config.page_attachment_class_name = 'PageAttachment'
expect(subject).to receive(:template_dir).and_return('partial_dir')
expect(subject).to receive(:render).with(partial: "partial_dir/wiki_page_attachments", locals: { page: 'MyPage' }).and_return('partial_body')
expect(subject.wiki_page_attachments('MyPage')).to eq 'partial_body'
end
end
end
| 41.535714 | 178 | 0.70409 |
ed906e3f54c8edc3a922827fdbaf5c0011481b63 | 11,959 | require "test_helper"
class AttachableTest < ActiveSupport::TestCase
include ActionDispatch::TestProcess
test "allows attachment" do
assert build(:publication).allows_attachments?
end
test "allows different attachment types" do
attachable = Publication.new
assert attachable.allows_attachment_type?("file")
assert attachable.allows_attachment_type?("external")
assert attachable.allows_attachment_type?("html")
assert_not attachable.allows_attachment_type?("unknown")
end
test "new attachments are put to the end of the list" do
publication = create(
:publication,
:with_file_attachment,
attachments: [
attachment1 = build(:file_attachment, ordering: 0),
attachment2 = build(:file_attachment, ordering: 1, file: file_fixture("whitepaper.pdf")),
],
)
attachment3 = FileAttachment.new(title: "Title", attachment_data: build(:attachment_data, file: file_fixture("sample.rtf")))
publication.attachments << attachment3
assert_equal [attachment1, attachment2, attachment3], publication.attachments.reload
end
test "creating a new attachable thing with multiple attachments sets the correct ordering" do
publication = build(
:publication,
:with_file_attachment,
attachments: [
attachment1 = build(:file_attachment),
attachment2 = build(:file_attachment, file: file_fixture("whitepaper.pdf")),
],
)
publication.save!
assert_equal [attachment1, attachment2], publication.attachments
assert_equal 0, attachment1.ordering
assert_equal 1, attachment2.ordering
end
test "should be invalid if an edition has an attachment but no alternative format provider" do
attachment = build(:file_attachment)
publication = build(:publication, attachments: [attachment], alternative_format_provider: nil)
assert_not publication.valid?
end
test "should be invalid if an edition has an attachment but alternative format provider has no email address set" do
attachment = build(:file_attachment)
organisation = build(:organisation, alternative_format_contact_email: nil)
publication = build(:publication, attachments: [attachment], alternative_format_provider: organisation)
assert_not publication.valid?
end
test "should be valid without alternative format provider if no attachments" do
publication = build(:publication, attachments: [])
assert publication.valid?
end
test "should say a edition does not have a thumbnail when it has no attachments" do
edition = create(:publication)
assert_not edition.has_thumbnail?
end
test "should say a edition does not have a thumbnail when it has no thumbnailable attachments" do
sample_csv = build(:file_attachment, file: upload_fixture("sample-from-excel.csv", "text/csv"))
edition = build(:publication)
edition.attachments << sample_csv
assert_not edition.has_thumbnail?
end
def build_edition_with_three_attachments
edition = create(:publication)
edition.attachments << @sample_csv = create(:file_attachment, file: upload_fixture("sample-from-excel.csv", "text/csv"), attachable: edition)
edition.attachments << @greenpaper_pdf = create(:file_attachment, file: upload_fixture("greenpaper.pdf", "application/pdf"), attachable: edition)
edition.attachments << @two_pages_pdf = create(:file_attachment, file: upload_fixture("two-pages.pdf"), attachable: edition)
edition
end
test "should say an edition has a thumbnail when it has a thumbnailable attachment" do
edition = build_edition_with_three_attachments
assert edition.has_thumbnail?
end
test "should return the URL of a thumbnail when the edition has a thumbnailable attachment" do
edition = build_edition_with_three_attachments
assert_equal @greenpaper_pdf.url(:thumbnail), edition.thumbnail_url
end
test "should include attachment details into the #search_index" do
attachment = build(
:file_attachment,
title: "The title of the attachment",
hoc_paper_number: "1234",
parliamentary_session: "2013-14",
command_paper_number: "Cm. 1234",
unique_reference: "w123",
isbn: "0140620222",
)
edition = create(
:publication,
:with_file_attachment,
attachments: [attachment],
)
index = edition
.attachments
.to_a
.index { |edition_attachment| edition_attachment.is_a?(FileAttachment) }
assert_equal "The title of the attachment", edition.search_index["attachments"][index][:title]
assert_equal attachment.isbn, edition.search_index["attachments"][index][:isbn]
assert_equal attachment.unique_reference, edition.search_index["attachments"][index][:unique_reference]
assert_equal attachment.command_paper_number, edition.search_index["attachments"][index][:command_paper_number]
assert_equal attachment.hoc_paper_number, edition.search_index["attachments"][index][:hoc_paper_number]
end
test "#reorder_attachments should update the ordering of its attachments" do
attachable = create(:consultation)
a, b, c = 3.times.map { create(:file_attachment, attachable: attachable) }
attachable.reload.reorder_attachments([b.id, a.id, c.id])
assert_equal [b, a, c], attachable.reload.attachments
end
test "#reorder_attachments should handle existing negative orderings" do
attachable = create(:consultation)
a = create(:file_attachment, attachable: attachable, ordering: -1)
b = create(:file_attachment, attachable: attachable, ordering: 0, file: file_fixture("whitepaper.pdf"))
c = create(:file_attachment, attachable: attachable, ordering: 1, file: file_fixture("simple.pdf"))
attachable.reload.reorder_attachments([b.id, a.id, c.id])
assert_equal [b, a, c], attachable.reload.attachments
end
test "#reorder_attachments handles deleted attachments that had high ordering values" do
attachable = create(:consultation)
a = create(:file_attachment, attachable: attachable, ordering: 0)
b = create(:file_attachment, attachable: attachable, ordering: 1)
create(:file_attachment, attachable: attachable, ordering: 2, deleted: true)
attachable.reload.reorder_attachments([b.id, a.id])
assert_equal [b, a], attachable.reload.attachments
end
test "#reorder_attachments handles deleted attachments that had low ordering values" do
attachable = create(:consultation)
create(:file_attachment, attachable: attachable, ordering: 0, deleted: true)
create(:file_attachment, attachable: attachable, ordering: 1, deleted: true)
create(:file_attachment, attachable: attachable, ordering: 2, deleted: true)
a = create(:file_attachment, attachable: attachable, ordering: 3)
b = create(:file_attachment, attachable: attachable, ordering: 4)
attachable.reload.reorder_attachments([b.id, a.id])
assert_equal [b, a], attachable.reload.attachments
end
test "has html_attachments association to fetch only HtmlAttachments" do
attachment1 = build(:file_attachment, ordering: 0)
attachment2 = build(:html_attachment, title: "Test HTML attachment", ordering: 1)
attachment3 = build(:html_attachment, title: "Title", body: "Testing")
publication = create(
:publication,
:with_file_attachment,
attachments: [attachment1, attachment2],
)
publication.attachments << attachment3
assert_equal [attachment2, attachment3], publication.html_attachments.reload
end
test "attachment association excludes soft-deleted Attachments" do
publication = create(
:publication,
:with_file_attachment,
attachments: [
attachment1 = build(:file_attachment),
build(:html_attachment, title: "HTML attachment", deleted: true),
],
)
assert_equal [attachment1], publication.attachments.reload
end
test "html_attachment association excludes soft-deleted HtmlAttachments" do
publication = create(
:publication,
attachments: [
attachment1 = build(:html_attachment, title: "Test HTML attachment"),
build(:html_attachment, title: "Another HTML attachment", deleted: true),
],
)
assert_equal [attachment1], publication.html_attachments.reload
end
test "#has_command_paper? is true if an attachment is a command paper" do
pub = build(:publication)
pub.stubs(:attachments).returns([
OpenStruct.new(is_command_paper?: false),
])
assert_not pub.has_command_paper?
pub.stubs(:attachments).returns([
OpenStruct.new(is_command_paper?: false),
OpenStruct.new(is_command_paper?: true),
])
assert pub.has_command_paper?
end
test "#has_act_paper? is true if an attachment is an act paper" do
pub = build(:publication)
pub.stubs(:attachments).returns([
OpenStruct.new(is_act_paper?: false),
])
assert_not pub.has_act_paper?
pub.stubs(:attachments).returns([
OpenStruct.new(is_act_paper?: false),
OpenStruct.new(is_act_paper?: true),
])
assert pub.has_act_paper?
end
test "re-editioned editions deep-clones attachments" do
file_attachment = build(:file_attachment, attachable: nil, ordering: 0)
html_attachment = build(:html_attachment, attachable: nil, ordering: 1)
publication = create(
:published_publication,
:with_alternative_format_provider,
attachments: [file_attachment, html_attachment],
)
draft = publication.create_draft(create(:writer))
assert_equal 2, draft.attachments.size
attachment1 = draft.attachments[0]
assert attachment1.persisted?
assert file_attachment.id != attachment1.id
assert_equal file_attachment.attachment_data, attachment1.attachment_data
assert_equal file_attachment.title, attachment1.title
attachment2 = draft.attachments[1]
assert attachment2.persisted?
assert html_attachment.id != attachment2.id
assert_equal html_attachment.govspeak_content.body, attachment2.govspeak_content.body
assert_equal html_attachment.title, attachment2.title
end
test "re-editioned editions persists invalid attachments" do
file_attachment = build(:file_attachment, command_paper_number: "invalid")
file_attachment.save!(validate: false)
publication = create(
:published_publication,
:with_alternative_format_provider,
attachments: [file_attachment],
)
draft = publication.create_draft(create(:writer))
assert_equal 1, draft.reload.attachments.size
assert draft.attachments[0].persisted?
end
test "#delete_all_attachments soft-deletes any attachments that the edition has" do
publication = create(:draft_publication)
publication.attachments << attachment1 = build(:file_attachment)
publication.attachments << attachment2 = build(:html_attachment)
publication.delete_all_attachments
assert Attachment.find(attachment1.id).deleted?
assert Attachment.find(attachment2.id).deleted?
end
test "#deleted_html_attachments returns associated HTML attachments that have been deleted" do
publication = create(
:draft_publication,
attachments: [
attachment1 = build(:html_attachment, title: "First"),
attachment2 = build(:html_attachment, title: "Second"),
],
)
attachment1.destroy!
attachment2.destroy!
assert_equal [attachment1, attachment2], publication.deleted_html_attachments
end
test "#deleted_html_attachments doesn't return undeleted attachments" do
publication = create(
:draft_publication,
attachments: [
build(:html_attachment, title: "First"),
],
)
assert_empty publication.deleted_html_attachments
end
test "#attachables returns array including itself" do
attachable_edition = build(:edition)
assert attachable_edition.allows_attachments?
assert_equal [attachable_edition], attachable_edition.attachables
end
end
| 36.129909 | 149 | 0.731667 |
ac5cdd73d30d6a560be87579791942f89d721d2a | 584 | cask 'intensify-pro' do
version '1.2.3_952'
sha256 '147cc6db790e3ea6d7d51fbbcde5c27957cc4df24120b1ec79afde2d70d44dd5'
# amazonaws.com/IntensifyCK was verified as official when first introduced to the cask
url "https://creativekit.s3.amazonaws.com/IntensifyCK/IntensifyCK_Distribution_v#{version.dots_to_underscores}.zip"
appcast 'http://cdn.macphun.com/updates/IntensifyPro/appcast.xml',
checkpoint: 'dd6bc7a7e2b41782984ed47a7e4edc7af2898990bbdd5b9c61f85f6d63523ab0'
name 'Intensify Pro'
homepage 'https://macphun.com/intensify'
app 'Intensify CK.app'
end
| 41.714286 | 117 | 0.80137 |
b99c50b8957a8c765452b5f821dc4adbd0081add | 247 | class CreateScenarioMemberships < ActiveRecord::Migration[4.2]
def change
create_table :scenario_memberships do |t|
t.integer :agent_id, :null => false
t.integer :scenario_id, :null => false
t.timestamps
end
end
end
| 22.454545 | 62 | 0.688259 |
e9147b23cc3ec9c669d5bb62173cd8cc4f754339 | 12,142 | require 'dyio/lookup_hashes'
module Bowler
BOWLER_VERSION = 3
# Handles sending commands to the dyio, validating Bowler packets,
# and parsing Bowler packets into ruby data structures.
# All parsed packets have a :raw_res key containing the raw packet metadata and data with minimal processing
# (see {#parse_command} for the format of this data)
class CommandHandler
HEADER_SIZE = 11
# Creates a new command handler
# @param [DyIO] dyio_obj the {DyIO} representing the device to which the peripheral is connected
def initialize(dyio_obj)
@dyio = dyio_obj
end
# Sets the given channel number to the given value
# @param [Finxum] num the number of the channel to set
# @param [Array,Fixnum] val the value to which to set the channel
# @param [Hash] opts_hash a hash of options, including
# :val_size to specify a target value size
# and :time to specify a duration
def set_channel_value(num, val, opts_hsh)
res = nil
val_bytes = unless (val.is_a? Array)
val.to_a(opts_hsh[:val_size])
else
val
end
unless opts_hsh[:time].nil?
time_bytes = opts_hsh[:time].to_a(opts_hsh[:time_size])
self.send_command('schv', :post, num, val_bytes, time_bytes)
else
#puts 'I like cereal'
self.send_command('schv', :post, num, val_bytes)
end
end
# Sets the given channel number to the given mode
# @param [Finxum] num the number of the channel to set
# @param [Symbol] the mode to which to set the given channel (see {CommandHandler::CHAN_MODE_VALS})
# @param [true,false] async whether or not to set the channel to asynchronous mode
def set_channel_mode(num, mode, async=false)
self.send_command('schm', :post, num, CHAN_MODE_VALS[mode], (async ? 1 : 0))
end
# Parse an error packet into a BowlerException (and raise it)
def parse_error_command(res)
zone = res[:data][0]
section = res[:data][1]
raise BowlerException.new(zone,section), "Error RPC received"
end
# Parses a channel mode packet into `!{:mode => mode, :channel => channel_number}`
def parse_channel_mode(res)
{:raw_res => res, :mode => CHAN_MODE_NAMES[res[:data][1]], :channel => res[:data][0]}
end
# Parses a raw channel value packet, but doesn't do much, since the channel
# value's interpretation is largely dependent on the device connected
def parse_channel_value(res)
{:raw_res => res, :channel_num => res[:data][0], :raw_val => res[:data][1..-1]} # note: can only be interpreted based on which channel mode is set, so metadata parsed in channel class
end
# Parses a firmware revision packet into `!{:revisions => {:dyio => [x,y,z], :bootloader => [x,y,z]}}`
def parse_firmware_revision(res)
rv = {:raw_res => res, :revisions => {}}
#(0..res[:data].length/3 - 1).each do |ind|
# rv[:revisions].push res[:data][ind*3..(ind*3+2)]
#end
rv[:revisions][:dyio] = res[:data][0..2]
rv[:revisions][:bootloader] = res[:data][3..5]
rv
end
# Parses a channel modes packet into `!{:channels => [{:mode => mode, :editable => boolean}]}`
def parse_channel_modes(res)
rv = {:raw_res => res, :channels => []}
res[:data].each_with_index do |chan,ind|
cm = CHAN_MODE_NAMES[chan] || nil
editable = true
if (cm.nil?)
cm = :digital_in
editable = false
self.set_channel_mode(ind, cm, false)
end
rv[:channels].push({:mode => cm, :editable => editable})
end
rv
end
# Parses a channel values packet into `!{:channels => [[channelvalue],[channelvalue],...]}` (see #parse_channel_value)
def parse_channel_values(res)
rv = {:raw_res => res}
rv[:channels] = res[:data].reduce([[]]) do |acc,elem|
if acc[-1].length < 4
acc[-1].push(elem)
else
acc.push([elem])
end
acc
end
rv
end
# Sends a power-on command
def power
# TODO: handle disableBrownoutProtected
self.send_command('_pwr', :get)
end
# Parses a power packet into `!{:voltage => voltage (in what units?), :banks => [:regulated or :unpowered or :powered, same types]}`
def parse_power(res)
rv =
{
:raw_res => res,
:voltage => ((res[:data][2] << 8) | res[:data][3])/1000.0,
:banks => []
}
rv[:banks][0] = case (res[:data][0])
when 1
:regulated
when 0
if (rv[:voltage] < 5.0)
:unpowered
else
:powered
end
else
:powered
end
rv[:banks][1] = case (res[:data][1])
when 1
:regulated
when 0
if (rv[:voltage] < 5.0)
:unpowered
else
:powered
end
else
:powered
end
rv
end
alias :power_on :power
# Sends a command to start the heartbeat with the given frequency
def start_heartbeat(hb)
res = self.send_command('safe', :post, 1, hb & 0x00FF, hb & 0xFF00) # expects a 16-bit integer (2 bytes), the 1 is for 'true'
rv = {:raw_res => res}
end
# Sends a command to retrieve the DyIO's info string, or to set the info string if a string is speficied
def get_info(name=nil)
# TODO: make get_info and set_info
res = if name.nil?
self.send_command('info', :get)
else
self.send_command('info', :critical, name) # takes up to 16 bytes?
end
end
# Parses an info packet into `!{:string => string}`
def parse_get_info(res)
# note: does not return any formatted data
{:raw_res => res, :string => res[:data]}
end
# Parses a bowler packet into `!{:revision => number, :mac_address => bytes, :namespace_id => number, :full_transaction_id => number, :direction => :upstream or :downstream,
# :given_size => number, :given_crc => number, :rpc => string, :data => bytes, :method => :status or :get or :post or :critical or :async or [:other, number], :calculated_crc => number,
# :calculated_size => number}` (NOTE: does not actually compare the calculated size and crc with the given size and crc)
def parse_command(datagram)
return nil if datagram.nil? or datagram.length < HEADER_SIZE
res =
{
:revision => datagram[0],
:mac_address => datagram[1..6],
# method is 7 and is filled in below
:namespace_id => datagram[8] & 0x7F,
:full_transaction_id => datagram[8],
:direction => (datagram[8] < 0 ? :upstream : :downstream),
:given_size => datagram[9],
:given_crc => datagram[10],
:rpc => datagram[HEADER_SIZE..HEADER_SIZE+3].pack('C*'),
:data => datagram[HEADER_SIZE+4..-1]
}
res[:method] = case datagram[7]
when 0x00
:status
when 0x10
:get
when 0x20
:post
when 0x30
:critical
when 0x40
:async
else
[:other, datagram[7]]
end
res[:calculated_size] = (res[:data].nil? ? res[:rpc].length : res[:data].length+res[:rpc].length)
res[:calculated_crc] = datagram[0..HEADER_SIZE-2].reduce(0) {|acc,v| acc + v} & 0x000000FF
# error checking should be done in a different method
res
end
# Builds a datagram byte array/String from the given rpc name, type symbol, and arguments.
# Any argument which responds to #bytes is converted that way, any Fixnum is converted as
# `[number]`, if the value responds to #to_a it is converted as such, and finally any other
# value is converted using #to_s and String#bytes.
def build_datagram(name, type, *args)
raise 'RPC name cannot be nil' if name.nil?
datagram = []
# datagram fmt:
datagram.push(BOWLER_VERSION) # revision
datagram.push(*(@dyio.mac_address_bytes)) # mac address (from @dyio)
datagram.push(
case (type) # method (type) id
when :status
0x00
when :get
0x10
when :post
0x20
when :critical
0x30
when :async
0x40
else
raise "Unrecognized type #{type.to_s}"
end
)
datagram.push(0) # transaction id (currently 0, TODO: pass in this value)
arg_size = args.reduce(0) do |acc, v|
if (v.is_a? Fixnum)
acc + 1
else
acc + v.length
end
end
datagram.push(name.length + arg_size) # (command and data) length
datagram.push(datagram.reduce(0) {|acc,v| acc + v} & 0x000000FF) # (datagram so far) CRC
datagram.push(*(name.bytes))
arg_bytes = args.reduce([]) do |acc, v|
if (v.respond_to? (:bytes))
acc.concat(v.bytes)
elsif (v.is_a? Fixnum)
acc.concat([v])
elsif (v.respond_to? :to_a)
acc.concat(v.to_a)
else
acc.concat(v.to_s.bytes.to_a)
end
end
datagram.push(*arg_bytes)
datagram
end
# Sends a command with the given name, type symbol, and arguments, and calls the given block
# when the dyio returns a response (for synchronous commands)
def send_command(name, type, *args, &blk)
#puts "processing #{name}"
dg = build_datagram(name,type,*args)
defer = @dyio.send_datagram(dg, type, EVENT_LOOKUP_NAMES[name] || name.to_sym)
pm = proc {|rv, &blk| blk.call(rv) unless blk.nil?}
defer.default_callback(&pm)
defer.default_errback(&pm)
unless blk.nil? or type == :async
defer
else
EM::Synchrony.sync defer
end
#@dyio.handle.send(('next_'+name+'_event').to_sym, &pm)
end
# Validate a Bowler packet (currently just checks to see if it is nil)
def validate_result(rv)
raise 'Null response' if rv.nil?
end
# Allows you to call methods as `command_to.get_something` -- commands can be
# (get|post|critical|status|async|set)_commandname (set translates to post, and sticks set back on the
# beginning of the command name), or just commandname, in which case
# a type of post is assumed unless the first argument to the method is a type symbol. Currently, namespaces are ignored
# and the command namespace is set to 0
def method_missing(sym, *args)
raise "Unknown method #{sym.id2name}" if sym.id2name.start_with? 'parse'
parts = sym.id2name.match /^(.+?)_(.+)_(.+?)_(.+?)$/ # [action]_[commandname]_from_[namespace]
if (parts.nil?)
parts = sym.id2name.split('_', 2)
end
if (parts.nil? || !([:status,:get,:post,:critical,:async, :set].include? parts[0].to_sym))
# handle undefined commands
if ([:status, :get, :post, :critical, :async].include? args[0])
command = EVENT_LOOKUP_RPCS[sym] || sym.to_s
self.send_command(command, *args)
else
# assume post
command = EVENT_LOOKUP_RPCS[sym] || sym.to_s
self.send_command(command, :post, *args)
end
else
method = parts[0].to_sym
name = parts[1].to_sym
if (method == :set)
method = :post
name = ('set_'+name.to_s).to_sym
end
command = EVENT_LOOKUP_RPCS[name] || name.to_s
namespace = 0 #ignore namespace lookup for now: namespace = if (parts.length > 2) then parts[3] else 0 end
self.send_command(command, method, *args)
end
end
end
end
| 36.136905 | 189 | 0.571734 |
1caf5770247f03cf7976e9eb54e13cdbe7461d63 | 9,306 | #!/usr/bin/ruby
# -*- coding: utf-8 -*-
require 'csv'
require 'nokogiri'
require 'open-uri'
#require 'awesome_print'
class String
def to_nil
self.empty? ? nil : self
end
end
base_url = 'http://stats.njcaa.org/sports/bsb'
#http://stats.njcaa.org/sports/bsb/2013-14/div1/teams/connorsstatecollege?view=lineup
encoding_options = {
:invalid => :replace, # Replace invalid byte sequences
:undef => :replace, # Replace anything not defined in ASCII
:replace => '', # Use a blank for those replacements
:universal_newline => true # Always break lines with \n
}
player_hitting_xpath = '//*[@id="mainbody"]/div[2]/div[2]/div[3]/div[2]/table/tr[position()>1 and not(@class="totals")]'
player_extended_hitting_xpath = '//*[@id="mainbody"]/div[2]/div[2]/div[3]/div[3]/table/tr[position()>1 and not(@class="totals")]'
player_pitching_xpath = '//*[@id="mainbody"]/div[2]/div[2]/div[3]/div[4]/table/tr[position()>1 and not(@class="totals")]'
player_fielding_xpath = '//*[@id="mainbody"]/div[2]/div[2]/div[3]/div[5]/table/tr[position()>1 and not(@class="totals")]'
rosters_xpath = '//*[@id="mainbody"]/div[2]/div[2]/a'
nthreads = 10
base_sleep = 0
sleep_increment = 3
retries = 4
njcaa_roster_files = CSV.open("csv/njcaa_roster_files_mt.csv","w",{:col_sep => "\t"})
njcaa_player_hitting = CSV.open("csv/njcaa_player_hitting_mt.csv","w",{:col_sep => "\t"})
njcaa_player_extended_hitting = CSV.open("csv/njcaa_player_extended_hitting_mt.csv","w",{:col_sep => "\t"})
njcaa_player_pitching = CSV.open("csv/njcaa_player_pitching_mt.csv","w",{:col_sep => "\t"})
njcaa_player_fielding = CSV.open("csv/njcaa_player_fielding_mt.csv","w",{:col_sep => "\t"})
njcaa_schools = CSV.open("csv/njcaa_schools_revised.csv","r",{:col_sep => "\t", :headers => TRUE})
# Headers
njcaa_roster_files << ["year", "division_id", "school_id",
"roster_url", "original_filename", "saved_filename",
"content_disposition", "meta"]
njcaa_player_hitting << ["year", "division_id", "school_id",
"uniform_number", "player_id", "player_name", "player_url",
"class_year", "position",
"g", "ab", "r", "h", "b2b", "b3b", "hr", "rbi", "bb", "k", "sb", "cs",
"avg", "obp", "slg"]
njcaa_player_extended_hitting << ["year", "division_id", "school_id",
"uniform_number", "player_id", "player_name", "player_url",
"class_year", "position",
"g", "hbp", "sf", "sh", "tb", "xbh", "hdp", "go", "fo", "go_fo", "pa"]
njcaa_player_pitching << ["year", "division_id", "school_id",
"uniform_number", "player_id", "player_name", "player_url",
"class_year", "position",
"g", "gs", "w", "l", "sv", "cg", "ip", "h", "r", "er", "b", "k",
"k_g", "hr", "era"]
njcaa_player_fielding << ["year", "division_id", "school_id",
"uniform_number", "player_id", "player_name", "player_url",
"class_year", "position",
"g", "tc", "po", "a", "e", "fpct", "dp", "sba", "rcs",
"rcs_percent", "pb", "ci"]
# Get schools
schools = []
njcaa_schools.each do |school|
if not(school["school_id"]==nil)
schools << [school["year"],school["division_id"],school["school_id"]]
end
end
n = schools.size
gpt = (n.to_f/nthreads.to_f).ceil
threads = []
schools.each_slice(gpt).with_index do |schools_slice,i|
threads << Thread.new(schools_slice) do |t_schools|
found = 0
n_t = t_schools.size
t_schools.each_with_index do |school,j|
sleep_time = base_sleep
year = school[0]
division_id = school[1]
school_id = school[2]
# Need to parse year to use as a parameter
#http://stats.njcaa.org/sports/bsb/2013-14/div1/teams/connorsstatecollege?view=lineup
player_hitting_url = 'http://anonymouse.org/cgi-bin/anon-www.cgi/http://stats.njcaa.org/sports/bsb/2013-14/div%d/teams/%s?view=lineup' % [division_id, school_id]
# print "Thread #{thread_id}, sleep #{sleep_time} ... "
# sleep sleep_time
tries = 0
begin
page = Nokogiri::HTML(open(player_hitting_url))
rescue
sleep_time += sleep_increment
# print "sleep #{sleep_time} ... "
sleep sleep_time
tries += 1
if (tries > retries)
next
else
retry
end
end
sleep_time = base_sleep
found += 1
print "#{i}, #{school_id} : #{j+1}/#{n_t}; found #{found}/#{n_t}\n"
page.xpath(player_hitting_xpath).each do |tr|
row = [year, division_id, school_id]
tr.xpath("td").each_with_index do |td,k|
text = td.text.strip rescue nil
# Remove non-ASCII characters
text.encode(Encoding.find('ASCII'), encoding_options) rescue nil
# Replace double space with single space
text.gsub!(" "," ")
if (text=="-")
text=nil
end
text = text.to_nil rescue nil
case
when (k==1)
link = td.search("a").first
if not(link.nil?)
link_url = link.attributes["href"].text.split("cgi/")[1]
player_id = link_url.split("/")[-1]
else
link_url = nil
player_id = nil
end
row += [player_id, text, link_url]
when not(k==2)
row += [text]
end
end
njcaa_player_hitting << row
end
page.xpath(player_extended_hitting_xpath).each do |tr|
row = [year, division_id, school_id]
tr.xpath("td").each_with_index do |td,k|
text = td.text.strip rescue nil
# Remove non-ASCII characters
text.encode(Encoding.find('ASCII'), encoding_options) rescue nil
# Replace double space with single space
text.gsub!(" "," ")
if (text=="-")
text=nil
end
text = text.to_nil rescue nil
case
when (k==1)
link = td.search("a").first
if not(link.nil?)
link_url = link.attributes["href"].text.split("cgi/")[1]
player_id = link_url.split("/")[-1]
else
link_url = nil
player_id = nil
end
row += [player_id, text, link_url]
when not(k==2)
row += [text]
end
end
njcaa_player_extended_hitting << row
end
page.xpath(player_pitching_xpath).each do |tr|
row = [year, division_id, school_id]
tr.xpath("td").each_with_index do |td,k|
text = td.text.strip rescue nil
# Remove non-ASCII characters
text.encode(Encoding.find('ASCII'), encoding_options) rescue nil
# Replace double space with single space
text.gsub!(" "," ")
if (text=="-")
text=nil
end
text = text.to_nil rescue nil
case
when (k==1)
link = td.search("a").first
if not(link.nil?)
link_url = link.attributes["href"].text.split("cgi/")[1]
player_id = link_url.split("/")[-1]
else
link_url = nil
player_id = nil
end
row += [player_id, text, link_url]
when not(k==2)
row += [text]
end
end
njcaa_player_pitching << row
end
page.xpath(player_fielding_xpath).each do |tr|
row = [year, division_id, school_id]
tr.xpath("td").each_with_index do |td,k|
text = td.text.strip rescue nil
# Remove non-ASCII characters
text.encode(Encoding.find('ASCII'), encoding_options) rescue nil
# Replace double space with single space
text.gsub!(" "," ")
if (text=="-")
text=nil
end
text = text.to_nil rescue nil
case
when (k==1)
link = td.search("a").first
if not(link.nil?)
link_url = link.attributes["href"].text.split("cgi/")[1]
player_id = link_url.split("/")[-1]
else
link_url = nil
player_id = nil
end
row += [player_id, text, link_url]
when not(k==2)
row += [text]
end
end
njcaa_player_fielding << row
end
# Roster files
page.xpath(rosters_xpath).each do |link|
extension = link.text.downcase
link_href = link.attributes["href"]
relative_url = link.attributes["href"].text.split("../")[1]
full_url = base_url+"/2013-14/div#{division_id}/"+relative_url
roster_file = open(link_href)
roster_cd = roster_file.meta['content-disposition']
roster_filename = roster_cd.match(/filename=(\"?)(.+)\1/)[2] rescue nil
filename = "#{school_id}-#{division_id}-#{year}.#{extension}"
File.write("roster/#{filename}", roster_file.read)
njcaa_roster_files << [year, division_id, school_id, full_url, roster_filename, filename, roster_cd, roster_file.meta]
end
end
end
end
threads.each(&:join)
njcaa_roster_files.close
njcaa_player_hitting.close
njcaa_player_extended_hitting.close
njcaa_player_pitching.close
njcaa_player_fielding.close
| 26.4375 | 167 | 0.57017 |
61c06f99cfc4ac5f2adc26d5a13338ea5fe875e9 | 306 | Deface::Override.new(:virtual_path => "spree/admin/shared/_menu",
:name => "affiliate_admin_tab",
:insert_bottom => "[data-hook='admin_tabs']",
:text => "<%= tab(:affiliates, :icon => 'icon-group') %>",
:disabled => false) | 61.2 | 79 | 0.480392 |
e894eabbe6b0c8fe2cd60c09d64a7b5720061030 | 464 | # -*- encoding : utf-8 -*-
module Snippr
module SegmentFilter
class Base
def initialize(filter_value)
@filter_value = filter_value
end
def self.filters
@available_filters
end
def self.inherited(subclass)
@available_filters ||= []
@available_filters << subclass
end
def active?
raise NotImplementedError("Subclasses need to implement #active?")
end
end
end
end
| 18.56 | 74 | 0.609914 |
6114ba318141ddd42490aed7c76fe5a6505bfc62 | 83 | require 'test_helper'
class TeamImprovementsHelperTest < ActionView::TestCase
end
| 16.6 | 55 | 0.843373 |
1d645c63ed9204c959110f4d523e2ca2802ef077 | 3,138 | #
# Author:: Daniel DeLeo (<[email protected]>)
# Author:: Tim Hinderliter (<[email protected]>)
# Author:: Seth Falcon (<[email protected]>)
# Copyright:: Copyright 2009-2016, Daniel DeLeo
# Copyright:: Copyright 2010-2016, Chef Software 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/provider"
require "chef/provider/deploy"
require "chef/json_compat"
class Chef
class Provider
class Deploy
class Revision < Chef::Provider::Deploy
provides :deploy_revision
provides :deploy_branch
def all_releases
sorted_releases
end
def action_deploy
validate_release_history!
super
end
def cleanup!
super
known_releases = sorted_releases
Dir["#{Chef::Util::PathHelper.escape_glob_dir(new_resource.deploy_to)}/releases/*"].each do |release_dir|
unless known_releases.include?(release_dir)
converge_by("Remove unknown release in #{release_dir}") do
FileUtils.rm_rf(release_dir)
end
end
end
end
protected
def release_created(release)
sorted_releases { |r| r.delete(release); r << release }
end
def release_deleted(release)
sorted_releases { |r| r.delete(release) }
end
def release_slug
scm_provider.revision_slug
end
private
def sorted_releases
cache = load_cache
if block_given?
yield cache
save_cache(cache)
end
cache
end
def validate_release_history!
sorted_releases do |release_list|
release_list.each do |path|
release_list.delete(path) unless ::File.exist?(path)
end
end
end
def sorted_releases_from_filesystem
Dir.glob(Chef::Util::PathHelper.escape_glob_dir(new_resource.deploy_to) + "/releases/*").sort_by { |d| ::File.ctime(d) }
end
def load_cache
begin
Chef::JSONCompat.parse(Chef::FileCache.load("revision-deploys/#{new_resource.name}"))
rescue Chef::Exceptions::FileNotFound
sorted_releases_from_filesystem
end
end
def save_cache(cache)
Chef::FileCache.store("revision-deploys/#{new_resource.name}", Chef::JSONCompat.to_json(cache))
cache
end
end
end
end
end
| 28.527273 | 131 | 0.604207 |
6ad9712235e6392cf4e2bf141be90b61cd4bde36 | 1,948 | #!/usr/bin/env ruby
require "date"
p Date.today
def usage
puts "usage: #{$PROGRAM_NAME} [domain name]"
exit 1
end
usage if ARGV.size != 1
domain = ARGV[0]
Signal.trap(:INT) {
puts "recv sigint"
exit()
}
srv = {
LOCAL: ["192.168.1.1"],
AdGuard: ["94.140.14.14", "94.140.15.15", "94.140.14.14"],
Alternate: ["76.76.19.19", "76.223.122.150"],
Baidu: ["180.76.76.76", "114.114.114.114"],
Cloudflare: ["1.1.1.1", "1.0.0.1", "1.1.1.2", "1.1.1.3"],
CleanBrowsing: ["185.228.168.9", "185.228.169.9"],
CyberGhost: ["38.132.106.139", "194.187.251.67"],
Comodo_Secure: ["8.26.56.26", "8.20.247.20"],
Dyn_Internet: ["216.146.35.35", "216.146.36.36"],
Freenom_World: ["80.80.80.80", "80.80.81.81"],
Google: ["8.8.8.8","8.8.4.4"],
NTT_America: ["129.250.35.250", "129.250.35.251"],
Norton: ["199.85.126.10", "199.85.127.10"],
OpenDNS: ["208.67.222.123", "208.67.220.123", "208.67.222.123"],
OpenNIC: ["161.97.219.84", "104.168.144.17"],
puntCAT: ["109.69.8.51"],
Quad101_DNS: ["101.101.101.101", "101.102.103.104"],
Quad9: ["9.9.9.9", "149.112.112.112"],
SafeDNS: ["195.46.39.39", "195.46.39.40"],
SkyDNS: ["193.58.251.251"],
Sprintlink: ["204.117.214.10", "199.2.252.10", "204.97.212.10"],
UltraRecursive: ["156.154.70.1", "156.154.71.1"],
Verisign_Public: ["64.6.64.6", "64.6.65.6"],
Yandex_DNS: ["77.88.8.8", "77.88.8.1"],
}
srv.each do |k, v|
v.each do |s|
puts "===== #{k}: #{s} ====="
res = `dig #{domain} @#{s} | awk '/Query/ {print $4}'`.gsub("\n", "").to_i
case res
when 0..500
puts "\e[32mQueryTime: #{res} [ms]\e[0m"
when 501..999
puts "\e[31mQueryTime: #{res} [ms]\e[0m"
else
puts "\e[41mQueryTime: #{res} [ms]\e[0m"
end
system("dig #{domain} @#{s} +short", exception: true)
puts
end
end
| 30.920635 | 78 | 0.51848 |
5dbfcc819997ddc99813af329f85a995baaf05ce | 3,861 | require 'oga'
require 'ostruct'
REQUIRED_ATTRIBUTES = "".freeze
module OGP
class OpenGraph
# Accessor for storing all open graph data
attr_accessor :data
# Required Accessors
attr_accessor :title, :type, :url
attr_accessor :images
# Optional Accessors
attr_accessor :description, :determiner, :site_name
attr_accessor :audios
attr_accessor :locales
attr_accessor :videos
def initialize(source)
if source.nil? || source.empty?
raise ArgumentError, '`source` cannot be nil or empty.'
end
raise MalformedSourceError unless source.include?('</html>')
source.force_encoding('UTF-8') if source.encoding != 'UTF-8'
self.data = {}
self.images = []
self.audios = []
self.locales = []
self.videos = []
document = Oga.parse_html(source)
check_required_attributes(document)
parse_attributes(document)
end
def image
return if images.nil?
images.first
end
private
def check_required_attributes(document)
# REQUIRED_ATTRIBUTES.each do |attribute_name|
# raise MissingAttributeError, "Missing required attribute: #{attribute_name}" unless attribute_exists(document, attribute_name)
# end
end
# rubocop:disable Metrics/CyclomaticComplexity
def parse_attributes(document)
document.xpath('//head/meta[starts-with(@property, \'og:\')]').each do |attribute|
attribute_name = attribute.get('property').downcase.gsub('og:', '')
if data.has_key?(attribute_name)
# There can be multiple entries for the same og tag, see
# https://open.spotify.com/album/3NkIlQR6wZwPCQiP1vPjF8 for an example
# where there are multiple `restrictions:country:allowed` og tags.
#
# In this case store the content values as an array.
if !data[attribute_name].kind_of?(Array)
data[attribute_name] = [ data[attribute_name] ]
end
data[attribute_name] << attribute.get('content')
else
data[attribute_name] = attribute.get('content')
end
case attribute_name
when /^image$/i
images << OpenStruct.new(url: attribute.get('content').to_s)
when /^image:(.+)/i
images << OpenStruct.new unless images.last
images.last[Regexp.last_match[1].gsub('-', '_')] = attribute.get('content').to_s
when /^audio$/i
audios << OpenStruct.new(url: attribute.get('content').to_s)
when /^audio:(.+)/i
audios << OpenStruct.new unless audios.last
audios.last[Regexp.last_match[1].gsub('-', '_')] = attribute.get('content').to_s
when /^locale/i
locales << attribute.get('content').to_s
when /^video$/i
videos << OpenStruct.new(url: attribute.get('content').to_s)
when /^video:(.+)/i
videos << OpenStruct.new unless videos.last
videos.last[Regexp.last_match[1].gsub('-', '_')] = attribute.get('content').to_s
else
begin
instance_variable_set("@#{attribute_name}", attribute.get('content'))
rescue NameError
warn("Some og tag names include colons `:`, such as Spotify song
pages (`restrictions:country:allowed`), which will result in a
NameError. Please rely on data[attribute_name] instead. Setting
top-level instance variables is deprecated and will be removed in
the next major version.")
end
end
end
end
def attribute_exists(document, name)
document.at_xpath("boolean(//head/meta[@property='og:#{name}'])")
end
end
class MissingAttributeError < StandardError
end
class MalformedSourceError < StandardError
end
end
| 33 | 136 | 0.622119 |
339dcf51033caf5d77ca37d40b0295d32a96c8cb | 525 | cask 'vitamin-r' do
if MacOS.version <= :el_capitan
version '2.58'
sha256 'c6c631430b44359aa022d9ca5ca6e98dbdf7258f2ceae0353f344a035682661e'
else
version '3.05'
sha256 '685de0390b0b80c517320a853c7e2f2c6a30e5c49c50ae0c342268cb9ebba632'
end
url "http://www.publicspace.net/download/signedVitamin#{version.major}.zip"
appcast "http://www.publicspace.net/app/vitamin#{version.major}.xml"
name 'Vitamin-R'
homepage 'http://www.publicspace.net/Vitamin-R/'
app "Vitamin-R #{version.major}.app"
end
| 30.882353 | 77 | 0.754286 |
39c61eaa9f7ce0c4f6754dc7e8814e5cf9221e70 | 7,476 | module Diplomat
# Methods for interacting with the Consul event API endpoint
class Event < Diplomat::RestClient
@access_methods = %i[fire get_all get]
# Send an event
# @param name [String] the event name
# @param value [String] the payload of the event
# @param service [String] the target service name
# @param node [String] the target node name
# @param tag [String] the target tag name, must only be used with service
# @param dc [String] the dc to target
# @param options [Hash] options parameter hash
# @return [nil]
# rubocop:disable Metrics/ParameterLists
def fire(name, value = nil, service = nil, node = nil, tag = nil, dc = nil, options = {})
custom_params = []
custom_params << use_named_parameter('service', service) if service
custom_params << use_named_parameter('node', node) if node
custom_params << use_named_parameter('tag', tag) if tag
custom_params << use_named_parameter('dc', dc) if dc
send_put_request(@conn, ["/v1/event/fire/#{name}"], options, value, custom_params)
nil
end
# rubocop:enable Metrics/ParameterLists
# Get the list of events matching name
# @param name [String] the name of the event (regex)
# @param not_found [Symbol] behaviour if there are no events matching name;
# :reject with exception, :return degenerate value, or :wait for a non-empty list
# @param found [Symbol] behaviour if there are already events matching name;
# :reject with exception, :return its current value, or :wait for its next value
# @return [Array[hash]] The list of { :name, :payload } hashes
# @param options [Hash] options parameter hash
# @note
# Events are sent via the gossip protocol; there is no guarantee of delivery
# success or order, but the local agent will store up to 256 events that do
# arrive. This method lists those events.
# It has the same semantics as Kv::get, except the value returned is a list
# i.e. the current value is all events up until now, the next value is the
# current list plus the next event to arrive.
# To get a specific event in the sequence, @see #get
# When trying to get a list of events matching a name, there are two possibilities:
# - The list doesn't (yet) exist / is empty
# - The list exists / is non-empty
# The combination of not_found and found behaviour gives maximum possible
# flexibility. For X: reject, R: return, W: wait
# - X X - meaningless; never return a value
# - X R - "normal" non-blocking get operation. Default
# - X W - get the next value only (must have a current value)
# - R X - meaningless; never return a meaningful value
# - R R - "safe" non-blocking, non-throwing get-or-default operation
# - R W - get the next value or a default
# - W X - get the first value only (must not have a current value)
# - W R - get the first or current value; always return something, but
# block only when necessary
# - W W - get the first or next value; wait until there is an update
def get_all(name = nil, not_found = :reject, found = :return, options = {})
# Event list never returns 404 or blocks, but may return an empty list
@raw = send_get_request(@conn, ['/v1/event/list'], options, use_named_parameter('name', name))
if JSON.parse(@raw.body).count.zero?
case not_found
when :reject
raise Diplomat::EventNotFound, name
when :return
return []
end
else
case found
when :reject
raise Diplomat::EventAlreadyExists, name
when :return
@raw = parse_body
return return_payload
end
end
@raw = wait_for_next_event(['/v1/event/list'], options, use_named_parameter('name', name))
@raw = parse_body
return_payload
end
# Get a specific event in the sequence matching name
# @param name [String] the name of the event (regex)
# @param token [String|Symbol] the ordinate of the event in the sequence;
# String are tokens returned by previous calls to this function
# Symbols are the special tokens :first, :last, and :next
# @param not_found [Symbol] behaviour if there is no matching event;
# :reject with exception, :return degenerate value, or :wait for event
# @param found [Symbol] behaviour if there is a matching event;
# :reject with exception, or :return its current value
# @return [hash] A hash with keys :value and :token;
# :value is a further hash of the :name and :payload of the event,
# :token is the event's ordinate in the sequence and can be passed to future calls to get the subsequent event
# @param options [Hash] options parameter hash
# @note
# Whereas the consul API for events returns all past events that match
# name, this method allows retrieval of individual events from that
# sequence. However, because consul's API isn't conducive to this, we can
# offer first, last, next (last + 1) events, or arbitrary events in the
# middle, though these can only be identified relative to the preceding
# event. However, this is ideal for iterating through the sequence of
# events (while being sure that none are missed).
# rubocop:disable PerceivedComplexity
def get(name = nil, token = :last, not_found = :wait, found = :return, options = {})
@raw = send_get_request(@conn, ['/v1/event/list'], options, use_named_parameter('name', name))
body = JSON.parse(@raw.body)
# TODO: deal with unknown symbols, invalid indices (find_index will return nil)
idx = case token
when :first then 0
when :last then body.length - 1
when :next then body.length
else body.find_index { |e| e['ID'] == token } + 1
end
if JSON.parse(@raw.body).count.zero? || idx == body.length
case not_found
when :reject
raise Diplomat::EventNotFound, name
when :return
event_name = ''
event_payload = ''
event_token = :last
when :wait
@raw = wait_for_next_event(['/v1/event/list'], options, use_named_parameter('name', name))
@raw = parse_body
# If it's possible for two events to arrive at once,
# this needs to #find again:
event = @raw.last
event_name = event['Name']
event_payload = Base64.decode64(event['Payload'])
event_token = event['ID']
end
else
case found
when :reject
raise Diplomat::EventAlreadyExits, name
when :return
event = body[idx]
event_name = event['Name']
event_payload = event['Payload'].nil? ? nil : Base64.decode64(event['Payload'])
event_token = event['ID']
end
end
{
value: { name: event_name, payload: event_payload },
token: event_token
}
end
# rubocop:enable PerceivedComplexity
private
def wait_for_next_event(url, options = {}, param = nil)
if options.nil?
options = { timeout: 86_400 }
else
options[:timeout] = 86_400
end
index = @raw.headers['x-consul-index']
param += use_named_parameter('index', index)
send_get_request(@conn, url, options, param)
end
end
end
| 44.766467 | 116 | 0.640316 |
ab0196c6d07fcf56cae73e1e708f7040b3535a56 | 1,981 | class Libtar < Formula
desc "C library for manipulating POSIX tar files"
homepage "https://repo.or.cz/libtar.git"
url "https://repo.or.cz/libtar.git",
tag: "v1.2.20",
revision: "0907a9034eaf2a57e8e4a9439f793f3f05d446cd"
bottle do
cellar :any
rebuild 2
sha256 "7424cf8229c7aea825592a76227da3355f32a43b9fbc5e140a0cf1eb07d05c8e" => :big_sur
sha256 "7481da1834936b6237f152fe8b7e22196ad5c76833af39c9e9f74eae6347c9a5" => :arm64_big_sur
sha256 "35617f312e3c6fb1e473a5d20a559dcbd1815544bdd99c95419ac7e6e8abf9f6" => :catalina
sha256 "070d9355e6d03dcb64ea33ecf7e3b99972e0b3ca5fc8e60e89616f0a061ee0e5" => :mojave
sha256 "a263cfaa1499f0c82902009964df0a310e7841ddff29409c67ede0a79157c31e" => :high_sierra
sha256 "68bdebde24477a815ea03289878ad57e8a1f719b417bef430bf477c2d760cad7" => :sierra
sha256 "018f1c9897f52b783878db67db39a5933a4863a3f9dedc2af9b6bf13f2161957" => :el_capitan
sha256 "d8d138fb4c1cf8c33aaaf8633cd748e9a423e84f1df886ae1842d4816b1f34a0" => :yosemite
sha256 "b8eb40cc1715243eb0ff85eddd2a5f5546e19ca7278ce30b08bd8e1bd3f0682f" => :mavericks
sha256 "895b12d04e1cda40eb0458d3125a534aa38daed594ff3f68fd65a8e3f5bc86f0" => :x86_64_linux # glibc 2.19
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
def install
system "autoreconf", "--force", "--install"
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}",
"--mandir=#{man}"
system "make", "install"
end
test do
(testpath/"homebrew.txt").write "This is a simple example"
system "tar", "-cvf", "test.tar", "homebrew.txt"
rm "homebrew.txt"
refute_predicate testpath/"homebrew.txt", :exist?
assert_predicate testpath/"test.tar", :exist?
system bin/"libtar", "-x", "test.tar"
assert_predicate testpath/"homebrew.txt", :exist?
end
end
| 42.148936 | 107 | 0.722867 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.