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
|
---|---|---|---|---|---|
038207e9d9f9b4e7211b7ce849b8a5bb8ce5984a | 6,552 | require 'httparty'
require 'cgi'
require 'json'
class FCM
include HTTParty
base_uri 'https://fcm.googleapis.com/fcm/send'
default_timeout 30
format :json
# constants
GROUP_NOTIFICATION_BASE_URI = 'https://android.googleapis.com/gcm'
attr_accessor :timeout, :api_key
def initialize(api_key, client_options = {})
@api_key = api_key
@client_options = client_options
end
# {
# "collapse_key": "score_update",
# "time_to_live": 108,
# "delay_while_idle": true,
# "registration_ids": ["4", "8", "15", "16", "23", "42"],
# "data" : {
# "score": "5x1",
# "time": "15:10"
# }
# }
# fcm = FCM.new("API_KEY")
# fcm.send(registration_ids: ["4sdsx", "8sdsd"], {data: {score: "5x1"}})
def send_notification(registration_ids, options = {})
post_body = build_post_body(registration_ids, options)
params = {
body: post_body.to_json,
headers: {
'Authorization' => "key=#{@api_key}",
'Content-Type' => 'application/json'
}
}
response = self.class.post('/send', params.merge(@client_options))
build_response(response, registration_ids)
end
alias send send_notification
def create_notification_key(key_name, project_id, registration_ids = [])
post_body = build_post_body(registration_ids, operation: 'create',
notification_key_name: key_name)
params = {
body: post_body.to_json,
headers: {
'Content-Type' => 'application/json',
'project_id' => project_id,
'Authorization' => "key=#{@api_key}"
}
}
response = nil
for_uri(GROUP_NOTIFICATION_BASE_URI) do
response = self.class.post('/notification', params.merge(@client_options))
end
build_response(response)
end
alias create create_notification_key
def add_registration_ids(key_name, project_id, notification_key, registration_ids)
post_body = build_post_body(registration_ids, operation: 'add',
notification_key_name: key_name,
notification_key: notification_key)
params = {
body: post_body.to_json,
headers: {
'Content-Type' => 'application/json',
'project_id' => project_id,
'Authorization' => "key=#{@api_key}"
}
}
response = nil
for_uri(GROUP_NOTIFICATION_BASE_URI) do
response = self.class.post('/notification', params.merge(@client_options))
end
build_response(response)
end
alias add add_registration_ids
def remove_registration_ids(key_name, project_id, notification_key, registration_ids)
post_body = build_post_body(registration_ids, operation: 'remove',
notification_key_name: key_name,
notification_key: notification_key)
params = {
body: post_body.to_json,
headers: {
'Content-Type' => 'application/json',
'project_id' => project_id,
'Authorization' => "key=#{@api_key}"
}
}
response = nil
for_uri(GROUP_NOTIFICATION_BASE_URI) do
response = self.class.post('/notification', params.merge(@client_options))
end
build_response(response)
end
alias remove remove_registration_ids
def recover_notification_key(key_name, project_id)
params = {
query: {
notification_key_name: key_name
},
headers: {
'Content-Type' => 'application/json',
'project_id' => project_id,
'Authorization' => "key=#{@api_key}"
}
}
response = nil
for_uri(GROUP_NOTIFICATION_BASE_URI) do
response = self.class.get('/notification', params.merge(@client_options))
end
build_response(response)
end
def send_with_notification_key(notification_key, options = {})
body = { to: notification_key }.merge(options)
params = {
body: body.to_json,
headers: {
'Authorization' => "key=#{@api_key}",
'Content-Type' => 'application/json'
}
}
response = self.class.post('/send', params.merge(@client_options))
build_response(response)
end
def send_to_topic(topic, options = {})
if topic =~ /[a-zA-Z0-9\-_.~%]+/
send_with_notification_key('/topics/' + topic, options)
end
end
private
def for_uri(uri)
current_uri = self.class.base_uri
self.class.base_uri uri
yield
self.class.base_uri current_uri
end
def build_post_body(registration_ids, options = {})
ids = registration_ids.is_a?(String) ? [registration_ids] : registration_ids
{ registration_ids: ids }.merge(options)
end
def build_response(response, registration_ids = [])
body = response.body || {}
response_hash = { body: body, headers: response.headers, status_code: response.code }
case response.code
when 200
response_hash[:response] = 'success'
body = JSON.parse(body) unless body.empty?
response_hash[:canonical_ids] = build_canonical_ids(body, registration_ids) unless registration_ids.empty?
response_hash[:not_registered_ids] = build_not_registered_ids(body, registration_ids) unless registration_ids.empty?
when 400
response_hash[:response] = 'Only applies for JSON requests. Indicates that the request could not be parsed as JSON, or it contained invalid fields.'
when 401
response_hash[:response] = 'There was an error authenticating the sender account.'
when 503
response_hash[:response] = 'Server is temporarily unavailable.'
when 500..599
response_hash[:response] = 'There was an internal error in the FCM server while trying to process the request.'
end
response_hash
end
def build_canonical_ids(body, registration_ids)
canonical_ids = []
unless body.empty?
if body['canonical_ids'] > 0
body['results'].each_with_index do |result, index|
canonical_ids << { old: registration_ids[index], new: result['registration_id'] } if has_canonical_id?(result)
end
end
end
canonical_ids
end
def build_not_registered_ids(body, registration_id)
not_registered_ids = []
unless body.empty?
if body['failure'] > 0
body['results'].each_with_index do |result, index|
not_registered_ids << registration_id[index] if is_not_registered?(result)
end
end
end
not_registered_ids
end
def has_canonical_id?(result)
!result['registration_id'].nil?
end
def is_not_registered?(result)
result['error'] == 'NotRegistered'
end
end
| 29.12 | 154 | 0.65293 |
1d4d64f1ba1ea63356859002f4f040e26e6f6138 | 495 | # 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_07_01
module Models
#
# Defines values for PcError
#
module PcError
InternalError = "InternalError"
AgentStopped = "AgentStopped"
CaptureFailed = "CaptureFailed"
LocalFileFailed = "LocalFileFailed"
StorageFailed = "StorageFailed"
end
end
end
| 24.75 | 70 | 0.70101 |
1ad5644b03cb0d26483e93e48ff3bbd51486f7bf | 876 | # encoding: utf-8
require 'rubygems'
require 'bundler'
Bundler.setup
require 'rack/cors'
require 'dotenv'
Dotenv.load('.env.development')
# The actual server code is in src/server.rb
require './server'
# The server can run in two modes, 'production' and 'development'
# the mode is set in the RACK_ENV or RAILS_ENV environment variables
ENV['RACK_ENV'] = ENV['RAILS_ENV'] if ENV['RAILS_ENV']
# This sets up the bits of the server
# enable CORS for the client app
puts "#{ENV['CLIENT_URL']}"
use Rack::Cors do |config|
config.allow do |allow|
allow.origins "#{ENV['CLIENT_URL']}"
allow.resource '*',
:methods => [:get, :options],
:headers => :any,
:max_age => 0
end
end
# To compress the data going back and forth
use Rack::Deflater
# This logs access and errors
use Rack::CommonLogger
# This is defined in src/server.rb
run TwentyFiftyServer
| 25.028571 | 68 | 0.704338 |
bf650eab6decd4128f108e311a363c131a30aa8f | 155 | require "bootstrap/datepicker/enhanced/version"
module Bootstrap
module Datepicker
module Enhanced
# Your code goes here...
end
end
end
| 15.5 | 47 | 0.716129 |
219fe09ee40f1d2044cee269895a0a1eff62e95e | 835 | Rails.application.routes.draw do
root 'home_pages#home'
get '/help', to: 'home_pages#help'
get '/about', to: 'home_pages#about'
get '/contact', to: 'home_pages#contact'
get '/signup', to: 'users#new'
# post '/signup', to: 'users#create'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
resources :users do
member do
get :following, :followers
end
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :microposts, only: [:create, :destroy]
resources :relationships, only: [:create, :destroy]
end
| 36.304348 | 101 | 0.652695 |
91147ca2e60332df4637052cbe7b28684a1cac43 | 102 | Administrator.create!(
email: '[email protected]',
password: 'foobar'
) | 25.5 | 43 | 0.529412 |
08a123ed18268adbc5cc5795be0c451eb16034ab | 6,191 | require 'net/http'
module Fae
class NetlifyApi
def initialize()
@netlify_api_user = Fae.netlify[:api_user]
@netlify_api_token = Fae.netlify[:api_token]
@site = Fae.netlify[:site]
@site_id = Fae.netlify[:site_id]
@endpoint_base = Fae.netlify[:api_base]
@logger = Logger.new(Rails.root.join('log', 'netlify_api.log'))
end
def get_deploys
path = "sites/#{@site_id}/deploys?per_page=15"
get_deploys_env_response(path)
end
def run_deploy(deploy_hook_type, current_user)
hook = Fae::DeployHook.find_by_environment(deploy_hook_type)
if hook.present?
post("#{hook.url}?trigger_title=#{current_user.full_name.gsub(' ', '+')}+triggered+a+#{deploy_hook_type.titleize}+deploy")
return true
end
false
end
private
def get(endpoint, params = nil)
begin
uri = URI.parse(endpoint)
request = Net::HTTP::Get.new(uri)
set_headers(request)
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) {|http|
http.request(request)
}
return JSON.parse(response.body) if response.present? && response.body.present?
rescue Exception => e
@logger.info "\n"
@logger.info "Failed getting on #{DateTime.now} to #{endpoint}"
@logger.info "Params: #{params}"
@logger.info "Reason: #{e}"
end
end
def post(endpoint, params = nil)
begin
uri = URI.parse(endpoint)
request = Net::HTTP::Post.new(uri)
set_headers(request)
request.body = params.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) {|http|
http.request(request)
}
return JSON.parse(response.body) if response.present? && response.body.present?
rescue Exception => e
@logger.info "\n"
@logger.info "Failed posting on #{DateTime.now} to #{endpoint}"
@logger.info "Params: #{params}"
@logger.info "Reason: #{e}"
end
end
def set_headers(request)
request['User-Agent'] = "#{@site} (#{@netlify_api_user})"
request['Authorization'] = "Bearer #{@netlify_api_token}"
end
def get_deploys_env_response(path)
return get "#{@endpoint_base}#{path}" unless Rails.env.test?
[
{
"state"=>"building",
"name"=>"building-test",
"created_at"=>"2021-10-22T14:56:18.163Z",
"updated_at"=>"2021-10-22T14:57:55.905Z",
"error_message"=>nil,
"commit_ref"=>nil,
"branch"=>"staging",
"title"=>"Staging building",
"review_url"=>nil,
"published_at"=>nil,
"context"=>"branch-deploy",
"deploy_time"=>93,
"committer"=>nil,
"skipped_log"=>nil,
"manual_deploy"=>false,
},
{
"state"=>"processing",
"name"=>"processing-test",
"created_at"=>"2021-10-22T14:56:18.163Z",
"updated_at"=>"2021-10-22T14:57:55.905Z",
"error_message"=>nil,
"commit_ref"=>nil,
"branch"=>"staging",
"title"=>"Staging processing",
"review_url"=>nil,
"published_at"=>nil,
"context"=>"branch-deploy",
"deploy_time"=>93,
"committer"=>nil,
"skipped_log"=>nil,
"manual_deploy"=>false,
},
{
"state"=>"ready",
"name"=>"complete-test",
"created_at"=>"2021-10-22T14:56:18.163Z",
"updated_at"=>"2021-10-22T14:57:55.905Z",
"error_message"=>nil,
"commit_ref"=>'string',
"branch"=>"staging",
"title"=>"Staging complete",
"review_url"=>nil,
"published_at"=>nil,
"context"=>"branch-deploy",
"deploy_time"=>93,
"committer"=>nil,
"skipped_log"=>nil,
"manual_deploy"=>false,
},
{
"state"=>"ready",
"name"=>"admin-test",
"created_at"=>"2021-10-22T14:56:18.163Z",
"updated_at"=>"2021-10-22T14:57:55.905Z",
"error_message"=>nil,
"commit_ref"=>nil,
"branch"=>"staging",
"title"=>"Staging admin complete",
"review_url"=>nil,
"published_at"=>nil,
"context"=>"branch-deploy",
"deploy_time"=>93,
"committer"=>nil,
"skipped_log"=>nil,
"manual_deploy"=>false,
},
{
"state"=>"error",
"name"=>"error-test",
"created_at"=>"2021-10-22T14:56:18.163Z",
"updated_at"=>"2021-10-22T14:57:55.905Z",
"error_message"=>'Error!',
"commit_ref"=>nil,
"branch"=>"staging",
"title"=>"FINE admin triggered a Staging build",
"review_url"=>nil,
"published_at"=>nil,
"context"=>"branch-deploy",
"deploy_time"=>93,
"committer"=>nil,
"skipped_log"=>nil,
"manual_deploy"=>false,
},
{
"state"=>"ready",
"name"=>"fae-dummy",
"created_at"=>"2021-10-22T14:56:18.163Z",
"updated_at"=>"2021-10-22T14:57:55.905Z",
"error_message"=>nil,
"commit_ref"=>nil,
"branch"=>"master",
"title"=>"A production build",
"review_url"=>nil,
"published_at"=>nil,
"context"=>"production",
"deploy_time"=>93,
"committer"=>nil,
"skipped_log"=>nil,
"manual_deploy"=>false,
},
{
"state"=>"ready",
"name"=>"fae-dummy",
"created_at"=>"2021-10-22T14:56:18.163Z",
"updated_at"=>"2021-10-22T14:57:55.905Z",
"error_message"=>nil,
"commit_ref"=>nil,
"branch"=>"master",
"title"=>"Another production build",
"review_url"=>nil,
"published_at"=>nil,
"context"=>"production",
"deploy_time"=>93,
"committer"=>nil,
"skipped_log"=>nil,
"manual_deploy"=>false,
},
]
end
end
end | 31.426396 | 130 | 0.518818 |
1102c67818b2c5fa358b339bef69dba59fa8cbb0 | 1,290 | module BandwidthIris
SIP_CREDENTIAL_PATH = 'sipcredentials'
class SipCredential
extend ClientWrapper
include ApiItem
def self.list(client, query = nil)
list = client.make_request(:get, client.concat_account_path(SIP_CREDENTIAL_PATH), query)[0][:sip_credential]
list = if list.is_a?(Array) then list else [list] end
list.map do |i|
SipCredential.new(i, client)
end
end
wrap_client_arg :list
def self.get(client, id)
data = client.make_request(:get, "#{client.concat_account_path(SIP_CREDENTIAL_PATH)}/#{id}")[0]
SipCredential.new(data[:sip_credential], client)
end
wrap_client_arg :get
def self.create(client, item)
data = client.make_request(
:post,
client.concat_account_path(SIP_CREDENTIAL_PATH),
{ :sip_credentials => { :sip_credential => item } }
)[0][:valid_sip_credentials]
SipCredential.new(data[:sip_credential], client)
end
wrap_client_arg :create
def update(data)
@client.make_request(:put,"#{@client.concat_account_path(SIP_CREDENTIAL_PATH)}/#{user_name}", {:sip_credential => data})
end
def delete
@client.make_request(:delete,"#{@client.concat_account_path(SIP_CREDENTIAL_PATH)}/#{user_name}")
end
end
end
| 30 | 126 | 0.681395 |
e849f6382bff9968acc6eadf0e0d432f60d1205a | 1,637 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
module API
module V3
class WorkPackageCollectionFromQueryParamsService
def initialize(user)
self.current_user = user
end
def call(params = {})
query = Query.new_default(name: '_', project: params[:project])
WorkPackageCollectionFromQueryService
.new(query, current_user)
.call(params)
end
private
attr_accessor :current_user
end
end
end
| 32.74 | 91 | 0.728772 |
878b6eb830e163ca12faed7cf363e10b6a2d04fe | 27,983 | require 'ascii_charts'
require 'gruff'
require 'zlib'
require_relative 'models.rb'
LEVEL_PATTERN = /S[ILU]?-[ABCDEX]-[0-9][0-9]?-[0-9][0-9]?|[?!]-[ABCDE]-[0-9][0-9]?/i
EPISODE_PATTERN = /S[ILU]?-[ABCDEX]-[0-9][0-9]?/i
NAME_PATTERN = /(for|of) (.*)[\.\?]?/i
def parse_type(msg)
(msg[/level/i] ? Level : (msg[/episode/i] ? Episode : nil))
end
def normalize_name(name)
name.split('-').map { |s| s[/\A[0-9]\Z/].nil? ? s : "0#{s}" }.join('-')
end
def parse_player(msg, username)
p = msg[/for (.*)[\.\?]?/i, 1]
if p.nil?
raise "I couldn't find a player with your username! Have you identified yourself (with '@inne++ my name is <N++ display name>')?" unless User.exists?(username: username)
User.find_by(username: username).player
else
raise "#{p} doesn't have any high scores! Either you misspelled the name, or they're exceptionally bad..." unless Player.exists?(name: p)
Player.find_by(name: p)
end
end
def parse_video_author(msg)
return msg[/by (.*)[\.\?]?\Z/i, 1]
end
def parse_challenge(msg)
return msg[/([GTOCE][+-][+-])+/i]
end
def parse_challenge_code(msg)
return msg[/([!?]+)[^-]/, 1]
end
def parse_videos(msg)
author = parse_video_author(msg)
msg = msg.chomp(" by " + author.to_s)
highscoreable = parse_level_or_episode(msg)
challenge = parse_challenge(msg)
code = parse_challenge_code(msg)
videos = highscoreable.videos
videos = videos.where('lower(author) = ? or lower(author_tag) = ?', author.downcase, author.downcase) unless author.nil?
videos = videos.where(challenge: challenge) unless challenge.nil?
videos = videos.where(challenge_code: code) unless code.nil?
raise "That level doesn't have any videos!" if highscoreable.videos.empty?
raise "I couldn't find any videos matching that request! Are you looking for one of these videos?\n```#{highscoreable.videos.map(&:format_description).join("\n")}```" if videos.empty?
return videos
end
def parse_steam_id(msg)
id = msg[/is (.*)[\.\?]?/i, 1]
raise "I couldn't figure out what your Steam ID was! You need to send a message in the format 'my steam id is <id>'." if id.nil?
raise "Your Steam ID needs to be numerical! #{id} is not valid." if id !~ /\A\d+\Z/
return id
end
def parse_level_or_episode(msg)
level = msg[LEVEL_PATTERN]
episode = msg[EPISODE_PATTERN]
name = msg[NAME_PATTERN, 2]
ret = nil
if level
ret = Level.find_by(name: normalize_name(level).upcase)
elsif episode
ret = Episode.find_by(name: normalize_name(episode).upcase)
elsif !msg[/(level of the day|lotd)/].nil?
ret = get_current(Level)
elsif !msg[/(episode of the week|eotw)/].nil?
ret = get_current(Episode)
elsif name
ret = Level.find_by("UPPER(longname) LIKE ?", name.upcase)
else
msg = "I couldn't figure out which level or episode you wanted scores for! You need to send either a level " +
"or episode ID that looks like SI-A-00-00 or SI-A-00, or a level name, using 'for <name>.'"
raise msg
end
raise "I couldn't find anything by that name :(" if ret.nil?
ret
end
def parse_rank(msg)
rank = msg[/top\s*([0-9][0-9]?)/i, 1]
rank ? rank.to_i : nil
end
def parse_bottom_rank(msg)
rank = msg[/bottom\s*([0-9][0-9]?)/i, 1]
rank ? 20 - rank.to_i : nil
end
def parse_ranks(msg)
ranks = msg.scan(/\s+([0-9][0-9]?)/).map{ |r| r[0].to_i }.reject{ |r| r < 0 || r > 19 }
ranks.empty? ? [0] : ranks
end
def parse_tabs(msg)
ret = []
ret << :SI if msg =~ /\b(intro|SI|I)\b/i
ret << :S if msg =~ /(\b|\A|\s)(N++|S|solo)(\b|\Z|\s)/i
ret << :SU if msg =~ /\b(SU|UE|U|ultimate)\b/i
ret << :SL if msg =~ /\b(legacy|SL|L)\b/i
ret << :SS if msg =~ /(\A|\s)(secret|\?)(\Z|\s)/i
ret << :SS2 if msg =~ /(\A|\s)(ultimate secret|!)(\Z|\s)/i
ret
end
def format_rank(rank)
rank == 1 ? "0th" : "top #{rank}"
end
def format_type(type)
(type || 'Overall').to_s
end
def format_ties(ties)
ties ? " with ties" : ""
end
def format_tab(tab)
(tab == :SS2 ? '!' : (tab == :SS ? '?' : tab.to_s))
end
def format_tabs(tabs)
tabs.map { |t| format_tab(t) }.to_sentence + (tabs.empty? ? "" : " ")
end
def format_time
Time.now.strftime("on %A %B %-d at %H:%M:%S (%z)")
end
def send_top_n_count(event)
msg = event.content
player = parse_player(msg, event.user.name)
rank = parse_rank(msg) || 1
type = parse_type(msg)
tabs = parse_tabs(msg)
ties = !!(msg =~ /ties/i)
count = player.top_n_count(rank, type, tabs, ties)
header = format_rank(rank)
type = format_type(type).downcase
tabs = format_tabs(tabs)
ties = format_ties(ties)
event << "#{player.name} has #{count} #{tabs}#{type} #{header} scores#{ties}."
end
def send_rankings(event)
msg = event.content
type = parse_type(msg)
tabs = parse_tabs(msg)
rank = parse_rank(msg) || 1
ties = !!(msg =~ /ties/i)
if msg =~ /average/i
if msg =~ /point/i
players = Player.where(id: Player.joins(:scores).group('players.id').having('count(highscoreable_id) > 50').pluck(:id))
rankings = players.rankings { |p| p.average_points(type, tabs) }
header = "average point rankings "
format = "%.3f"
else
players = Player.where(id: Player.joins(:scores).group('players.id').having('count(highscoreable_id) > 50').pluck(:id))
rankings = players.rankings { |p| p.average_points(type, tabs) }.map{|p| [p[0], 20-p[1]] }
header = "average rank rankings "
format = "%.3fth"
end
elsif msg =~ /point/i
rankings = Player.rankings { |p| p.points(type, tabs) }
header = "point rankings "
format = "%d"
elsif msg =~ /score/i
rankings = Player.rankings { |p| p.total_score(type, tabs) }
header = "score rankings "
format = "%.3f"
elsif msg =~ /tied/i
rankings = Player.rankings { |p| p.top_n_count(1, type, tabs, true) - p.top_n_count(1, type, tabs, false) }
header = "tied 0th rankings "
format = "%d"
else
rankings = Player.rankings { |p| p.top_n_count(rank, type, tabs, ties) }
rank = format_rank(rank)
ties = (ties ? "with ties " : "")
header = "#{rank} rankings #{ties}"
format = "%d"
end
type = format_type(type)
tabs = format_tabs(tabs)
top = rankings.take(20).select { |r| r[1] > 0 }.each_with_index.map { |r, i| "#{HighScore.format_rank(i)}: #{r[0].name} (#{format % r[1]})" }
.join("\n")
event << "#{type} #{tabs}#{header}#{format_time}:\n```#{top}```"
end
def send_total_score(event)
player = parse_player(event.content, event.user.name)
type = parse_type(event.content)
tabs = parse_tabs(event.content)
score = player.total_score(type, tabs)
type = format_type(type).downcase
tabs = format_tabs(tabs)
event << "#{player.name}'s total #{tabs}#{type.to_s.downcase} score is #{"%.3f" % [score]}."
end
def send_spreads(event)
msg = event.content
n = (msg[/([0-9][0-9]?)(st|nd|th)/, 1] || 1).to_i
type = parse_type(msg) || Level
tabs = parse_tabs(msg)
smallest = !!(msg =~ /smallest/)
if n == 0
event << "I can't show you the spread between 0th and 0th..."
return
end
spreads = HighScore.spreads(n, type, tabs)
.sort_by { |level, spread| (smallest ? spread : -spread) }
.take(20)
.map { |s| "#{s[0]} (#{"%.3f" % [s[1]]})"}
.join("\n\t")
spread = smallest ? "smallest" : "largest"
rank = (n == 1 ? "1st" : (n == 2 ? "2nd" : (n == 3 ? "3rd" : "#{n}th")))
type = format_type(type).downcase
tabs = tabs.empty? ? "All " : format_tabs(tabs)
event << "#{tabs}#{type}s with the #{spread} spread between 0th and #{rank}:\n\t#{spreads}"
end
def send_scores(event)
msg = event.content
scores = parse_level_or_episode(msg)
scores.update_scores
# Send immediately here - using << delays sending until after the event has been processed,
# and we want to download the scores for the episode in the background after sending since it
# takes a few seconds
event.send_message("Current high scores for #{scores.format_name}:\n```#{scores.format_scores}```")
if scores.is_a?(Episode)
Level.where("UPPER(name) LIKE ?", scores.name.upcase + '%').each(&:update_scores)
end
end
def send_screenshot(event)
msg = event.content
scores = parse_level_or_episode(msg)
name = scores.name.upcase.gsub(/\?/, 'SS').gsub(/!/, 'SS2')
screenshot = "screenshots/#{name}.jpg"
if File.exist? screenshot
event.attach_file(File::open(screenshot))
else
event << "I don't have a screenshot for #{scores.format_name}... :("
end
end
def send_stats(event)
msg = event.content
player = parse_player(msg, event.user.name)
tabs = parse_tabs(msg)
counts = player.score_counts(tabs)
histdata = counts[:levels].zip(counts[:episodes])
.each_with_index
.map { |a, i| [i, a[0] + a[1]]}
histogram = AsciiCharts::Cartesian.new(
histdata,
bar: true,
hide_zero: true,
max_y_vals: 15,
title: 'Score histogram'
).draw
totals = counts[:levels].zip(counts[:episodes])
.each_with_index
.map { |a, i| "#{HighScore.format_rank(i)}: #{"\t%3d \t%3d\t\t %3d" % [a[0] + a[1], a[0], a[1]]}" }
.join("\n\t")
overall = "Totals: \t%3d \t%3d\t\t %3d" % counts[:levels].zip(counts[:episodes])
.map { |a| [a[0] + a[1], a[0], a[1]] }
.reduce([0, 0, 0]) { |sums, curr| sums.zip(curr).map { |a| a[0] + a[1] } }
tabs = tabs.empty? ? "" : " in the #{format_tabs(tabs)} #{tabs.length == 1 ? 'tab' : 'tabs'}"
event << "Player high score counts for #{player.name}#{tabs}:\n```\t Overall:\tLevel:\tEpisode:\n\t#{totals}\n#{overall}"
event << "#{histogram}```"
end
def send_list(event)
msg = event.content
player = parse_player(msg, event.user.name)
type = parse_type(msg)
tabs = parse_tabs(msg)
rank = parse_rank(msg) || 20
bott = parse_bottom_rank(msg) || 0
ties = !!(msg =~ /ties/i)
all = player.scores_by_rank(type, tabs)
if rank == 20 && bott == 0 && !!msg[/0th/i]
rank = 1
bott = 0
end
tmpfile = File.join(Dir.tmpdir, "scores-#{player.name.delete(":")}.txt")
File::open(tmpfile, "w", crlf_newline: true) do |f|
all[bott..rank-1].each_with_index do |scores, i|
list = scores.map { |s| "#{HighScore.format_rank(s.rank)}: #{s.highscoreable.name} (#{"%.3f" % [s.score]})" }
.join("\n ")
f.write("#{bott+i}:\n ")
f.write(list)
f.write("\n")
end
end
event.attach_file(File::open(tmpfile))
end
def send_community(event)
msg = event.content
tabs = parse_tabs(msg)
condition = !(tabs&[:SS, :SS2]).empty? || tabs.empty?
text = ""
levels = Score.total_scores(Level, tabs, true)
episodes = Score.total_scores(Episode, tabs, false)
levels_no_secrets = (condition ? Score.total_scores(Level, tabs, false) : levels)
difference = levels_no_secrets[0] - 4 * 90 * episodes[1] - episodes[0]
# For every episode, we subtract the additional 90 seconds
# 4 of the 5 individual levels give you at the start to be able
# to compare an episode score with the sum of its level scores.
text << "Total level score: #{levels[0]}\n"
text << "Total episode score: #{episodes[0]}\n"
text << (condition ? "Total level score (w/o secrets): #{levels_no_secrets[0]}\n" : "")
text << "Difference between level and episode 0ths: #{"%.3f" % [difference]}\n\n"
text << "Average level score: #{"%.3f" % [levels[0]/levels[1]]}\n"
text << "Average episode score: #{"%.3f" % [episodes[0]/episodes[1]]}\n"
text << "Average difference between level and episode 0ths: #{"%.3f" % [difference/episodes[1]]}\n"
event << "Community's total #{format_tabs(tabs)}scores #{format_time}:\n```#{text}```"
end
def send_maxable(event)
msg = event.content
type = parse_type(msg) || Level
tabs = parse_tabs(msg)
ties = HighScore.ties(type, tabs)
.select { |level, tie| tie < 20 }
.sort_by { |level, tie| -tie }
.take(20)
.map { |s| "#{s[0]} (#{s[1]})" }
.join("\n")
type = format_type(type).downcase
tabs = tabs.empty? ? "All " : format_tabs(tabs)
event << "#{tabs}#{type}s with the most ties for 0th #{format_time}:\n```\n#{ties}```"
end
def send_maxed(event)
msg = event.content
type = parse_type(msg) || Level
tabs = parse_tabs(msg)
ties = HighScore.ties(type, tabs)
.select { |level, tie| tie == 20 }
.map { |s| "#{s[0]}\n" }
ties_list = ties.join
type = format_type(type).downcase
tabs = tabs.empty? ? "All " : format_tabs(tabs)
event << "#{tabs}potentially maxed #{type}s (with at least 20 ties for 0th) #{format_time}:\n" +
"```\n#{ties_list}```There's a total of #{ties.count{|s| s.length>1}} potentially maxed #{type}s."
end
def send_cleanliness(event)
msg = event.content
tabs = parse_tabs(msg)
cleanest = !!msg[/cleanest/i]
episodes = tabs.empty? ? Episode.all : Episode.where(tab: tabs)
cleanliness = episodes.map{ |e| e.cleanliness }
.sort_by{ |e| (cleanest ? e[1] : -e[1]) }
.map{ |e| "#{e[0]}:#{e[0][1] == '-' ? " " : " "}%.3f" % [e[1]] }
.take(20)
.join("\n")
tabs = tabs.empty? ? "All " : format_tabs(tabs)
event << "#{tabs}#{cleanest ? "cleanest" : "dirtiest"} episodes #{format_time}:\n```#{cleanliness}```"
end
def send_ownages(event)
msg = event.content
tabs = parse_tabs(msg)
ties = !!(msg =~ /ties/i)
episodes = tabs.empty? ? Episode.all : Episode.where(tab: tabs)
ownages = episodes.map{ |e| e.ownage }
.select{ |e| e[1] == true }
.map{ |e| "#{e[0]}:#{e[0][1]=='-' ? " " : " "}#{e[2]}" }
ownages_list = ownages.join("\n")
tabs = tabs.empty? ? "All " : format_tabs(tabs)
list = "```#{ownages_list}```" unless ownages.count == 0
event << "#{tabs}episode ownages #{format_time}:\n#{list}There's a total of #{ownages.count} episode ownages."
end
def send_missing(event)
msg = event.content
player = parse_player(msg, event.user.name)
type = parse_type(msg)
tabs = parse_tabs(msg)
rank = parse_rank(msg) || 20
ties = !!(msg =~ /ties/i)
missing = player.missing_top_ns(rank, type, tabs, ties).join("\n")
tmpfile = File.join(Dir.tmpdir, "missing-#{player.name.delete(":")}.txt")
File::open(tmpfile, "w", crlf_newline: true) do |f|
f.write(missing)
end
event.attach_file(File::open(tmpfile))
end
def send_suggestions(event)
msg = event.content
player = parse_player(msg, event.user.name)
type = parse_type(msg) || Level
tabs = parse_tabs(msg)
n = (msg[/\b[0-9][0-9]?\b/] || 10).to_i
improvable = player.improvable_scores(type, tabs)
.sort_by { |level, gap| -gap }
.take(n)
.map { |level, gap| "#{level} (-#{"%.3f" % [gap]})" }
.join("\n")
missing = player.missing_top_ns(20, type, tabs, false).sample(n).join("\n")
type = type.to_s.downcase
tabs = tabs.empty? ? "" : " in the #{format_tabs(tabs)} #{tabs.length == 1 ? 'tab' : 'tabs'}"
event << "Your #{n} most improvable #{type}s#{tabs} are:\n```#{improvable}```"
event << "You're not on the board for:\n```#{missing}```"
end
def send_level_id(event)
level = parse_level_or_episode(event.content.gsub(/level/, ""))
event << "#{level.longname} is level #{level.name}."
end
def send_level_name(event)
level = parse_level_or_episode(event.content.gsub(/level/, ""))
raise "Episodes don't have a name!" if level.is_a?(Episode)
event << "#{level.name} is called #{level.longname}."
end
def send_points(event)
msg = event.content
player = parse_player(msg, event.user.name)
type = parse_type(msg)
tabs = parse_tabs(msg)
points = player.points(type, tabs)
type = format_type(type).downcase
tabs = format_tabs(tabs)
event << "#{player.name} has #{points} #{type} #{tabs}points."
end
def send_average_points(event)
msg = event.content
player = parse_player(msg, event.user.name)
type = parse_type(msg)
tabs = parse_tabs(msg)
average = player.average_points(type, tabs)
type = format_type(type).downcase
tabs = format_tabs(tabs)
event << "#{player.name} has #{"%.3f" % [average]} #{type} #{tabs}average points."
end
def send_diff(event)
type = parse_type(event.content) || Level
current = get_current(type)
old_scores = get_saved_scores(type)
since = type == Level ? "yesterday" : "last week"
diff = current.format_difference(old_scores)
event << "Score changes on #{current.format_name} since #{since}:\n```#{diff}```"
end
def do_analysis(scores, rank)
run = scores.get_replay_info(rank)
return nil if run.nil?
player = run['user_name']
replay_id = run['replay_id'].to_s
score = "%.3f" % [run['score'].to_f / 1000]
analysis = scores.analyze_replay(replay_id)
gold = "%.0f" % [((run['score'].to_f / 1000) + (analysis.size.to_f / 60) - 90) / 2]
{'player' => player, 'scores' => scores.format_name, 'rank' => rank, 'score' => score, 'analysis' => analysis, 'gold' => gold}
end
def send_analysis(event)
msg = event.content
scores = parse_level_or_episode(msg)
ranks = parse_ranks(msg)
analysis = ranks.map{ |rank| do_analysis(scores, rank) }.compact
log("analysis: " + analysis.join("\n"))
length = analysis.map{ |a| a['analysis'].size }.max
log("length: " + length)
padding = Math.log(length, 10).to_i + 1
table_header = " " * padding + "|" + "JRL|" * analysis.size
separation = "-" * table_header.size
# 3 types of result formatting, only 2 being used.
raw_result = analysis.map{ |a|
a['analysis'].map{ |b|
[b % 2 == 1, b / 2 % 2 == 1, b / 4 % 2 == 1]
}.map{ |f|
frame = ""
if f[0] then frame.concat("j") end
if f[1] then frame.concat("r") end
if f[2] then frame.concat("l") end
frame
}.join(".")
}.join("\n\n")
table_result = analysis.map{ |a|
table = a['analysis'].map{ |b|
[b % 2 == 1 ? "^" : " ", b / 2 % 2 == 1 ? ">" : " ", b / 4 % 2 == 1 ? "<" : " "].push("|")
}
while table.size < length do table.push([" ", " ", " ", "|"]) end
table.transpose
}.flatten(1)
.transpose
.each_with_index
.map{ |l, i| "%0#{padding}d|#{l.join}" % [i + 1] }
.insert(0, table_header)
.insert(1, separation)
.join("\n")
key_result = analysis.map{ |a|
a['analysis'].map{ |f|
case f
when 0 then "-"
when 1 then "^"
when 2 then ">"
when 3 then "/"
when 4 then "<"
when 5 then "\\"
when 6 then "≤"
when 7 then "|"
else "?"
end
}.join
.scan(/.{,60}/)
.reject{ |f| f.empty? }
.each_with_index
.map{ |f, i| "%0#{padding}d #{f}" % [60*i] }
.join("\n")
}.join("\n\n")
properties = analysis.map{ |a|
"[#{a['player']}, #{a['score']}, #{a['analysis'].size}f, rank #{a['rank']}, gold #{a['gold']}]"
}.join("\n")
explanation = "[**-** Nothing, **^** Jump, **>** Right, **<** Left, **/** Right Jump, **\\\\** Left Jump, **≤** Left Right, **|** Left Right Jump]"
header = "Replay analysis for #{scores.format_name} #{format_time}.\n#{properties}\n#{explanation}"
result = "#{header}\n```#{key_result}```"
if result.size > 2000 then result = result[0..1993] + "...```" end
event << "#{result}"
tmpfile = File.join(Dir.tmpdir, "analysis-#{scores.name}.txt")
File::open(tmpfile, "w", crlf_newline: true) do |f|
f.write(table_result)
end
event.attach_file(File::open(tmpfile))
end
def send_history(event)
msg = event.content
type = parse_type(msg)
tabs = parse_tabs(msg)
rank = parse_rank(msg) || 1
ties = !!(msg =~ /ties/i)
if msg =~ /point/
history = Player.points_histories(type, tabs)
header = "point "
elsif msg =~ /score/
history = Player.score_histories(type, tabs)
header = "score "
else
history = Player.rank_histories(rank, type, tabs, ties)
header = format_rank(rank) + format_ties(ties)
end
history = history.sort_by { |player, data| data.max_by { |k, v| v }[1] }
.reverse
.take(30)
.select { |player, data| data.any? { |k, v| v > rank * 2 * tabs.length } }
type = format_type(type)
tabs = format_tabs(tabs)
graph = Gruff::Line.new(1280, 2000)
graph.title = "#{type} #{tabs}#{header}history"
graph.theme_pastel
graph.colors = []
graph.legend_font_size = 10
graph.marker_font_size = 10
graph.legend_box_size = 10
graph.line_width = 1
graph.hide_dots = true
step = Math.cbrt(history.count).ceil
step.times do |i|
step.times do |j|
step.times do |k|
scale = 0xFF / (step - 1)
colour = ((scale * i) << 16) + ((scale * j) << 8) + (scale * k)
graph.add_color("##{"%06x" % [colour]}")
end
end
end
graph.colors = graph.colors.shuffle
history.each { |player, data| graph.dataxy(player, data.keys, data.values) }
tmpfile = File.join(Dir.tmpdir, "history.png")
graph.write(tmpfile)
event.attach_file(File.open(tmpfile))
end
def identify(event)
msg = event.content
user = event.user.name
nick = msg[/my name is (.*)[\.]?$/i, 1]
raise "I couldn't figure out who you were! You have to send a message in the form 'my name is <username>.'" if nick.nil?
player = Player.find_or_create_by(name: nick)
user = User.find_or_create_by(username: user)
user.player = player
user.save
event << "Awesome! From now on you can omit your username and I'll look up scores for #{nick}."
end
def add_steam_id(event)
msg = event.content
id = parse_steam_id(msg)
User.find_by(username: event.user.name)
.update(steam_id: id)
event << "Thanks! From now on I'll try to use your Steam ID to retrieve scores when I need to."
end
def hello(event)
event << "Hi!"
if $channel.nil?
$channel = event.channel
send_times(event)
end
end
def thanks(event)
event << "You're welcome!"
end
def send_level_time(event)
next_level = get_next_update(Level) - Time.now
next_level_hours = (next_level / (60 * 60)).to_i
next_level_minutes = (next_level / 60).to_i - (next_level / (60 * 60)).to_i * 60
event << "I'll post a new level of the day in #{next_level_hours} hours and #{next_level_minutes} minutes."
end
def send_episode_time(event)
next_episode = get_next_update(Episode) - Time.now
next_episode_days = (next_episode / (24 * 60 * 60)).to_i
next_episode_hours = (next_episode / (60 * 60)).to_i - (next_episode / (24 * 60 * 60)).to_i * 24
event << "I'll post a new episode of the week in #{next_episode_days} days and #{next_episode_hours} hours."
end
def send_times(event)
send_level_time(event)
send_episode_time(event)
end
def send_help(event)
msg = "The commands I understand are:\n"
File.open('README.md').read.each_line do |line|
line = line.gsub("\n", "")
if line == " "
event.send_message(msg)
msg = "Commands continued...\n"
else
msg += "\n**#{line.gsub(/^### /, "")}**\n" if line =~ /^### /
msg += " *#{line.gsub(/^- /, "").gsub(/\*/, "")}*\n" if line =~ /^- \*/
end
end
event.send_message(msg)
event << "In any of these commands, if you see '<level>', replace that with either a level/episode ID (eg. SI-A-00-00) or a level name (eg. supercomplexity)"
event << "If you see '<tab>', you can replace that with any combination of SI/intro, S/N++, SU/ultimate, SL/legacy, ?/secret, and !/ultimate secret, or you can leave it off for overall totals."
event << "If the command is related to a specific player, you can specify it by ending your message with 'for <username>'. Otherwise, I'll use the one you specified earlier."
end
def send_level(event)
event << "The current level of the day is #{get_current(Level).format_name}."
end
def send_episode(event)
event << "The current episode of the week is #{get_current(Episode).format_name}."
end
def dump(event)
log("current level/episode: #{get_current(Level).format_name}, #{get_current(Episode).format_name}") unless get_current(Level).nil?
log("next updates: scores #{get_next_update('score')}, level #{get_next_update(Level)}, episode #{get_next_update(Episode)}")
event << "I dumped some things to the log for you to look at."
end
def send_videos(event)
videos = parse_videos(event.content)
# If we have more than one video, we probably shouldn't spam the channel too hard...
# so we'll make people be more specific unless we can narrow it down.
if videos.length == 1
event << videos[0].url
return
end
descriptions = videos.map(&:format_description).join("\n")
default = videos.where(challenge: ["G++", "?!"])
# If we don't have a specific challenge to look up, we default to sending
# one without challenges
if default.length == 1
# Send immediately, so the video link shows above the additional videos
event.send_message(default[0].url)
event << "\nI have some challenge videos for this level as well! You can ask for them by being more specific about challenges and authors, by saying '<challenge> video for <level>' or 'video for <level> by <author>':\n```#{descriptions}```"
return
end
event << "You're going to have to be more specific! I know about the following videos for this level:\n```#{descriptions}```"
end
# TODO set level of the day on startup
def respond(event)
msg = event.content
# strip off the @inne++ mention, if present
msg.sub!(/\A<@[0-9]*> */, '')
# match exactly "lotd" or "eotw", regardless of capitalization or leading/trailing whitespace
if msg =~ /\A\s*lotd\s*\Z/i
send_level(event)
return
elsif msg =~ /\A\s*eotw\s*\Z/i
send_episode(event)
return
end
# exclusively global methods, this conditional avoids the problem stated in the comment below
if !msg[NAME_PATTERN, 2]
send_rankings(event) if msg =~ /rank/i && msg !~ /history/i
send_history(event) if msg =~ /history/i && msg !~ /rank/i
send_spreads(event) if msg =~ /spread/i
send_diff(event) if msg =~ /diff/i
send_community(event) if msg =~ /community/i
send_maxable(event) if msg =~ /maxable/i
send_maxed(event) if msg =~ /maxed/i
send_cleanliness(event) if msg =~ /cleanest/i || msg =~ /dirtiest/i
send_ownages(event) if msg =~ /ownage/i
send_help(event) if msg =~ /\bhelp\b/i || msg =~ /\bcommands\b/i
end
# on this methods, we will exclude a few problematic words that appear
# in some level names which would accidentally trigger them
hello(event) if msg =~ /\bhello\b/i || msg =~ /\bhi\b/i
thanks(event) if msg =~ /\bthank you\b/i || msg =~ /\bthanks\b/i
dump(event) if msg =~ /dump/i
send_level(event) if msg =~ /what.*(level|lotd)/i
send_episode(event) if msg =~ /what.*(episode|eotw)/i
send_episode_time(event) if msg =~ /when.*next.*(episode|eotw)/i
send_level_time(event) if msg =~ /when.*next.*(level|lotd)/i
send_points(event) if msg =~ /\bpoints/i && msg !~ /history/i && msg !~ /rank/i && msg !~ /average/i && msg !~ /floating/i && msg !~ /legrange/i
send_average_points(event) if msg =~ /\bpoints/i && msg !~ /history/i && msg !~ /rank/i && msg =~ /average/i && msg !~ /floating/i && msg !~ /legrange/i
send_scores(event) if msg =~ /scores/i && !!msg[NAME_PATTERN, 2]
send_total_score(event) if msg =~ /total\b/i && msg !~ /history/i && msg !~ /rank/i
send_top_n_count(event) if msg =~ /how many/i
send_stats(event) if msg =~ /\bstat/i && msg !~ /generator/i && msg !~ /hooligan/i && msg !~ /space station/i
send_screenshot(event) if msg =~ /screenshot/i
send_suggestions(event) if msg =~ /worst/i && msg !~ /nightmare/i
send_list(event) if msg =~ /\blist\b/i && msg !~ /of inappropriate words/i
send_missing(event) if msg =~ /missing/i
send_level_name(event) if msg =~ /\blevel name\b/i
send_level_id(event) if msg =~ /\blevel id\b/i
send_analysis(event) if msg =~ /analysis/i
identify(event) if msg =~ /my name is/i
add_steam_id(event) if msg =~ /my steam id is/i
send_videos(event) if msg =~ /\bvideo\b/i || msg =~ /\bmovie\b/i
rescue RuntimeError => e
# Exceptions raised in here are user error, indicating that we couldn't
# figure out what they were asking for, so send the error message out
# to the channel
event << e
end
| 33.155213 | 244 | 0.624093 |
4a20746f8ea18c1916cca56b34726fc35266abc5 | 7,955 | class FitsDatastream < ActiveFedora::OmDatastream
include OM::XML::Document
set_terminology do |t|
t.root(:path => "fits",
:xmlns => "http://hul.harvard.edu/ois/xml/ns/fits/fits_output",
:schema => "http://hul.harvard.edu/ois/xml/xsd/fits/fits_output.xsd")
t.identification {
t.identity {
t.format_label(:path=>{:attribute=>"format"})
t.mime_type(:path=>{:attribute=>"mimetype"}, index_as: [:stored_searchable])
}
}
t.fileinfo {
t.file_size(:path=>"size")
t.last_modified(:path=>"lastmodified")
t.filename(:path=>"filename")
t.original_checksum(:path=>"md5checksum")
t.rights_basis(:path=>"rightsBasis")
t.copyright_basis(:path=>"copyrightBasis")
t.copyright_note(:path=>"copyrightNote")
}
t.filestatus {
t.well_formed(:path=>"well-formed")
t.valid(:path=>"valid")
t.status_message(:path=>"message")
}
t.metadata {
t.document {
t.file_title(:path=>"title")
t.file_author(:path=>"author")
t.file_language(:path=>"language")
t.page_count(:path=>"pageCount")
t.word_count(:path=>"wordCount")
t.character_count(:path=>"characterCount")
t.paragraph_count(:path=>"paragraphCount")
t.line_count(:path=>"lineCount")
t.table_count(:path=>"tableCount")
t.graphics_count(:path=>"graphicsCount")
}
t.image {
t.byte_order(:path=>"byteOrder")
t.compression(:path=>"compressionScheme")
t.width(:path=>"imageWidth")
t.height(:path=>"imageHeight")
t.color_space(:path=>"colorSpace")
t.profile_name(:path=>"iccProfileName")
t.profile_version(:path=>"iccProfileVersion")
t.orientation(:path=>"orientation")
t.color_map(:path=>"colorMap")
t.image_producer(:path=>"imageProducer")
t.capture_device(:path=>"captureDevice")
t.scanning_software(:path=>"scanningSoftwareName")
t.exif_version(:path=>"exifVersion")
t.gps_timestamp(:path=>"gpsTimeStamp")
t.latitude(:path=>"gpsDestLatitude")
t.longitude(:path=>"gpsDestLongitude")
}
t.text {
t.character_set(:path=>"charset")
t.markup_basis(:path=>"markupBasis")
t.markup_language(:path=>"markupLanguage")
}
t.audio {
t.duration(:path=>"duration")
t.bit_depth(:path=>"bitDepth")
t.sample_rate(:path=>"sampleRate")
t.channels(:path=>"channels")
t.data_format(:path=>"dataFormatType")
t.offset(:path=>"offset")
}
t.video {
# Not yet implemented in FITS
}
}
t.format_label(:proxy=>[:identification, :identity, :format_label])
t.mime_type(:proxy=>[:identification, :identity, :mime_type])
t.file_size(:proxy=>[:fileinfo, :file_size])
t.last_modified(:proxy=>[:fileinfo, :last_modified])
t.filename(:proxy=>[:fileinfo, :filename])
t.original_checksum(:proxy=>[:fileinfo, :original_checksum])
t.rights_basis(:proxy=>[:fileinfo, :rights_basis])
t.copyright_basis(:proxy=>[:fileinfo, :copyright_basis])
t.copyright_note(:proxy=>[:fileinfo, :copyright_note])
t.well_formed(:proxy=>[:filestatus, :well_formed])
t.valid(:proxy=>[:filestatus, :valid])
t.status_message(:proxy=>[:filestatus, :status_message])
t.file_title(:proxy=>[:metadata, :document, :file_title])
t.file_author(:proxy=>[:metadata, :document, :file_author])
t.page_count(:proxy=>[:metadata, :document, :page_count])
t.file_language(:proxy=>[:metadata, :document, :file_language])
t.word_count(:proxy=>[:metadata, :document, :word_count])
t.character_count(:proxy=>[:metadata, :document, :character_count])
t.paragraph_count(:proxy=>[:metadata, :document, :paragraph_count])
t.line_count(:proxy=>[:metadata, :document, :line_count])
t.table_count(:proxy=>[:metadata, :document, :table_count])
t.graphics_count(:proxy=>[:metadata, :document, :graphics_count])
t.byte_order(:proxy=>[:metadata, :image, :byte_order])
t.compression(:proxy=>[:metadata, :image, :compression])
t.width(:proxy=>[:metadata, :image, :width])
t.height(:proxy=>[:metadata, :image, :height])
t.color_space(:proxy=>[:metadata, :image, :color_space])
t.profile_name(:proxy=>[:metadata, :image, :profile_name])
t.profile_version(:proxy=>[:metadata, :image, :profile_version])
t.orientation(:proxy=>[:metadata, :image, :orientation])
t.color_map(:proxy=>[:metadata, :image, :color_map])
t.image_producer(:proxy=>[:metadata, :image, :image_producer])
t.capture_device(:proxy=>[:metadata, :image, :capture_device])
t.scanning_software(:proxy=>[:metadata, :image, :scanning_software])
t.exif_version(:proxy=>[:metadata, :image, :exif_version])
t.gps_timestamp(:proxy=>[:metadata, :image, :gps_timestamp])
t.latitude(:proxy=>[:metadata, :image, :latitude])
t.longitude(:proxy=>[:metadata, :image, :longitude])
t.character_set(:proxy=>[:metadata, :text, :character_set])
t.markup_basis(:proxy=>[:metadata, :text, :markup_basis])
t.markup_language(:proxy=>[:metadata, :text, :markup_language])
t.duration(:proxy=>[:metadata, :audio, :duration])
t.bit_depth(:proxy=>[:metadata, :audio, :bit_depth])
t.sample_rate(:proxy=>[:metadata, :audio, :sample_rate])
t.channels(:proxy=>[:metadata, :audio, :channels])
t.data_format(:proxy=>[:metadata, :audio, :data_format])
t.offset(:proxy=>[:metadata, :audio, :offset])
end
def self.xml_template
builder = Nokogiri::XML::Builder.new do |xml|
xml.fits(:xmlns => 'http://hul.harvard.edu/ois/xml/ns/fits/fits_output',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' =>
"http://hul.harvard.edu/ois/xml/ns/fits/fits_output
http://hul.harvard.edu/ois/xml/xsd/fits/fits_output.xsd",
:version => "0.6.0",
:timestamp => "1/25/12 11:04 AM") {
xml.identification {
xml.identity(:format => '', :mimetype => '',
:toolname => 'FITS', :toolversion => '') {
xml.tool(:toolname => '', :toolversion => '')
xml.version(:toolname => '', :toolversion => '')
xml.externalIdentifier(:toolname => '', :toolversion => '')
}
}
xml.fileinfo {
xml.size(:toolname => '', :toolversion => '')
xml.creatingApplicatioName(:toolname => '', :toolversion => '',
:status => '')
xml.lastmodified(:toolname => '', :toolversion => '', :status => '')
xml.filepath(:toolname => '', :toolversion => '', :status => '')
xml.filename(:toolname => '', :toolversion => '', :status => '')
xml.md5checksum(:toolname => '', :toolversion => '', :status => '')
xml.fslastmodified(:toolname => '', :toolversion => '', :status => '')
}
xml.filestatus {
xml.tag! "well-formed", :toolname => '', :toolversion => '', :status => ''
xml.valid(:toolname => '', :toolversion => '', :status => '')
}
xml.metadata {
xml.document {
xml.title(:toolname => '', :toolversion => '', :status => '')
xml.author(:toolname => '', :toolversion => '', :status => '')
xml.pageCount(:toolname => '', :toolversion => '')
xml.isTagged(:toolname => '', :toolversion => '')
xml.hasOutline(:toolname => '', :toolversion => '')
xml.hasAnnotations(:toolname => '', :toolversion => '')
xml.isRightsManaged(:toolname => '', :toolversion => '',
:status => '')
xml.isProtected(:toolname => '', :toolversion => '')
xml.hasForms(:toolname => '', :toolversion => '', :status => '')
}
}
}
end
builder.doc
end
end
| 45.457143 | 84 | 0.591703 |
289964916609cbcffa712ea46135fc26cb07a674 | 268,643 | # Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module DialogflowV2
# Represents a conversational agent.
class GoogleCloudDialogflowV2Agent
include Google::Apis::Core::Hashable
# Optional. API version displayed in Dialogflow console. If not specified,
# V2 API is assumed. Clients are free to query different service endpoints
# for different API versions. However, bots connectors and webhook calls will
# follow the specified API version.
# Corresponds to the JSON property `apiVersion`
# @return [String]
attr_accessor :api_version
# Optional. The URI of the agent's avatar.
# Avatars are used throughout the Dialogflow console and in the self-hosted
# [Web
# Demo](https://cloud.google.com/dialogflow/docs/integrations/web-demo)
# integration.
# Corresponds to the JSON property `avatarUri`
# @return [String]
attr_accessor :avatar_uri
# Optional. To filter out false positive results and still get variety in
# matched natural language inputs for your agent, you can tune the machine
# learning classification threshold. If the returned score value is less than
# the threshold value, then a fallback intent will be triggered or, if there
# are no fallback intents defined, no intent will be triggered. The score
# values range from 0.0 (completely uncertain) to 1.0 (completely certain).
# If set to 0.0, the default of 0.3 is used.
# Corresponds to the JSON property `classificationThreshold`
# @return [Float]
attr_accessor :classification_threshold
# Required. The default language of the agent as a language tag. See
# [Language
# Support](https://cloud.google.com/dialogflow/docs/reference/language)
# for a list of the currently supported language codes. This field cannot be
# set by the `Update` method.
# Corresponds to the JSON property `defaultLanguageCode`
# @return [String]
attr_accessor :default_language_code
# Optional. The description of this agent.
# The maximum length is 500 characters. If exceeded, the request is rejected.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Required. The name of this agent.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# Optional. Determines whether this agent should log conversation queries.
# Corresponds to the JSON property `enableLogging`
# @return [Boolean]
attr_accessor :enable_logging
alias_method :enable_logging?, :enable_logging
# Optional. Determines how intents are detected from user queries.
# Corresponds to the JSON property `matchMode`
# @return [String]
attr_accessor :match_mode
# Required. The project of this agent.
# Format: `projects/<Project ID>`.
# Corresponds to the JSON property `parent`
# @return [String]
attr_accessor :parent
# Optional. The list of all languages supported by this agent (except for the
# `default_language_code`).
# Corresponds to the JSON property `supportedLanguageCodes`
# @return [Array<String>]
attr_accessor :supported_language_codes
# Optional. The agent tier. If not specified, TIER_STANDARD is assumed.
# Corresponds to the JSON property `tier`
# @return [String]
attr_accessor :tier
# Required. The time zone of this agent from the
# [time zone database](https://www.iana.org/time-zones), e.g.,
# America/New_York, Europe/Paris.
# Corresponds to the JSON property `timeZone`
# @return [String]
attr_accessor :time_zone
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@api_version = args[:api_version] if args.key?(:api_version)
@avatar_uri = args[:avatar_uri] if args.key?(:avatar_uri)
@classification_threshold = args[:classification_threshold] if args.key?(:classification_threshold)
@default_language_code = args[:default_language_code] if args.key?(:default_language_code)
@description = args[:description] if args.key?(:description)
@display_name = args[:display_name] if args.key?(:display_name)
@enable_logging = args[:enable_logging] if args.key?(:enable_logging)
@match_mode = args[:match_mode] if args.key?(:match_mode)
@parent = args[:parent] if args.key?(:parent)
@supported_language_codes = args[:supported_language_codes] if args.key?(:supported_language_codes)
@tier = args[:tier] if args.key?(:tier)
@time_zone = args[:time_zone] if args.key?(:time_zone)
end
end
# Represents a part of a message possibly annotated with an entity. The part
# can be an entity or purely a part of the message between two entities or
# message start/end.
class GoogleCloudDialogflowV2AnnotatedMessagePart
include Google::Apis::Core::Hashable
# The [Dialogflow system entity
# type](https://cloud.google.com/dialogflow/docs/reference/system-entities)
# of this message part. If this is empty, Dialogflow could not annotate the
# phrase part with a system entity.
# Corresponds to the JSON property `entityType`
# @return [String]
attr_accessor :entity_type
# The [Dialogflow system entity formatted value
# ](https://cloud.google.com/dialogflow/docs/reference/system-entities) of
# this message part. For example for a system entity of type
# `@sys.unit-currency`, this may contain:
# <pre>
# `
# "amount": 5,
# "currency": "USD"
# `
# </pre>
# Corresponds to the JSON property `formattedValue`
# @return [Object]
attr_accessor :formatted_value
# A part of a message possibly annotated with an entity.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entity_type = args[:entity_type] if args.key?(:entity_type)
@formatted_value = args[:formatted_value] if args.key?(:formatted_value)
@text = args[:text] if args.key?(:text)
end
end
# The request message for EntityTypes.BatchCreateEntities.
class GoogleCloudDialogflowV2BatchCreateEntitiesRequest
include Google::Apis::Core::Hashable
# Required. The entities to create.
# Corresponds to the JSON property `entities`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2EntityTypeEntity>]
attr_accessor :entities
# Optional. The language of entity synonyms defined in `entities`. If not
# specified, the agent's default language is used.
# [Many
# languages](https://cloud.google.com/dialogflow/docs/reference/language)
# are supported. Note: languages must be enabled in the agent before they can
# be used.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entities = args[:entities] if args.key?(:entities)
@language_code = args[:language_code] if args.key?(:language_code)
end
end
# The request message for EntityTypes.BatchDeleteEntities.
class GoogleCloudDialogflowV2BatchDeleteEntitiesRequest
include Google::Apis::Core::Hashable
# Required. The reference `values` of the entities to delete. Note that
# these are not fully-qualified names, i.e. they don't start with
# `projects/<Project ID>`.
# Corresponds to the JSON property `entityValues`
# @return [Array<String>]
attr_accessor :entity_values
# Optional. The language of entity synonyms defined in `entities`. If not
# specified, the agent's default language is used.
# [Many
# languages](https://cloud.google.com/dialogflow/docs/reference/language)
# are supported. Note: languages must be enabled in the agent before they can
# be used.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entity_values = args[:entity_values] if args.key?(:entity_values)
@language_code = args[:language_code] if args.key?(:language_code)
end
end
# The request message for EntityTypes.BatchDeleteEntityTypes.
class GoogleCloudDialogflowV2BatchDeleteEntityTypesRequest
include Google::Apis::Core::Hashable
# Required. The names entity types to delete. All names must point to the
# same agent as `parent`.
# Corresponds to the JSON property `entityTypeNames`
# @return [Array<String>]
attr_accessor :entity_type_names
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entity_type_names = args[:entity_type_names] if args.key?(:entity_type_names)
end
end
# The request message for Intents.BatchDeleteIntents.
class GoogleCloudDialogflowV2BatchDeleteIntentsRequest
include Google::Apis::Core::Hashable
# Required. The collection of intents to delete. Only intent `name` must be
# filled in.
# Corresponds to the JSON property `intents`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Intent>]
attr_accessor :intents
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@intents = args[:intents] if args.key?(:intents)
end
end
# The request message for EntityTypes.BatchUpdateEntities.
class GoogleCloudDialogflowV2BatchUpdateEntitiesRequest
include Google::Apis::Core::Hashable
# Required. The entities to update or create.
# Corresponds to the JSON property `entities`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2EntityTypeEntity>]
attr_accessor :entities
# Optional. The language of entity synonyms defined in `entities`. If not
# specified, the agent's default language is used.
# [Many
# languages](https://cloud.google.com/dialogflow/docs/reference/language)
# are supported. Note: languages must be enabled in the agent before they can
# be used.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Optional. The mask to control which fields get updated.
# Corresponds to the JSON property `updateMask`
# @return [String]
attr_accessor :update_mask
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entities = args[:entities] if args.key?(:entities)
@language_code = args[:language_code] if args.key?(:language_code)
@update_mask = args[:update_mask] if args.key?(:update_mask)
end
end
# The request message for EntityTypes.BatchUpdateEntityTypes.
class GoogleCloudDialogflowV2BatchUpdateEntityTypesRequest
include Google::Apis::Core::Hashable
# This message is a wrapper around a collection of entity types.
# Corresponds to the JSON property `entityTypeBatchInline`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2EntityTypeBatch]
attr_accessor :entity_type_batch_inline
# The URI to a Google Cloud Storage file containing entity types to update
# or create. The file format can either be a serialized proto (of
# EntityBatch type) or a JSON object. Note: The URI must start with
# "gs://".
# Corresponds to the JSON property `entityTypeBatchUri`
# @return [String]
attr_accessor :entity_type_batch_uri
# Optional. The language of entity synonyms defined in `entity_types`. If not
# specified, the agent's default language is used.
# [Many
# languages](https://cloud.google.com/dialogflow/docs/reference/language)
# are supported. Note: languages must be enabled in the agent before they can
# be used.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Optional. The mask to control which fields get updated.
# Corresponds to the JSON property `updateMask`
# @return [String]
attr_accessor :update_mask
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entity_type_batch_inline = args[:entity_type_batch_inline] if args.key?(:entity_type_batch_inline)
@entity_type_batch_uri = args[:entity_type_batch_uri] if args.key?(:entity_type_batch_uri)
@language_code = args[:language_code] if args.key?(:language_code)
@update_mask = args[:update_mask] if args.key?(:update_mask)
end
end
# The response message for EntityTypes.BatchUpdateEntityTypes.
class GoogleCloudDialogflowV2BatchUpdateEntityTypesResponse
include Google::Apis::Core::Hashable
# The collection of updated or created entity types.
# Corresponds to the JSON property `entityTypes`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2EntityType>]
attr_accessor :entity_types
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entity_types = args[:entity_types] if args.key?(:entity_types)
end
end
# The request message for Intents.BatchUpdateIntents.
class GoogleCloudDialogflowV2BatchUpdateIntentsRequest
include Google::Apis::Core::Hashable
# This message is a wrapper around a collection of intents.
# Corresponds to the JSON property `intentBatchInline`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentBatch]
attr_accessor :intent_batch_inline
# The URI to a Google Cloud Storage file containing intents to update or
# create. The file format can either be a serialized proto (of IntentBatch
# type) or JSON object. Note: The URI must start with "gs://".
# Corresponds to the JSON property `intentBatchUri`
# @return [String]
attr_accessor :intent_batch_uri
# Optional. The resource view to apply to the returned intent.
# Corresponds to the JSON property `intentView`
# @return [String]
attr_accessor :intent_view
# Optional. The language of training phrases, parameters and rich messages
# defined in `intents`. If not specified, the agent's default language is
# used. [Many
# languages](https://cloud.google.com/dialogflow/docs/reference/language)
# are supported. Note: languages must be enabled in the agent before they can
# be used.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Optional. The mask to control which fields get updated.
# Corresponds to the JSON property `updateMask`
# @return [String]
attr_accessor :update_mask
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@intent_batch_inline = args[:intent_batch_inline] if args.key?(:intent_batch_inline)
@intent_batch_uri = args[:intent_batch_uri] if args.key?(:intent_batch_uri)
@intent_view = args[:intent_view] if args.key?(:intent_view)
@language_code = args[:language_code] if args.key?(:language_code)
@update_mask = args[:update_mask] if args.key?(:update_mask)
end
end
# The response message for Intents.BatchUpdateIntents.
class GoogleCloudDialogflowV2BatchUpdateIntentsResponse
include Google::Apis::Core::Hashable
# The collection of updated or created intents.
# Corresponds to the JSON property `intents`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Intent>]
attr_accessor :intents
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@intents = args[:intents] if args.key?(:intents)
end
end
# Represents a context.
class GoogleCloudDialogflowV2Context
include Google::Apis::Core::Hashable
# Optional. The number of conversational query requests after which the
# context expires. If set to `0` (the default) the context expires
# immediately. Contexts expire automatically after 20 minutes if there
# are no matching queries.
# Corresponds to the JSON property `lifespanCount`
# @return [Fixnum]
attr_accessor :lifespan_count
# Required. The unique identifier of the context. Format:
# `projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>`,
# or `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
# ID>/sessions/<Session ID>/contexts/<Context ID>`.
# The `Context ID` is always converted to lowercase, may only contain
# characters in a-zA-Z0-9_-% and may be at most 250 bytes long.
# If `Environment ID` is not specified, we assume default 'draft'
# environment. If `User ID` is not specified, we assume default '-' user.
# The following context names are reserved for internal use by Dialogflow.
# You should not use these contexts or create contexts with these names:
# * `__system_counters__`
# * `*_id_dialog_context`
# * `*_dialog_params_size`
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Optional. The collection of parameters associated with this context.
# Refer to [this
# doc](https://cloud.google.com/dialogflow/docs/intents-actions-parameters)
# for syntax.
# Corresponds to the JSON property `parameters`
# @return [Hash<String,Object>]
attr_accessor :parameters
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@lifespan_count = args[:lifespan_count] if args.key?(:lifespan_count)
@name = args[:name] if args.key?(:name)
@parameters = args[:parameters] if args.key?(:parameters)
end
end
# Represents a notification sent to Cloud Pub/Sub subscribers for conversation
# lifecycle events.
class GoogleCloudDialogflowV2ConversationEvent
include Google::Apis::Core::Hashable
# The unique identifier of the conversation this notification
# refers to.
# Format: `projects/<Project ID>/conversations/<Conversation ID>`.
# Corresponds to the JSON property `conversation`
# @return [String]
attr_accessor :conversation
# The `Status` type defines a logical error model that is suitable for
# different programming environments, including REST APIs and RPC APIs. It is
# used by [gRPC](https://github.com/grpc). Each `Status` message contains
# three pieces of data: error code, error message, and error details.
# You can find out more about this error model and how to work with it in the
# [API Design Guide](https://cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `errorStatus`
# @return [Google::Apis::DialogflowV2::GoogleRpcStatus]
attr_accessor :error_status
# Represents a message posted into a conversation.
# Corresponds to the JSON property `newMessagePayload`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Message]
attr_accessor :new_message_payload
# The type of the event that this notification refers to.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@conversation = args[:conversation] if args.key?(:conversation)
@error_status = args[:error_status] if args.key?(:error_status)
@new_message_payload = args[:new_message_payload] if args.key?(:new_message_payload)
@type = args[:type] if args.key?(:type)
end
end
# ============================================================================
# Requests and responses for custom methods.
# The request to detect user's intent.
class GoogleCloudDialogflowV2DetectIntentRequest
include Google::Apis::Core::Hashable
# The natural language speech audio to be processed. This field
# should be populated iff `query_input` is set to an input audio config.
# A single request can contain up to 1 minute of speech audio data.
# Corresponds to the JSON property `inputAudio`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :input_audio
# Instructs the speech synthesizer on how to generate the output audio content.
# If this audio config is supplied in a request, it overrides all existing
# text-to-speech settings applied to the agent.
# Corresponds to the JSON property `outputAudioConfig`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2OutputAudioConfig]
attr_accessor :output_audio_config
# Mask for output_audio_config indicating which settings in this
# request-level config should override speech synthesizer settings defined at
# agent-level.
# If unspecified or empty, output_audio_config replaces the agent-level
# config in its entirety.
# Corresponds to the JSON property `outputAudioConfigMask`
# @return [String]
attr_accessor :output_audio_config_mask
# Represents the query input. It can contain either:
# 1. An audio config which
# instructs the speech recognizer how to process the speech audio.
# 2. A conversational query in the form of text,.
# 3. An event that specifies which intent to trigger.
# Corresponds to the JSON property `queryInput`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2QueryInput]
attr_accessor :query_input
# Represents the parameters of the conversational query.
# Corresponds to the JSON property `queryParams`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2QueryParameters]
attr_accessor :query_params
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@input_audio = args[:input_audio] if args.key?(:input_audio)
@output_audio_config = args[:output_audio_config] if args.key?(:output_audio_config)
@output_audio_config_mask = args[:output_audio_config_mask] if args.key?(:output_audio_config_mask)
@query_input = args[:query_input] if args.key?(:query_input)
@query_params = args[:query_params] if args.key?(:query_params)
end
end
# The message returned from the DetectIntent method.
class GoogleCloudDialogflowV2DetectIntentResponse
include Google::Apis::Core::Hashable
# The audio data bytes encoded as specified in the request.
# Note: The output audio is generated based on the values of default platform
# text responses found in the `query_result.fulfillment_messages` field. If
# multiple default text responses exist, they will be concatenated when
# generating audio. If no default platform text responses exist, the
# generated audio content will be empty.
# Corresponds to the JSON property `outputAudio`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :output_audio
# Instructs the speech synthesizer on how to generate the output audio content.
# If this audio config is supplied in a request, it overrides all existing
# text-to-speech settings applied to the agent.
# Corresponds to the JSON property `outputAudioConfig`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2OutputAudioConfig]
attr_accessor :output_audio_config
# Represents the result of conversational query or event processing.
# Corresponds to the JSON property `queryResult`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2QueryResult]
attr_accessor :query_result
# The unique identifier of the response. It can be used to
# locate a response in the training example set or for reporting issues.
# Corresponds to the JSON property `responseId`
# @return [String]
attr_accessor :response_id
# The `Status` type defines a logical error model that is suitable for
# different programming environments, including REST APIs and RPC APIs. It is
# used by [gRPC](https://github.com/grpc). Each `Status` message contains
# three pieces of data: error code, error message, and error details.
# You can find out more about this error model and how to work with it in the
# [API Design Guide](https://cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `webhookStatus`
# @return [Google::Apis::DialogflowV2::GoogleRpcStatus]
attr_accessor :webhook_status
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@output_audio = args[:output_audio] if args.key?(:output_audio)
@output_audio_config = args[:output_audio_config] if args.key?(:output_audio_config)
@query_result = args[:query_result] if args.key?(:query_result)
@response_id = args[:response_id] if args.key?(:response_id)
@webhook_status = args[:webhook_status] if args.key?(:webhook_status)
end
end
# Represents an entity type.
# Entity types serve as a tool for extracting parameter values from natural
# language queries.
class GoogleCloudDialogflowV2EntityType
include Google::Apis::Core::Hashable
# Optional. Indicates whether the entity type can be automatically
# expanded.
# Corresponds to the JSON property `autoExpansionMode`
# @return [String]
attr_accessor :auto_expansion_mode
# Required. The name of the entity type.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# Optional. Enables fuzzy entity extraction during classification.
# Corresponds to the JSON property `enableFuzzyExtraction`
# @return [Boolean]
attr_accessor :enable_fuzzy_extraction
alias_method :enable_fuzzy_extraction?, :enable_fuzzy_extraction
# Optional. The collection of entity entries associated with the entity type.
# Corresponds to the JSON property `entities`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2EntityTypeEntity>]
attr_accessor :entities
# Required. Indicates the kind of entity type.
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# The unique identifier of the entity type.
# Required for EntityTypes.UpdateEntityType and
# EntityTypes.BatchUpdateEntityTypes methods.
# Format: `projects/<Project ID>/agent/entityTypes/<Entity Type ID>`.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@auto_expansion_mode = args[:auto_expansion_mode] if args.key?(:auto_expansion_mode)
@display_name = args[:display_name] if args.key?(:display_name)
@enable_fuzzy_extraction = args[:enable_fuzzy_extraction] if args.key?(:enable_fuzzy_extraction)
@entities = args[:entities] if args.key?(:entities)
@kind = args[:kind] if args.key?(:kind)
@name = args[:name] if args.key?(:name)
end
end
# This message is a wrapper around a collection of entity types.
class GoogleCloudDialogflowV2EntityTypeBatch
include Google::Apis::Core::Hashable
# A collection of entity types.
# Corresponds to the JSON property `entityTypes`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2EntityType>]
attr_accessor :entity_types
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entity_types = args[:entity_types] if args.key?(:entity_types)
end
end
# An **entity entry** for an associated entity type.
class GoogleCloudDialogflowV2EntityTypeEntity
include Google::Apis::Core::Hashable
# Required. A collection of value synonyms. For example, if the entity type
# is *vegetable*, and `value` is *scallions*, a synonym could be *green
# onions*.
# For `KIND_LIST` entity types:
# * This collection must contain exactly one synonym equal to `value`.
# Corresponds to the JSON property `synonyms`
# @return [Array<String>]
attr_accessor :synonyms
# Required. The primary value associated with this entity entry.
# For example, if the entity type is *vegetable*, the value could be
# *scallions*.
# For `KIND_MAP` entity types:
# * A reference value to be used in place of synonyms.
# For `KIND_LIST` entity types:
# * A string that can contain references to other entity types (with or
# without aliases).
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@synonyms = args[:synonyms] if args.key?(:synonyms)
@value = args[:value] if args.key?(:value)
end
end
# Events allow for matching intents by event name instead of the natural
# language input. For instance, input `<event: ` name: "welcome_event",
# parameters: ` name: "Sam" ` `>` can trigger a personalized welcome response.
# The parameter `name` may be used by the agent in the response:
# `"Hello #welcome_event.name! What can I do for you today?"`.
class GoogleCloudDialogflowV2EventInput
include Google::Apis::Core::Hashable
# Required. The language of this query. See [Language
# Support](https://cloud.google.com/dialogflow/docs/reference/language)
# for a list of the currently supported language codes. Note that queries in
# the same session do not necessarily need to specify the same language.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Required. The unique identifier of the event.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# The collection of parameters associated with the event.
# Corresponds to the JSON property `parameters`
# @return [Hash<String,Object>]
attr_accessor :parameters
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@language_code = args[:language_code] if args.key?(:language_code)
@name = args[:name] if args.key?(:name)
@parameters = args[:parameters] if args.key?(:parameters)
end
end
# The request message for Agents.ExportAgent.
class GoogleCloudDialogflowV2ExportAgentRequest
include Google::Apis::Core::Hashable
# Required. The [Google Cloud Storage](https://cloud.google.com/storage/docs/)
# URI to export the agent to.
# The format of this URI must be `gs://<bucket-name>/<object-name>`.
# If left unspecified, the serialized agent is returned inline.
# Corresponds to the JSON property `agentUri`
# @return [String]
attr_accessor :agent_uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@agent_uri = args[:agent_uri] if args.key?(:agent_uri)
end
end
# The response message for Agents.ExportAgent.
class GoogleCloudDialogflowV2ExportAgentResponse
include Google::Apis::Core::Hashable
# Zip compressed raw byte content for agent.
# Corresponds to the JSON property `agentContent`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :agent_content
# The URI to a file containing the exported agent. This field is populated
# only if `agent_uri` is specified in `ExportAgentRequest`.
# Corresponds to the JSON property `agentUri`
# @return [String]
attr_accessor :agent_uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@agent_content = args[:agent_content] if args.key?(:agent_content)
@agent_uri = args[:agent_uri] if args.key?(:agent_uri)
end
end
# Represents a fulfillment.
class GoogleCloudDialogflowV2Fulfillment
include Google::Apis::Core::Hashable
# Optional. The human-readable name of the fulfillment, unique within the agent.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# Optional. Whether fulfillment is enabled.
# Corresponds to the JSON property `enabled`
# @return [Boolean]
attr_accessor :enabled
alias_method :enabled?, :enabled
# Optional. The field defines whether the fulfillment is enabled for certain
# features.
# Corresponds to the JSON property `features`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2FulfillmentFeature>]
attr_accessor :features
# Represents configuration for a generic web service.
# Dialogflow supports two mechanisms for authentications:
# - Basic authentication with username and password.
# - Authentication with additional authentication headers.
# More information could be found at:
# https://cloud.google.com/dialogflow/docs/fulfillment-configure.
# Corresponds to the JSON property `genericWebService`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2FulfillmentGenericWebService]
attr_accessor :generic_web_service
# Required. The unique identifier of the fulfillment.
# Format: `projects/<Project ID>/agent/fulfillment`.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@display_name = args[:display_name] if args.key?(:display_name)
@enabled = args[:enabled] if args.key?(:enabled)
@features = args[:features] if args.key?(:features)
@generic_web_service = args[:generic_web_service] if args.key?(:generic_web_service)
@name = args[:name] if args.key?(:name)
end
end
# Whether fulfillment is enabled for the specific feature.
class GoogleCloudDialogflowV2FulfillmentFeature
include Google::Apis::Core::Hashable
# The type of the feature that enabled for fulfillment.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@type = args[:type] if args.key?(:type)
end
end
# Represents configuration for a generic web service.
# Dialogflow supports two mechanisms for authentications:
# - Basic authentication with username and password.
# - Authentication with additional authentication headers.
# More information could be found at:
# https://cloud.google.com/dialogflow/docs/fulfillment-configure.
class GoogleCloudDialogflowV2FulfillmentGenericWebService
include Google::Apis::Core::Hashable
# Optional. Indicates if generic web service is created through Cloud Functions
# integration. Defaults to false.
# Corresponds to the JSON property `isCloudFunction`
# @return [Boolean]
attr_accessor :is_cloud_function
alias_method :is_cloud_function?, :is_cloud_function
# Optional. The password for HTTP Basic authentication.
# Corresponds to the JSON property `password`
# @return [String]
attr_accessor :password
# Optional. The HTTP request headers to send together with fulfillment requests.
# Corresponds to the JSON property `requestHeaders`
# @return [Hash<String,String>]
attr_accessor :request_headers
# Required. The fulfillment URI for receiving POST requests.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
# Optional. The user name for HTTP Basic authentication.
# Corresponds to the JSON property `username`
# @return [String]
attr_accessor :username
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@is_cloud_function = args[:is_cloud_function] if args.key?(:is_cloud_function)
@password = args[:password] if args.key?(:password)
@request_headers = args[:request_headers] if args.key?(:request_headers)
@uri = args[:uri] if args.key?(:uri)
@username = args[:username] if args.key?(:username)
end
end
# The request message for Agents.ImportAgent.
class GoogleCloudDialogflowV2ImportAgentRequest
include Google::Apis::Core::Hashable
# Zip compressed raw byte content for agent.
# Corresponds to the JSON property `agentContent`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :agent_content
# The URI to a Google Cloud Storage file containing the agent to import.
# Note: The URI must start with "gs://".
# Corresponds to the JSON property `agentUri`
# @return [String]
attr_accessor :agent_uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@agent_content = args[:agent_content] if args.key?(:agent_content)
@agent_uri = args[:agent_uri] if args.key?(:agent_uri)
end
end
# Instructs the speech recognizer how to process the audio content.
class GoogleCloudDialogflowV2InputAudioConfig
include Google::Apis::Core::Hashable
# Required. Audio encoding of the audio content to process.
# Corresponds to the JSON property `audioEncoding`
# @return [String]
attr_accessor :audio_encoding
# Optional. If `true`, Dialogflow returns SpeechWordInfo in
# StreamingRecognitionResult with information about the recognized speech
# words, e.g. start and end time offsets. If false or unspecified, Speech
# doesn't return any word-level information.
# Corresponds to the JSON property `enableWordInfo`
# @return [Boolean]
attr_accessor :enable_word_info
alias_method :enable_word_info?, :enable_word_info
# Required. The language of the supplied audio. Dialogflow does not do
# translations. See [Language
# Support](https://cloud.google.com/dialogflow/docs/reference/language)
# for a list of the currently supported language codes. Note that queries in
# the same session do not necessarily need to specify the same language.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Optional. Which Speech model to select for the given request. Select the
# model best suited to your domain to get best results. If a model is not
# explicitly specified, then we auto-select a model based on the parameters
# in the InputAudioConfig.
# If enhanced speech model is enabled for the agent and an enhanced
# version of the specified model for the language does not exist, then the
# speech is recognized using the standard version of the specified model.
# Refer to
# [Cloud Speech API
# documentation](https://cloud.google.com/speech-to-text/docs/basics#select-
# model)
# for more details.
# Corresponds to the JSON property `model`
# @return [String]
attr_accessor :model
# Optional. Which variant of the Speech model to use.
# Corresponds to the JSON property `modelVariant`
# @return [String]
attr_accessor :model_variant
# Optional. A list of strings containing words and phrases that the speech
# recognizer should recognize with higher likelihood.
# See [the Cloud Speech
# documentation](https://cloud.google.com/speech-to-text/docs/basics#phrase-
# hints)
# for more details.
# This field is deprecated. Please use [speech_contexts]() instead. If you
# specify both [phrase_hints]() and [speech_contexts](), Dialogflow will
# treat the [phrase_hints]() as a single additional [SpeechContext]().
# Corresponds to the JSON property `phraseHints`
# @return [Array<String>]
attr_accessor :phrase_hints
# Required. Sample rate (in Hertz) of the audio content sent in the query.
# Refer to
# [Cloud Speech API
# documentation](https://cloud.google.com/speech-to-text/docs/basics) for
# more details.
# Corresponds to the JSON property `sampleRateHertz`
# @return [Fixnum]
attr_accessor :sample_rate_hertz
# Optional. If `false` (default), recognition does not cease until the
# client closes the stream.
# If `true`, the recognizer will detect a single spoken utterance in input
# audio. Recognition ceases when it detects the audio's voice has
# stopped or paused. In this case, once a detected intent is received, the
# client should close the stream and start a new request with a new stream as
# needed.
# Note: This setting is relevant only for streaming methods.
# Note: When specified, InputAudioConfig.single_utterance takes precedence
# over StreamingDetectIntentRequest.single_utterance.
# Corresponds to the JSON property `singleUtterance`
# @return [Boolean]
attr_accessor :single_utterance
alias_method :single_utterance?, :single_utterance
# Optional. Context information to assist speech recognition.
# See [the Cloud Speech
# documentation](https://cloud.google.com/speech-to-text/docs/basics#phrase-
# hints)
# for more details.
# Corresponds to the JSON property `speechContexts`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2SpeechContext>]
attr_accessor :speech_contexts
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@audio_encoding = args[:audio_encoding] if args.key?(:audio_encoding)
@enable_word_info = args[:enable_word_info] if args.key?(:enable_word_info)
@language_code = args[:language_code] if args.key?(:language_code)
@model = args[:model] if args.key?(:model)
@model_variant = args[:model_variant] if args.key?(:model_variant)
@phrase_hints = args[:phrase_hints] if args.key?(:phrase_hints)
@sample_rate_hertz = args[:sample_rate_hertz] if args.key?(:sample_rate_hertz)
@single_utterance = args[:single_utterance] if args.key?(:single_utterance)
@speech_contexts = args[:speech_contexts] if args.key?(:speech_contexts)
end
end
# Represents an intent.
# Intents convert a number of user expressions or patterns into an action. An
# action is an extraction of a user command or sentence semantics.
class GoogleCloudDialogflowV2Intent
include Google::Apis::Core::Hashable
# Optional. The name of the action associated with the intent.
# Note: The action name must not contain whitespaces.
# Corresponds to the JSON property `action`
# @return [String]
attr_accessor :action
# Optional. The list of platforms for which the first responses will be
# copied from the messages in PLATFORM_UNSPECIFIED (i.e. default platform).
# Corresponds to the JSON property `defaultResponsePlatforms`
# @return [Array<String>]
attr_accessor :default_response_platforms
# Required. The name of this intent.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# Optional. The collection of event names that trigger the intent.
# If the collection of input contexts is not empty, all of the contexts must
# be present in the active user session for an event to trigger this intent.
# Corresponds to the JSON property `events`
# @return [Array<String>]
attr_accessor :events
# Read-only. Information about all followup intents that have this intent as
# a direct or indirect parent. We populate this field only in the output.
# Corresponds to the JSON property `followupIntentInfo`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentFollowupIntentInfo>]
attr_accessor :followup_intent_info
# Optional. The list of context names required for this intent to be
# triggered.
# Format: `projects/<Project ID>/agent/sessions/-/contexts/<Context ID>`.
# Corresponds to the JSON property `inputContextNames`
# @return [Array<String>]
attr_accessor :input_context_names
# Optional. Indicates whether this is a fallback intent.
# Corresponds to the JSON property `isFallback`
# @return [Boolean]
attr_accessor :is_fallback
alias_method :is_fallback?, :is_fallback
# Optional. The collection of rich messages corresponding to the
# `Response` field in the Dialogflow console.
# Corresponds to the JSON property `messages`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessage>]
attr_accessor :messages
# Optional. Indicates whether Machine Learning is disabled for the intent.
# Note: If `ml_disabled` setting is set to true, then this intent is not
# taken into account during inference in `ML ONLY` match mode. Also,
# auto-markup in the UI is turned off.
# Corresponds to the JSON property `mlDisabled`
# @return [Boolean]
attr_accessor :ml_disabled
alias_method :ml_disabled?, :ml_disabled
# The unique identifier of this intent.
# Required for Intents.UpdateIntent and Intents.BatchUpdateIntents
# methods.
# Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Optional. The collection of contexts that are activated when the intent
# is matched. Context messages in this collection should not set the
# parameters field. Setting the `lifespan_count` to 0 will reset the context
# when the intent is matched.
# Format: `projects/<Project ID>/agent/sessions/-/contexts/<Context ID>`.
# Corresponds to the JSON property `outputContexts`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Context>]
attr_accessor :output_contexts
# Optional. The collection of parameters associated with the intent.
# Corresponds to the JSON property `parameters`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentParameter>]
attr_accessor :parameters
# Read-only after creation. The unique identifier of the parent intent in the
# chain of followup intents. You can set this field when creating an intent,
# for example with CreateIntent or
# BatchUpdateIntents, in order to make this
# intent a followup intent.
# It identifies the parent followup intent.
# Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
# Corresponds to the JSON property `parentFollowupIntentName`
# @return [String]
attr_accessor :parent_followup_intent_name
# Optional. The priority of this intent. Higher numbers represent higher
# priorities.
# - If the supplied value is unspecified or 0, the service
# translates the value to 500,000, which corresponds to the
# `Normal` priority in the console.
# - If the supplied value is negative, the intent is ignored
# in runtime detect intent requests.
# Corresponds to the JSON property `priority`
# @return [Fixnum]
attr_accessor :priority
# Optional. Indicates whether to delete all contexts in the current
# session when this intent is matched.
# Corresponds to the JSON property `resetContexts`
# @return [Boolean]
attr_accessor :reset_contexts
alias_method :reset_contexts?, :reset_contexts
# Read-only. The unique identifier of the root intent in the chain of
# followup intents. It identifies the correct followup intents chain for
# this intent. We populate this field only in the output.
# Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
# Corresponds to the JSON property `rootFollowupIntentName`
# @return [String]
attr_accessor :root_followup_intent_name
# Optional. The collection of examples that the agent is
# trained on.
# Corresponds to the JSON property `trainingPhrases`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentTrainingPhrase>]
attr_accessor :training_phrases
# Optional. Indicates whether webhooks are enabled for the intent.
# Corresponds to the JSON property `webhookState`
# @return [String]
attr_accessor :webhook_state
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action = args[:action] if args.key?(:action)
@default_response_platforms = args[:default_response_platforms] if args.key?(:default_response_platforms)
@display_name = args[:display_name] if args.key?(:display_name)
@events = args[:events] if args.key?(:events)
@followup_intent_info = args[:followup_intent_info] if args.key?(:followup_intent_info)
@input_context_names = args[:input_context_names] if args.key?(:input_context_names)
@is_fallback = args[:is_fallback] if args.key?(:is_fallback)
@messages = args[:messages] if args.key?(:messages)
@ml_disabled = args[:ml_disabled] if args.key?(:ml_disabled)
@name = args[:name] if args.key?(:name)
@output_contexts = args[:output_contexts] if args.key?(:output_contexts)
@parameters = args[:parameters] if args.key?(:parameters)
@parent_followup_intent_name = args[:parent_followup_intent_name] if args.key?(:parent_followup_intent_name)
@priority = args[:priority] if args.key?(:priority)
@reset_contexts = args[:reset_contexts] if args.key?(:reset_contexts)
@root_followup_intent_name = args[:root_followup_intent_name] if args.key?(:root_followup_intent_name)
@training_phrases = args[:training_phrases] if args.key?(:training_phrases)
@webhook_state = args[:webhook_state] if args.key?(:webhook_state)
end
end
# This message is a wrapper around a collection of intents.
class GoogleCloudDialogflowV2IntentBatch
include Google::Apis::Core::Hashable
# A collection of intents.
# Corresponds to the JSON property `intents`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Intent>]
attr_accessor :intents
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@intents = args[:intents] if args.key?(:intents)
end
end
# Represents a single followup intent in the chain.
class GoogleCloudDialogflowV2IntentFollowupIntentInfo
include Google::Apis::Core::Hashable
# The unique identifier of the followup intent.
# Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
# Corresponds to the JSON property `followupIntentName`
# @return [String]
attr_accessor :followup_intent_name
# The unique identifier of the followup intent's parent.
# Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
# Corresponds to the JSON property `parentFollowupIntentName`
# @return [String]
attr_accessor :parent_followup_intent_name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@followup_intent_name = args[:followup_intent_name] if args.key?(:followup_intent_name)
@parent_followup_intent_name = args[:parent_followup_intent_name] if args.key?(:parent_followup_intent_name)
end
end
# Corresponds to the `Response` field in the Dialogflow console.
class GoogleCloudDialogflowV2IntentMessage
include Google::Apis::Core::Hashable
# The basic card message. Useful for displaying information.
# Corresponds to the JSON property `basicCard`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageBasicCard]
attr_accessor :basic_card
# Browse Carousel Card for Actions on Google.
# https://developers.google.com/actions/assistant/responses#browsing_carousel
# Corresponds to the JSON property `browseCarouselCard`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageBrowseCarouselCard]
attr_accessor :browse_carousel_card
# The card response message.
# Corresponds to the JSON property `card`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageCard]
attr_accessor :card
# The card for presenting a carousel of options to select from.
# Corresponds to the JSON property `carouselSelect`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageCarouselSelect]
attr_accessor :carousel_select
# The image response message.
# Corresponds to the JSON property `image`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageImage]
attr_accessor :image
# The suggestion chip message that allows the user to jump out to the app
# or website associated with this agent.
# Corresponds to the JSON property `linkOutSuggestion`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageLinkOutSuggestion]
attr_accessor :link_out_suggestion
# The card for presenting a list of options to select from.
# Corresponds to the JSON property `listSelect`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageListSelect]
attr_accessor :list_select
# The media content card for Actions on Google.
# Corresponds to the JSON property `mediaContent`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageMediaContent]
attr_accessor :media_content
# Returns a response containing a custom, platform-specific payload.
# See the Intent.Message.Platform type for a description of the
# structure that may be required for your platform.
# Corresponds to the JSON property `payload`
# @return [Hash<String,Object>]
attr_accessor :payload
# Optional. The platform that this message is intended for.
# Corresponds to the JSON property `platform`
# @return [String]
attr_accessor :platform
# The quick replies response message.
# Corresponds to the JSON property `quickReplies`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageQuickReplies]
attr_accessor :quick_replies
# The collection of simple response candidates.
# This message in `QueryResult.fulfillment_messages` and
# `WebhookResponse.fulfillment_messages` should contain only one
# `SimpleResponse`.
# Corresponds to the JSON property `simpleResponses`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageSimpleResponses]
attr_accessor :simple_responses
# The collection of suggestions.
# Corresponds to the JSON property `suggestions`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageSuggestions]
attr_accessor :suggestions
# Table card for Actions on Google.
# Corresponds to the JSON property `tableCard`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageTableCard]
attr_accessor :table_card
# The text response message.
# Corresponds to the JSON property `text`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageText]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@basic_card = args[:basic_card] if args.key?(:basic_card)
@browse_carousel_card = args[:browse_carousel_card] if args.key?(:browse_carousel_card)
@card = args[:card] if args.key?(:card)
@carousel_select = args[:carousel_select] if args.key?(:carousel_select)
@image = args[:image] if args.key?(:image)
@link_out_suggestion = args[:link_out_suggestion] if args.key?(:link_out_suggestion)
@list_select = args[:list_select] if args.key?(:list_select)
@media_content = args[:media_content] if args.key?(:media_content)
@payload = args[:payload] if args.key?(:payload)
@platform = args[:platform] if args.key?(:platform)
@quick_replies = args[:quick_replies] if args.key?(:quick_replies)
@simple_responses = args[:simple_responses] if args.key?(:simple_responses)
@suggestions = args[:suggestions] if args.key?(:suggestions)
@table_card = args[:table_card] if args.key?(:table_card)
@text = args[:text] if args.key?(:text)
end
end
# The basic card message. Useful for displaying information.
class GoogleCloudDialogflowV2IntentMessageBasicCard
include Google::Apis::Core::Hashable
# Optional. The collection of card buttons.
# Corresponds to the JSON property `buttons`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageBasicCardButton>]
attr_accessor :buttons
# Required, unless image is present. The body text of the card.
# Corresponds to the JSON property `formattedText`
# @return [String]
attr_accessor :formatted_text
# The image response message.
# Corresponds to the JSON property `image`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageImage]
attr_accessor :image
# Optional. The subtitle of the card.
# Corresponds to the JSON property `subtitle`
# @return [String]
attr_accessor :subtitle
# Optional. The title of the card.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@buttons = args[:buttons] if args.key?(:buttons)
@formatted_text = args[:formatted_text] if args.key?(:formatted_text)
@image = args[:image] if args.key?(:image)
@subtitle = args[:subtitle] if args.key?(:subtitle)
@title = args[:title] if args.key?(:title)
end
end
# The button object that appears at the bottom of a card.
class GoogleCloudDialogflowV2IntentMessageBasicCardButton
include Google::Apis::Core::Hashable
# Opens the given URI.
# Corresponds to the JSON property `openUriAction`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageBasicCardButtonOpenUriAction]
attr_accessor :open_uri_action
# Required. The title of the button.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@open_uri_action = args[:open_uri_action] if args.key?(:open_uri_action)
@title = args[:title] if args.key?(:title)
end
end
# Opens the given URI.
class GoogleCloudDialogflowV2IntentMessageBasicCardButtonOpenUriAction
include Google::Apis::Core::Hashable
# Required. The HTTP or HTTPS scheme URI.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# Browse Carousel Card for Actions on Google.
# https://developers.google.com/actions/assistant/responses#browsing_carousel
class GoogleCloudDialogflowV2IntentMessageBrowseCarouselCard
include Google::Apis::Core::Hashable
# Optional. Settings for displaying the image. Applies to every image in
# items.
# Corresponds to the JSON property `imageDisplayOptions`
# @return [String]
attr_accessor :image_display_options
# Required. List of items in the Browse Carousel Card. Minimum of two
# items, maximum of ten.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageBrowseCarouselCardBrowseCarouselCardItem>]
attr_accessor :items
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@image_display_options = args[:image_display_options] if args.key?(:image_display_options)
@items = args[:items] if args.key?(:items)
end
end
# Browsing carousel tile
class GoogleCloudDialogflowV2IntentMessageBrowseCarouselCardBrowseCarouselCardItem
include Google::Apis::Core::Hashable
# Optional. Description of the carousel item. Maximum of four lines of
# text.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Optional. Text that appears at the bottom of the Browse Carousel
# Card. Maximum of one line of text.
# Corresponds to the JSON property `footer`
# @return [String]
attr_accessor :footer
# The image response message.
# Corresponds to the JSON property `image`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageImage]
attr_accessor :image
# Actions on Google action to open a given url.
# Corresponds to the JSON property `openUriAction`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenUrlAction]
attr_accessor :open_uri_action
# Required. Title of the carousel item. Maximum of two lines of text.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@footer = args[:footer] if args.key?(:footer)
@image = args[:image] if args.key?(:image)
@open_uri_action = args[:open_uri_action] if args.key?(:open_uri_action)
@title = args[:title] if args.key?(:title)
end
end
# Actions on Google action to open a given url.
class GoogleCloudDialogflowV2IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenUrlAction
include Google::Apis::Core::Hashable
# Required. URL
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
# Optional. Specifies the type of viewer that is used when opening
# the URL. Defaults to opening via web browser.
# Corresponds to the JSON property `urlTypeHint`
# @return [String]
attr_accessor :url_type_hint
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@url = args[:url] if args.key?(:url)
@url_type_hint = args[:url_type_hint] if args.key?(:url_type_hint)
end
end
# The card response message.
class GoogleCloudDialogflowV2IntentMessageCard
include Google::Apis::Core::Hashable
# Optional. The collection of card buttons.
# Corresponds to the JSON property `buttons`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageCardButton>]
attr_accessor :buttons
# Optional. The public URI to an image file for the card.
# Corresponds to the JSON property `imageUri`
# @return [String]
attr_accessor :image_uri
# Optional. The subtitle of the card.
# Corresponds to the JSON property `subtitle`
# @return [String]
attr_accessor :subtitle
# Optional. The title of the card.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@buttons = args[:buttons] if args.key?(:buttons)
@image_uri = args[:image_uri] if args.key?(:image_uri)
@subtitle = args[:subtitle] if args.key?(:subtitle)
@title = args[:title] if args.key?(:title)
end
end
# Contains information about a button.
class GoogleCloudDialogflowV2IntentMessageCardButton
include Google::Apis::Core::Hashable
# Optional. The text to send back to the Dialogflow API or a URI to
# open.
# Corresponds to the JSON property `postback`
# @return [String]
attr_accessor :postback
# Optional. The text to show on the button.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@postback = args[:postback] if args.key?(:postback)
@text = args[:text] if args.key?(:text)
end
end
# The card for presenting a carousel of options to select from.
class GoogleCloudDialogflowV2IntentMessageCarouselSelect
include Google::Apis::Core::Hashable
# Required. Carousel items.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageCarouselSelectItem>]
attr_accessor :items
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@items = args[:items] if args.key?(:items)
end
end
# An item in the carousel.
class GoogleCloudDialogflowV2IntentMessageCarouselSelectItem
include Google::Apis::Core::Hashable
# Optional. The body text of the card.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The image response message.
# Corresponds to the JSON property `image`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageImage]
attr_accessor :image
# Additional info about the select item for when it is triggered in a
# dialog.
# Corresponds to the JSON property `info`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageSelectItemInfo]
attr_accessor :info
# Required. Title of the carousel item.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@image = args[:image] if args.key?(:image)
@info = args[:info] if args.key?(:info)
@title = args[:title] if args.key?(:title)
end
end
# Column properties for TableCard.
class GoogleCloudDialogflowV2IntentMessageColumnProperties
include Google::Apis::Core::Hashable
# Required. Column heading.
# Corresponds to the JSON property `header`
# @return [String]
attr_accessor :header
# Optional. Defines text alignment for all cells in this column.
# Corresponds to the JSON property `horizontalAlignment`
# @return [String]
attr_accessor :horizontal_alignment
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@header = args[:header] if args.key?(:header)
@horizontal_alignment = args[:horizontal_alignment] if args.key?(:horizontal_alignment)
end
end
# The image response message.
class GoogleCloudDialogflowV2IntentMessageImage
include Google::Apis::Core::Hashable
# Optional. A text description of the image to be used for accessibility,
# e.g., screen readers.
# Corresponds to the JSON property `accessibilityText`
# @return [String]
attr_accessor :accessibility_text
# Optional. The public URI to an image file.
# Corresponds to the JSON property `imageUri`
# @return [String]
attr_accessor :image_uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@accessibility_text = args[:accessibility_text] if args.key?(:accessibility_text)
@image_uri = args[:image_uri] if args.key?(:image_uri)
end
end
# The suggestion chip message that allows the user to jump out to the app
# or website associated with this agent.
class GoogleCloudDialogflowV2IntentMessageLinkOutSuggestion
include Google::Apis::Core::Hashable
# Required. The name of the app or site this chip is linking to.
# Corresponds to the JSON property `destinationName`
# @return [String]
attr_accessor :destination_name
# Required. The URI of the app or site to open when the user taps the
# suggestion chip.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@destination_name = args[:destination_name] if args.key?(:destination_name)
@uri = args[:uri] if args.key?(:uri)
end
end
# The card for presenting a list of options to select from.
class GoogleCloudDialogflowV2IntentMessageListSelect
include Google::Apis::Core::Hashable
# Required. List items.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageListSelectItem>]
attr_accessor :items
# Optional. Subtitle of the list.
# Corresponds to the JSON property `subtitle`
# @return [String]
attr_accessor :subtitle
# Optional. The overall title of the list.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@items = args[:items] if args.key?(:items)
@subtitle = args[:subtitle] if args.key?(:subtitle)
@title = args[:title] if args.key?(:title)
end
end
# An item in the list.
class GoogleCloudDialogflowV2IntentMessageListSelectItem
include Google::Apis::Core::Hashable
# Optional. The main text describing the item.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The image response message.
# Corresponds to the JSON property `image`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageImage]
attr_accessor :image
# Additional info about the select item for when it is triggered in a
# dialog.
# Corresponds to the JSON property `info`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageSelectItemInfo]
attr_accessor :info
# Required. The title of the list item.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@image = args[:image] if args.key?(:image)
@info = args[:info] if args.key?(:info)
@title = args[:title] if args.key?(:title)
end
end
# The media content card for Actions on Google.
class GoogleCloudDialogflowV2IntentMessageMediaContent
include Google::Apis::Core::Hashable
# Required. List of media objects.
# Corresponds to the JSON property `mediaObjects`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageMediaContentResponseMediaObject>]
attr_accessor :media_objects
# Optional. What type of media is the content (ie "audio").
# Corresponds to the JSON property `mediaType`
# @return [String]
attr_accessor :media_type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@media_objects = args[:media_objects] if args.key?(:media_objects)
@media_type = args[:media_type] if args.key?(:media_type)
end
end
# Response media object for media content card.
class GoogleCloudDialogflowV2IntentMessageMediaContentResponseMediaObject
include Google::Apis::Core::Hashable
# Required. Url where the media is stored.
# Corresponds to the JSON property `contentUrl`
# @return [String]
attr_accessor :content_url
# Optional. Description of media card.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The image response message.
# Corresponds to the JSON property `icon`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageImage]
attr_accessor :icon
# The image response message.
# Corresponds to the JSON property `largeImage`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageImage]
attr_accessor :large_image
# Required. Name of media card.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@content_url = args[:content_url] if args.key?(:content_url)
@description = args[:description] if args.key?(:description)
@icon = args[:icon] if args.key?(:icon)
@large_image = args[:large_image] if args.key?(:large_image)
@name = args[:name] if args.key?(:name)
end
end
# The quick replies response message.
class GoogleCloudDialogflowV2IntentMessageQuickReplies
include Google::Apis::Core::Hashable
# Optional. The collection of quick replies.
# Corresponds to the JSON property `quickReplies`
# @return [Array<String>]
attr_accessor :quick_replies
# Optional. The title of the collection of quick replies.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@quick_replies = args[:quick_replies] if args.key?(:quick_replies)
@title = args[:title] if args.key?(:title)
end
end
# Additional info about the select item for when it is triggered in a
# dialog.
class GoogleCloudDialogflowV2IntentMessageSelectItemInfo
include Google::Apis::Core::Hashable
# Required. A unique key that will be sent back to the agent if this
# response is given.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
# Optional. A list of synonyms that can also be used to trigger this
# item in dialog.
# Corresponds to the JSON property `synonyms`
# @return [Array<String>]
attr_accessor :synonyms
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@key = args[:key] if args.key?(:key)
@synonyms = args[:synonyms] if args.key?(:synonyms)
end
end
# The simple response message containing speech or text.
class GoogleCloudDialogflowV2IntentMessageSimpleResponse
include Google::Apis::Core::Hashable
# Optional. The text to display.
# Corresponds to the JSON property `displayText`
# @return [String]
attr_accessor :display_text
# One of text_to_speech or ssml must be provided. Structured spoken
# response to the user in the SSML format. Mutually exclusive with
# text_to_speech.
# Corresponds to the JSON property `ssml`
# @return [String]
attr_accessor :ssml
# One of text_to_speech or ssml must be provided. The plain text of the
# speech output. Mutually exclusive with ssml.
# Corresponds to the JSON property `textToSpeech`
# @return [String]
attr_accessor :text_to_speech
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@display_text = args[:display_text] if args.key?(:display_text)
@ssml = args[:ssml] if args.key?(:ssml)
@text_to_speech = args[:text_to_speech] if args.key?(:text_to_speech)
end
end
# The collection of simple response candidates.
# This message in `QueryResult.fulfillment_messages` and
# `WebhookResponse.fulfillment_messages` should contain only one
# `SimpleResponse`.
class GoogleCloudDialogflowV2IntentMessageSimpleResponses
include Google::Apis::Core::Hashable
# Required. The list of simple responses.
# Corresponds to the JSON property `simpleResponses`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageSimpleResponse>]
attr_accessor :simple_responses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@simple_responses = args[:simple_responses] if args.key?(:simple_responses)
end
end
# The suggestion chip message that the user can tap to quickly post a reply
# to the conversation.
class GoogleCloudDialogflowV2IntentMessageSuggestion
include Google::Apis::Core::Hashable
# Required. The text shown the in the suggestion chip.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@title = args[:title] if args.key?(:title)
end
end
# The collection of suggestions.
class GoogleCloudDialogflowV2IntentMessageSuggestions
include Google::Apis::Core::Hashable
# Required. The list of suggested replies.
# Corresponds to the JSON property `suggestions`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageSuggestion>]
attr_accessor :suggestions
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@suggestions = args[:suggestions] if args.key?(:suggestions)
end
end
# Table card for Actions on Google.
class GoogleCloudDialogflowV2IntentMessageTableCard
include Google::Apis::Core::Hashable
# Optional. List of buttons for the card.
# Corresponds to the JSON property `buttons`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageBasicCardButton>]
attr_accessor :buttons
# Optional. Display properties for the columns in this table.
# Corresponds to the JSON property `columnProperties`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageColumnProperties>]
attr_accessor :column_properties
# The image response message.
# Corresponds to the JSON property `image`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageImage]
attr_accessor :image
# Optional. Rows in this table of data.
# Corresponds to the JSON property `rows`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageTableCardRow>]
attr_accessor :rows
# Optional. Subtitle to the title.
# Corresponds to the JSON property `subtitle`
# @return [String]
attr_accessor :subtitle
# Required. Title of the card.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@buttons = args[:buttons] if args.key?(:buttons)
@column_properties = args[:column_properties] if args.key?(:column_properties)
@image = args[:image] if args.key?(:image)
@rows = args[:rows] if args.key?(:rows)
@subtitle = args[:subtitle] if args.key?(:subtitle)
@title = args[:title] if args.key?(:title)
end
end
# Cell of TableCardRow.
class GoogleCloudDialogflowV2IntentMessageTableCardCell
include Google::Apis::Core::Hashable
# Required. Text in this cell.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@text = args[:text] if args.key?(:text)
end
end
# Row of TableCard.
class GoogleCloudDialogflowV2IntentMessageTableCardRow
include Google::Apis::Core::Hashable
# Optional. List of cells that make up this row.
# Corresponds to the JSON property `cells`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessageTableCardCell>]
attr_accessor :cells
# Optional. Whether to add a visual divider after this row.
# Corresponds to the JSON property `dividerAfter`
# @return [Boolean]
attr_accessor :divider_after
alias_method :divider_after?, :divider_after
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@cells = args[:cells] if args.key?(:cells)
@divider_after = args[:divider_after] if args.key?(:divider_after)
end
end
# The text response message.
class GoogleCloudDialogflowV2IntentMessageText
include Google::Apis::Core::Hashable
# Optional. The collection of the agent's responses.
# Corresponds to the JSON property `text`
# @return [Array<String>]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@text = args[:text] if args.key?(:text)
end
end
# Represents intent parameters.
class GoogleCloudDialogflowV2IntentParameter
include Google::Apis::Core::Hashable
# Optional. The default value to use when the `value` yields an empty
# result.
# Default values can be extracted from contexts by using the following
# syntax: `#context_name.parameter_name`.
# Corresponds to the JSON property `defaultValue`
# @return [String]
attr_accessor :default_value
# Required. The name of the parameter.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# Optional. The name of the entity type, prefixed with `@`, that
# describes values of the parameter. If the parameter is
# required, this must be provided.
# Corresponds to the JSON property `entityTypeDisplayName`
# @return [String]
attr_accessor :entity_type_display_name
# Optional. Indicates whether the parameter represents a list of values.
# Corresponds to the JSON property `isList`
# @return [Boolean]
attr_accessor :is_list
alias_method :is_list?, :is_list
# Optional. Indicates whether the parameter is required. That is,
# whether the intent cannot be completed without collecting the parameter
# value.
# Corresponds to the JSON property `mandatory`
# @return [Boolean]
attr_accessor :mandatory
alias_method :mandatory?, :mandatory
# The unique identifier of this parameter.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Optional. The collection of prompts that the agent can present to the
# user in order to collect a value for the parameter.
# Corresponds to the JSON property `prompts`
# @return [Array<String>]
attr_accessor :prompts
# Optional. The definition of the parameter value. It can be:
# - a constant string,
# - a parameter value defined as `$parameter_name`,
# - an original parameter value defined as `$parameter_name.original`,
# - a parameter value from some context defined as
# `#context_name.parameter_name`.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@default_value = args[:default_value] if args.key?(:default_value)
@display_name = args[:display_name] if args.key?(:display_name)
@entity_type_display_name = args[:entity_type_display_name] if args.key?(:entity_type_display_name)
@is_list = args[:is_list] if args.key?(:is_list)
@mandatory = args[:mandatory] if args.key?(:mandatory)
@name = args[:name] if args.key?(:name)
@prompts = args[:prompts] if args.key?(:prompts)
@value = args[:value] if args.key?(:value)
end
end
# Represents an example that the agent is trained on.
class GoogleCloudDialogflowV2IntentTrainingPhrase
include Google::Apis::Core::Hashable
# Output only. The unique identifier of this training phrase.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Required. The ordered list of training phrase parts.
# The parts are concatenated in order to form the training phrase.
# Note: The API does not automatically annotate training phrases like the
# Dialogflow Console does.
# Note: Do not forget to include whitespace at part boundaries,
# so the training phrase is well formatted when the parts are concatenated.
# If the training phrase does not need to be annotated with parameters,
# you just need a single part with only the Part.text field set.
# If you want to annotate the training phrase, you must create multiple
# parts, where the fields of each part are populated in one of two ways:
# - `Part.text` is set to a part of the phrase that has no parameters.
# - `Part.text` is set to a part of the phrase that you want to annotate,
# and the `entity_type`, `alias`, and `user_defined` fields are all
# set.
# Corresponds to the JSON property `parts`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentTrainingPhrasePart>]
attr_accessor :parts
# Optional. Indicates how many times this example was added to
# the intent. Each time a developer adds an existing sample by editing an
# intent or training, this counter is increased.
# Corresponds to the JSON property `timesAddedCount`
# @return [Fixnum]
attr_accessor :times_added_count
# Required. The type of the training phrase.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
@parts = args[:parts] if args.key?(:parts)
@times_added_count = args[:times_added_count] if args.key?(:times_added_count)
@type = args[:type] if args.key?(:type)
end
end
# Represents a part of a training phrase.
class GoogleCloudDialogflowV2IntentTrainingPhrasePart
include Google::Apis::Core::Hashable
# Optional. The parameter name for the value extracted from the
# annotated part of the example.
# This field is required for annotated parts of the training phrase.
# Corresponds to the JSON property `alias`
# @return [String]
attr_accessor :alias
# Optional. The entity type name prefixed with `@`.
# This field is required for annotated parts of the training phrase.
# Corresponds to the JSON property `entityType`
# @return [String]
attr_accessor :entity_type
# Required. The text for this part.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
# Optional. Indicates whether the text was manually annotated.
# This field is set to true when the Dialogflow Console is used to
# manually annotate the part. When creating an annotated part with the
# API, you must set this to true.
# Corresponds to the JSON property `userDefined`
# @return [Boolean]
attr_accessor :user_defined
alias_method :user_defined?, :user_defined
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@alias = args[:alias] if args.key?(:alias)
@entity_type = args[:entity_type] if args.key?(:entity_type)
@text = args[:text] if args.key?(:text)
@user_defined = args[:user_defined] if args.key?(:user_defined)
end
end
# The response message for Contexts.ListContexts.
class GoogleCloudDialogflowV2ListContextsResponse
include Google::Apis::Core::Hashable
# The list of contexts. There will be a maximum number of items
# returned based on the page_size field in the request.
# Corresponds to the JSON property `contexts`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Context>]
attr_accessor :contexts
# Token to retrieve the next page of results, or empty if there are no
# more results in the list.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@contexts = args[:contexts] if args.key?(:contexts)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
end
end
# The response message for EntityTypes.ListEntityTypes.
class GoogleCloudDialogflowV2ListEntityTypesResponse
include Google::Apis::Core::Hashable
# The list of agent entity types. There will be a maximum number of items
# returned based on the page_size field in the request.
# Corresponds to the JSON property `entityTypes`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2EntityType>]
attr_accessor :entity_types
# Token to retrieve the next page of results, or empty if there are no
# more results in the list.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entity_types = args[:entity_types] if args.key?(:entity_types)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
end
end
# The response message for Intents.ListIntents.
class GoogleCloudDialogflowV2ListIntentsResponse
include Google::Apis::Core::Hashable
# The list of agent intents. There will be a maximum number of items
# returned based on the page_size field in the request.
# Corresponds to the JSON property `intents`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Intent>]
attr_accessor :intents
# Token to retrieve the next page of results, or empty if there are no
# more results in the list.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@intents = args[:intents] if args.key?(:intents)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
end
end
# The response message for SessionEntityTypes.ListSessionEntityTypes.
class GoogleCloudDialogflowV2ListSessionEntityTypesResponse
include Google::Apis::Core::Hashable
# Token to retrieve the next page of results, or empty if there are no
# more results in the list.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
# The list of session entity types. There will be a maximum number of items
# returned based on the page_size field in the request.
# Corresponds to the JSON property `sessionEntityTypes`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2SessionEntityType>]
attr_accessor :session_entity_types
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
@session_entity_types = args[:session_entity_types] if args.key?(:session_entity_types)
end
end
# Represents a message posted into a conversation.
class GoogleCloudDialogflowV2Message
include Google::Apis::Core::Hashable
# Required. The message content.
# Corresponds to the JSON property `content`
# @return [String]
attr_accessor :content
# Output only. The time when the message was created.
# Corresponds to the JSON property `createTime`
# @return [String]
attr_accessor :create_time
# Optional. The message language.
# This should be a [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt)
# language tag. Example: "en-US".
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Represents the result of annotation for the message.
# Corresponds to the JSON property `messageAnnotation`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2MessageAnnotation]
attr_accessor :message_annotation
# The unique identifier of the message.
# Format: `projects/<Project ID>/conversations/<Conversation
# ID>/messages/<Message ID>`.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Output only. The participant that sends this message.
# Corresponds to the JSON property `participant`
# @return [String]
attr_accessor :participant
# Output only. The role of the participant.
# Corresponds to the JSON property `participantRole`
# @return [String]
attr_accessor :participant_role
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@content = args[:content] if args.key?(:content)
@create_time = args[:create_time] if args.key?(:create_time)
@language_code = args[:language_code] if args.key?(:language_code)
@message_annotation = args[:message_annotation] if args.key?(:message_annotation)
@name = args[:name] if args.key?(:name)
@participant = args[:participant] if args.key?(:participant)
@participant_role = args[:participant_role] if args.key?(:participant_role)
end
end
# Represents the result of annotation for the message.
class GoogleCloudDialogflowV2MessageAnnotation
include Google::Apis::Core::Hashable
# Indicates whether the text message contains entities.
# Corresponds to the JSON property `containEntities`
# @return [Boolean]
attr_accessor :contain_entities
alias_method :contain_entities?, :contain_entities
# The collection of annotated message parts ordered by their
# position in the message. You can recover the annotated message by
# concatenating [AnnotatedMessagePart.text].
# Corresponds to the JSON property `parts`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2AnnotatedMessagePart>]
attr_accessor :parts
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@contain_entities = args[:contain_entities] if args.key?(:contain_entities)
@parts = args[:parts] if args.key?(:parts)
end
end
# Represents the contents of the original request that was passed to
# the `[Streaming]DetectIntent` call.
class GoogleCloudDialogflowV2OriginalDetectIntentRequest
include Google::Apis::Core::Hashable
# Optional. This field is set to the value of the `QueryParameters.payload`
# field passed in the request. Some integrations that query a Dialogflow
# agent may provide additional information in the payload.
# In particular for the Telephony Gateway this field has the form:
# <pre>`
# "telephony": `
# "caller_id": "+18558363987"
# `
# `</pre>
# Note: The caller ID field (`caller_id`) will be redacted for Standard
# Edition agents and populated with the caller ID in [E.164
# format](https://en.wikipedia.org/wiki/E.164) for Enterprise Edition agents.
# Corresponds to the JSON property `payload`
# @return [Hash<String,Object>]
attr_accessor :payload
# The source of this request, e.g., `google`, `facebook`, `slack`. It is set
# by Dialogflow-owned servers.
# Corresponds to the JSON property `source`
# @return [String]
attr_accessor :source
# Optional. The version of the protocol used for this request.
# This field is AoG-specific.
# Corresponds to the JSON property `version`
# @return [String]
attr_accessor :version
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@payload = args[:payload] if args.key?(:payload)
@source = args[:source] if args.key?(:source)
@version = args[:version] if args.key?(:version)
end
end
# Instructs the speech synthesizer on how to generate the output audio content.
# If this audio config is supplied in a request, it overrides all existing
# text-to-speech settings applied to the agent.
class GoogleCloudDialogflowV2OutputAudioConfig
include Google::Apis::Core::Hashable
# Required. Audio encoding of the synthesized audio content.
# Corresponds to the JSON property `audioEncoding`
# @return [String]
attr_accessor :audio_encoding
# The synthesis sample rate (in hertz) for this audio. If not
# provided, then the synthesizer will use the default sample rate based on
# the audio encoding. If this is different from the voice's natural sample
# rate, then the synthesizer will honor this request by converting to the
# desired sample rate (which might result in worse audio quality).
# Corresponds to the JSON property `sampleRateHertz`
# @return [Fixnum]
attr_accessor :sample_rate_hertz
# Configuration of how speech should be synthesized.
# Corresponds to the JSON property `synthesizeSpeechConfig`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2SynthesizeSpeechConfig]
attr_accessor :synthesize_speech_config
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@audio_encoding = args[:audio_encoding] if args.key?(:audio_encoding)
@sample_rate_hertz = args[:sample_rate_hertz] if args.key?(:sample_rate_hertz)
@synthesize_speech_config = args[:synthesize_speech_config] if args.key?(:synthesize_speech_config)
end
end
# Represents the query input. It can contain either:
# 1. An audio config which
# instructs the speech recognizer how to process the speech audio.
# 2. A conversational query in the form of text,.
# 3. An event that specifies which intent to trigger.
class GoogleCloudDialogflowV2QueryInput
include Google::Apis::Core::Hashable
# Instructs the speech recognizer how to process the audio content.
# Corresponds to the JSON property `audioConfig`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2InputAudioConfig]
attr_accessor :audio_config
# Events allow for matching intents by event name instead of the natural
# language input. For instance, input `<event: ` name: "welcome_event",
# parameters: ` name: "Sam" ` `>` can trigger a personalized welcome response.
# The parameter `name` may be used by the agent in the response:
# `"Hello #welcome_event.name! What can I do for you today?"`.
# Corresponds to the JSON property `event`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2EventInput]
attr_accessor :event
# Represents the natural language text to be processed.
# Corresponds to the JSON property `text`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2TextInput]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@audio_config = args[:audio_config] if args.key?(:audio_config)
@event = args[:event] if args.key?(:event)
@text = args[:text] if args.key?(:text)
end
end
# Represents the parameters of the conversational query.
class GoogleCloudDialogflowV2QueryParameters
include Google::Apis::Core::Hashable
# The collection of contexts to be activated before this query is
# executed.
# Corresponds to the JSON property `contexts`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Context>]
attr_accessor :contexts
# An object representing a latitude/longitude pair. This is expressed as a pair
# of doubles representing degrees latitude and degrees longitude. Unless
# specified otherwise, this must conform to the
# <a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84
# standard</a>. Values must be within normalized ranges.
# Corresponds to the JSON property `geoLocation`
# @return [Google::Apis::DialogflowV2::GoogleTypeLatLng]
attr_accessor :geo_location
# This field can be used to pass custom data into the webhook
# associated with the agent. Arbitrary JSON objects are supported.
# Corresponds to the JSON property `payload`
# @return [Hash<String,Object>]
attr_accessor :payload
# Specifies whether to delete all contexts in the current session
# before the new ones are activated.
# Corresponds to the JSON property `resetContexts`
# @return [Boolean]
attr_accessor :reset_contexts
alias_method :reset_contexts?, :reset_contexts
# Configures the types of sentiment analysis to perform.
# Corresponds to the JSON property `sentimentAnalysisRequestConfig`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2SentimentAnalysisRequestConfig]
attr_accessor :sentiment_analysis_request_config
# Additional session entity types to replace or extend developer
# entity types with. The entity synonyms apply to all languages and persist
# for the session of this query.
# Corresponds to the JSON property `sessionEntityTypes`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2SessionEntityType>]
attr_accessor :session_entity_types
# The time zone of this conversational query from the
# [time zone database](https://www.iana.org/time-zones), e.g.,
# America/New_York, Europe/Paris. If not provided, the time zone specified in
# agent settings is used.
# Corresponds to the JSON property `timeZone`
# @return [String]
attr_accessor :time_zone
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@contexts = args[:contexts] if args.key?(:contexts)
@geo_location = args[:geo_location] if args.key?(:geo_location)
@payload = args[:payload] if args.key?(:payload)
@reset_contexts = args[:reset_contexts] if args.key?(:reset_contexts)
@sentiment_analysis_request_config = args[:sentiment_analysis_request_config] if args.key?(:sentiment_analysis_request_config)
@session_entity_types = args[:session_entity_types] if args.key?(:session_entity_types)
@time_zone = args[:time_zone] if args.key?(:time_zone)
end
end
# Represents the result of conversational query or event processing.
class GoogleCloudDialogflowV2QueryResult
include Google::Apis::Core::Hashable
# The action name from the matched intent.
# Corresponds to the JSON property `action`
# @return [String]
attr_accessor :action
# This field is set to:
# - `false` if the matched intent has required parameters and not all of
# the required parameter values have been collected.
# - `true` if all required parameter values have been collected, or if the
# matched intent doesn't contain any required parameters.
# Corresponds to the JSON property `allRequiredParamsPresent`
# @return [Boolean]
attr_accessor :all_required_params_present
alias_method :all_required_params_present?, :all_required_params_present
# Free-form diagnostic information for the associated detect intent request.
# The fields of this data can change without notice, so you should not write
# code that depends on its structure.
# The data may contain:
# - webhook call latency
# - webhook errors
# Corresponds to the JSON property `diagnosticInfo`
# @return [Hash<String,Object>]
attr_accessor :diagnostic_info
# The collection of rich messages to present to the user.
# Corresponds to the JSON property `fulfillmentMessages`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessage>]
attr_accessor :fulfillment_messages
# The text to be pronounced to the user or shown on the screen.
# Note: This is a legacy field, `fulfillment_messages` should be preferred.
# Corresponds to the JSON property `fulfillmentText`
# @return [String]
attr_accessor :fulfillment_text
# Represents an intent.
# Intents convert a number of user expressions or patterns into an action. An
# action is an extraction of a user command or sentence semantics.
# Corresponds to the JSON property `intent`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Intent]
attr_accessor :intent
# The intent detection confidence. Values range from 0.0
# (completely uncertain) to 1.0 (completely certain).
# This value is for informational purpose only and is only used to
# help match the best intent within the classification threshold.
# This value may change for the same end-user expression at any time due to a
# model retraining or change in implementation.
# If there are `multiple knowledge_answers` messages, this value is set to
# the greatest `knowledgeAnswers.match_confidence` value in the list.
# Corresponds to the JSON property `intentDetectionConfidence`
# @return [Float]
attr_accessor :intent_detection_confidence
# The language that was triggered during intent detection.
# See [Language
# Support](https://cloud.google.com/dialogflow/docs/reference/language)
# for a list of the currently supported language codes.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# The collection of output contexts. If applicable,
# `output_contexts.parameters` contains entries with name
# `<parameter name>.original` containing the original parameter values
# before the query.
# Corresponds to the JSON property `outputContexts`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Context>]
attr_accessor :output_contexts
# The collection of extracted parameters.
# Corresponds to the JSON property `parameters`
# @return [Hash<String,Object>]
attr_accessor :parameters
# The original conversational query text:
# - If natural language text was provided as input, `query_text` contains
# a copy of the input.
# - If natural language speech audio was provided as input, `query_text`
# contains the speech recognition result. If speech recognizer produced
# multiple alternatives, a particular one is picked.
# - If automatic spell correction is enabled, `query_text` will contain the
# corrected user input.
# Corresponds to the JSON property `queryText`
# @return [String]
attr_accessor :query_text
# The result of sentiment analysis as configured by
# `sentiment_analysis_request_config`.
# Corresponds to the JSON property `sentimentAnalysisResult`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2SentimentAnalysisResult]
attr_accessor :sentiment_analysis_result
# The Speech recognition confidence between 0.0 and 1.0. A higher number
# indicates an estimated greater likelihood that the recognized words are
# correct. The default of 0.0 is a sentinel value indicating that confidence
# was not set.
# This field is not guaranteed to be accurate or set. In particular this
# field isn't set for StreamingDetectIntent since the streaming endpoint has
# separate confidence estimates per portion of the audio in
# StreamingRecognitionResult.
# Corresponds to the JSON property `speechRecognitionConfidence`
# @return [Float]
attr_accessor :speech_recognition_confidence
# If the query was fulfilled by a webhook call, this field is set to the
# value of the `payload` field returned in the webhook response.
# Corresponds to the JSON property `webhookPayload`
# @return [Hash<String,Object>]
attr_accessor :webhook_payload
# If the query was fulfilled by a webhook call, this field is set to the
# value of the `source` field returned in the webhook response.
# Corresponds to the JSON property `webhookSource`
# @return [String]
attr_accessor :webhook_source
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action = args[:action] if args.key?(:action)
@all_required_params_present = args[:all_required_params_present] if args.key?(:all_required_params_present)
@diagnostic_info = args[:diagnostic_info] if args.key?(:diagnostic_info)
@fulfillment_messages = args[:fulfillment_messages] if args.key?(:fulfillment_messages)
@fulfillment_text = args[:fulfillment_text] if args.key?(:fulfillment_text)
@intent = args[:intent] if args.key?(:intent)
@intent_detection_confidence = args[:intent_detection_confidence] if args.key?(:intent_detection_confidence)
@language_code = args[:language_code] if args.key?(:language_code)
@output_contexts = args[:output_contexts] if args.key?(:output_contexts)
@parameters = args[:parameters] if args.key?(:parameters)
@query_text = args[:query_text] if args.key?(:query_text)
@sentiment_analysis_result = args[:sentiment_analysis_result] if args.key?(:sentiment_analysis_result)
@speech_recognition_confidence = args[:speech_recognition_confidence] if args.key?(:speech_recognition_confidence)
@webhook_payload = args[:webhook_payload] if args.key?(:webhook_payload)
@webhook_source = args[:webhook_source] if args.key?(:webhook_source)
end
end
# The request message for Agents.RestoreAgent.
class GoogleCloudDialogflowV2RestoreAgentRequest
include Google::Apis::Core::Hashable
# Zip compressed raw byte content for agent.
# Corresponds to the JSON property `agentContent`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :agent_content
# The URI to a Google Cloud Storage file containing the agent to restore.
# Note: The URI must start with "gs://".
# Corresponds to the JSON property `agentUri`
# @return [String]
attr_accessor :agent_uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@agent_content = args[:agent_content] if args.key?(:agent_content)
@agent_uri = args[:agent_uri] if args.key?(:agent_uri)
end
end
# The response message for Agents.SearchAgents.
class GoogleCloudDialogflowV2SearchAgentsResponse
include Google::Apis::Core::Hashable
# The list of agents. There will be a maximum number of items returned based
# on the page_size field in the request.
# Corresponds to the JSON property `agents`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Agent>]
attr_accessor :agents
# Token to retrieve the next page of results, or empty if there are no
# more results in the list.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@agents = args[:agents] if args.key?(:agents)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
end
end
# The sentiment, such as positive/negative feeling or association, for a unit
# of analysis, such as the query text.
class GoogleCloudDialogflowV2Sentiment
include Google::Apis::Core::Hashable
# A non-negative number in the [0, +inf) range, which represents the absolute
# magnitude of sentiment, regardless of score (positive or negative).
# Corresponds to the JSON property `magnitude`
# @return [Float]
attr_accessor :magnitude
# Sentiment score between -1.0 (negative sentiment) and 1.0 (positive
# sentiment).
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@magnitude = args[:magnitude] if args.key?(:magnitude)
@score = args[:score] if args.key?(:score)
end
end
# Configures the types of sentiment analysis to perform.
class GoogleCloudDialogflowV2SentimentAnalysisRequestConfig
include Google::Apis::Core::Hashable
# Instructs the service to perform sentiment analysis on
# `query_text`. If not provided, sentiment analysis is not performed on
# `query_text`.
# Corresponds to the JSON property `analyzeQueryTextSentiment`
# @return [Boolean]
attr_accessor :analyze_query_text_sentiment
alias_method :analyze_query_text_sentiment?, :analyze_query_text_sentiment
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@analyze_query_text_sentiment = args[:analyze_query_text_sentiment] if args.key?(:analyze_query_text_sentiment)
end
end
# The result of sentiment analysis as configured by
# `sentiment_analysis_request_config`.
class GoogleCloudDialogflowV2SentimentAnalysisResult
include Google::Apis::Core::Hashable
# The sentiment, such as positive/negative feeling or association, for a unit
# of analysis, such as the query text.
# Corresponds to the JSON property `queryTextSentiment`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Sentiment]
attr_accessor :query_text_sentiment
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@query_text_sentiment = args[:query_text_sentiment] if args.key?(:query_text_sentiment)
end
end
# Represents a session entity type.
# Extends or replaces a custom entity type at the user session level (we
# refer to the entity types defined at the agent level as "custom entity
# types").
# Note: session entity types apply to all queries, regardless of the language.
class GoogleCloudDialogflowV2SessionEntityType
include Google::Apis::Core::Hashable
# Required. The collection of entities associated with this session entity
# type.
# Corresponds to the JSON property `entities`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2EntityTypeEntity>]
attr_accessor :entities
# Required. Indicates whether the additional data should override or
# supplement the custom entity type definition.
# Corresponds to the JSON property `entityOverrideMode`
# @return [String]
attr_accessor :entity_override_mode
# Required. The unique identifier of this session entity type. Format:
# `projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type
# Display Name>`, or `projects/<Project ID>/agent/environments/<Environment
# ID>/users/<User ID>/sessions/<Session ID>/entityTypes/<Entity Type Display
# Name>`.
# If `Environment ID` is not specified, we assume default 'draft'
# environment. If `User ID` is not specified, we assume default '-' user.
# `<Entity Type Display Name>` must be the display name of an existing entity
# type in the same agent that will be overridden or supplemented.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entities = args[:entities] if args.key?(:entities)
@entity_override_mode = args[:entity_override_mode] if args.key?(:entity_override_mode)
@name = args[:name] if args.key?(:name)
end
end
# Hints for the speech recognizer to help with recognition in a specific
# conversation state.
class GoogleCloudDialogflowV2SpeechContext
include Google::Apis::Core::Hashable
# Optional. Boost for this context compared to other contexts:
# * If the boost is positive, Dialogflow will increase the probability that
# the phrases in this context are recognized over similar sounding phrases.
# * If the boost is unspecified or non-positive, Dialogflow will not apply
# any boost.
# Dialogflow recommends that you use boosts in the range (0, 20] and that you
# find a value that fits your use case with binary search.
# Corresponds to the JSON property `boost`
# @return [Float]
attr_accessor :boost
# Optional. A list of strings containing words and phrases that the speech
# recognizer should recognize with higher likelihood.
# This list can be used to:
# * improve accuracy for words and phrases you expect the user to say,
# e.g. typical commands for your Dialogflow agent
# * add additional words to the speech recognizer vocabulary
# * ...
# See the [Cloud Speech
# documentation](https://cloud.google.com/speech-to-text/quotas) for usage
# limits.
# Corresponds to the JSON property `phrases`
# @return [Array<String>]
attr_accessor :phrases
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@boost = args[:boost] if args.key?(:boost)
@phrases = args[:phrases] if args.key?(:phrases)
end
end
# Configuration of how speech should be synthesized.
class GoogleCloudDialogflowV2SynthesizeSpeechConfig
include Google::Apis::Core::Hashable
# Optional. An identifier which selects 'audio effects' profiles that are
# applied on (post synthesized) text to speech. Effects are applied on top of
# each other in the order they are given.
# Corresponds to the JSON property `effectsProfileId`
# @return [Array<String>]
attr_accessor :effects_profile_id
# Optional. Speaking pitch, in the range [-20.0, 20.0]. 20 means increase 20
# semitones from the original pitch. -20 means decrease 20 semitones from the
# original pitch.
# Corresponds to the JSON property `pitch`
# @return [Float]
attr_accessor :pitch
# Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 is the normal
# native speed supported by the specific voice. 2.0 is twice as fast, and
# 0.5 is half as fast. If unset(0.0), defaults to the native 1.0 speed. Any
# other values < 0.25 or > 4.0 will return an error.
# Corresponds to the JSON property `speakingRate`
# @return [Float]
attr_accessor :speaking_rate
# Description of which voice to use for speech synthesis.
# Corresponds to the JSON property `voice`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2VoiceSelectionParams]
attr_accessor :voice
# Optional. Volume gain (in dB) of the normal native volume supported by the
# specific voice, in the range [-96.0, 16.0]. If unset, or set to a value of
# 0.0 (dB), will play at normal native signal amplitude. A value of -6.0 (dB)
# will play at approximately half the amplitude of the normal native signal
# amplitude. A value of +6.0 (dB) will play at approximately twice the
# amplitude of the normal native signal amplitude. We strongly recommend not
# to exceed +10 (dB) as there's usually no effective increase in loudness for
# any value greater than that.
# Corresponds to the JSON property `volumeGainDb`
# @return [Float]
attr_accessor :volume_gain_db
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@effects_profile_id = args[:effects_profile_id] if args.key?(:effects_profile_id)
@pitch = args[:pitch] if args.key?(:pitch)
@speaking_rate = args[:speaking_rate] if args.key?(:speaking_rate)
@voice = args[:voice] if args.key?(:voice)
@volume_gain_db = args[:volume_gain_db] if args.key?(:volume_gain_db)
end
end
# Represents the natural language text to be processed.
class GoogleCloudDialogflowV2TextInput
include Google::Apis::Core::Hashable
# Required. The language of this conversational query. See [Language
# Support](https://cloud.google.com/dialogflow/docs/reference/language)
# for a list of the currently supported language codes. Note that queries in
# the same session do not necessarily need to specify the same language.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Required. The UTF-8 encoded natural language text to be processed.
# Text length must not exceed 256 characters.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@language_code = args[:language_code] if args.key?(:language_code)
@text = args[:text] if args.key?(:text)
end
end
# The request message for Agents.TrainAgent.
class GoogleCloudDialogflowV2TrainAgentRequest
include Google::Apis::Core::Hashable
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
end
end
# Represents a single validation error.
class GoogleCloudDialogflowV2ValidationError
include Google::Apis::Core::Hashable
# The names of the entries that the error is associated with.
# Format:
# - "projects/<Project ID>/agent", if the error is associated with the entire
# agent.
# - "projects/<Project ID>/agent/intents/<Intent ID>", if the error is
# associated with certain intents.
# - "projects/<Project
# ID>/agent/intents/<Intent Id>/trainingPhrases/<Training Phrase ID>", if the
# error is associated with certain intent training phrases.
# - "projects/<Project ID>/agent/intents/<Intent Id>/parameters/<Parameter
# ID>", if the error is associated with certain intent parameters.
# - "projects/<Project ID>/agent/entities/<Entity ID>", if the error is
# associated with certain entities.
# Corresponds to the JSON property `entries`
# @return [Array<String>]
attr_accessor :entries
# The detailed error messsage.
# Corresponds to the JSON property `errorMessage`
# @return [String]
attr_accessor :error_message
# The severity of the error.
# Corresponds to the JSON property `severity`
# @return [String]
attr_accessor :severity
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entries = args[:entries] if args.key?(:entries)
@error_message = args[:error_message] if args.key?(:error_message)
@severity = args[:severity] if args.key?(:severity)
end
end
# Represents the output of agent validation.
class GoogleCloudDialogflowV2ValidationResult
include Google::Apis::Core::Hashable
# Contains all validation errors.
# Corresponds to the JSON property `validationErrors`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2ValidationError>]
attr_accessor :validation_errors
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@validation_errors = args[:validation_errors] if args.key?(:validation_errors)
end
end
# Description of which voice to use for speech synthesis.
class GoogleCloudDialogflowV2VoiceSelectionParams
include Google::Apis::Core::Hashable
# Optional. The name of the voice. If not set, the service will choose a
# voice based on the other parameters such as language_code and
# ssml_gender.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Optional. The preferred gender of the voice. If not set, the service will
# choose a voice based on the other parameters such as language_code and
# name. Note that this is only a preference, not requirement. If a
# voice of the appropriate gender is not available, the synthesizer should
# substitute a voice with a different gender rather than failing the request.
# Corresponds to the JSON property `ssmlGender`
# @return [String]
attr_accessor :ssml_gender
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
@ssml_gender = args[:ssml_gender] if args.key?(:ssml_gender)
end
end
# The request message for a webhook call.
class GoogleCloudDialogflowV2WebhookRequest
include Google::Apis::Core::Hashable
# Represents the contents of the original request that was passed to
# the `[Streaming]DetectIntent` call.
# Corresponds to the JSON property `originalDetectIntentRequest`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2OriginalDetectIntentRequest]
attr_accessor :original_detect_intent_request
# Represents the result of conversational query or event processing.
# Corresponds to the JSON property `queryResult`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2QueryResult]
attr_accessor :query_result
# The unique identifier of the response. Contains the same value as
# `[Streaming]DetectIntentResponse.response_id`.
# Corresponds to the JSON property `responseId`
# @return [String]
attr_accessor :response_id
# The unique identifier of detectIntent request session.
# Can be used to identify end-user inside webhook implementation.
# Format: `projects/<Project ID>/agent/sessions/<Session ID>`, or
# `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
# ID>/sessions/<Session ID>`.
# Corresponds to the JSON property `session`
# @return [String]
attr_accessor :session
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@original_detect_intent_request = args[:original_detect_intent_request] if args.key?(:original_detect_intent_request)
@query_result = args[:query_result] if args.key?(:query_result)
@response_id = args[:response_id] if args.key?(:response_id)
@session = args[:session] if args.key?(:session)
end
end
# The response message for a webhook call.
# This response is validated by the Dialogflow server. If validation fails,
# an error will be returned in the QueryResult.diagnostic_info field.
# Setting JSON fields to an empty value with the wrong type is a common error.
# To avoid this error:
# - Use `""` for empty strings
# - Use ```` or `null` for empty objects
# - Use `[]` or `null` for empty arrays
# For more information, see the
# [Protocol Buffers Language
# Guide](https://developers.google.com/protocol-buffers/docs/proto3#json).
class GoogleCloudDialogflowV2WebhookResponse
include Google::Apis::Core::Hashable
# Events allow for matching intents by event name instead of the natural
# language input. For instance, input `<event: ` name: "welcome_event",
# parameters: ` name: "Sam" ` `>` can trigger a personalized welcome response.
# The parameter `name` may be used by the agent in the response:
# `"Hello #welcome_event.name! What can I do for you today?"`.
# Corresponds to the JSON property `followupEventInput`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2EventInput]
attr_accessor :followup_event_input
# Optional. The collection of rich messages to present to the user. This
# value is passed directly to `QueryResult.fulfillment_messages`.
# Corresponds to the JSON property `fulfillmentMessages`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2IntentMessage>]
attr_accessor :fulfillment_messages
# Optional. The text to be shown on the screen. This value is passed directly
# to `QueryResult.fulfillment_text`.
# Corresponds to the JSON property `fulfillmentText`
# @return [String]
attr_accessor :fulfillment_text
# Optional. The collection of output contexts. This value is passed directly
# to `QueryResult.output_contexts`.
# Corresponds to the JSON property `outputContexts`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2Context>]
attr_accessor :output_contexts
# Optional. This value is passed directly to `QueryResult.webhook_payload`.
# See the related `fulfillment_messages[i].payload field`, which may be used
# as an alternative to this field.
# This field can be used for Actions on Google responses.
# It should have a structure similar to the JSON message shown here. For more
# information, see
# [Actions on Google Webhook
# Format](https://developers.google.com/actions/dialogflow/webhook)
# <pre>`
# "google": `
# "expectUserResponse": true,
# "richResponse": `
# "items": [
# `
# "simpleResponse": `
# "textToSpeech": "this is a simple response"
# `
# `
# ]
# `
# `
# `</pre>
# Corresponds to the JSON property `payload`
# @return [Hash<String,Object>]
attr_accessor :payload
# Optional. Additional session entity types to replace or extend developer
# entity types with. The entity synonyms apply to all languages and persist
# for the session of this query. Setting the session entity types inside
# webhook overwrites the session entity types that have been set through
# `DetectIntentRequest.query_params.session_entity_types`.
# Corresponds to the JSON property `sessionEntityTypes`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2SessionEntityType>]
attr_accessor :session_entity_types
# Optional. This value is passed directly to `QueryResult.webhook_source`.
# Corresponds to the JSON property `source`
# @return [String]
attr_accessor :source
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@followup_event_input = args[:followup_event_input] if args.key?(:followup_event_input)
@fulfillment_messages = args[:fulfillment_messages] if args.key?(:fulfillment_messages)
@fulfillment_text = args[:fulfillment_text] if args.key?(:fulfillment_text)
@output_contexts = args[:output_contexts] if args.key?(:output_contexts)
@payload = args[:payload] if args.key?(:payload)
@session_entity_types = args[:session_entity_types] if args.key?(:session_entity_types)
@source = args[:source] if args.key?(:source)
end
end
# Represents an annotated conversation dataset.
# ConversationDataset can have multiple AnnotatedConversationDataset, each of
# them represents one result from one annotation task.
# AnnotatedConversationDataset can only be generated from annotation task,
# which will be triggered by LabelConversation.
class GoogleCloudDialogflowV2beta1AnnotatedConversationDataset
include Google::Apis::Core::Hashable
# Output only. Number of examples that have annotations in the annotated
# conversation dataset.
# Corresponds to the JSON property `completedExampleCount`
# @return [Fixnum]
attr_accessor :completed_example_count
# Output only. Creation time of this annotated conversation dataset.
# Corresponds to the JSON property `createTime`
# @return [String]
attr_accessor :create_time
# Optional. The description of the annotated conversation dataset.
# Maximum of 10000 bytes.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Required. The display name of the annotated conversation dataset.
# It's specified when user starts an annotation task. Maximum of 64 bytes.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# Output only. Number of examples in the annotated conversation dataset.
# Corresponds to the JSON property `exampleCount`
# @return [Fixnum]
attr_accessor :example_count
# Output only. AnnotatedConversationDataset resource name. Format:
# `projects/<Project ID>/conversationDatasets/<Conversation Dataset
# ID>/annotatedConversationDatasets/<Annotated Conversation Dataset ID>`
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Output only. Question type name that identifies a labeling task.
# A question is a single task that a worker answers. A question type is set
# of related questions. Each question belongs to a particular question type.
# It can be used in CrowdCompute UI to filter and manage labeling tasks.
# Corresponds to the JSON property `questionTypeName`
# @return [String]
attr_accessor :question_type_name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@completed_example_count = args[:completed_example_count] if args.key?(:completed_example_count)
@create_time = args[:create_time] if args.key?(:create_time)
@description = args[:description] if args.key?(:description)
@display_name = args[:display_name] if args.key?(:display_name)
@example_count = args[:example_count] if args.key?(:example_count)
@name = args[:name] if args.key?(:name)
@question_type_name = args[:question_type_name] if args.key?(:question_type_name)
end
end
# The response message for EntityTypes.BatchUpdateEntityTypes.
class GoogleCloudDialogflowV2beta1BatchUpdateEntityTypesResponse
include Google::Apis::Core::Hashable
# The collection of updated or created entity types.
# Corresponds to the JSON property `entityTypes`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1EntityType>]
attr_accessor :entity_types
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entity_types = args[:entity_types] if args.key?(:entity_types)
end
end
# The response message for Intents.BatchUpdateIntents.
class GoogleCloudDialogflowV2beta1BatchUpdateIntentsResponse
include Google::Apis::Core::Hashable
# The collection of updated or created intents.
# Corresponds to the JSON property `intents`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1Intent>]
attr_accessor :intents
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@intents = args[:intents] if args.key?(:intents)
end
end
# Represents a context.
class GoogleCloudDialogflowV2beta1Context
include Google::Apis::Core::Hashable
# Optional. The number of conversational query requests after which the
# context expires. If set to `0` (the default) the context expires
# immediately. Contexts expire automatically after 20 minutes if there
# are no matching queries.
# Corresponds to the JSON property `lifespanCount`
# @return [Fixnum]
attr_accessor :lifespan_count
# Required. The unique identifier of the context. Format:
# `projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>`,
# or `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
# ID>/sessions/<Session ID>/contexts/<Context ID>`.
# The `Context ID` is always converted to lowercase, may only contain
# characters in a-zA-Z0-9_-% and may be at most 250 bytes long.
# If `Environment ID` is not specified, we assume default 'draft'
# environment. If `User ID` is not specified, we assume default '-' user.
# The following context names are reserved for internal use by Dialogflow.
# You should not use these contexts or create contexts with these names:
# * `__system_counters__`
# * `*_id_dialog_context`
# * `*_dialog_params_size`
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Optional. The collection of parameters associated with this context.
# Refer to [this
# doc](https://cloud.google.com/dialogflow/docs/intents-actions-parameters)
# for syntax.
# Corresponds to the JSON property `parameters`
# @return [Hash<String,Object>]
attr_accessor :parameters
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@lifespan_count = args[:lifespan_count] if args.key?(:lifespan_count)
@name = args[:name] if args.key?(:name)
@parameters = args[:parameters] if args.key?(:parameters)
end
end
# Represents an entity type.
# Entity types serve as a tool for extracting parameter values from natural
# language queries.
class GoogleCloudDialogflowV2beta1EntityType
include Google::Apis::Core::Hashable
# Optional. Indicates whether the entity type can be automatically
# expanded.
# Corresponds to the JSON property `autoExpansionMode`
# @return [String]
attr_accessor :auto_expansion_mode
# Required. The name of the entity type.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# Optional. Enables fuzzy entity extraction during classification.
# Corresponds to the JSON property `enableFuzzyExtraction`
# @return [Boolean]
attr_accessor :enable_fuzzy_extraction
alias_method :enable_fuzzy_extraction?, :enable_fuzzy_extraction
# Optional. The collection of entity entries associated with the entity type.
# Corresponds to the JSON property `entities`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1EntityTypeEntity>]
attr_accessor :entities
# Required. Indicates the kind of entity type.
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# The unique identifier of the entity type.
# Required for EntityTypes.UpdateEntityType and
# EntityTypes.BatchUpdateEntityTypes methods.
# Format: `projects/<Project ID>/agent/entityTypes/<Entity Type ID>`.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@auto_expansion_mode = args[:auto_expansion_mode] if args.key?(:auto_expansion_mode)
@display_name = args[:display_name] if args.key?(:display_name)
@enable_fuzzy_extraction = args[:enable_fuzzy_extraction] if args.key?(:enable_fuzzy_extraction)
@entities = args[:entities] if args.key?(:entities)
@kind = args[:kind] if args.key?(:kind)
@name = args[:name] if args.key?(:name)
end
end
# An **entity entry** for an associated entity type.
class GoogleCloudDialogflowV2beta1EntityTypeEntity
include Google::Apis::Core::Hashable
# Required. A collection of value synonyms. For example, if the entity type
# is *vegetable*, and `value` is *scallions*, a synonym could be *green
# onions*.
# For `KIND_LIST` entity types:
# * This collection must contain exactly one synonym equal to `value`.
# Corresponds to the JSON property `synonyms`
# @return [Array<String>]
attr_accessor :synonyms
# Required. The primary value associated with this entity entry.
# For example, if the entity type is *vegetable*, the value could be
# *scallions*.
# For `KIND_MAP` entity types:
# * A reference value to be used in place of synonyms.
# For `KIND_LIST` entity types:
# * A string that can contain references to other entity types (with or
# without aliases).
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@synonyms = args[:synonyms] if args.key?(:synonyms)
@value = args[:value] if args.key?(:value)
end
end
# Events allow for matching intents by event name instead of the natural
# language input. For instance, input `<event: ` name: "welcome_event",
# parameters: ` name: "Sam" ` `>` can trigger a personalized welcome response.
# The parameter `name` may be used by the agent in the response:
# `"Hello #welcome_event.name! What can I do for you today?"`.
class GoogleCloudDialogflowV2beta1EventInput
include Google::Apis::Core::Hashable
# Required. The language of this query. See [Language
# Support](https://cloud.google.com/dialogflow/docs/reference/language)
# for a list of the currently supported language codes. Note that queries in
# the same session do not necessarily need to specify the same language.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Required. The unique identifier of the event.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# The collection of parameters associated with the event.
# Corresponds to the JSON property `parameters`
# @return [Hash<String,Object>]
attr_accessor :parameters
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@language_code = args[:language_code] if args.key?(:language_code)
@name = args[:name] if args.key?(:name)
@parameters = args[:parameters] if args.key?(:parameters)
end
end
# The response message for Agents.ExportAgent.
class GoogleCloudDialogflowV2beta1ExportAgentResponse
include Google::Apis::Core::Hashable
# Zip compressed raw byte content for agent.
# Corresponds to the JSON property `agentContent`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :agent_content
# The URI to a file containing the exported agent. This field is populated
# only if `agent_uri` is specified in `ExportAgentRequest`.
# Corresponds to the JSON property `agentUri`
# @return [String]
attr_accessor :agent_uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@agent_content = args[:agent_content] if args.key?(:agent_content)
@agent_uri = args[:agent_uri] if args.key?(:agent_uri)
end
end
# Represents an intent.
# Intents convert a number of user expressions or patterns into an action. An
# action is an extraction of a user command or sentence semantics.
class GoogleCloudDialogflowV2beta1Intent
include Google::Apis::Core::Hashable
# Optional. The name of the action associated with the intent.
# Note: The action name must not contain whitespaces.
# Corresponds to the JSON property `action`
# @return [String]
attr_accessor :action
# Optional. The list of platforms for which the first responses will be
# copied from the messages in PLATFORM_UNSPECIFIED (i.e. default platform).
# Corresponds to the JSON property `defaultResponsePlatforms`
# @return [Array<String>]
attr_accessor :default_response_platforms
# Required. The name of this intent.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# Optional. Indicates that this intent ends an interaction. Some integrations
# (e.g., Actions on Google or Dialogflow phone gateway) use this information
# to close interaction with an end user. Default is false.
# Corresponds to the JSON property `endInteraction`
# @return [Boolean]
attr_accessor :end_interaction
alias_method :end_interaction?, :end_interaction
# Optional. The collection of event names that trigger the intent.
# If the collection of input contexts is not empty, all of the contexts must
# be present in the active user session for an event to trigger this intent.
# Corresponds to the JSON property `events`
# @return [Array<String>]
attr_accessor :events
# Read-only. Information about all followup intents that have this intent as
# a direct or indirect parent. We populate this field only in the output.
# Corresponds to the JSON property `followupIntentInfo`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentFollowupIntentInfo>]
attr_accessor :followup_intent_info
# Optional. The list of context names required for this intent to be
# triggered.
# Format: `projects/<Project ID>/agent/sessions/-/contexts/<Context ID>`.
# Corresponds to the JSON property `inputContextNames`
# @return [Array<String>]
attr_accessor :input_context_names
# Optional. Indicates whether this is a fallback intent.
# Corresponds to the JSON property `isFallback`
# @return [Boolean]
attr_accessor :is_fallback
alias_method :is_fallback?, :is_fallback
# Optional. The collection of rich messages corresponding to the
# `Response` field in the Dialogflow console.
# Corresponds to the JSON property `messages`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessage>]
attr_accessor :messages
# Optional. Indicates whether Machine Learning is disabled for the intent.
# Note: If `ml_disabled` setting is set to true, then this intent is not
# taken into account during inference in `ML ONLY` match mode. Also,
# auto-markup in the UI is turned off.
# Corresponds to the JSON property `mlDisabled`
# @return [Boolean]
attr_accessor :ml_disabled
alias_method :ml_disabled?, :ml_disabled
# Optional. Indicates whether Machine Learning is enabled for the intent.
# Note: If `ml_enabled` setting is set to false, then this intent is not
# taken into account during inference in `ML ONLY` match mode. Also,
# auto-markup in the UI is turned off.
# DEPRECATED! Please use `ml_disabled` field instead.
# NOTE: If both `ml_enabled` and `ml_disabled` are either not set or false,
# then the default value is determined as follows:
# - Before April 15th, 2018 the default is:
# ml_enabled = false / ml_disabled = true.
# - After April 15th, 2018 the default is:
# ml_enabled = true / ml_disabled = false.
# Corresponds to the JSON property `mlEnabled`
# @return [Boolean]
attr_accessor :ml_enabled
alias_method :ml_enabled?, :ml_enabled
# The unique identifier of this intent.
# Required for Intents.UpdateIntent and Intents.BatchUpdateIntents
# methods.
# Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Optional. The collection of contexts that are activated when the intent
# is matched. Context messages in this collection should not set the
# parameters field. Setting the `lifespan_count` to 0 will reset the context
# when the intent is matched.
# Format: `projects/<Project ID>/agent/sessions/-/contexts/<Context ID>`.
# Corresponds to the JSON property `outputContexts`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1Context>]
attr_accessor :output_contexts
# Optional. The collection of parameters associated with the intent.
# Corresponds to the JSON property `parameters`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentParameter>]
attr_accessor :parameters
# Read-only after creation. The unique identifier of the parent intent in the
# chain of followup intents. You can set this field when creating an intent,
# for example with CreateIntent or
# BatchUpdateIntents, in order to make this
# intent a followup intent.
# It identifies the parent followup intent.
# Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
# Corresponds to the JSON property `parentFollowupIntentName`
# @return [String]
attr_accessor :parent_followup_intent_name
# The priority of this intent. Higher numbers represent higher
# priorities.
# - If the supplied value is unspecified or 0, the service
# translates the value to 500,000, which corresponds to the
# `Normal` priority in the console.
# - If the supplied value is negative, the intent is ignored
# in runtime detect intent requests.
# Corresponds to the JSON property `priority`
# @return [Fixnum]
attr_accessor :priority
# Optional. Indicates whether to delete all contexts in the current
# session when this intent is matched.
# Corresponds to the JSON property `resetContexts`
# @return [Boolean]
attr_accessor :reset_contexts
alias_method :reset_contexts?, :reset_contexts
# Read-only. The unique identifier of the root intent in the chain of
# followup intents. It identifies the correct followup intents chain for
# this intent. We populate this field only in the output.
# Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
# Corresponds to the JSON property `rootFollowupIntentName`
# @return [String]
attr_accessor :root_followup_intent_name
# Optional. The collection of examples that the agent is
# trained on.
# Corresponds to the JSON property `trainingPhrases`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentTrainingPhrase>]
attr_accessor :training_phrases
# Optional. Indicates whether webhooks are enabled for the intent.
# Corresponds to the JSON property `webhookState`
# @return [String]
attr_accessor :webhook_state
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action = args[:action] if args.key?(:action)
@default_response_platforms = args[:default_response_platforms] if args.key?(:default_response_platforms)
@display_name = args[:display_name] if args.key?(:display_name)
@end_interaction = args[:end_interaction] if args.key?(:end_interaction)
@events = args[:events] if args.key?(:events)
@followup_intent_info = args[:followup_intent_info] if args.key?(:followup_intent_info)
@input_context_names = args[:input_context_names] if args.key?(:input_context_names)
@is_fallback = args[:is_fallback] if args.key?(:is_fallback)
@messages = args[:messages] if args.key?(:messages)
@ml_disabled = args[:ml_disabled] if args.key?(:ml_disabled)
@ml_enabled = args[:ml_enabled] if args.key?(:ml_enabled)
@name = args[:name] if args.key?(:name)
@output_contexts = args[:output_contexts] if args.key?(:output_contexts)
@parameters = args[:parameters] if args.key?(:parameters)
@parent_followup_intent_name = args[:parent_followup_intent_name] if args.key?(:parent_followup_intent_name)
@priority = args[:priority] if args.key?(:priority)
@reset_contexts = args[:reset_contexts] if args.key?(:reset_contexts)
@root_followup_intent_name = args[:root_followup_intent_name] if args.key?(:root_followup_intent_name)
@training_phrases = args[:training_phrases] if args.key?(:training_phrases)
@webhook_state = args[:webhook_state] if args.key?(:webhook_state)
end
end
# Represents a single followup intent in the chain.
class GoogleCloudDialogflowV2beta1IntentFollowupIntentInfo
include Google::Apis::Core::Hashable
# The unique identifier of the followup intent.
# Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
# Corresponds to the JSON property `followupIntentName`
# @return [String]
attr_accessor :followup_intent_name
# The unique identifier of the followup intent's parent.
# Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
# Corresponds to the JSON property `parentFollowupIntentName`
# @return [String]
attr_accessor :parent_followup_intent_name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@followup_intent_name = args[:followup_intent_name] if args.key?(:followup_intent_name)
@parent_followup_intent_name = args[:parent_followup_intent_name] if args.key?(:parent_followup_intent_name)
end
end
# Corresponds to the `Response` field in the Dialogflow console.
class GoogleCloudDialogflowV2beta1IntentMessage
include Google::Apis::Core::Hashable
# The basic card message. Useful for displaying information.
# Corresponds to the JSON property `basicCard`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageBasicCard]
attr_accessor :basic_card
# Browse Carousel Card for Actions on Google.
# https://developers.google.com/actions/assistant/responses#browsing_carousel
# Corresponds to the JSON property `browseCarouselCard`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard]
attr_accessor :browse_carousel_card
# The card response message.
# Corresponds to the JSON property `card`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageCard]
attr_accessor :card
# The card for presenting a carousel of options to select from.
# Corresponds to the JSON property `carouselSelect`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageCarouselSelect]
attr_accessor :carousel_select
# The image response message.
# Corresponds to the JSON property `image`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageImage]
attr_accessor :image
# The suggestion chip message that allows the user to jump out to the app
# or website associated with this agent.
# Corresponds to the JSON property `linkOutSuggestion`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageLinkOutSuggestion]
attr_accessor :link_out_suggestion
# The card for presenting a list of options to select from.
# Corresponds to the JSON property `listSelect`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageListSelect]
attr_accessor :list_select
# The media content card for Actions on Google.
# Corresponds to the JSON property `mediaContent`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageMediaContent]
attr_accessor :media_content
# Returns a response containing a custom, platform-specific payload.
# See the Intent.Message.Platform type for a description of the
# structure that may be required for your platform.
# Corresponds to the JSON property `payload`
# @return [Hash<String,Object>]
attr_accessor :payload
# Optional. The platform that this message is intended for.
# Corresponds to the JSON property `platform`
# @return [String]
attr_accessor :platform
# The quick replies response message.
# Corresponds to the JSON property `quickReplies`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageQuickReplies]
attr_accessor :quick_replies
# Carousel Rich Business Messaging (RBM) rich card.
# Rich cards allow you to respond to users with more vivid content, e.g.
# with media and suggestions.
# For more details about RBM rich cards, please see:
# https://developers.google.com/rcs-business-messaging/rbm/guides/build/send-
# messages#rich-cards.
# If you want to show a single card with more control over the layout,
# please use RbmStandaloneCard instead.
# Corresponds to the JSON property `rbmCarouselRichCard`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmCarouselCard]
attr_accessor :rbm_carousel_rich_card
# Standalone Rich Business Messaging (RBM) rich card.
# Rich cards allow you to respond to users with more vivid content, e.g.
# with media and suggestions.
# For more details about RBM rich cards, please see:
# https://developers.google.com/rcs-business-messaging/rbm/guides/build/send-
# messages#rich-cards.
# You can group multiple rich cards into one using RbmCarouselCard but
# carousel cards will give you less control over the card layout.
# Corresponds to the JSON property `rbmStandaloneRichCard`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmStandaloneCard]
attr_accessor :rbm_standalone_rich_card
# Rich Business Messaging (RBM) text response with suggestions.
# Corresponds to the JSON property `rbmText`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmText]
attr_accessor :rbm_text
# The collection of simple response candidates.
# This message in `QueryResult.fulfillment_messages` and
# `WebhookResponse.fulfillment_messages` should contain only one
# `SimpleResponse`.
# Corresponds to the JSON property `simpleResponses`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageSimpleResponses]
attr_accessor :simple_responses
# The collection of suggestions.
# Corresponds to the JSON property `suggestions`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageSuggestions]
attr_accessor :suggestions
# Table card for Actions on Google.
# Corresponds to the JSON property `tableCard`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageTableCard]
attr_accessor :table_card
# Plays audio from a file in Telephony Gateway.
# Corresponds to the JSON property `telephonyPlayAudio`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageTelephonyPlayAudio]
attr_accessor :telephony_play_audio
# Synthesizes speech and plays back the synthesized audio to the caller in
# Telephony Gateway.
# Telephony Gateway takes the synthesizer settings from
# `DetectIntentResponse.output_audio_config` which can either be set
# at request-level or can come from the agent-level synthesizer config.
# Corresponds to the JSON property `telephonySynthesizeSpeech`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageTelephonySynthesizeSpeech]
attr_accessor :telephony_synthesize_speech
# Transfers the call in Telephony Gateway.
# Corresponds to the JSON property `telephonyTransferCall`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageTelephonyTransferCall]
attr_accessor :telephony_transfer_call
# The text response message.
# Corresponds to the JSON property `text`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageText]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@basic_card = args[:basic_card] if args.key?(:basic_card)
@browse_carousel_card = args[:browse_carousel_card] if args.key?(:browse_carousel_card)
@card = args[:card] if args.key?(:card)
@carousel_select = args[:carousel_select] if args.key?(:carousel_select)
@image = args[:image] if args.key?(:image)
@link_out_suggestion = args[:link_out_suggestion] if args.key?(:link_out_suggestion)
@list_select = args[:list_select] if args.key?(:list_select)
@media_content = args[:media_content] if args.key?(:media_content)
@payload = args[:payload] if args.key?(:payload)
@platform = args[:platform] if args.key?(:platform)
@quick_replies = args[:quick_replies] if args.key?(:quick_replies)
@rbm_carousel_rich_card = args[:rbm_carousel_rich_card] if args.key?(:rbm_carousel_rich_card)
@rbm_standalone_rich_card = args[:rbm_standalone_rich_card] if args.key?(:rbm_standalone_rich_card)
@rbm_text = args[:rbm_text] if args.key?(:rbm_text)
@simple_responses = args[:simple_responses] if args.key?(:simple_responses)
@suggestions = args[:suggestions] if args.key?(:suggestions)
@table_card = args[:table_card] if args.key?(:table_card)
@telephony_play_audio = args[:telephony_play_audio] if args.key?(:telephony_play_audio)
@telephony_synthesize_speech = args[:telephony_synthesize_speech] if args.key?(:telephony_synthesize_speech)
@telephony_transfer_call = args[:telephony_transfer_call] if args.key?(:telephony_transfer_call)
@text = args[:text] if args.key?(:text)
end
end
# The basic card message. Useful for displaying information.
class GoogleCloudDialogflowV2beta1IntentMessageBasicCard
include Google::Apis::Core::Hashable
# Optional. The collection of card buttons.
# Corresponds to the JSON property `buttons`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageBasicCardButton>]
attr_accessor :buttons
# Required, unless image is present. The body text of the card.
# Corresponds to the JSON property `formattedText`
# @return [String]
attr_accessor :formatted_text
# The image response message.
# Corresponds to the JSON property `image`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageImage]
attr_accessor :image
# Optional. The subtitle of the card.
# Corresponds to the JSON property `subtitle`
# @return [String]
attr_accessor :subtitle
# Optional. The title of the card.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@buttons = args[:buttons] if args.key?(:buttons)
@formatted_text = args[:formatted_text] if args.key?(:formatted_text)
@image = args[:image] if args.key?(:image)
@subtitle = args[:subtitle] if args.key?(:subtitle)
@title = args[:title] if args.key?(:title)
end
end
# The button object that appears at the bottom of a card.
class GoogleCloudDialogflowV2beta1IntentMessageBasicCardButton
include Google::Apis::Core::Hashable
# Opens the given URI.
# Corresponds to the JSON property `openUriAction`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageBasicCardButtonOpenUriAction]
attr_accessor :open_uri_action
# Required. The title of the button.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@open_uri_action = args[:open_uri_action] if args.key?(:open_uri_action)
@title = args[:title] if args.key?(:title)
end
end
# Opens the given URI.
class GoogleCloudDialogflowV2beta1IntentMessageBasicCardButtonOpenUriAction
include Google::Apis::Core::Hashable
# Required. The HTTP or HTTPS scheme URI.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# Browse Carousel Card for Actions on Google.
# https://developers.google.com/actions/assistant/responses#browsing_carousel
class GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard
include Google::Apis::Core::Hashable
# Optional. Settings for displaying the image. Applies to every image in
# items.
# Corresponds to the JSON property `imageDisplayOptions`
# @return [String]
attr_accessor :image_display_options
# Required. List of items in the Browse Carousel Card. Minimum of two
# items, maximum of ten.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItem>]
attr_accessor :items
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@image_display_options = args[:image_display_options] if args.key?(:image_display_options)
@items = args[:items] if args.key?(:items)
end
end
# Browsing carousel tile
class GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItem
include Google::Apis::Core::Hashable
# Optional. Description of the carousel item. Maximum of four lines of
# text.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Optional. Text that appears at the bottom of the Browse Carousel
# Card. Maximum of one line of text.
# Corresponds to the JSON property `footer`
# @return [String]
attr_accessor :footer
# The image response message.
# Corresponds to the JSON property `image`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageImage]
attr_accessor :image
# Actions on Google action to open a given url.
# Corresponds to the JSON property `openUriAction`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenUrlAction]
attr_accessor :open_uri_action
# Required. Title of the carousel item. Maximum of two lines of text.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@footer = args[:footer] if args.key?(:footer)
@image = args[:image] if args.key?(:image)
@open_uri_action = args[:open_uri_action] if args.key?(:open_uri_action)
@title = args[:title] if args.key?(:title)
end
end
# Actions on Google action to open a given url.
class GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenUrlAction
include Google::Apis::Core::Hashable
# Required. URL
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
# Optional. Specifies the type of viewer that is used when opening
# the URL. Defaults to opening via web browser.
# Corresponds to the JSON property `urlTypeHint`
# @return [String]
attr_accessor :url_type_hint
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@url = args[:url] if args.key?(:url)
@url_type_hint = args[:url_type_hint] if args.key?(:url_type_hint)
end
end
# The card response message.
class GoogleCloudDialogflowV2beta1IntentMessageCard
include Google::Apis::Core::Hashable
# Optional. The collection of card buttons.
# Corresponds to the JSON property `buttons`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageCardButton>]
attr_accessor :buttons
# Optional. The public URI to an image file for the card.
# Corresponds to the JSON property `imageUri`
# @return [String]
attr_accessor :image_uri
# Optional. The subtitle of the card.
# Corresponds to the JSON property `subtitle`
# @return [String]
attr_accessor :subtitle
# Optional. The title of the card.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@buttons = args[:buttons] if args.key?(:buttons)
@image_uri = args[:image_uri] if args.key?(:image_uri)
@subtitle = args[:subtitle] if args.key?(:subtitle)
@title = args[:title] if args.key?(:title)
end
end
# Optional. Contains information about a button.
class GoogleCloudDialogflowV2beta1IntentMessageCardButton
include Google::Apis::Core::Hashable
# Optional. The text to send back to the Dialogflow API or a URI to
# open.
# Corresponds to the JSON property `postback`
# @return [String]
attr_accessor :postback
# Optional. The text to show on the button.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@postback = args[:postback] if args.key?(:postback)
@text = args[:text] if args.key?(:text)
end
end
# The card for presenting a carousel of options to select from.
class GoogleCloudDialogflowV2beta1IntentMessageCarouselSelect
include Google::Apis::Core::Hashable
# Required. Carousel items.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageCarouselSelectItem>]
attr_accessor :items
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@items = args[:items] if args.key?(:items)
end
end
# An item in the carousel.
class GoogleCloudDialogflowV2beta1IntentMessageCarouselSelectItem
include Google::Apis::Core::Hashable
# Optional. The body text of the card.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The image response message.
# Corresponds to the JSON property `image`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageImage]
attr_accessor :image
# Additional info about the select item for when it is triggered in a
# dialog.
# Corresponds to the JSON property `info`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageSelectItemInfo]
attr_accessor :info
# Required. Title of the carousel item.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@image = args[:image] if args.key?(:image)
@info = args[:info] if args.key?(:info)
@title = args[:title] if args.key?(:title)
end
end
# Column properties for TableCard.
class GoogleCloudDialogflowV2beta1IntentMessageColumnProperties
include Google::Apis::Core::Hashable
# Required. Column heading.
# Corresponds to the JSON property `header`
# @return [String]
attr_accessor :header
# Optional. Defines text alignment for all cells in this column.
# Corresponds to the JSON property `horizontalAlignment`
# @return [String]
attr_accessor :horizontal_alignment
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@header = args[:header] if args.key?(:header)
@horizontal_alignment = args[:horizontal_alignment] if args.key?(:horizontal_alignment)
end
end
# The image response message.
class GoogleCloudDialogflowV2beta1IntentMessageImage
include Google::Apis::Core::Hashable
# A text description of the image to be used for accessibility,
# e.g., screen readers. Required if image_uri is set for CarouselSelect.
# Corresponds to the JSON property `accessibilityText`
# @return [String]
attr_accessor :accessibility_text
# Optional. The public URI to an image file.
# Corresponds to the JSON property `imageUri`
# @return [String]
attr_accessor :image_uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@accessibility_text = args[:accessibility_text] if args.key?(:accessibility_text)
@image_uri = args[:image_uri] if args.key?(:image_uri)
end
end
# The suggestion chip message that allows the user to jump out to the app
# or website associated with this agent.
class GoogleCloudDialogflowV2beta1IntentMessageLinkOutSuggestion
include Google::Apis::Core::Hashable
# Required. The name of the app or site this chip is linking to.
# Corresponds to the JSON property `destinationName`
# @return [String]
attr_accessor :destination_name
# Required. The URI of the app or site to open when the user taps the
# suggestion chip.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@destination_name = args[:destination_name] if args.key?(:destination_name)
@uri = args[:uri] if args.key?(:uri)
end
end
# The card for presenting a list of options to select from.
class GoogleCloudDialogflowV2beta1IntentMessageListSelect
include Google::Apis::Core::Hashable
# Required. List items.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageListSelectItem>]
attr_accessor :items
# Optional. Subtitle of the list.
# Corresponds to the JSON property `subtitle`
# @return [String]
attr_accessor :subtitle
# Optional. The overall title of the list.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@items = args[:items] if args.key?(:items)
@subtitle = args[:subtitle] if args.key?(:subtitle)
@title = args[:title] if args.key?(:title)
end
end
# An item in the list.
class GoogleCloudDialogflowV2beta1IntentMessageListSelectItem
include Google::Apis::Core::Hashable
# Optional. The main text describing the item.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The image response message.
# Corresponds to the JSON property `image`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageImage]
attr_accessor :image
# Additional info about the select item for when it is triggered in a
# dialog.
# Corresponds to the JSON property `info`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageSelectItemInfo]
attr_accessor :info
# Required. The title of the list item.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@image = args[:image] if args.key?(:image)
@info = args[:info] if args.key?(:info)
@title = args[:title] if args.key?(:title)
end
end
# The media content card for Actions on Google.
class GoogleCloudDialogflowV2beta1IntentMessageMediaContent
include Google::Apis::Core::Hashable
# Required. List of media objects.
# Corresponds to the JSON property `mediaObjects`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageMediaContentResponseMediaObject>]
attr_accessor :media_objects
# Optional. What type of media is the content (ie "audio").
# Corresponds to the JSON property `mediaType`
# @return [String]
attr_accessor :media_type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@media_objects = args[:media_objects] if args.key?(:media_objects)
@media_type = args[:media_type] if args.key?(:media_type)
end
end
# Response media object for media content card.
class GoogleCloudDialogflowV2beta1IntentMessageMediaContentResponseMediaObject
include Google::Apis::Core::Hashable
# Required. Url where the media is stored.
# Corresponds to the JSON property `contentUrl`
# @return [String]
attr_accessor :content_url
# Optional. Description of media card.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The image response message.
# Corresponds to the JSON property `icon`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageImage]
attr_accessor :icon
# The image response message.
# Corresponds to the JSON property `largeImage`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageImage]
attr_accessor :large_image
# Required. Name of media card.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@content_url = args[:content_url] if args.key?(:content_url)
@description = args[:description] if args.key?(:description)
@icon = args[:icon] if args.key?(:icon)
@large_image = args[:large_image] if args.key?(:large_image)
@name = args[:name] if args.key?(:name)
end
end
# The quick replies response message.
class GoogleCloudDialogflowV2beta1IntentMessageQuickReplies
include Google::Apis::Core::Hashable
# Optional. The collection of quick replies.
# Corresponds to the JSON property `quickReplies`
# @return [Array<String>]
attr_accessor :quick_replies
# Optional. The title of the collection of quick replies.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@quick_replies = args[:quick_replies] if args.key?(:quick_replies)
@title = args[:title] if args.key?(:title)
end
end
# Rich Business Messaging (RBM) Card content
class GoogleCloudDialogflowV2beta1IntentMessageRbmCardContent
include Google::Apis::Core::Hashable
# Optional. Description of the card (at most 2000 bytes).
# At least one of the title, description or media must be set.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Rich Business Messaging (RBM) Media displayed in Cards
# The following media-types are currently supported:
# ## Image Types
# image/jpeg
# image/jpg'
# image/gif
# image/png
# ## Video Types
# video/h263
# video/m4v
# video/mp4
# video/mpeg
# video/mpeg4
# video/webm
# Corresponds to the JSON property `media`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia]
attr_accessor :media
# Optional. List of suggestions to include in the card.
# Corresponds to the JSON property `suggestions`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestion>]
attr_accessor :suggestions
# Optional. Title of the card (at most 200 bytes).
# At least one of the title, description or media must be set.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@media = args[:media] if args.key?(:media)
@suggestions = args[:suggestions] if args.key?(:suggestions)
@title = args[:title] if args.key?(:title)
end
end
# Rich Business Messaging (RBM) Media displayed in Cards
# The following media-types are currently supported:
# ## Image Types
# image/jpeg
# image/jpg'
# image/gif
# image/png
# ## Video Types
# video/h263
# video/m4v
# video/mp4
# video/mpeg
# video/mpeg4
# video/webm
class GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia
include Google::Apis::Core::Hashable
# Required. Publicly reachable URI of the file. The RBM platform
# determines the MIME type of the file from the content-type field in
# the HTTP headers when the platform fetches the file. The content-type
# field must be present and accurate in the HTTP response from the URL.
# Corresponds to the JSON property `fileUri`
# @return [String]
attr_accessor :file_uri
# Required for cards with vertical orientation. The height of the media
# within a rich card with a vertical layout. (https://goo.gl/NeFCjz).
# For a standalone card with horizontal layout, height is not
# customizable, and this field is ignored.
# Corresponds to the JSON property `height`
# @return [String]
attr_accessor :height
# Optional. Publicly reachable URI of the thumbnail.If you don't
# provide a thumbnail URI, the RBM platform displays a blank
# placeholder thumbnail until the user's device downloads the file.
# Depending on the user's setting, the file may not download
# automatically and may require the user to tap a download button.
# Corresponds to the JSON property `thumbnailUri`
# @return [String]
attr_accessor :thumbnail_uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@file_uri = args[:file_uri] if args.key?(:file_uri)
@height = args[:height] if args.key?(:height)
@thumbnail_uri = args[:thumbnail_uri] if args.key?(:thumbnail_uri)
end
end
# Carousel Rich Business Messaging (RBM) rich card.
# Rich cards allow you to respond to users with more vivid content, e.g.
# with media and suggestions.
# For more details about RBM rich cards, please see:
# https://developers.google.com/rcs-business-messaging/rbm/guides/build/send-
# messages#rich-cards.
# If you want to show a single card with more control over the layout,
# please use RbmStandaloneCard instead.
class GoogleCloudDialogflowV2beta1IntentMessageRbmCarouselCard
include Google::Apis::Core::Hashable
# Required. The cards in the carousel. A carousel must have at least
# 2 cards and at most 10.
# Corresponds to the JSON property `cardContents`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmCardContent>]
attr_accessor :card_contents
# Required. The width of the cards in the carousel.
# Corresponds to the JSON property `cardWidth`
# @return [String]
attr_accessor :card_width
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@card_contents = args[:card_contents] if args.key?(:card_contents)
@card_width = args[:card_width] if args.key?(:card_width)
end
end
# Standalone Rich Business Messaging (RBM) rich card.
# Rich cards allow you to respond to users with more vivid content, e.g.
# with media and suggestions.
# For more details about RBM rich cards, please see:
# https://developers.google.com/rcs-business-messaging/rbm/guides/build/send-
# messages#rich-cards.
# You can group multiple rich cards into one using RbmCarouselCard but
# carousel cards will give you less control over the card layout.
class GoogleCloudDialogflowV2beta1IntentMessageRbmStandaloneCard
include Google::Apis::Core::Hashable
# Rich Business Messaging (RBM) Card content
# Corresponds to the JSON property `cardContent`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmCardContent]
attr_accessor :card_content
# Required. Orientation of the card.
# Corresponds to the JSON property `cardOrientation`
# @return [String]
attr_accessor :card_orientation
# Required if orientation is horizontal.
# Image preview alignment for standalone cards with horizontal layout.
# Corresponds to the JSON property `thumbnailImageAlignment`
# @return [String]
attr_accessor :thumbnail_image_alignment
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@card_content = args[:card_content] if args.key?(:card_content)
@card_orientation = args[:card_orientation] if args.key?(:card_orientation)
@thumbnail_image_alignment = args[:thumbnail_image_alignment] if args.key?(:thumbnail_image_alignment)
end
end
# Rich Business Messaging (RBM) suggested client-side action that the user
# can choose from the card.
class GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedAction
include Google::Apis::Core::Hashable
# Opens the user's default dialer app with the specified phone number
# but does not dial automatically (https://goo.gl/ergbB2).
# Corresponds to the JSON property `dial`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionDial]
attr_accessor :dial
# Opens the user's default web browser app to the specified uri
# (https://goo.gl/6GLJD2). If the user has an app installed that is
# registered as the default handler for the URL, then this app will be
# opened instead, and its icon will be used in the suggested action UI.
# Corresponds to the JSON property `openUrl`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionOpenUri]
attr_accessor :open_url
# Opaque payload that the Dialogflow receives in a user event
# when the user taps the suggested action. This data will be also
# forwarded to webhook to allow performing custom business logic.
# Corresponds to the JSON property `postbackData`
# @return [String]
attr_accessor :postback_data
# Opens the device's location chooser so the user can pick a location
# to send back to the agent (https://goo.gl/GXotJW).
# Corresponds to the JSON property `shareLocation`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionShareLocation]
attr_accessor :share_location
# Text to display alongside the action.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@dial = args[:dial] if args.key?(:dial)
@open_url = args[:open_url] if args.key?(:open_url)
@postback_data = args[:postback_data] if args.key?(:postback_data)
@share_location = args[:share_location] if args.key?(:share_location)
@text = args[:text] if args.key?(:text)
end
end
# Opens the user's default dialer app with the specified phone number
# but does not dial automatically (https://goo.gl/ergbB2).
class GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionDial
include Google::Apis::Core::Hashable
# Required. The phone number to fill in the default dialer app.
# This field should be in [E.164](https://en.wikipedia.org/wiki/E.164)
# format. An example of a correctly formatted phone number:
# +15556767888.
# Corresponds to the JSON property `phoneNumber`
# @return [String]
attr_accessor :phone_number
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@phone_number = args[:phone_number] if args.key?(:phone_number)
end
end
# Opens the user's default web browser app to the specified uri
# (https://goo.gl/6GLJD2). If the user has an app installed that is
# registered as the default handler for the URL, then this app will be
# opened instead, and its icon will be used in the suggested action UI.
class GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionOpenUri
include Google::Apis::Core::Hashable
# Required. The uri to open on the user device
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# Opens the device's location chooser so the user can pick a location
# to send back to the agent (https://goo.gl/GXotJW).
class GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionShareLocation
include Google::Apis::Core::Hashable
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
end
end
# Rich Business Messaging (RBM) suggested reply that the user can click
# instead of typing in their own response.
class GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedReply
include Google::Apis::Core::Hashable
# Opaque payload that the Dialogflow receives in a user event
# when the user taps the suggested reply. This data will be also
# forwarded to webhook to allow performing custom business logic.
# Corresponds to the JSON property `postbackData`
# @return [String]
attr_accessor :postback_data
# Suggested reply text.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@postback_data = args[:postback_data] if args.key?(:postback_data)
@text = args[:text] if args.key?(:text)
end
end
# Rich Business Messaging (RBM) suggestion. Suggestions allow user to
# easily select/click a predefined response or perform an action (like
# opening a web uri).
class GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestion
include Google::Apis::Core::Hashable
# Rich Business Messaging (RBM) suggested client-side action that the user
# can choose from the card.
# Corresponds to the JSON property `action`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedAction]
attr_accessor :action
# Rich Business Messaging (RBM) suggested reply that the user can click
# instead of typing in their own response.
# Corresponds to the JSON property `reply`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedReply]
attr_accessor :reply
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action = args[:action] if args.key?(:action)
@reply = args[:reply] if args.key?(:reply)
end
end
# Rich Business Messaging (RBM) text response with suggestions.
class GoogleCloudDialogflowV2beta1IntentMessageRbmText
include Google::Apis::Core::Hashable
# Optional. One or more suggestions to show to the user.
# Corresponds to the JSON property `rbmSuggestion`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestion>]
attr_accessor :rbm_suggestion
# Required. Text sent and displayed to the user.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@rbm_suggestion = args[:rbm_suggestion] if args.key?(:rbm_suggestion)
@text = args[:text] if args.key?(:text)
end
end
# Additional info about the select item for when it is triggered in a
# dialog.
class GoogleCloudDialogflowV2beta1IntentMessageSelectItemInfo
include Google::Apis::Core::Hashable
# Required. A unique key that will be sent back to the agent if this
# response is given.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
# Optional. A list of synonyms that can also be used to trigger this
# item in dialog.
# Corresponds to the JSON property `synonyms`
# @return [Array<String>]
attr_accessor :synonyms
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@key = args[:key] if args.key?(:key)
@synonyms = args[:synonyms] if args.key?(:synonyms)
end
end
# The simple response message containing speech or text.
class GoogleCloudDialogflowV2beta1IntentMessageSimpleResponse
include Google::Apis::Core::Hashable
# Optional. The text to display.
# Corresponds to the JSON property `displayText`
# @return [String]
attr_accessor :display_text
# One of text_to_speech or ssml must be provided. Structured spoken
# response to the user in the SSML format. Mutually exclusive with
# text_to_speech.
# Corresponds to the JSON property `ssml`
# @return [String]
attr_accessor :ssml
# One of text_to_speech or ssml must be provided. The plain text of the
# speech output. Mutually exclusive with ssml.
# Corresponds to the JSON property `textToSpeech`
# @return [String]
attr_accessor :text_to_speech
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@display_text = args[:display_text] if args.key?(:display_text)
@ssml = args[:ssml] if args.key?(:ssml)
@text_to_speech = args[:text_to_speech] if args.key?(:text_to_speech)
end
end
# The collection of simple response candidates.
# This message in `QueryResult.fulfillment_messages` and
# `WebhookResponse.fulfillment_messages` should contain only one
# `SimpleResponse`.
class GoogleCloudDialogflowV2beta1IntentMessageSimpleResponses
include Google::Apis::Core::Hashable
# Required. The list of simple responses.
# Corresponds to the JSON property `simpleResponses`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageSimpleResponse>]
attr_accessor :simple_responses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@simple_responses = args[:simple_responses] if args.key?(:simple_responses)
end
end
# The suggestion chip message that the user can tap to quickly post a reply
# to the conversation.
class GoogleCloudDialogflowV2beta1IntentMessageSuggestion
include Google::Apis::Core::Hashable
# Required. The text shown the in the suggestion chip.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@title = args[:title] if args.key?(:title)
end
end
# The collection of suggestions.
class GoogleCloudDialogflowV2beta1IntentMessageSuggestions
include Google::Apis::Core::Hashable
# Required. The list of suggested replies.
# Corresponds to the JSON property `suggestions`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageSuggestion>]
attr_accessor :suggestions
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@suggestions = args[:suggestions] if args.key?(:suggestions)
end
end
# Table card for Actions on Google.
class GoogleCloudDialogflowV2beta1IntentMessageTableCard
include Google::Apis::Core::Hashable
# Optional. List of buttons for the card.
# Corresponds to the JSON property `buttons`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageBasicCardButton>]
attr_accessor :buttons
# Optional. Display properties for the columns in this table.
# Corresponds to the JSON property `columnProperties`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageColumnProperties>]
attr_accessor :column_properties
# The image response message.
# Corresponds to the JSON property `image`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageImage]
attr_accessor :image
# Optional. Rows in this table of data.
# Corresponds to the JSON property `rows`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageTableCardRow>]
attr_accessor :rows
# Optional. Subtitle to the title.
# Corresponds to the JSON property `subtitle`
# @return [String]
attr_accessor :subtitle
# Required. Title of the card.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@buttons = args[:buttons] if args.key?(:buttons)
@column_properties = args[:column_properties] if args.key?(:column_properties)
@image = args[:image] if args.key?(:image)
@rows = args[:rows] if args.key?(:rows)
@subtitle = args[:subtitle] if args.key?(:subtitle)
@title = args[:title] if args.key?(:title)
end
end
# Cell of TableCardRow.
class GoogleCloudDialogflowV2beta1IntentMessageTableCardCell
include Google::Apis::Core::Hashable
# Required. Text in this cell.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@text = args[:text] if args.key?(:text)
end
end
# Row of TableCard.
class GoogleCloudDialogflowV2beta1IntentMessageTableCardRow
include Google::Apis::Core::Hashable
# Optional. List of cells that make up this row.
# Corresponds to the JSON property `cells`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessageTableCardCell>]
attr_accessor :cells
# Optional. Whether to add a visual divider after this row.
# Corresponds to the JSON property `dividerAfter`
# @return [Boolean]
attr_accessor :divider_after
alias_method :divider_after?, :divider_after
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@cells = args[:cells] if args.key?(:cells)
@divider_after = args[:divider_after] if args.key?(:divider_after)
end
end
# Plays audio from a file in Telephony Gateway.
class GoogleCloudDialogflowV2beta1IntentMessageTelephonyPlayAudio
include Google::Apis::Core::Hashable
# Required. URI to a Google Cloud Storage object containing the audio to
# play, e.g., "gs://bucket/object". The object must contain a single
# channel (mono) of linear PCM audio (2 bytes / sample) at 8kHz.
# This object must be readable by the `service-<Project
# Number>@gcp-sa-dialogflow.iam.gserviceaccount.com` service account
# where <Project Number> is the number of the Telephony Gateway project
# (usually the same as the Dialogflow agent project). If the Google Cloud
# Storage bucket is in the Telephony Gateway project, this permission is
# added by default when enabling the Dialogflow V2 API.
# For audio from other sources, consider using the
# `TelephonySynthesizeSpeech` message with SSML.
# Corresponds to the JSON property `audioUri`
# @return [String]
attr_accessor :audio_uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@audio_uri = args[:audio_uri] if args.key?(:audio_uri)
end
end
# Synthesizes speech and plays back the synthesized audio to the caller in
# Telephony Gateway.
# Telephony Gateway takes the synthesizer settings from
# `DetectIntentResponse.output_audio_config` which can either be set
# at request-level or can come from the agent-level synthesizer config.
class GoogleCloudDialogflowV2beta1IntentMessageTelephonySynthesizeSpeech
include Google::Apis::Core::Hashable
# The SSML to be synthesized. For more information, see
# [SSML](https://developers.google.com/actions/reference/ssml).
# Corresponds to the JSON property `ssml`
# @return [String]
attr_accessor :ssml
# The raw text to be synthesized.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@ssml = args[:ssml] if args.key?(:ssml)
@text = args[:text] if args.key?(:text)
end
end
# Transfers the call in Telephony Gateway.
class GoogleCloudDialogflowV2beta1IntentMessageTelephonyTransferCall
include Google::Apis::Core::Hashable
# Required. The phone number to transfer the call to
# in [E.164 format](https://en.wikipedia.org/wiki/E.164).
# We currently only allow transferring to US numbers (+1xxxyyyzzzz).
# Corresponds to the JSON property `phoneNumber`
# @return [String]
attr_accessor :phone_number
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@phone_number = args[:phone_number] if args.key?(:phone_number)
end
end
# The text response message.
class GoogleCloudDialogflowV2beta1IntentMessageText
include Google::Apis::Core::Hashable
# Optional. The collection of the agent's responses.
# Corresponds to the JSON property `text`
# @return [Array<String>]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@text = args[:text] if args.key?(:text)
end
end
# Represents intent parameters.
class GoogleCloudDialogflowV2beta1IntentParameter
include Google::Apis::Core::Hashable
# Optional. The default value to use when the `value` yields an empty
# result.
# Default values can be extracted from contexts by using the following
# syntax: `#context_name.parameter_name`.
# Corresponds to the JSON property `defaultValue`
# @return [String]
attr_accessor :default_value
# Required. The name of the parameter.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# Optional. The name of the entity type, prefixed with `@`, that
# describes values of the parameter. If the parameter is
# required, this must be provided.
# Corresponds to the JSON property `entityTypeDisplayName`
# @return [String]
attr_accessor :entity_type_display_name
# Optional. Indicates whether the parameter represents a list of values.
# Corresponds to the JSON property `isList`
# @return [Boolean]
attr_accessor :is_list
alias_method :is_list?, :is_list
# Optional. Indicates whether the parameter is required. That is,
# whether the intent cannot be completed without collecting the parameter
# value.
# Corresponds to the JSON property `mandatory`
# @return [Boolean]
attr_accessor :mandatory
alias_method :mandatory?, :mandatory
# The unique identifier of this parameter.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Optional. The collection of prompts that the agent can present to the
# user in order to collect a value for the parameter.
# Corresponds to the JSON property `prompts`
# @return [Array<String>]
attr_accessor :prompts
# Optional. The definition of the parameter value. It can be:
# - a constant string,
# - a parameter value defined as `$parameter_name`,
# - an original parameter value defined as `$parameter_name.original`,
# - a parameter value from some context defined as
# `#context_name.parameter_name`.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@default_value = args[:default_value] if args.key?(:default_value)
@display_name = args[:display_name] if args.key?(:display_name)
@entity_type_display_name = args[:entity_type_display_name] if args.key?(:entity_type_display_name)
@is_list = args[:is_list] if args.key?(:is_list)
@mandatory = args[:mandatory] if args.key?(:mandatory)
@name = args[:name] if args.key?(:name)
@prompts = args[:prompts] if args.key?(:prompts)
@value = args[:value] if args.key?(:value)
end
end
# Represents an example that the agent is trained on.
class GoogleCloudDialogflowV2beta1IntentTrainingPhrase
include Google::Apis::Core::Hashable
# Output only. The unique identifier of this training phrase.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Required. The ordered list of training phrase parts.
# The parts are concatenated in order to form the training phrase.
# Note: The API does not automatically annotate training phrases like the
# Dialogflow Console does.
# Note: Do not forget to include whitespace at part boundaries,
# so the training phrase is well formatted when the parts are concatenated.
# If the training phrase does not need to be annotated with parameters,
# you just need a single part with only the Part.text field set.
# If you want to annotate the training phrase, you must create multiple
# parts, where the fields of each part are populated in one of two ways:
# - `Part.text` is set to a part of the phrase that has no parameters.
# - `Part.text` is set to a part of the phrase that you want to annotate,
# and the `entity_type`, `alias`, and `user_defined` fields are all
# set.
# Corresponds to the JSON property `parts`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentTrainingPhrasePart>]
attr_accessor :parts
# Optional. Indicates how many times this example was added to
# the intent. Each time a developer adds an existing sample by editing an
# intent or training, this counter is increased.
# Corresponds to the JSON property `timesAddedCount`
# @return [Fixnum]
attr_accessor :times_added_count
# Required. The type of the training phrase.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
@parts = args[:parts] if args.key?(:parts)
@times_added_count = args[:times_added_count] if args.key?(:times_added_count)
@type = args[:type] if args.key?(:type)
end
end
# Represents a part of a training phrase.
class GoogleCloudDialogflowV2beta1IntentTrainingPhrasePart
include Google::Apis::Core::Hashable
# Optional. The parameter name for the value extracted from the
# annotated part of the example.
# This field is required for annotated parts of the training phrase.
# Corresponds to the JSON property `alias`
# @return [String]
attr_accessor :alias
# Optional. The entity type name prefixed with `@`.
# This field is required for annotated parts of the training phrase.
# Corresponds to the JSON property `entityType`
# @return [String]
attr_accessor :entity_type
# Required. The text for this part.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
# Optional. Indicates whether the text was manually annotated.
# This field is set to true when the Dialogflow Console is used to
# manually annotate the part. When creating an annotated part with the
# API, you must set this to true.
# Corresponds to the JSON property `userDefined`
# @return [Boolean]
attr_accessor :user_defined
alias_method :user_defined?, :user_defined
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@alias = args[:alias] if args.key?(:alias)
@entity_type = args[:entity_type] if args.key?(:entity_type)
@text = args[:text] if args.key?(:text)
@user_defined = args[:user_defined] if args.key?(:user_defined)
end
end
# Represents the result of querying a Knowledge base.
class GoogleCloudDialogflowV2beta1KnowledgeAnswers
include Google::Apis::Core::Hashable
# A list of answers from Knowledge Connector.
# Corresponds to the JSON property `answers`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1KnowledgeAnswersAnswer>]
attr_accessor :answers
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@answers = args[:answers] if args.key?(:answers)
end
end
# An answer from Knowledge Connector.
class GoogleCloudDialogflowV2beta1KnowledgeAnswersAnswer
include Google::Apis::Core::Hashable
# The piece of text from the `source` knowledge base document that answers
# this conversational query.
# Corresponds to the JSON property `answer`
# @return [String]
attr_accessor :answer
# The corresponding FAQ question if the answer was extracted from a FAQ
# Document, empty otherwise.
# Corresponds to the JSON property `faqQuestion`
# @return [String]
attr_accessor :faq_question
# The system's confidence score that this Knowledge answer is a good match
# for this conversational query.
# The range is from 0.0 (completely uncertain) to 1.0 (completely certain).
# Note: The confidence score is likely to vary somewhat (possibly even for
# identical requests), as the underlying model is under constant
# improvement. It may be deprecated in the future. We recommend using
# `match_confidence_level` which should be generally more stable.
# Corresponds to the JSON property `matchConfidence`
# @return [Float]
attr_accessor :match_confidence
# The system's confidence level that this knowledge answer is a good match
# for this conversational query.
# NOTE: The confidence level for a given `<query, answer>` pair may change
# without notice, as it depends on models that are constantly being
# improved. However, it will change less frequently than the confidence
# score below, and should be preferred for referencing the quality of an
# answer.
# Corresponds to the JSON property `matchConfidenceLevel`
# @return [String]
attr_accessor :match_confidence_level
# Indicates which Knowledge Document this answer was extracted from.
# Format: `projects/<Project ID>/knowledgeBases/<Knowledge Base
# ID>/documents/<Document ID>`.
# Corresponds to the JSON property `source`
# @return [String]
attr_accessor :source
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@answer = args[:answer] if args.key?(:answer)
@faq_question = args[:faq_question] if args.key?(:faq_question)
@match_confidence = args[:match_confidence] if args.key?(:match_confidence)
@match_confidence_level = args[:match_confidence_level] if args.key?(:match_confidence_level)
@source = args[:source] if args.key?(:source)
end
end
# Metadata in google::longrunning::Operation for Knowledge operations.
class GoogleCloudDialogflowV2beta1KnowledgeOperationMetadata
include Google::Apis::Core::Hashable
# Required. The current state of this operation.
# Corresponds to the JSON property `state`
# @return [String]
attr_accessor :state
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@state = args[:state] if args.key?(:state)
end
end
# The response for
# ConversationDatasets.LabelConversation.
class GoogleCloudDialogflowV2beta1LabelConversationResponse
include Google::Apis::Core::Hashable
# Represents an annotated conversation dataset.
# ConversationDataset can have multiple AnnotatedConversationDataset, each of
# them represents one result from one annotation task.
# AnnotatedConversationDataset can only be generated from annotation task,
# which will be triggered by LabelConversation.
# Corresponds to the JSON property `annotatedConversationDataset`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1AnnotatedConversationDataset]
attr_accessor :annotated_conversation_dataset
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@annotated_conversation_dataset = args[:annotated_conversation_dataset] if args.key?(:annotated_conversation_dataset)
end
end
# Represents the contents of the original request that was passed to
# the `[Streaming]DetectIntent` call.
class GoogleCloudDialogflowV2beta1OriginalDetectIntentRequest
include Google::Apis::Core::Hashable
# Optional. This field is set to the value of the `QueryParameters.payload`
# field passed in the request. Some integrations that query a Dialogflow
# agent may provide additional information in the payload.
# In particular for the Telephony Gateway this field has the form:
# <pre>`
# "telephony": `
# "caller_id": "+18558363987"
# `
# `</pre>
# Note: The caller ID field (`caller_id`) will be redacted for Standard
# Edition agents and populated with the caller ID in [E.164
# format](https://en.wikipedia.org/wiki/E.164) for Enterprise Edition agents.
# Corresponds to the JSON property `payload`
# @return [Hash<String,Object>]
attr_accessor :payload
# The source of this request, e.g., `google`, `facebook`, `slack`. It is set
# by Dialogflow-owned servers.
# Corresponds to the JSON property `source`
# @return [String]
attr_accessor :source
# Optional. The version of the protocol used for this request.
# This field is AoG-specific.
# Corresponds to the JSON property `version`
# @return [String]
attr_accessor :version
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@payload = args[:payload] if args.key?(:payload)
@source = args[:source] if args.key?(:source)
@version = args[:version] if args.key?(:version)
end
end
# Represents the result of conversational query or event processing.
class GoogleCloudDialogflowV2beta1QueryResult
include Google::Apis::Core::Hashable
# The action name from the matched intent.
# Corresponds to the JSON property `action`
# @return [String]
attr_accessor :action
# This field is set to:
# - `false` if the matched intent has required parameters and not all of
# the required parameter values have been collected.
# - `true` if all required parameter values have been collected, or if the
# matched intent doesn't contain any required parameters.
# Corresponds to the JSON property `allRequiredParamsPresent`
# @return [Boolean]
attr_accessor :all_required_params_present
alias_method :all_required_params_present?, :all_required_params_present
# Free-form diagnostic information for the associated detect intent request.
# The fields of this data can change without notice, so you should not write
# code that depends on its structure.
# The data may contain:
# - webhook call latency
# - webhook errors
# Corresponds to the JSON property `diagnosticInfo`
# @return [Hash<String,Object>]
attr_accessor :diagnostic_info
# The collection of rich messages to present to the user.
# Corresponds to the JSON property `fulfillmentMessages`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessage>]
attr_accessor :fulfillment_messages
# The text to be pronounced to the user or shown on the screen.
# Note: This is a legacy field, `fulfillment_messages` should be preferred.
# Corresponds to the JSON property `fulfillmentText`
# @return [String]
attr_accessor :fulfillment_text
# Represents an intent.
# Intents convert a number of user expressions or patterns into an action. An
# action is an extraction of a user command or sentence semantics.
# Corresponds to the JSON property `intent`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1Intent]
attr_accessor :intent
# The intent detection confidence. Values range from 0.0
# (completely uncertain) to 1.0 (completely certain).
# This value is for informational purpose only and is only used to
# help match the best intent within the classification threshold.
# This value may change for the same end-user expression at any time due to a
# model retraining or change in implementation.
# If there are `multiple knowledge_answers` messages, this value is set to
# the greatest `knowledgeAnswers.match_confidence` value in the list.
# Corresponds to the JSON property `intentDetectionConfidence`
# @return [Float]
attr_accessor :intent_detection_confidence
# Represents the result of querying a Knowledge base.
# Corresponds to the JSON property `knowledgeAnswers`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1KnowledgeAnswers]
attr_accessor :knowledge_answers
# The language that was triggered during intent detection.
# See [Language
# Support](https://cloud.google.com/dialogflow/docs/reference/language)
# for a list of the currently supported language codes.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# The collection of output contexts. If applicable,
# `output_contexts.parameters` contains entries with name
# `<parameter name>.original` containing the original parameter values
# before the query.
# Corresponds to the JSON property `outputContexts`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1Context>]
attr_accessor :output_contexts
# The collection of extracted parameters.
# Corresponds to the JSON property `parameters`
# @return [Hash<String,Object>]
attr_accessor :parameters
# The original conversational query text:
# - If natural language text was provided as input, `query_text` contains
# a copy of the input.
# - If natural language speech audio was provided as input, `query_text`
# contains the speech recognition result. If speech recognizer produced
# multiple alternatives, a particular one is picked.
# - If automatic spell correction is enabled, `query_text` will contain the
# corrected user input.
# Corresponds to the JSON property `queryText`
# @return [String]
attr_accessor :query_text
# The result of sentiment analysis as configured by
# `sentiment_analysis_request_config`.
# Corresponds to the JSON property `sentimentAnalysisResult`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1SentimentAnalysisResult]
attr_accessor :sentiment_analysis_result
# The Speech recognition confidence between 0.0 and 1.0. A higher number
# indicates an estimated greater likelihood that the recognized words are
# correct. The default of 0.0 is a sentinel value indicating that confidence
# was not set.
# This field is not guaranteed to be accurate or set. In particular this
# field isn't set for StreamingDetectIntent since the streaming endpoint has
# separate confidence estimates per portion of the audio in
# StreamingRecognitionResult.
# Corresponds to the JSON property `speechRecognitionConfidence`
# @return [Float]
attr_accessor :speech_recognition_confidence
# If the query was fulfilled by a webhook call, this field is set to the
# value of the `payload` field returned in the webhook response.
# Corresponds to the JSON property `webhookPayload`
# @return [Hash<String,Object>]
attr_accessor :webhook_payload
# If the query was fulfilled by a webhook call, this field is set to the
# value of the `source` field returned in the webhook response.
# Corresponds to the JSON property `webhookSource`
# @return [String]
attr_accessor :webhook_source
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action = args[:action] if args.key?(:action)
@all_required_params_present = args[:all_required_params_present] if args.key?(:all_required_params_present)
@diagnostic_info = args[:diagnostic_info] if args.key?(:diagnostic_info)
@fulfillment_messages = args[:fulfillment_messages] if args.key?(:fulfillment_messages)
@fulfillment_text = args[:fulfillment_text] if args.key?(:fulfillment_text)
@intent = args[:intent] if args.key?(:intent)
@intent_detection_confidence = args[:intent_detection_confidence] if args.key?(:intent_detection_confidence)
@knowledge_answers = args[:knowledge_answers] if args.key?(:knowledge_answers)
@language_code = args[:language_code] if args.key?(:language_code)
@output_contexts = args[:output_contexts] if args.key?(:output_contexts)
@parameters = args[:parameters] if args.key?(:parameters)
@query_text = args[:query_text] if args.key?(:query_text)
@sentiment_analysis_result = args[:sentiment_analysis_result] if args.key?(:sentiment_analysis_result)
@speech_recognition_confidence = args[:speech_recognition_confidence] if args.key?(:speech_recognition_confidence)
@webhook_payload = args[:webhook_payload] if args.key?(:webhook_payload)
@webhook_source = args[:webhook_source] if args.key?(:webhook_source)
end
end
# The sentiment, such as positive/negative feeling or association, for a unit
# of analysis, such as the query text.
class GoogleCloudDialogflowV2beta1Sentiment
include Google::Apis::Core::Hashable
# A non-negative number in the [0, +inf) range, which represents the absolute
# magnitude of sentiment, regardless of score (positive or negative).
# Corresponds to the JSON property `magnitude`
# @return [Float]
attr_accessor :magnitude
# Sentiment score between -1.0 (negative sentiment) and 1.0 (positive
# sentiment).
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@magnitude = args[:magnitude] if args.key?(:magnitude)
@score = args[:score] if args.key?(:score)
end
end
# The result of sentiment analysis as configured by
# `sentiment_analysis_request_config`.
class GoogleCloudDialogflowV2beta1SentimentAnalysisResult
include Google::Apis::Core::Hashable
# The sentiment, such as positive/negative feeling or association, for a unit
# of analysis, such as the query text.
# Corresponds to the JSON property `queryTextSentiment`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1Sentiment]
attr_accessor :query_text_sentiment
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@query_text_sentiment = args[:query_text_sentiment] if args.key?(:query_text_sentiment)
end
end
# Represents a session entity type.
# Extends or replaces a custom entity type at the user session level (we
# refer to the entity types defined at the agent level as "custom entity
# types").
# Note: session entity types apply to all queries, regardless of the language.
class GoogleCloudDialogflowV2beta1SessionEntityType
include Google::Apis::Core::Hashable
# Required. The collection of entities associated with this session entity
# type.
# Corresponds to the JSON property `entities`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1EntityTypeEntity>]
attr_accessor :entities
# Required. Indicates whether the additional data should override or
# supplement the custom entity type definition.
# Corresponds to the JSON property `entityOverrideMode`
# @return [String]
attr_accessor :entity_override_mode
# Required. The unique identifier of this session entity type. Format:
# `projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type
# Display Name>`, or
# `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
# ID>/sessions/<Session ID>/entityTypes/<Entity Type Display Name>`.
# If `Environment ID` is not specified, we assume default 'draft'
# environment. If `User ID` is not specified, we assume default '-' user.
# `<Entity Type Display Name>` must be the display name of an existing entity
# type in the same agent that will be overridden or supplemented.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entities = args[:entities] if args.key?(:entities)
@entity_override_mode = args[:entity_override_mode] if args.key?(:entity_override_mode)
@name = args[:name] if args.key?(:name)
end
end
# The request message for a webhook call.
class GoogleCloudDialogflowV2beta1WebhookRequest
include Google::Apis::Core::Hashable
# Alternative query results from KnowledgeService.
# Corresponds to the JSON property `alternativeQueryResults`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1QueryResult>]
attr_accessor :alternative_query_results
# Represents the contents of the original request that was passed to
# the `[Streaming]DetectIntent` call.
# Corresponds to the JSON property `originalDetectIntentRequest`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1OriginalDetectIntentRequest]
attr_accessor :original_detect_intent_request
# Represents the result of conversational query or event processing.
# Corresponds to the JSON property `queryResult`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1QueryResult]
attr_accessor :query_result
# The unique identifier of the response. Contains the same value as
# `[Streaming]DetectIntentResponse.response_id`.
# Corresponds to the JSON property `responseId`
# @return [String]
attr_accessor :response_id
# The unique identifier of detectIntent request session.
# Can be used to identify end-user inside webhook implementation.
# Format: `projects/<Project ID>/agent/sessions/<Session ID>`, or
# `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
# ID>/sessions/<Session ID>`.
# Corresponds to the JSON property `session`
# @return [String]
attr_accessor :session
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@alternative_query_results = args[:alternative_query_results] if args.key?(:alternative_query_results)
@original_detect_intent_request = args[:original_detect_intent_request] if args.key?(:original_detect_intent_request)
@query_result = args[:query_result] if args.key?(:query_result)
@response_id = args[:response_id] if args.key?(:response_id)
@session = args[:session] if args.key?(:session)
end
end
# The response message for a webhook call.
# This response is validated by the Dialogflow server. If validation fails,
# an error will be returned in the QueryResult.diagnostic_info field.
# Setting JSON fields to an empty value with the wrong type is a common error.
# To avoid this error:
# - Use `""` for empty strings
# - Use ```` or `null` for empty objects
# - Use `[]` or `null` for empty arrays
# For more information, see the
# [Protocol Buffers Language
# Guide](https://developers.google.com/protocol-buffers/docs/proto3#json).
class GoogleCloudDialogflowV2beta1WebhookResponse
include Google::Apis::Core::Hashable
# Optional. Indicates that this intent ends an interaction. Some integrations
# (e.g., Actions on Google or Dialogflow phone gateway) use this information
# to close interaction with an end user. Default is false.
# Corresponds to the JSON property `endInteraction`
# @return [Boolean]
attr_accessor :end_interaction
alias_method :end_interaction?, :end_interaction
# Events allow for matching intents by event name instead of the natural
# language input. For instance, input `<event: ` name: "welcome_event",
# parameters: ` name: "Sam" ` `>` can trigger a personalized welcome response.
# The parameter `name` may be used by the agent in the response:
# `"Hello #welcome_event.name! What can I do for you today?"`.
# Corresponds to the JSON property `followupEventInput`
# @return [Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1EventInput]
attr_accessor :followup_event_input
# Optional. The collection of rich messages to present to the user. This
# value is passed directly to `QueryResult.fulfillment_messages`.
# Corresponds to the JSON property `fulfillmentMessages`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1IntentMessage>]
attr_accessor :fulfillment_messages
# Optional. The text to be shown on the screen. This value is passed directly
# to `QueryResult.fulfillment_text`.
# Corresponds to the JSON property `fulfillmentText`
# @return [String]
attr_accessor :fulfillment_text
# Optional. The collection of output contexts. This value is passed directly
# to `QueryResult.output_contexts`.
# Corresponds to the JSON property `outputContexts`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1Context>]
attr_accessor :output_contexts
# Optional. This value is passed directly to `QueryResult.webhook_payload`.
# See the related `fulfillment_messages[i].payload field`, which may be used
# as an alternative to this field.
# This field can be used for Actions on Google responses.
# It should have a structure similar to the JSON message shown here. For more
# information, see
# [Actions on Google Webhook
# Format](https://developers.google.com/actions/dialogflow/webhook)
# <pre>`
# "google": `
# "expectUserResponse": true,
# "richResponse": `
# "items": [
# `
# "simpleResponse": `
# "textToSpeech": "this is a simple response"
# `
# `
# ]
# `
# `
# `</pre>
# Corresponds to the JSON property `payload`
# @return [Hash<String,Object>]
attr_accessor :payload
# Optional. Additional session entity types to replace or extend developer
# entity types with. The entity synonyms apply to all languages and persist
# for the session of this query. Setting the session entity types inside
# webhook overwrites the session entity types that have been set through
# `DetectIntentRequest.query_params.session_entity_types`.
# Corresponds to the JSON property `sessionEntityTypes`
# @return [Array<Google::Apis::DialogflowV2::GoogleCloudDialogflowV2beta1SessionEntityType>]
attr_accessor :session_entity_types
# Optional. This value is passed directly to `QueryResult.webhook_source`.
# Corresponds to the JSON property `source`
# @return [String]
attr_accessor :source
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@end_interaction = args[:end_interaction] if args.key?(:end_interaction)
@followup_event_input = args[:followup_event_input] if args.key?(:followup_event_input)
@fulfillment_messages = args[:fulfillment_messages] if args.key?(:fulfillment_messages)
@fulfillment_text = args[:fulfillment_text] if args.key?(:fulfillment_text)
@output_contexts = args[:output_contexts] if args.key?(:output_contexts)
@payload = args[:payload] if args.key?(:payload)
@session_entity_types = args[:session_entity_types] if args.key?(:session_entity_types)
@source = args[:source] if args.key?(:source)
end
end
# The response message for Operations.ListOperations.
class GoogleLongrunningListOperationsResponse
include Google::Apis::Core::Hashable
# The standard List next-page token.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
# A list of operations that matches the specified filter in the request.
# Corresponds to the JSON property `operations`
# @return [Array<Google::Apis::DialogflowV2::GoogleLongrunningOperation>]
attr_accessor :operations
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
@operations = args[:operations] if args.key?(:operations)
end
end
# This resource represents a long-running operation that is the result of a
# network API call.
class GoogleLongrunningOperation
include Google::Apis::Core::Hashable
# If the value is `false`, it means the operation is still in progress.
# If `true`, the operation is completed, and either `error` or `response` is
# available.
# Corresponds to the JSON property `done`
# @return [Boolean]
attr_accessor :done
alias_method :done?, :done
# The `Status` type defines a logical error model that is suitable for
# different programming environments, including REST APIs and RPC APIs. It is
# used by [gRPC](https://github.com/grpc). Each `Status` message contains
# three pieces of data: error code, error message, and error details.
# You can find out more about this error model and how to work with it in the
# [API Design Guide](https://cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::DialogflowV2::GoogleRpcStatus]
attr_accessor :error
# Service-specific metadata associated with the operation. It typically
# contains progress information and common metadata such as create time.
# Some services might not provide such metadata. Any method that returns a
# long-running operation should document the metadata type, if any.
# Corresponds to the JSON property `metadata`
# @return [Hash<String,Object>]
attr_accessor :metadata
# The server-assigned name, which is only unique within the same service that
# originally returns it. If you use the default HTTP mapping, the
# `name` should be a resource name ending with `operations/`unique_id``.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# The normal response of the operation in case of success. If the original
# method returns no data on success, such as `Delete`, the response is
# `google.protobuf.Empty`. If the original method is standard
# `Get`/`Create`/`Update`, the response should be the resource. For other
# methods, the response should have the type `XxxResponse`, where `Xxx`
# is the original method name. For example, if the original method name
# is `TakeSnapshot()`, the inferred response type is
# `TakeSnapshotResponse`.
# Corresponds to the JSON property `response`
# @return [Hash<String,Object>]
attr_accessor :response
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@done = args[:done] if args.key?(:done)
@error = args[:error] if args.key?(:error)
@metadata = args[:metadata] if args.key?(:metadata)
@name = args[:name] if args.key?(:name)
@response = args[:response] if args.key?(:response)
end
end
# A generic empty message that you can re-use to avoid defining duplicated
# empty messages in your APIs. A typical example is to use it as the request
# or the response type of an API method. For instance:
# service Foo `
# rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
# `
# The JSON representation for `Empty` is empty JSON object ````.
class GoogleProtobufEmpty
include Google::Apis::Core::Hashable
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
end
end
# The `Status` type defines a logical error model that is suitable for
# different programming environments, including REST APIs and RPC APIs. It is
# used by [gRPC](https://github.com/grpc). Each `Status` message contains
# three pieces of data: error code, error message, and error details.
# You can find out more about this error model and how to work with it in the
# [API Design Guide](https://cloud.google.com/apis/design/errors).
class GoogleRpcStatus
include Google::Apis::Core::Hashable
# The status code, which should be an enum value of google.rpc.Code.
# Corresponds to the JSON property `code`
# @return [Fixnum]
attr_accessor :code
# A list of messages that carry the error details. There is a common set of
# message types for APIs to use.
# Corresponds to the JSON property `details`
# @return [Array<Hash<String,Object>>]
attr_accessor :details
# A developer-facing error message, which should be in English. Any
# user-facing error message should be localized and sent in the
# google.rpc.Status.details field, or localized by the client.
# Corresponds to the JSON property `message`
# @return [String]
attr_accessor :message
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@code = args[:code] if args.key?(:code)
@details = args[:details] if args.key?(:details)
@message = args[:message] if args.key?(:message)
end
end
# An object representing a latitude/longitude pair. This is expressed as a pair
# of doubles representing degrees latitude and degrees longitude. Unless
# specified otherwise, this must conform to the
# <a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84
# standard</a>. Values must be within normalized ranges.
class GoogleTypeLatLng
include Google::Apis::Core::Hashable
# The latitude in degrees. It must be in the range [-90.0, +90.0].
# Corresponds to the JSON property `latitude`
# @return [Float]
attr_accessor :latitude
# The longitude in degrees. It must be in the range [-180.0, +180.0].
# Corresponds to the JSON property `longitude`
# @return [Float]
attr_accessor :longitude
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@latitude = args[:latitude] if args.key?(:latitude)
@longitude = args[:longitude] if args.key?(:longitude)
end
end
end
end
end
| 42.662061 | 142 | 0.640296 |
21f474cd76e033f2f2aa7405283fe5a407502b6d | 1,705 | #
# Be sure to run `pod lib lint AVCompositionDebugView.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 https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'AVCompositionDebugView'
s.version = '0.1.0'
s.summary = 'A short description of AVCompositionDebugView.'
# 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.description = <<-DESC
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/TizianoCoroneo/AVCompositionDebugView'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'TizianoCoroneo' => '[email protected]' }
s.source = { :git => 'https://github.com/TizianoCoroneo/AVCompositionDebugView.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '11.0'
s.source_files = 'AVCompositionDebugView/Classes/**/*'
# s.resource_bundles = {
# 'AVCompositionDebugView' => ['AVCompositionDebugView/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 39.651163 | 121 | 0.660411 |
267a49d4d8552acd2ce16ce6f09f09ea33ad71a5 | 10,006 | # bandwidth
#
# This file was automatically generated by APIMATIC v2.0
# ( https://apimatic.io ).
module Bandwidth
# API utility class
class APIHelper
# Serializes an array parameter (creates key value pairs).
# @param [String] The name of the parameter.
# @param [Array] The value of the parameter.
# @param [String] The format of the serialization.
def self.serialize_array(key, array, formatting: 'indexed')
tuples = []
if formatting == 'unindexed'
tuples += array.map { |element| ["#{key}[]", element] }
elsif formatting == 'indexed'
tuples += array.map.with_index do |element, index|
["#{key}[#{index}]", element]
end
elsif formatting == 'plain'
tuples += array.map { |element| [key, element] }
else
raise ArgumentError, 'Invalid format provided.'
end
tuples
end
# Replaces template parameters in the given url.
# @param [String] The query string builder to replace the template
# parameters.
# @param [Hash] The parameters to replace in the url.
def self.append_url_with_template_parameters(query_builder, parameters)
# perform parameter validation
unless query_builder.instance_of? String
raise ArgumentError, 'Given value for parameter \"query_builder\" is
invalid.'
end
# Return if there are no parameters to replace.
return query_builder if parameters.nil?
# Iterate and append parameters.
parameters.each do |key, value|
replace_value = ''
if value.nil?
replace_value = ''
elsif value.instance_of? Array
value.map! { |element| CGI.escape(element.to_s) }
replace_value = value.join('/')
else
replace_value = CGI.escape(value.to_s)
end
# Find the template parameter and replace it with its value.
query_builder = query_builder.gsub('{' + key.to_s + '}', replace_value)
end
query_builder
end
# Appends the given set of parameters to the given query string.
# @param [String] The query string builder to add the query parameters to.
# @param [Hash] The parameters to append.
# @param [String] The format of array parameter serialization.
def self.append_url_with_query_parameters(query_builder, parameters,
array_serialization: 'indexed')
# Perform parameter validation.
unless query_builder.instance_of? String
raise ArgumentError, 'Given value for parameter \"query_builder\"
is invalid.'
end
# Return if there are no parameters to replace.
return query_builder if parameters.nil?
parameters.each do |key, value|
seperator = query_builder.include?('?') ? '&' : '?'
unless value.nil?
if value.instance_of? Array
value.compact!
query_builder += if array_serialization == 'csv'
"#{seperator}#{key}=#{value.map do |element|
CGI.escape(element.to_s)
end.join(',')}"
elsif array_serialization == 'psv'
"#{seperator}#{key}=#{value.map do |element|
CGI.escape(element.to_s)
end.join('|')}"
elsif array_serialization == 'tsv'
"#{seperator}#{key}=#{value.map do |element|
CGI.escape(element.to_s)
end.join("\t")}"
else
"#{seperator}#{APIHelper.serialize_array(
key, value, formatting: array_serialization
).map { |k, v| "#{k}=#{CGI.escape(v.to_s)}" }
.join('&')}"
end
else
query_builder += "#{seperator}#{key}=#{CGI.escape(value.to_s)}"
end
end
end
query_builder
end
# Validates and processes the given Url.
# @param [String] The given Url to process.
# @return [String] Pre-processed Url as string.
def self.clean_url(url)
# Perform parameter validation.
raise ArgumentError, 'Invalid Url.' unless url.instance_of? String
# Ensure that the urls are absolute.
matches = url.match(%r{^(https?:\/\/[^\/]+)})
raise ArgumentError, 'Invalid Url format.' if matches.nil?
# Get the http protocol match.
protocol = matches[1]
# Check if parameters exist.
index = url.index('?')
# Remove redundant forward slashes.
query = url[protocol.length...(!index.nil? ? index : url.length)]
query.gsub!(%r{\/\/+}, '/')
# Get the parameters.
parameters = !index.nil? ? url[url.index('?')...url.length] : ''
# Return processed url.
protocol + query + parameters
end
# Parses JSON string.
# @param [String] A JSON string.
def self.json_deserialize(json)
return JSON.parse(json)
rescue StandardError
raise TypeError, 'Server responded with invalid JSON.'
end
# Removes elements with empty values from a hash.
# @param [Hash] The hash to clean.
def self.clean_hash(hash)
hash.delete_if { |_key, value| value.to_s.strip.empty? }
end
# Form encodes a hash of parameters.
# @param [Hash] The hash of parameters to encode.
# @return [Hash] A hash with the same parameters form encoded.
def self.form_encode_parameters(form_parameters,
array_serialization: 'indexed')
encoded = {}
form_parameters.each do |key, value|
encoded.merge!(APIHelper.form_encode(value, key, formatting:
array_serialization))
end
encoded
end
def self.custom_merge(a, b)
x = {}
a.each do |key, value_a|
b.each do |k, value_b|
next unless key == k
x[k] = []
if value_a.instance_of? Array
value_a.each do |v|
x[k].push(v)
end
else
x[k].push(value_a)
end
if value_b.instance_of? Array
value_b.each do |v|
x[k].push(v)
end
else
x[k].push(value_b)
end
a.delete(k)
b.delete(k)
end
end
x.merge!(a)
x.merge!(b)
x
end
# Form encodes an object.
# @param [Dynamic] An object to form encode.
# @param [String] The name of the object.
# @return [Hash] A form encoded representation of the object in the form
# of a hash.
def self.form_encode(obj, instance_name, formatting: 'indexed')
retval = {}
serializable_types = [String, Numeric, TrueClass,
FalseClass, Date, DateTime]
# If this is a structure, resolve it's field names.
obj = obj.to_hash if obj.is_a? BaseModel
# Create a form encoded hash for this object.
if obj.nil?
nil
elsif obj.instance_of? Array
if formatting == 'indexed'
obj.each_with_index do |value, index|
retval.merge!(APIHelper.form_encode(value, instance_name + '[' +
index.to_s + ']'))
end
elsif serializable_types.map { |x| obj[0].is_a? x }.any?
obj.each do |value|
abc = if formatting == 'unindexed'
APIHelper.form_encode(value, instance_name + '[]',
formatting: formatting)
else
APIHelper.form_encode(value, instance_name,
formatting: formatting)
end
retval = APIHelper.custom_merge(retval, abc)
end
else
obj.each_with_index do |value, index|
retval.merge!(APIHelper.form_encode(value, instance_name + '[' +
index.to_s + ']', formatting: formatting))
end
end
elsif obj.instance_of? Hash
obj.each do |key, value|
retval.merge!(APIHelper.form_encode(value, instance_name + '[' +
key.to_s + ']', formatting: formatting))
end
elsif obj.instance_of? File
retval[instance_name] = UploadIO.new(
obj, 'application/octet-stream', File.basename(obj.path)
)
else
retval[instance_name] = obj
end
retval
end
# Retrieves a field from a Hash/Array based on an Array of keys/indexes
# @param [Hash, Array] The hash to extract data from
# @param [Array<String, Integer>] The keys/indexes to use
# @return [Object] The extracted value
def self.map_response(obj, keys)
val = obj
begin
keys.each do |key|
val = if val.is_a? Array
if key.to_i.to_s == key
val[key.to_i]
else
val = nil
end
else
val.fetch(key.to_sym)
end
end
rescue NoMethodError, TypeError, IndexError
val = nil
end
val
end
# Safely converts a string into an rfc3339 DateTime object
# @param [String] The datetime string
# @return [DateTime] A DateTime object of rfc3339 format
def self.rfc3339(date_time)
# missing timezone information
if date_time.end_with?('Z') || date_time.index('+')
DateTime.rfc3339(date_time)
else
DateTime.rfc3339(date_time + 'Z')
end
end
end
end
| 35.108772 | 80 | 0.539476 |
6a3d56a6e2db1cbb7f03bad2d7752a1cb4d304e2 | 347 | FactoryBot.define do
factory :category do
resume
name { Faker::Lorem.word }
factory :category_with_items do
transient do
item_count { 5 }
end
after_create do |category, evaluator|
create_list(:list_item, evaluator.item_count, category: category)
category.reload
end
end
end
end
| 20.411765 | 73 | 0.645533 |
1cb3b4fb21e3f61f827149cbcf06be58eb3fa638 | 18,248 | # frozen_string_literal: true
require "bundler/compatibility_guard"
require "bundler/vendored_fileutils"
require "pathname"
require "rbconfig"
require "thread"
require "bundler/errors"
require "bundler/environment_preserver"
require "bundler/plugin"
require "bundler/rubygems_ext"
require "bundler/rubygems_integration"
require "bundler/version"
require "bundler/constants"
require "bundler/current_ruby"
require "bundler/build_metadata"
module Bundler
environment_preserver = EnvironmentPreserver.new(ENV, EnvironmentPreserver::BUNDLER_KEYS)
ORIGINAL_ENV = environment_preserver.restore
ENV.replace(environment_preserver.backup)
SUDO_MUTEX = Mutex.new
autoload :Definition, "bundler/definition"
autoload :Dependency, "bundler/dependency"
autoload :DepProxy, "bundler/dep_proxy"
autoload :Deprecate, "bundler/deprecate"
autoload :Dsl, "bundler/dsl"
autoload :EndpointSpecification, "bundler/endpoint_specification"
autoload :Env, "bundler/env"
autoload :Fetcher, "bundler/fetcher"
autoload :FeatureFlag, "bundler/feature_flag"
autoload :GemHelper, "bundler/gem_helper"
autoload :GemHelpers, "bundler/gem_helpers"
autoload :GemRemoteFetcher, "bundler/gem_remote_fetcher"
autoload :GemVersionPromoter, "bundler/gem_version_promoter"
autoload :Graph, "bundler/graph"
autoload :Index, "bundler/index"
autoload :Injector, "bundler/injector"
autoload :Installer, "bundler/installer"
autoload :LazySpecification, "bundler/lazy_specification"
autoload :LockfileParser, "bundler/lockfile_parser"
autoload :MatchPlatform, "bundler/match_platform"
autoload :ProcessLock, "bundler/process_lock"
autoload :RemoteSpecification, "bundler/remote_specification"
autoload :Resolver, "bundler/resolver"
autoload :Retry, "bundler/retry"
autoload :RubyDsl, "bundler/ruby_dsl"
autoload :RubyGemsGemInstaller, "bundler/rubygems_gem_installer"
autoload :RubyVersion, "bundler/ruby_version"
autoload :Runtime, "bundler/runtime"
autoload :Settings, "bundler/settings"
autoload :SharedHelpers, "bundler/shared_helpers"
autoload :Source, "bundler/source"
autoload :SourceList, "bundler/source_list"
autoload :SpecSet, "bundler/spec_set"
autoload :StubSpecification, "bundler/stub_specification"
autoload :UI, "bundler/ui"
autoload :URICredentialsFilter, "bundler/uri_credentials_filter"
autoload :VersionRanges, "bundler/version_ranges"
class << self
def configure
@configured ||= configure_gem_home_and_path
end
def ui
(defined?(@ui) && @ui) || (self.ui = UI::Silent.new)
end
def ui=(ui)
Bundler.rubygems.ui = ui ? UI::RGProxy.new(ui) : nil
@ui = ui
end
# Returns absolute path of where gems are installed on the filesystem.
def bundle_path
@bundle_path ||= Pathname.new(configured_bundle_path.path).expand_path(root)
end
def configured_bundle_path
@configured_bundle_path ||= settings.path.tap(&:validate!)
end
# Returns absolute location of where binstubs are installed to.
def bin_path
@bin_path ||= begin
path = settings[:bin] || "bin"
path = Pathname.new(path).expand_path(root).expand_path
SharedHelpers.filesystem_access(path) {|p| FileUtils.mkdir_p(p) }
path
end
end
def setup(*groups)
# Return if all groups are already loaded
return @setup if defined?(@setup) && @setup
definition.validate_runtime!
SharedHelpers.print_major_deprecations!
if groups.empty?
# Load all groups, but only once
@setup = load.setup
else
load.setup(*groups)
end
end
def require(*groups)
setup(*groups).require(*groups)
end
def load
@load ||= Runtime.new(root, definition)
end
def environment
SharedHelpers.major_deprecation 2, "Bundler.environment has been removed in favor of Bundler.load"
load
end
# Returns an instance of Bundler::Definition for given Gemfile and lockfile
#
# @param unlock [Hash, Boolean, nil] Gems that have been requested
# to be updated or true if all gems should be updated
# @return [Bundler::Definition]
def definition(unlock = nil)
@definition = nil if unlock
@definition ||= begin
configure
Definition.build(default_gemfile, default_lockfile, unlock)
end
end
def frozen_bundle?
frozen = settings[:deployment]
frozen ||= settings[:frozen] unless feature_flag.deployment_means_frozen?
frozen
end
def locked_gems
@locked_gems ||=
if defined?(@definition) && @definition
definition.locked_gems
elsif Bundler.default_lockfile.file?
lock = Bundler.read_file(Bundler.default_lockfile)
LockfileParser.new(lock)
end
end
def ruby_scope
"#{Bundler.rubygems.ruby_engine}/#{Bundler.rubygems.config_map[:ruby_version]}"
end
def user_home
@user_home ||= begin
home = Bundler.rubygems.user_home
bundle_home = home ? File.join(home, ".bundle") : nil
warning = if home.nil?
"Your home directory is not set."
elsif !File.directory?(home)
"`#{home}` is not a directory."
elsif !File.writable?(home) && (!File.directory?(bundle_home) || !File.writable?(bundle_home))
"`#{home}` is not writable."
end
if warning
Kernel.send(:require, "etc")
user_home = tmp_home_path(Etc.getlogin, warning)
Bundler.ui.warn "#{warning}\nBundler will use `#{user_home}' as your home directory temporarily.\n"
user_home
else
Pathname.new(home)
end
end
end
def tmp_home_path(login, warning)
login ||= "unknown"
Kernel.send(:require, "tmpdir")
path = Pathname.new(Dir.tmpdir).join("bundler", "home")
SharedHelpers.filesystem_access(path) do |tmp_home_path|
unless tmp_home_path.exist?
tmp_home_path.mkpath
tmp_home_path.chmod(0o777)
end
tmp_home_path.join(login).tap(&:mkpath)
end
rescue RuntimeError => e
raise e.exception("#{warning}\nBundler also failed to create a temporary home directory at `#{path}':\n#{e}")
end
def user_bundle_path(dir = "home")
env_var, fallback = case dir
when "home"
["BUNDLE_USER_HOME", Pathname.new(user_home).join(".bundle")]
when "cache"
["BUNDLE_USER_CACHE", user_bundle_path.join("cache")]
when "config"
["BUNDLE_USER_CONFIG", user_bundle_path.join("config")]
when "plugin"
["BUNDLE_USER_PLUGIN", user_bundle_path.join("plugin")]
else
raise BundlerError, "Unknown user path requested: #{dir}"
end
# `fallback` will already be a Pathname, but Pathname.new() is
# idempotent so it's OK
Pathname.new(ENV.fetch(env_var, fallback))
end
def user_cache
user_bundle_path("cache")
end
def home
bundle_path.join("bundler")
end
def install_path
home.join("gems")
end
def specs_path
bundle_path.join("specifications")
end
def root
@root ||= begin
SharedHelpers.root
rescue GemfileNotFound
bundle_dir = default_bundle_dir
raise GemfileNotFound, "Could not locate Gemfile or .bundle/ directory" unless bundle_dir
Pathname.new(File.expand_path("..", bundle_dir))
end
end
def app_config_path
if app_config = ENV["BUNDLE_APP_CONFIG"]
Pathname.new(app_config).expand_path(root)
else
root.join(".bundle")
end
end
def app_cache(custom_path = nil)
path = custom_path || root
Pathname.new(path).join(settings.app_cache_path)
end
def tmp(name = Process.pid.to_s)
Kernel.send(:require, "tmpdir")
Pathname.new(Dir.mktmpdir(["bundler", name]))
end
def rm_rf(path)
FileUtils.remove_entry_secure(path) if path && File.exist?(path)
rescue ArgumentError
message = <<EOF
It is a security vulnerability to allow your home directory to be world-writable, and bundler can not continue.
You should probably consider fixing this issue by running `chmod o-w ~` on *nix.
Please refer to http://ruby-doc.org/stdlib-2.1.2/libdoc/fileutils/rdoc/FileUtils.html#method-c-remove_entry_secure for details.
EOF
File.world_writable?(path) ? Bundler.ui.warn(message) : raise
raise PathError, "Please fix the world-writable issue with your #{path} directory"
end
def settings
@settings ||= Settings.new(app_config_path)
rescue GemfileNotFound
@settings = Settings.new(Pathname.new(".bundle").expand_path)
end
# @return [Hash] Environment present before Bundler was activated
def original_env
ORIGINAL_ENV.clone
end
# @deprecated Use `original_env` instead
# @return [Hash] Environment with all bundler-related variables removed
def clean_env
Bundler::SharedHelpers.major_deprecation(2, "`Bundler.clean_env` has weird edge cases, use `.original_env` instead")
env = original_env
if env.key?("BUNDLER_ORIG_MANPATH")
env["MANPATH"] = env["BUNDLER_ORIG_MANPATH"]
end
env.delete_if {|k, _| k[0, 7] == "BUNDLE_" }
if env.key?("RUBYOPT")
env["RUBYOPT"] = env["RUBYOPT"].sub "-rbundler/setup", ""
end
if env.key?("RUBYLIB")
rubylib = env["RUBYLIB"].split(File::PATH_SEPARATOR)
rubylib.delete(File.expand_path("..", __FILE__))
env["RUBYLIB"] = rubylib.join(File::PATH_SEPARATOR)
end
env
end
def with_original_env
with_env(original_env) { yield }
end
def with_clean_env
with_env(clean_env) { yield }
end
def clean_system(*args)
with_clean_env { Kernel.system(*args) }
end
def clean_exec(*args)
with_clean_env { Kernel.exec(*args) }
end
def local_platform
return Gem::Platform::RUBY if settings[:force_ruby_platform]
Gem::Platform.local
end
def default_gemfile
SharedHelpers.default_gemfile
end
def default_lockfile
SharedHelpers.default_lockfile
end
def default_bundle_dir
SharedHelpers.default_bundle_dir
end
def system_bindir
# Gem.bindir doesn't always return the location that RubyGems will install
# system binaries. If you put '-n foo' in your .gemrc, RubyGems will
# install binstubs there instead. Unfortunately, RubyGems doesn't expose
# that directory at all, so rather than parse .gemrc ourselves, we allow
# the directory to be set as well, via `bundle config bindir foo`.
Bundler.settings[:system_bindir] || Bundler.rubygems.gem_bindir
end
def use_system_gems?
configured_bundle_path.use_system_gems?
end
def requires_sudo?
return @requires_sudo if defined?(@requires_sudo_ran)
sudo_present = which "sudo" if settings.allow_sudo?
if sudo_present
# the bundle path and subdirectories need to be writable for RubyGems
# to be able to unpack and install gems without exploding
path = bundle_path
path = path.parent until path.exist?
# bins are written to a different location on OS X
bin_dir = Pathname.new(Bundler.system_bindir)
bin_dir = bin_dir.parent until bin_dir.exist?
# if any directory is not writable, we need sudo
files = [path, bin_dir] | Dir[bundle_path.join("build_info/*").to_s] | Dir[bundle_path.join("*").to_s]
unwritable_files = files.reject {|f| File.writable?(f) }
sudo_needed = !unwritable_files.empty?
if sudo_needed
Bundler.ui.warn "Following files may not be writable, so sudo is needed:\n #{unwritable_files.map(&:to_s).sort.join("\n ")}"
end
end
@requires_sudo_ran = true
@requires_sudo = settings.allow_sudo? && sudo_present && sudo_needed
end
def mkdir_p(path, options = {})
if requires_sudo? && !options[:no_sudo]
sudo "mkdir -p '#{path}'" unless File.exist?(path)
else
SharedHelpers.filesystem_access(path, :write) do |p|
FileUtils.mkdir_p(p)
end
end
end
def which(executable)
if File.file?(executable) && File.executable?(executable)
executable
elsif paths = ENV["PATH"]
quote = '"'.freeze
paths.split(File::PATH_SEPARATOR).find do |path|
path = path[1..-2] if path.start_with?(quote) && path.end_with?(quote)
executable_path = File.expand_path(executable, path)
return executable_path if File.file?(executable_path) && File.executable?(executable_path)
end
end
end
def sudo(str)
SUDO_MUTEX.synchronize do
prompt = "\n\n" + <<-PROMPT.gsub(/^ {6}/, "").strip + " "
Your user account isn't allowed to install to the system RubyGems.
You can cancel this installation and run:
bundle install --path vendor/bundle
to install the gems into ./vendor/bundle/, or you can enter your password
and install the bundled gems to RubyGems using sudo.
Password:
PROMPT
unless @prompted_for_sudo ||= system(%(sudo -k -p "#{prompt}" true))
raise SudoNotPermittedError,
"Bundler requires sudo access to install at the moment. " \
"Try installing again, granting Bundler sudo access when prompted, or installing into a different path."
end
`sudo -p "#{prompt}" #{str}`
end
end
def read_file(file)
SharedHelpers.filesystem_access(file, :read) do
File.open(file, "r:UTF-8", &:read)
end
end
def load_marshal(data)
Marshal.load(data)
rescue StandardError => e
raise MarshalError, "#{e.class}: #{e.message}"
end
def load_gemspec(file, validate = false)
@gemspec_cache ||= {}
key = File.expand_path(file)
@gemspec_cache[key] ||= load_gemspec_uncached(file, validate)
# Protect against caching side-effected gemspecs by returning a
# new instance each time.
@gemspec_cache[key].dup if @gemspec_cache[key]
end
def load_gemspec_uncached(file, validate = false)
path = Pathname.new(file)
contents = read_file(file)
spec = if contents.start_with?("---") # YAML header
eval_yaml_gemspec(path, contents)
else
# Eval the gemspec from its parent directory, because some gemspecs
# depend on "./" relative paths.
SharedHelpers.chdir(path.dirname.to_s) do
eval_gemspec(path, contents)
end
end
return unless spec
spec.loaded_from = path.expand_path.to_s
Bundler.rubygems.validate(spec) if validate
spec
end
def clear_gemspec_cache
@gemspec_cache = {}
end
def git_present?
return @git_present if defined?(@git_present)
@git_present = Bundler.which("git") || Bundler.which("git.exe")
end
def feature_flag
@feature_flag ||= FeatureFlag.new(VERSION)
end
def reset!
reset_paths!
Plugin.reset!
reset_rubygems!
end
def reset_paths!
@bin_path = nil
@bundler_major_version = nil
@bundle_path = nil
@configured = nil
@configured_bundle_path = nil
@definition = nil
@load = nil
@locked_gems = nil
@root = nil
@settings = nil
@setup = nil
@user_home = nil
end
def reset_rubygems!
return unless defined?(@rubygems) && @rubygems
rubygems.undo_replacements
rubygems.reset
@rubygems = nil
end
private
def eval_yaml_gemspec(path, contents)
Kernel.send(:require, "bundler/psyched_yaml")
# If the YAML is invalid, Syck raises an ArgumentError, and Psych
# raises a Psych::SyntaxError. See psyched_yaml.rb for more info.
Gem::Specification.from_yaml(contents)
rescue YamlLibrarySyntaxError, ArgumentError, Gem::EndOfYAMLException, Gem::Exception
eval_gemspec(path, contents)
end
def eval_gemspec(path, contents)
eval(contents, TOPLEVEL_BINDING.dup, path.expand_path.to_s)
rescue ScriptError, StandardError => e
msg = "There was an error while loading `#{path.basename}`: #{e.message}"
if e.is_a?(LoadError) && RUBY_VERSION >= "1.9"
msg += "\nDoes it try to require a relative path? That's been removed in Ruby 1.9"
end
raise GemspecError, Dsl::DSLError.new(msg, path, e.backtrace, contents)
end
def configure_gem_home_and_path
configure_gem_path
configure_gem_home
bundle_path
end
def configure_gem_path(env = ENV)
blank_home = env["GEM_HOME"].nil? || env["GEM_HOME"].empty?
if !use_system_gems?
# this needs to be empty string to cause
# PathSupport.split_gem_path to only load up the
# Bundler --path setting as the GEM_PATH.
env["GEM_PATH"] = ""
elsif blank_home
possibles = [Bundler.rubygems.gem_dir, Bundler.rubygems.gem_path]
paths = possibles.flatten.compact.uniq.reject(&:empty?)
env["GEM_PATH"] = paths.join(File::PATH_SEPARATOR)
end
end
def configure_gem_home
Bundler::SharedHelpers.set_env "GEM_HOME", File.expand_path(bundle_path, root)
Bundler.rubygems.clear_paths
end
# @param env [Hash]
def with_env(env)
backup = ENV.to_hash
ENV.replace(env)
yield
ensure
ENV.replace(backup)
end
end
end
| 32.126761 | 136 | 0.638262 |
3302c7a6ae74ceb987e100275d1e95ac28e6ecfc | 8,744 | =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.3.1-SNAPSHOT
=end
require 'date'
require 'time'
module Petstore
class Order
attr_accessor :id
attr_accessor :pet_id
attr_accessor :quantity
attr_accessor :ship_date
# Order Status
attr_accessor :status
attr_accessor :complete
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.include?(value)
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'id' => :'id',
:'pet_id' => :'petId',
:'quantity' => :'quantity',
:'ship_date' => :'shipDate',
:'status' => :'status',
:'complete' => :'complete'
}
end
# Returns all the JSON keys this model knows about
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
def self.openapi_types
{
:'id' => :'Integer',
:'pet_id' => :'Integer',
:'quantity' => :'Integer',
:'ship_date' => :'Time',
:'status' => :'String',
:'complete' => :'Boolean'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Order` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Order`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'id')
self.id = attributes[:'id']
end
if attributes.key?(:'pet_id')
self.pet_id = attributes[:'pet_id']
end
if attributes.key?(:'quantity')
self.quantity = attributes[:'quantity']
end
if attributes.key?(:'ship_date')
self.ship_date = attributes[:'ship_date']
end
if attributes.key?(:'status')
self.status = attributes[:'status']
end
if attributes.key?(:'complete')
self.complete = attributes[:'complete']
else
self.complete = false
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
status_validator = EnumAttributeValidator.new('String', ["placed", "approved", "delivered"])
return false unless status_validator.valid?(@status)
true
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] status Object to be assigned
def status=(status)
validator = EnumAttributeValidator.new('String', ["placed", "approved", "delivered"])
unless validator.valid?(status)
fail ArgumentError, "invalid value for \"status\", must be one of #{validator.allowable_values}."
end
@status = status
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
id == o.id &&
pet_id == o.pet_id &&
quantity == o.quantity &&
ship_date == o.ship_date &&
status == o.status &&
complete == o.complete
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[id, pet_id, quantity, ship_date, status, complete].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
elsif type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :Time
Time.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
# models (e.g. Pet) or oneOf
klass = Petstore.const_get(type)
klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 29.049834 | 193 | 0.609446 |
2835e8c9e2eb24a784850dd7b51a086f2e206a95 | 5,828 | # === COPYRIGHT:
# Copyright (c) North Carolina State University
# Developed with funding for the National eXtension Initiative.
# === LICENSE:
# see LICENSE file
module ApplicationHelper
def bootstrap_alert_class(type)
baseclass = "alert"
case type
when :alert
"#{baseclass} alert-warning"
when :error
"#{baseclass} alert-error"
when :notice
"#{baseclass} alert-info"
when :success
"#{baseclass} alert-success"
else
"#{baseclass} #{type.to_s}"
end
end
def avatar_for_learner(learner, options = {})
image_size = options[:image_size] || :thumb
case image_size
when :medium then image_size_in_px = "100x100"
when :thumb then image_size_in_px = "50x50"
end
if(options[:event_types])
is_private = learner.is_private_for_event_types?(options[:event_types])
else
is_private = options[:is_private].nil? ? false : options[:is_private]
end
if(is_private)
image_tag("learn_avatar_private.png", :class => 'avatar size' + image_size_in_px, :size => image_size_in_px, :title => 'private profile').html_safe
elsif(!learner.avatar.present?)
image_tag("avatar_placeholder.png", :class => 'avatar size' + image_size_in_px, :size => image_size_in_px, :title => learner.name).html_safe
else
image_tag(learner.avatar_url(image_size), :class => 'avatar size' + image_size_in_px, :title => learner.name).html_safe
end
end
def link_to_learner(learner, options = {})
if(learner.nil?)
return 'unknown'
end
if(options[:event_types])
is_private = learner.is_private_for_event_types?(options[:event_types])
else
is_private = options[:is_private].nil? ? false : options[:is_private]
end
learner_link = options[:learner_link]
case learner_link
when 'portfolio'
link_path = portfolio_learner_path(learner.id)
else
link_path = portfolio_learner_path(learner.id)
end
if(!current_learner)
return (is_private ? 'private profile' : learner.name)
elsif(!is_private)
return link_to(learner.name, link_path).html_safe
elsif(current_learner == learner)
return link_to("#{learner.name} (seen as private profile)", link_path).html_safe
else
# current_learner, current_learner != learner, and is_private
return 'Private profile'
end
end
def link_to_learner_avatar(learner, options = {})
if(learner.nil?)
return ''
end
learner_link = options[:learner_link]
case learner_link
when 'portfolio'
link_path = portfolio_learner_path(learner.id)
else
link_path = portfolio_learner_path(learner.id)
end
if(options[:event_types])
is_private = learner.is_private_for_event_types?(options[:event_types])
else
is_private = options[:is_private].nil? ? false : options[:is_private]
end
if(!current_learner)
return avatar_for_learner(learner,options)
elsif(!is_private)
return link_to(avatar_for_learner(learner,options), link_path, :title => learner.name).html_safe
elsif(current_learner == learner)
return link_to(avatar_for_learner(learner,options), link_path, {:title => learner.name + " (Your connection is not displayed to other people)", :class => 'private_for_others'}).html_safe
else
# current_learner, current_learner != learner, and is_private
return "<a>#{avatar_for_learner(learner,options)}</a>".html_safe
end
end
def link_to_tag(tag)
link_to(tag.name, events_tag_path(:tags => tag.name), :class => "tag").html_safe
end
def flash_notifications
message = flash[:error] || flash[:notice] || flash[:warning]
return_string = ''
if message
type = flash.keys[0].to_s
return_string << '<div id="flash_notification" class="flash_notification ' + type + '"><p>' + message + '</p></div>'
return return_string.html_safe
end
end
def pagination_counts(collection)
if(collection.respond_to?('offset_value'))
"<p>Displaying <strong>#{collection.offset_value + 1}-#{collection.offset_value + collection.size} of #{collection.total_count}</strong></p>".html_safe
elsif(collection.respond_to?('offset'))
# hopefully this is an array from search - and while respond_to? doesn't work - probably because
# offset is a method_missing kind of thing - hopefully it responds to offset - if not, it'll just blow up and we'll deal with it then
"<p>Displaying <strong>#{collection.offset + 1}-#{collection.offset + collection.size} of #{collection.total_count}</strong></p>".html_safe
else
''
end
end
def sortable_link(column, title = nil, start_date, end_date, tag_tokens)
title ||= column.titleize
css_class = column == sort_column ? "current #{sort_direction}" : nil
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, {:sort => column, :direction => direction, :start_date => start_date, :end_date => end_date, :tag_tokens => tag_tokens}, {:class => css_class}
end
def sortable(column, title = nil, start_date, end_date, tag_tokens)
title ||= column.titleize
css_class = column == sort_column ? "current #{sort_direction}" : nil
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, {:sort => column, :direction => direction, :start_date => start_date, :end_date => end_date, :tag_tokens => tag_tokens}, {:class => css_class}
end
def timezone_select_default
reverse_mappings = ActiveSupport::TimeZone::MAPPING.invert
if cookies[:user_selected_timezone]
cookies[:user_selected_timezone]
elsif cookies[:system_timezone]
reverse_mappings[cookies[:system_timezone]]
else
Settings.default_display_timezone
end
end
end
| 36.425 | 192 | 0.687028 |
f8dcd8fd12668b00910325a3c726b04b321b6047 | 4,386 | # This file was automatically generated for SMASH by SMASH v2.0
# ( https://smashlabs.io ).
module Smash
# UserRegistrationModel Model.
class UserRegistrationModel < BaseModel
# TODO: Write general description for this method
# @return [String]
attr_accessor :key
# TODO: Write general description for this method
# @return [String]
attr_accessor :uid
# TODO: Write general description for this method
# @return [String]
attr_accessor :user
# TODO: Write general description for this method
# @return [String]
attr_accessor :password
# TODO: Write general description for this method
# @return [String]
attr_accessor :name
# TODO: Write general description for this method
# @return [String]
attr_accessor :email
# TODO: Write general description for this method
# @return [String]
attr_accessor :phone
# TODO: Write general description for this method
# @return [String]
attr_accessor :countrycode
# TODO: Write general description for this method
# @return [String]
attr_accessor :address
# TODO: Write general description for this method
# @return [String]
attr_accessor :a
# TODO: Write general description for this method
# @return [String]
attr_accessor :sa
# TODO: Write general description for this method
# @return [String]
attr_accessor :c
# TODO: Write general description for this method
# @return [String]
attr_accessor :s
# TODO: Write general description for this method
# @return [String]
attr_accessor :z
# A mapping from model property names to API property names.
def self.names
if @_hash.nil?
@_hash = {}
@_hash['key'] = 'key'
@_hash['uid'] = 'uid'
@_hash['user'] = 'user'
@_hash['password'] = 'password'
@_hash['name'] = 'name'
@_hash['email'] = 'email'
@_hash['phone'] = 'phone'
@_hash['countrycode'] = 'countrycode'
@_hash['address'] = 'address'
@_hash['a'] = 'a'
@_hash['sa'] = 'sa'
@_hash['c'] = 'c'
@_hash['s'] = 's'
@_hash['z'] = 'z'
end
@_hash
end
def initialize(key = nil,
uid = nil,
user = nil,
password = nil,
name = nil,
email = nil,
phone = nil,
countrycode = nil,
address = nil,
a = nil,
sa = nil,
c = nil,
s = nil,
z = nil,
additional_properties = {})
@key = key
@uid = uid
@user = user
@password = password
@name = name
@email = email
@phone = phone
@countrycode = countrycode
@address = address
@a = a
@sa = sa
@c = c
@s = s
@z = z
# Add additional model properties to the instance.
additional_properties.each do |_name, value|
instance_variable_set("@#{_name}", value)
end
end
# Creates an instance of the object from a hash.
def self.from_hash(hash)
return nil unless hash
# Extract variables from the hash.
key = hash['key']
uid = hash['uid']
user = hash['user']
password = hash['password']
name = hash['name']
email = hash['email']
phone = hash['phone']
countrycode = hash['countrycode']
address = hash['address']
a = hash['a']
sa = hash['sa']
c = hash['c']
s = hash['s']
z = hash['z']
# Clean out expected properties from Hash.
names.each_value { |k| hash.delete(k) }
# Create object from extracted values.
UserRegistrationModel.new(key,
uid,
user,
password,
name,
email,
phone,
countrycode,
address,
a,
sa,
c,
s,
z,
hash)
end
end
end
| 26.907975 | 64 | 0.49886 |
bb9d8d0977cb91cdb6132621cdfd8afcd93ed04b | 885 | # The enum of premissions
# We can turn this into a database model later if we need the flexibility
# It's possible to make these IDs instead of strings. I like the legibility of the strings, and given the likely size of the dataset, the additional performance of IDs feels unecessary at the moment. That said, it may still be a mistake to use strings instead of IDs, for which I apologize.
module Permission
REQUEST_REVIEWER = 'reviewer'
BOX_DESIGNER = 'designer'
BOX_ASSEMBLER = 'assembler'
TEAM_LEAD = 'team lead'
SHIPPER = 'shipper'
REIMBURSER = 'reimburser'
PURCHASER = 'purchaser'
VIEW_PURCHASES = 'view purchases'
VIEW_BOX_REQUESTS = 'view box requests'
REVIEW_FEEDBACK = 'review feedback'
WRITE_THANKYOUS = 'write thank you notes'
VOLUNTEER_AT_EVENTS = 'volunteer at events'
MANAGE_USERS = 'manage users'
VIEW_MESSAGE_LOGS = 'view message logs'
end
| 44.25 | 290 | 0.760452 |
62c2753d8b8ad00cb170ac31f978214575390302 | 2,354 | # frozen_string_literal: true
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.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
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# 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
| 35.134328 | 87 | 0.763381 |
f8837242b556f845ff7221035a61288a1831cbed | 621 |
class Name
Delimiter = '.'
def self.split *args
args
.flatten
.map{ _1.to_s.split Delimiter }
.flatten
.reject &:empty?
end
def set!(...)
@me = self.class.split(...)
end
def initialize(...)
set!(...)
end
# left-hand match
# (empty object matches everything)
def === o
other = self.class.split o
min = [@me.size, other.size].min
@me.take(min) == other.take(min)
end
def to_a
@me.clone
end
def to_s
@me.empty? ? Delimiter : @me.join(Delimiter)
end
alias :inspect :to_s
alias :to_str :to_s
def hash
to_s.hash
end
end
| 14.113636 | 48 | 0.568438 |
edc2d87b5afaf6f5414a4e280017c560e1273d66 | 214 | s = gets.chomp
k = gets.to_i
if s.size%k != 0
puts "NO"
exit
end
len = s.size/k
(0...s.size).step(len).each do |i|
if s[i,len] != s[i,len].reverse
puts "NO"
exit
end
end
puts "YES"
| 14.266667 | 35 | 0.523364 |
ac23110e6c30fc3c197a07702c31cb6e3e459bee | 6,323 | # ------------------------------------------------------------------------------------
# <copyright company="Aspose" file="get_document_hyperlinks_request.rb">
# Copyright (c) 2021 Aspose.Words for Cloud
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# </summary>
# ------------------------------------------------------------------------------------
module AsposeWordsCloud
#
# Request model for get_document_hyperlinks operation.
#
class GetDocumentHyperlinksRequest
# The filename of the input document.
attr_accessor :name
# Original document folder.
attr_accessor :folder
# Original document storage.
attr_accessor :storage
# Encoding that will be used to load an HTML (or TXT) document if the encoding is not specified in HTML.
attr_accessor :load_encoding
# Password for opening an encrypted document.
attr_accessor :password
#
# Initializes a new instance.
# @param name The filename of the input document.
# @param folder Original document folder.
# @param storage Original document storage.
# @param load_encoding Encoding that will be used to load an HTML (or TXT) document if the encoding is not specified in HTML.
# @param password Password for opening an encrypted document.
def initialize(name:, folder: nil, storage: nil, load_encoding: nil, password: nil)
self.name = name
self.folder = folder
self.storage = storage
self.load_encoding = load_encoding
self.password = password
end
# Creating batch part from request
def to_batch_part(api_client)
# verify the required parameter 'name' is set
raise ArgumentError, 'Missing the required parameter name when calling WordsApi.get_document_hyperlinks' if api_client.config.client_side_validation && self.name.nil?
# resource path
local_var_path = '/words/{name}/hyperlinks'[7..-1]
local_var_path = local_var_path.sub('{' + downcase_first_letter('Name') + '}', self.name.nil? ? '' : self.name.to_s)
local_var_path = local_var_path.sub('//', '/')
# query parameters
query_params = {}
query_params[downcase_first_letter('Folder')] = self.folder unless self.folder.nil?
query_params[downcase_first_letter('Storage')] = self.storage unless self.storage.nil?
query_params[downcase_first_letter('LoadEncoding')] = self.load_encoding unless self.load_encoding.nil?
query_params[downcase_first_letter('Password')] = self.password unless self.password.nil?
if query_params
query_params.each { |key, value| local_var_path = api_client.add_param_to_query(local_var_path, key, value) }
end
header_params = {}
# form parameters
form_params = {}
# http body (model)
post_body = nil
body = nil
part = ""
part.concat("GET".force_encoding('UTF-8'))
part.concat(" ".force_encoding('UTF-8'))
part.concat(local_var_path.force_encoding('UTF-8'))
part.concat(" \r\n".force_encoding('UTF-8'))
header_params.each_pair {|key, value| part.concat(key.dup.force_encoding('UTF-8') , ": ".force_encoding('UTF-8'), value.dup.force_encoding('UTF-8'), "\r\n".force_encoding('UTF-8')) }
part.concat("\r\n".force_encoding('UTF-8'))
if body
if body.is_a?(Hash)
body.each do |key, value|
part.concat(value, "\r\n")
end
else
part.concat(body)
end
end
part
end
def create_http_request(api_client)
# verify the required parameter 'name' is set
raise ArgumentError, 'Missing the required parameter name when calling WordsApi.get_document_hyperlinks' if api_client.config.client_side_validation && self.name.nil?
# resource path
local_var_path = '/words/{name}/hyperlinks'[1..-1]
local_var_path = local_var_path.sub('{' + downcase_first_letter('Name') + '}', self.name.nil? ? '' : self.name.to_s)
local_var_path = local_var_path.sub('//', '/')
# query parameters
query_params = {}
query_params[downcase_first_letter('Folder')] = self.folder unless self.folder.nil?
query_params[downcase_first_letter('Storage')] = self.storage unless self.storage.nil?
query_params[downcase_first_letter('LoadEncoding')] = self.load_encoding unless self.load_encoding.nil?
query_params[downcase_first_letter('Password')] = self.password unless self.password.nil?
# header parameters
header_params = {}
# HTTP header 'Content-Type'
header_params['Content-Type'] = api_client.select_header_content_type(['application/xml', 'application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
body = api_client.build_request_body(header_params, form_params, post_body)
{
'method': :GET,
'path': local_var_path,
'header_params': header_params,
'query_params': query_params,
'body': body,
'auth_names': ['JWT']
}
end
#
# Helper method to convert first letter to downcase
#
def downcase_first_letter(str)
str[0].downcase + str[1..-1]
end
# Get response type
def get_response_type
'HyperlinksResponse'
end
end
end
| 39.030864 | 188 | 0.671991 |
0887591fc9c5c61f3c108c837bea318de653e5da | 1,755 | require 'forwardable'
module ButtonDeployInterface
class Client
extend Forwardable
def_delegators :steps_manager, :step
def_delegators :connector, :connection_state
def initialize(certificate_path, private_key_path)
@connector = ButtonDeployInterface::AwsIot::Connector.new(certificate_path, private_key_path)
@deploy_button_topics = ButtonDeployInterface::AwsIot::ThingTopics.new
@update_publisher = ButtonDeployInterface::AwsIot::UpdatePublisher.new(connector)
@steps_manager = ButtonDeployInterface::AwsIot::Steps::Manager.new(update_publisher)
@interface_reactors = []
end
def setup
register_incoming_messages_callback
connector.connect
wait_for_connected
connector.subscribe(deploy_button_topics.update_documents)
end
def register_device_action_reactor(reactor)
raise ButtonDeployInterface::InvalidReactor unless reactor.respond_to?(:call)
@interface_reactors << reactor
end
def fingerprint_enroll(enroll_id)
payload = ButtonDeployInterface::AwsIot::Payloads::FingerprintEnroll.new(enroll_id).call
update_publisher.call(payload)
end
private
def register_incoming_messages_callback
callback = proc do |topic, payload|
ButtonDeployInterface::AwsIot::IncomingMessage::Parser.new(topic, payload, interface_reactors).process
end
connector.register_on_message_callback(callback)
end
def wait_for_connected
Timeout.timeout(ButtonDeployInterface::AwsIot::Constants::TIMEOUT_SEC) do
break if connector.connected?
sleep(0.5)
end
end
attr_reader :connector, :update_publisher, :deploy_button_topics, :interface_reactors, :steps_manager
end
end
| 30.789474 | 110 | 0.752137 |
7a01aae32ce4dc1fe8bdb2ce03daa029780844a1 | 3,460 | RSpec.describe MetadataRevision::ChangeHistoryValidator do
describe "#validate_each" do
let(:record) { build :metadata_revision }
let(:attribute) { :change_history }
let(:validator) { described_class.new(attributes: [attribute]) }
def change_history_item(id: SecureRandom.uuid,
note: "Note",
public_timestamp: Time.zone.today.rfc3339)
{ "id" => id, "note" => note, "public_timestamp" => public_timestamp }
end
it "validates when the change history is valid" do
change_history = [
change_history_item(public_timestamp: Time.zone.today.rfc3339),
change_history_item(public_timestamp: Time.zone.yesterday.rfc3339),
]
validator.validate_each(record, attribute, change_history)
expect(record).to be_valid
end
it "copes when two items have the same public_timestamp" do
change_history = [
change_history_item(public_timestamp: Time.zone.yesterday.rfc3339),
change_history_item(public_timestamp: Time.zone.yesterday.rfc3339),
]
validator.validate_each(record, attribute, change_history)
expect(record).to be_valid
end
it "fails validation if 'id' is missing" do
change_history = [change_history_item.except("id")]
expect { validator.validate_each(record, attribute, change_history) }
.to raise_error(ActiveModel::StrictValidationFailed,
"Change history has an entry with invalid keys")
end
it "fails validation if 'note' is missing" do
change_history = [change_history_item.except("note")]
expect { validator.validate_each(record, attribute, change_history) }
.to raise_error(ActiveModel::StrictValidationFailed,
"Change history has an entry with invalid keys")
end
it "fails validation if 'public_timestamp' is missing" do
change_history = [change_history_item.except("public_timestamp")]
expect { validator.validate_each(record, attribute, change_history) }
.to raise_error(ActiveModel::StrictValidationFailed,
"Change history has an entry with invalid keys")
end
it "fails validation if the 'id' is not a valid UUID" do
change_history = [change_history_item(id: "1234567-123-123-123-01234567890")]
expect { validator.validate_each(record, attribute, change_history) }
.to raise_error(ActiveModel::StrictValidationFailed,
"Change history has an entry with a non UUID id")
end
it "fails validation if 'public_timestamp' is not a valid date" do
change_history = [change_history_item(public_timestamp: "20201-13-32 29:61:61")]
expect { validator.validate_each(record, attribute, change_history) }
.to raise_error(ActiveModel::StrictValidationFailed,
"Change history has an entry with an invalid timestamp")
end
it "fails validation when notes are not in reverse chronological order" do
change_history = [
change_history_item(public_timestamp: Time.zone.yesterday.rfc3339),
change_history_item(public_timestamp: Time.zone.today.rfc3339),
]
expect { validator.validate_each(record, attribute, change_history) }
.to raise_error(ActiveModel::StrictValidationFailed,
"Change history is not in a reverse chronological ordering")
end
end
end
| 40.705882 | 86 | 0.681792 |
399c1999519fa7c6a152a54d618f167f183a862e | 78 | module Forum
class ApplicationController < ActionController::Base
end
end
| 15.6 | 54 | 0.807692 |
087f2c8eefdbfc23cbb3909dca188eb2c392f900 | 423 | require 'formula'
class Yaz < Formula
homepage 'http://www.indexdata.com/yaz'
url 'http://ftp.indexdata.dk/pub/yaz/yaz-5.0.7.tar.gz'
sha1 '72585ba2cb3e9bc30846bac473a8113433d69758'
depends_on 'pkg-config' => :build
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--with-xml2"
system "make install"
end
end
| 24.882353 | 58 | 0.609929 |
f7024f45c10e5ec5f4543e79c811176e532d05f2 | 1,213 | #
# Author:: Ryan Cragun (<[email protected]>)
# Copyright:: Copyright (c) 2019 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 "spec_helper"
describe Chef::Provider::User::MacUser do
before do
allow(ChefConfig).to receive(:windows?) { false }
end
let(:new_resource) { Chef::Resource::User::MacUser.new("jane") }
let(:provider) do
node = Chef::Node.new
events = Chef::EventDispatch::Dispatcher.new
run_context = Chef::RunContext.new(node, {}, events)
described_class.new(new_resource, run_context)
end
it "responds to load_current_resource" do
expect(provider).to respond_to(:load_current_resource)
end
end
| 31.102564 | 74 | 0.73042 |
61535b1b7588e1204c2e39a69c9ca9d873ece8b3 | 130 | require 'active_record'
require 'template'
require 'template_attribute'
require 'fiona/setting_template'
require 'fiona/settings'
| 21.666667 | 32 | 0.830769 |
e8fac4371dd523456a77e315691936ceff61e29e | 2,186 | # This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] = 'test'
require File.expand_path('../config/environment', __dir__)
require_relative '../lib/lastfm.rb'
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
require 'sidekiq/testing'
require 'capybara/rspec'
require 'action_cable/testing/rspec'
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Always load Genre Data
Rockburg::Application.load_tasks
Rake::Task['db:seed:test:genres'].invoke
# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# Include Devise test helpers.
config.include Devise::Test::ControllerHelpers, type: :controller
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
| 37.689655 | 86 | 0.752516 |
e9e84bf4bd05c31634554ab1a0b18230776c985b | 672 | class TodoList < ActiveRecord::Base
unloadable
belongs_to :author, :class_name => "User", :foreign_key => "author_id"
belongs_to :project, :class_name => "Project", :foreign_key => "project_id"
has_many :todo_items,
-> { order 'position' },
:dependent => :delete_all,
:foreign_key => :todo_list_id
acts_as_list
validates_presence_of :name
def as_json(options=nil)
{
:id => self.id,
:subject => self.name,
:is_private => self.is_private
}
end
def user_has_permissions(user)
return ((self.is_private == false) or (user and (self.author_id == user.id)))
end
end
| 25.846154 | 81 | 0.610119 |
ede330b2d2e550209c964c70b2bf5dd90b730648 | 3,432 | require 'rest_client'
require 'uri'
module HealthDataStandards
module Util
class VSNotFoundError < StandardError
end
class VSApi
attr_accessor :api_url, :ticket_url, :username, :password
def initialize(ticket_url, api_url, username, password, ticket_granting_ticket = nil)
@api_url = api_url
@ticket_url = ticket_url
@username = username
@password = password
@proxy_ticket = ticket_granting_ticket
end
def get_valueset(oid, effective_date = nil, include_draft = false, &block)
params = { id: oid, ticket: get_ticket }
params[:effectiveDate] = effective_date if effective_date
params[:includeDraft] = 'yes' if include_draft
vs = RestClient.get(api_url, params: params)
yield oid, vs if block_given?
vs
end
def process_valuesets(oids, effective_date = nil, &block)
oids.each do |oid|
vs = get_valueset(oid,effective_date)
yield oid,vs
end
end
def proxy_ticket
@proxy_ticket ||= get_proxy_ticket
end
def get_proxy_ticket
# the content type is set and the body is a string becuase the NLM service does not support urlencoded content and
# throws an error on that contnet type
RestClient.post(@ticket_url, username: @username, password: @password)
end
def get_ticket
RestClient.post("#{ticket_url}/#{proxy_ticket}", service: "http://umlsks.nlm.nih.gov")
end
def self.get_tgt_using_credentials(username, password, ticket_url)
RestClient.post(ticket_url, username: username, password: password)
end
end
class VSApiV2 < VSApi
# This default profile is used when the include_draft option is true without a profile specified.
# The VSAC V2 API needs a profile to be specified when using includeDraft. Future work on this
# class could include a function to fetch the list of profiles from the https://vsac.nlm.nih.gov/vsac/profiles
# call.
DEFAULT_PROFILE = "Most Recent CS Versions"
def initialize(ticket_url, api_url, username, password, ticket_granting_ticket = nil)
super(ticket_url, api_url, username, password, ticket_granting_ticket)
end
def get_valueset(oid, options = {}, &block)
version = options.fetch(:version, nil)
include_draft = options.fetch(:include_draft, false)
profile = options.fetch(:profile, DEFAULT_PROFILE)
effective_date = options.fetch(:effective_date, nil)
params = { id: oid, ticket: get_ticket }
params[:version] = version if version
params[:includeDraft] = 'yes' if include_draft
params[:profile] = profile if include_draft
params[:effectiveDate] = effective_date if effective_date
begin
vs = RestClient.get(api_url, :params=>params)
rescue RestClient::ResourceNotFound
raise VSNotFoundError, "No ValueSet found for oid '#{oid}'"
end
yield oid, vs if block_given?
vs
end
def process_valuesets(oids, options = {}, &block)
version = options.fetch(:version, nil)
include_draft = options.fetch(:include_draft, false)
oids.each do |oid|
vs = get_valueset(oid, version: version, include_draft: include_draft)
yield oid, vs
end
end
end
end
end
| 35.75 | 122 | 0.65676 |
03578df0a987322c997bcd1962b4172d6a13a040 | 19,377 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Ci::Build do
let_it_be(:group) { create(:group_with_plan, plan: :bronze_plan) }
let(:project) { create(:project, :repository, group: group) }
let(:pipeline) do
create(:ci_pipeline, project: project,
sha: project.commit.id,
ref: project.default_branch,
status: 'success')
end
let(:job) { create(:ci_build, pipeline: pipeline) }
let(:artifact) { create(:ee_ci_job_artifact, :sast, job: job, project: job.project) }
let(:valid_secrets) do
{
DATABASE_PASSWORD: {
vault: {
engine: { name: 'kv-v2', path: 'kv-v2' },
path: 'production/db',
field: 'password'
}
}
}
end
describe '.license_scan' do
subject(:build) { described_class.license_scan.first }
let(:artifact) { build.job_artifacts.first }
context 'with old license_management artifact' do
let!(:license_artifact) { create(:ee_ci_job_artifact, :license_management, job: job, project: job.project) }
it { expect(artifact.file_type).to eq 'license_management' }
end
context 'with new license_scanning artifact' do
let!(:license_artifact) { create(:ee_ci_job_artifact, :license_scanning, job: job, project: job.project) }
it { expect(artifact.file_type).to eq 'license_scanning' }
end
end
describe 'associations' do
it { is_expected.to have_many(:security_scans) }
end
describe '#shared_runners_minutes_limit_enabled?' do
subject { job.shared_runners_minutes_limit_enabled? }
shared_examples 'depends on runner presence and type' do
context 'for shared runner' do
before do
job.runner = create(:ci_runner, :instance)
end
context 'when project#shared_runners_minutes_limit_enabled? is true' do
specify do
expect(job.project).to receive(:shared_runners_minutes_limit_enabled?)
.and_return(true)
is_expected.to be_truthy
end
end
context 'when project#shared_runners_minutes_limit_enabled? is false' do
specify do
expect(job.project).to receive(:shared_runners_minutes_limit_enabled?)
.and_return(false)
is_expected.to be_falsey
end
end
end
context 'with specific runner' do
before do
job.runner = create(:ci_runner, :project)
end
it { is_expected.to be_falsey }
end
context 'without runner' do
it { is_expected.to be_falsey }
end
end
it_behaves_like 'depends on runner presence and type'
end
context 'updates pipeline minutes' do
let(:job) { create(:ci_build, :running, pipeline: pipeline) }
%w(success drop cancel).each do |event|
it "for event #{event}", :sidekiq_might_not_need_inline do
expect(Ci::Minutes::UpdateBuildMinutesService)
.to receive(:new).and_call_original
job.public_send(event)
end
end
end
describe '#stick_build_if_status_changed' do
it 'sticks the build if the status changed' do
job = create(:ci_build, :pending)
allow(Gitlab::Database::LoadBalancing).to receive(:enable?)
.and_return(true)
expect(Gitlab::Database::LoadBalancing::Sticking).to receive(:stick)
.with(:build, job.id)
job.update!(status: :running)
end
end
describe '#variables' do
subject { job.variables }
context 'when environment specific variable is defined' do
let(:environment_variable) do
{ key: 'ENV_KEY', value: 'environment', public: false, masked: false }
end
before do
job.update!(environment: 'staging')
create(:environment, name: 'staging', project: job.project)
variable =
build(:ci_variable,
environment_variable.slice(:key, :value)
.merge(project: project, environment_scope: 'stag*'))
variable.save!
end
context 'when there is a plan for the group' do
it 'GITLAB_FEATURES should include the features for that plan' do
expect(subject.to_runner_variables).to include({ key: 'GITLAB_FEATURES', value: anything, public: true, masked: false })
features_variable = subject.find { |v| v[:key] == 'GITLAB_FEATURES' }
expect(features_variable[:value]).to include('multiple_ldap_servers')
end
end
end
describe 'variable CI_HAS_OPEN_REQUIREMENTS' do
it "is included with value 'true' if there are open requirements" do
create(:requirement, project: project)
expect(subject).to include({ key: 'CI_HAS_OPEN_REQUIREMENTS',
value: 'true', public: true, masked: false })
end
it 'is not included if there are no open requirements' do
create(:requirement, project: project, state: :archived)
requirement_variable = subject.find { |var| var[:key] == 'CI_HAS_OPEN_REQUIREMENTS' }
expect(requirement_variable).to be_nil
end
end
end
describe '#collect_security_reports!' do
let(:security_reports) { ::Gitlab::Ci::Reports::Security::Reports.new(pipeline) }
subject { job.collect_security_reports!(security_reports) }
before do
stub_licensed_features(sast: true, dependency_scanning: true, container_scanning: true, dast: true)
end
context 'when build has a security report' do
context 'when there is a sast report' do
let!(:artifact) { create(:ee_ci_job_artifact, :sast, job: job, project: job.project) }
it 'parses blobs and add the results to the report' do
subject
expect(security_reports.get_report('sast', artifact).findings.size).to eq(33)
end
it 'adds the created date to the report' do
subject
expect(security_reports.get_report('sast', artifact).created_at.to_s).to eq(artifact.created_at.to_s)
end
end
context 'when there are multiple reports' do
let!(:sast_artifact) { create(:ee_ci_job_artifact, :sast, job: job, project: job.project) }
let!(:ds_artifact) { create(:ee_ci_job_artifact, :dependency_scanning, job: job, project: job.project) }
let!(:cs_artifact) { create(:ee_ci_job_artifact, :container_scanning, job: job, project: job.project) }
let!(:dast_artifact) { create(:ee_ci_job_artifact, :dast, job: job, project: job.project) }
it 'parses blobs and adds the results to the reports' do
subject
expect(security_reports.get_report('sast', sast_artifact).findings.size).to eq(33)
expect(security_reports.get_report('dependency_scanning', ds_artifact).findings.size).to eq(4)
expect(security_reports.get_report('container_scanning', cs_artifact).findings.size).to eq(8)
expect(security_reports.get_report('dast', dast_artifact).findings.size).to eq(20)
end
end
context 'when there is a corrupted sast report' do
let!(:artifact) { create(:ee_ci_job_artifact, :sast_with_corrupted_data, job: job, project: job.project) }
it 'stores an error' do
subject
expect(security_reports.get_report('sast', artifact)).to be_errored
end
end
end
context 'when there is unsupported file type' do
let!(:artifact) { create(:ee_ci_job_artifact, :codequality, job: job, project: job.project) }
before do
stub_const("Ci::JobArtifact::SECURITY_REPORT_FILE_TYPES", %w[codequality])
end
it 'stores an error' do
subject
expect(security_reports.get_report('codequality', artifact)).to be_errored
end
end
end
describe '#collect_license_scanning_reports!' do
subject { job.collect_license_scanning_reports!(license_scanning_report) }
let(:license_scanning_report) { build(:license_scanning_report) }
it { expect(license_scanning_report.licenses.count).to eq(0) }
context 'when the build has a license scanning report' do
before do
stub_licensed_features(license_scanning: true)
end
context 'when there is a new type report' do
before do
create(:ee_ci_job_artifact, :license_scanning, job: job, project: job.project)
end
it 'parses blobs and add the results to the report' do
expect { subject }.not_to raise_error
expect(license_scanning_report.licenses.count).to eq(4)
expect(license_scanning_report.licenses.map(&:name)).to contain_exactly("Apache 2.0", "MIT", "New BSD", "unknown")
expect(license_scanning_report.licenses.find { |x| x.name == 'MIT' }.dependencies.count).to eq(52)
end
end
context 'when there is an old type report' do
before do
create(:ee_ci_job_artifact, :license_management, job: job, project: job.project)
end
it 'parses blobs and add the results to the report' do
expect { subject }.not_to raise_error
expect(license_scanning_report.licenses.count).to eq(4)
expect(license_scanning_report.licenses.map(&:name)).to contain_exactly("Apache 2.0", "MIT", "New BSD", "unknown")
expect(license_scanning_report.licenses.find { |x| x.name == 'MIT' }.dependencies.count).to eq(52)
end
end
context 'when there is a corrupted report' do
before do
create(:ee_ci_job_artifact, :license_scan, :with_corrupted_data, job: job, project: job.project)
end
it 'returns an empty report' do
expect { subject }.not_to raise_error
expect(license_scanning_report).to be_empty
end
end
context 'when the license scanning feature is disabled' do
before do
stub_licensed_features(license_scanning: false)
create(:ee_ci_job_artifact, :license_scanning, job: job, project: job.project)
end
it 'does NOT parse license scanning report' do
subject
expect(license_scanning_report.licenses.count).to eq(0)
end
end
end
end
describe '#collect_dependency_list_reports!' do
let!(:dl_artifact) { create(:ee_ci_job_artifact, :dependency_list, job: job, project: job.project) }
let(:dependency_list_report) { Gitlab::Ci::Reports::DependencyList::Report.new }
subject { job.collect_dependency_list_reports!(dependency_list_report) }
context 'with available licensed feature' do
before do
stub_licensed_features(dependency_scanning: true)
end
it 'parses blobs and add the results to the report' do
subject
blob_path = "/#{project.full_path}/-/blob/#{job.sha}/yarn/yarn.lock"
mini_portile2 = dependency_list_report.dependencies[0]
yarn = dependency_list_report.dependencies[20]
expect(dependency_list_report.dependencies.count).to eq(21)
expect(mini_portile2[:name]).to eq('mini_portile2')
expect(yarn[:location][:blob_path]).to eq(blob_path)
end
end
context 'with different report format' do
let!(:dl_artifact) { create(:ee_ci_job_artifact, :dependency_scanning, job: job, project: job.project) }
let(:dependency_list_report) { Gitlab::Ci::Reports::DependencyList::Report.new }
before do
stub_licensed_features(dependency_scanning: true)
stub_feature_flags(standalone_vuln_dependency_list: false)
end
subject { job.collect_dependency_list_reports!(dependency_list_report) }
it 'parses blobs and add the results to the report' do
subject
blob_path = "/#{project.full_path}/-/blob/#{job.sha}/sast-sample-rails/Gemfile.lock"
netty = dependency_list_report.dependencies.first
ffi = dependency_list_report.dependencies.last
expect(dependency_list_report.dependencies.count).to eq(4)
expect(netty[:name]).to eq('io.netty/netty')
expect(ffi[:location][:blob_path]).to eq(blob_path)
end
end
context 'with disabled licensed feature' do
it 'does NOT parse dependency list report' do
subject
expect(dependency_list_report.dependencies).to be_empty
end
end
end
describe '#collect_licenses_for_dependency_list!' do
let!(:license_scan_artifact) { create(:ee_ci_job_artifact, :license_scanning, job: job, project: job.project) }
let(:dependency_list_report) { Gitlab::Ci::Reports::DependencyList::Report.new }
let(:dependency) { build(:dependency, :nokogiri) }
subject { job.collect_licenses_for_dependency_list!(dependency_list_report) }
before do
dependency_list_report.add_dependency(dependency)
end
context 'with available licensed feature' do
before do
stub_licensed_features(dependency_scanning: true)
end
it 'parses blobs and add found license' do
subject
nokogiri = dependency_list_report.dependencies.first
expect(nokogiri&.dig(:licenses, 0, :name)).to eq('MIT')
end
end
context 'with unavailable licensed feature' do
it 'does not add licenses' do
subject
nokogiri = dependency_list_report.dependencies.first
expect(nokogiri[:licenses]).to be_empty
end
end
end
describe '#collect_metrics_reports!' do
subject { job.collect_metrics_reports!(metrics_report) }
let(:metrics_report) { Gitlab::Ci::Reports::Metrics::Report.new }
context 'when there is a metrics report' do
before do
create(:ee_ci_job_artifact, :metrics, job: job, project: job.project)
end
context 'when license has metrics_reports' do
before do
stub_licensed_features(metrics_reports: true)
end
it 'parses blobs and add the results to the report' do
expect { subject }.to change { metrics_report.metrics.count }.from(0).to(2)
end
end
context 'when license does not have metrics_reports' do
before do
stub_licensed_features(license_scanning: false)
end
it 'does not parse metrics report' do
subject
expect(metrics_report.metrics.count).to eq(0)
end
end
end
end
describe '#collect_requirements_reports!' do
subject { job.collect_requirements_reports!(requirements_report) }
let(:requirements_report) { Gitlab::Ci::Reports::RequirementsManagement::Report.new }
context 'when there is a requirements report' do
before do
create(:ee_ci_job_artifact, :all_passing_requirements, job: job, project: job.project)
end
context 'when requirements are available' do
before do
stub_licensed_features(requirements: true)
end
it 'parses blobs and adds the results to the report' do
expect { subject }.to change { requirements_report.requirements.count }.from(0).to(1)
end
end
context 'when requirements are not available' do
before do
stub_licensed_features(requirements: false)
end
it 'does not parse requirements report' do
subject
expect(requirements_report.requirements.count).to eq(0)
end
end
end
end
describe '#retryable?' do
subject { build.retryable? }
let(:pipeline) { merge_request.all_pipelines.last }
let!(:build) { create(:ci_build, :canceled, pipeline: pipeline) }
context 'with pipeline for merged results' do
let(:merge_request) { create(:merge_request, :with_merge_request_pipeline) }
it { is_expected.to be true }
end
end
describe ".license_scan" do
it 'returns only license artifacts' do
create(:ci_build, job_artifacts: [create(:ci_job_artifact, :zip)])
build_with_license_scan = create(:ci_build, job_artifacts: [create(:ci_job_artifact, file_type: :license_scanning, file_format: :raw)])
expect(described_class.license_scan).to contain_exactly(build_with_license_scan)
end
end
describe 'ci_secrets_management_available?' do
subject { job.ci_secrets_management_available? }
context 'when build has no project' do
before do
job.update!(project: nil)
end
it { is_expected.to be false }
end
context 'when secrets management feature is available' do
before do
stub_licensed_features(ci_secrets_management: true)
end
it { is_expected.to be true }
end
context 'when secrets management feature is not available' do
before do
stub_licensed_features(ci_secrets_management: false)
end
it { is_expected.to be false }
end
end
describe '#runner_required_feature_names' do
let(:build) { create(:ci_build, secrets: secrets) }
subject { build.runner_required_feature_names }
context 'when secrets management feature is available' do
before do
stub_licensed_features(ci_secrets_management: true)
end
context 'when there are secrets defined' do
let(:secrets) { valid_secrets }
it { is_expected.to include(:vault_secrets) }
end
context 'when there are no secrets defined' do
let(:secrets) { {} }
it { is_expected.not_to include(:vault_secrets) }
end
end
context 'when secrets management feature is not available' do
before do
stub_licensed_features(ci_secrets_management: false)
end
context 'when there are secrets defined' do
let(:secrets) { valid_secrets }
it { is_expected.not_to include(:vault_secrets) }
end
context 'when there are no secrets defined' do
let(:secrets) { {} }
it { is_expected.not_to include(:vault_secrets) }
end
end
end
describe "secrets management usage data" do
context 'when secrets management feature is not available' do
before do
stub_licensed_features(ci_secrets_management: false)
end
it 'does not track unique users' do
expect(Gitlab::UsageDataCounters::HLLRedisCounter).not_to receive(:track_event)
create(:ci_build, secrets: valid_secrets)
end
end
context 'when secrets management feature is available' do
before do
stub_licensed_features(ci_secrets_management: true)
end
context 'when there are secrets defined' do
context 'on create' do
it 'tracks unique users' do
ci_build = build(:ci_build, secrets: valid_secrets)
expect(Gitlab::UsageDataCounters::HLLRedisCounter).to receive(:track_event).with('i_ci_secrets_management_vault_build_created', values: ci_build.user_id)
ci_build.save!
end
end
context 'on update' do
it 'does not track unique users' do
ci_build = create(:ci_build, secrets: valid_secrets)
expect(Gitlab::UsageDataCounters::HLLRedisCounter).not_to receive(:track_event)
ci_build.success
end
end
end
end
context 'when there are no secrets defined' do
let(:secrets) { {} }
it 'does not track unique users' do
expect(Gitlab::UsageDataCounters::HLLRedisCounter).not_to receive(:track_event)
create(:ci_build, secrets: {})
end
end
end
end
| 32.028099 | 165 | 0.661816 |
bb3f3deeb6b38727d9d9b583a923732a77808ec6 | 2,033 | require 'nokogiri/xml/parse_options'
require 'nokogiri/xml/sax'
require 'nokogiri/xml/fragment_handler'
require 'nokogiri/xml/node'
require 'nokogiri/xml/namespace'
require 'nokogiri/xml/attr'
require 'nokogiri/xml/dtd'
require 'nokogiri/xml/cdata'
require 'nokogiri/xml/document'
require 'nokogiri/xml/document_fragment'
require 'nokogiri/xml/processing_instruction'
require 'nokogiri/xml/node_set'
require 'nokogiri/xml/syntax_error'
require 'nokogiri/xml/xpath'
require 'nokogiri/xml/xpath_context'
require 'nokogiri/xml/builder'
require 'nokogiri/xml/reader'
require 'nokogiri/xml/notation'
require 'nokogiri/xml/entity_declaration'
require 'nokogiri/xml/schema'
require 'nokogiri/xml/relax_ng'
module Nokogiri
class << self
###
# Parse XML. Convenience method for Nokogiri::XML::Document.parse
def XML thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_XML, &block
Nokogiri::XML::Document.parse(thing, url, encoding, options, &block)
end
end
module XML
class << self
###
# Parse an XML document using the Nokogiri::XML::Reader API. See
# Nokogiri::XML::Reader for mor information
def Reader string_or_io, url = nil, encoding = nil, options = ParseOptions::STRICT
options = Nokogiri::XML::ParseOptions.new(options) if Fixnum === options
# Give the options to the user
yield options if block_given?
if string_or_io.respond_to? :read
return Reader.from_io(string_or_io, url, encoding, options.to_i)
end
Reader.from_memory(string_or_io, url, encoding, options.to_i)
end
###
# Parse XML. Convenience method for Nokogiri::XML::Document.parse
def parse thing, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML, &block
Document.parse(thing, url, encoding, options, &block)
end
####
# Parse a fragment from +string+ in to a NodeSet.
def fragment string
XML::DocumentFragment.parse(string)
end
end
end
end
| 32.269841 | 94 | 0.70487 |
bfcde7945cb36656e490ea6a8ce5ed7b6189f6f7 | 1,142 | module FontAwesome5Rails
module Parsers
module ParseMethods
def icon_type(type)
return 'fas' if type.nil?
case type.to_sym
when :far, :regular
'far'
when :fal, :light
'fal'
when :fab, :brand
'fab'
when :fad, :duotone
'fad'
else
'fas'
end
end
def icon_type_path(type)
return 'solid' if type.nil?
case type.to_sym
when :far, :regular
'regular'
when :fal, :light
'light'
when :fab, :brand
'brands'
when :fad, :duotone
'duotone'
else
'solid'
end
end
def prepend_fa(string)
"fa-#{string}"
end
def arr_with_fa(array)
array = handle_input(array)
array.split(' ').map { |s| prepend_fa(s) }
end
private
def handle_input(input)
case input
when Symbol
input.to_s.dasherize
when Array
input.join(' ').dasherize
else
input.to_s
end
end
end
end
end
| 18.419355 | 50 | 0.476357 |
184be5c2c5a8250537f279620a56020c573315d9 | 256 | # Dsl or Erb
module Lono::Builder::Configset
class Evaluator < Lono::CLI::Base
def evaluate
Registration.new(@blueprint).evaluate
combiner = Combiner.new(@options.merge(metas: Registration.metas))
combiner.combine
end
end
end
| 23.272727 | 72 | 0.699219 |
1dcbc3692e61e2556f48c904a6153af19a5b2f8a | 2,164 | require 'rails_helper'
describe Agents::SchedulerAgent do
let(:valid_params) {
{
name: 'Example',
options: {
'action' => 'run',
'schedule' => '0 * * * *'
},
}
}
let(:agent) {
described_class.create!(valid_params) { |agent|
agent.user = users(:bob)
}
}
it_behaves_like AgentControllerConcern
describe "validation" do
it "should validate schedule" do
expect(agent).to be_valid
agent.options.delete('schedule')
expect(agent).not_to be_valid
agent.options['schedule'] = nil
expect(agent).not_to be_valid
agent.options['schedule'] = ''
expect(agent).not_to be_valid
agent.options['schedule'] = '0'
expect(agent).not_to be_valid
agent.options['schedule'] = '*/15 * * * * * *'
expect(agent).not_to be_valid
agent.options['schedule'] = '*/1 * * * *'
expect(agent).to be_valid
agent.options['schedule'] = '*/1 * * *'
expect(agent).not_to be_valid
stub(agent).second_precision_enabled { true }
agent.options['schedule'] = '*/15 * * * * *'
expect(agent).to be_valid
stub(agent).second_precision_enabled { false }
agent.options['schedule'] = '*/10 * * * * *'
expect(agent).not_to be_valid
agent.options['schedule'] = '5/30 * * * * *'
expect(agent).not_to be_valid
agent.options['schedule'] = '*/15 * * * * *'
expect(agent).to be_valid
agent.options['schedule'] = '15,45 * * * * *'
expect(agent).to be_valid
agent.options['schedule'] = '0 * * * * *'
expect(agent).to be_valid
end
end
describe "save" do
it "should delete memory['scheduled_at'] if and only if options is changed" do
time = Time.now.to_i
agent.memory['scheduled_at'] = time
agent.save
expect(agent.memory['scheduled_at']).to eq(time)
agent.memory['scheduled_at'] = time
# Currently agent.options[]= is not detected
agent.options = {
'action' => 'run',
'schedule' => '*/5 * * * *'
}
agent.save
expect(agent.memory['scheduled_at']).to be_nil
end
end
end
| 24.590909 | 82 | 0.577634 |
615e9faf777546044df821a697ff0fa8d09b0c04 | 1,298 | class SearchController < ApplicationController
before_action :validate_q!, only: %i[results]
def results
# hand off to Enhancer chain
@enhanced_query = Enhancer.new(params).enhanced_query
# hand off enhanced query to builder
query = QueryBuilder.new(@enhanced_query).query
# builder hands off to wrapper which returns raw results here
response = TimdexBase::Client.query(TimdexSearch::Query, variables: query)
# Handle errors
@errors = extract_errors(response)
# Analayze results
# The @pagination instance variable includes info about next/previous pages (where they exist) to assist the UI.
@pagination = Analyzer.new(@enhanced_query, response).pagination if @errors.nil?
# Display stuff
@results = extract_results(response)
@facets = extract_facets(response)
end
private
def extract_errors(response)
response&.errors&.details&.to_h&.dig('data')
end
def extract_facets(response)
response&.data&.search&.to_h&.dig('aggregations')
end
def extract_results(response)
response&.data&.search&.to_h&.dig('records')
end
def validate_q!
return if params[:advanced].present?
return if params[:q]&.strip.present?
flash[:error] = 'A search term is required.'
redirect_to root_url
end
end
| 27.041667 | 116 | 0.718028 |
ed05a150f8b01e718445c5575b5a822d19f0ff07 | 2,298 | # frozen_string_literal: true
RSpec.shared_examples 'items list service' do
it 'avoids N+1' do
params = { board_id: board.id }
control = ActiveRecord::QueryRecorder.new { list_service(params).execute }
new_list
expect { list_service(params).execute }.not_to exceed_query_limit(control)
end
it 'returns opened items when list_id and list are missing' do
params = { board_id: board.id }
items = list_service(params).execute
expect(items).to match_array(backlog_items)
end
it 'returns opened items when listing items from Backlog' do
params = { board_id: board.id, id: backlog.id }
items = list_service(params).execute
expect(items).to match_array(backlog_items)
end
it 'returns opened items that have label list applied when listing items from a label list' do
params = { board_id: board.id, id: list1.id }
items = list_service(params).execute
expect(items).to match_array(list1_items)
end
it 'returns closed items when listing items from Closed sorted by closed_at in descending order' do
params = { board_id: board.id, id: closed.id }
items = list_service(params).execute
expect(items).to eq(closed_items)
end
it 'raises an error if the list does not belong to the board' do
list = create(list_factory) # rubocop:disable Rails/SaveBang
params = { board_id: board.id, id: list.id }
service = list_service(params)
expect { service.execute }.to raise_error(ActiveRecord::RecordNotFound)
end
it 'raises an error if list and list id are invalid or missing' do
params = { board_id: board.id, id: nil, list: nil }
service = list_service(params)
expect { service.execute }.to raise_error(ActiveRecord::RecordNotFound)
end
it 'returns items from all lists if :all_list is used' do
params = { board_id: board.id, all_lists: true }
items = list_service(params).execute
expect(items).to match_array(all_items)
end
it 'returns opened items that have label list applied when using list param' do
params = { board_id: board.id, list: list1 }
items = list_service(params).execute
expect(items).to match_array(list1_items)
end
def list_service(params)
args = [parent, user].push(params)
described_class.new(*args)
end
end
| 27.357143 | 101 | 0.710183 |
285d89d028298d9ab246d34350717451cb05428d | 907 | #
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint carbonvoice_audio.podspec` to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'carbonvoice_audio'
s.version = '1.0.6'
s.summary = 'Flutter audio plugin'
s.description = 'Flutter audio plugin interface'
s.homepage = 'https://github.com/PhononX/carbonvoice_audio'
s.license = { :file => '../LICENSE' }
s.author = { 'PhononX' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.dependency 'Flutter'
s.dependency 'CarbonVoiceAudio', '~> 1.1.7'
s.platform = :ios, '11.0'
# Flutter.framework does not contain a i386 slice.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
s.swift_version = '5.0'
end
| 39.434783 | 105 | 0.619625 |
bbf8db8a777e70e338195e59ce10239b6005db2a | 533 | class PasswordResetsController < ApplicationController
def new
end
def edit
@user = User.find_by_password_reset_token!(params[:id])
end
def update
@user = User.find_by_password_reset_token!(params[:id])
if @user.password_reset_sent_at < 2.hours.ago
redirect_to new_password_reset_path, :alert => "Password ↵
reset has expired."
elsif @user.update_attributes(params[:user])
redirect_to root_url, :notice => "Password has been reset."
else
render :edit
end
end
end
| 25.380952 | 70 | 0.701689 |
d59b70dec9042d0d1d80982e7fc94a24fe3c9320 | 1,579 | class Rubberband < Formula
desc "Audio time stretcher tool and library"
homepage "https://breakfastquay.com/rubberband/"
url "https://breakfastquay.com/files/releases/rubberband-1.8.2.tar.bz2"
sha256 "86bed06b7115b64441d32ae53634fcc0539a50b9b648ef87443f936782f6c3ca"
license "GPL-2.0"
revision 1
head "https://hg.sr.ht/~breakfastquay/rubberband", using: :hg
bottle do
cellar :any
rebuild 1
sha256 "dcfa2c05cc251d0c5e810040646fb5f9511fda2d1cad20ccadce96544a1ad7e3" => :catalina
sha256 "629837bd83bfcef1003bfb29759d15c29bb7c22740a70f6143bd4c16a5bd3362" => :mojave
sha256 "f592baa6b5e82c542a92df87789a51b6603e7e8070dfa7f910349a388135b6da" => :high_sierra
end
depends_on "pkg-config" => :build
depends_on "libsamplerate"
depends_on "libsndfile"
def install
system "make", "-f", "Makefile.osx"
# HACK: Manual install because "make install" is broken
# https://github.com/Homebrew/homebrew-core/issues/28660
bin.install "bin/rubberband"
lib.install "lib/librubberband.dylib" => "librubberband.2.1.1.dylib"
lib.install_symlink lib/"librubberband.2.1.1.dylib" => "librubberband.2.dylib"
lib.install_symlink lib/"librubberband.2.1.1.dylib" => "librubberband.dylib"
include.install "rubberband"
cp "rubberband.pc.in", "rubberband.pc"
inreplace "rubberband.pc", "%PREFIX%", opt_prefix
(lib/"pkgconfig").install "rubberband.pc"
end
test do
output = shell_output("#{bin}/rubberband -t2 #{test_fixtures("test.wav")} out.wav 2>&1")
assert_match "Pass 2: Processing...", output
end
end
| 37.595238 | 93 | 0.737175 |
ac6606e77d72b0087e035a61f127dbf91071d352 | 815 | require 'cairo'
require_relative 'arg_loader'
require_relative 'color_validator'
module Squib::Args
module_function def extract_paint(opts, deck)
Paint.new(deck.custom_colors).extract!(opts, deck)
end
class Paint
include ArgLoader
include ColorValidator
def initialize(custom_colors)
@custom_colors = custom_colors
end
def self.parameters
{ alpha: 1.0,
blend: :none,
mask: nil,
}
end
def self.expanding_parameters
parameters.keys # all of them are expandable
end
def self.params_with_units
[]
end
def validate_alpha(arg, _i)
raise 'alpha must respond to to_f' unless arg.respond_to? :to_f
arg.to_f
end
def validate_mask(arg, _i)
colorify(arg, @custom_colors)
end
end
end
| 18.522727 | 69 | 0.662577 |
ac14bfaeb97dac68530ea7f2dcf577133712c0c9 | 645 | require 'rails_helper'
RSpec.describe "newsletters/edit", :type => :view do
before(:each) do
@newsletter = assign(:newsletter, Newsletter.create!(
:name => "MyString",
:url => "MyString",
:description => "MyText"
))
end
it "renders the edit newsletter form" do
render
assert_select "form[action=?][method=?]", newsletter_path(@newsletter), "post" do
assert_select "input#newsletter_name[name=?]", "newsletter[name]"
assert_select "input#newsletter_url[name=?]", "newsletter[url]"
assert_select "textarea#newsletter_description[name=?]", "newsletter[description]"
end
end
end
| 25.8 | 88 | 0.665116 |
6288351c6406227d3cb2d0b68a41c761a9d48247 | 232 | require 'colorizable/color'
require 'colorizable/model_extensions'
module Colorizable
end
if defined?(ActiveRecord::Base)
ActiveRecord::Base.send(:include, Colorizable::ModelExtensions)
end
require 'colorizable/version_number'
| 19.333333 | 65 | 0.818966 |
b92b700b819b869f19f7e6d3944d533711e0d367 | 39 | json.partial! "mgmts/mgmt", mgmt: @mgmt | 39 | 39 | 0.717949 |
bb5cc7a431b8276e24195ebac7ae2d3ae3e43622 | 3,023 | require_relative './formulario_test'
require_relative './respuestafor_test'
require_relative './campo_test'
require_relative '../../test_helper'
module Mr519Gen
class ValorcampoTest < ActiveSupport::TestCase
PRUEBA_VALORCAMPO = {
valor: 1
}
setup do
Rails.application.config.x.formato_fecha = 'yyyy-mm-dd'
end
test "valido" do
f = Mr519Gen::Formulario.create(
Mr519Gen::FormularioTest::PRUEBA_FORMULARIO)
assert f.valid?
c = Mr519Gen::Campo.new(Mr519Gen::CampoTest::PRUEBA_CAMPO)
c.formulario = f
assert c.valid?
c.save
r = Mr519Gen::Respuestafor.new(
Mr519Gen::RespuestaforTest::PRUEBA_RESPUESTAFOR)
r.formulario = f
r.save
assert r.valid?
v = Mr519Gen::Valorcampo.new(PRUEBA_VALORCAMPO)
v.campo = c
v.respuestafor = r
assert v.valid?
assert_equal 'c: 1', v.presenta_valor
assert_equal '1', v.presenta_valor(false)
v.campo.tipo = Mr519Gen::ApplicationHelper::ENTERO
assert_equal 1, v.presenta_valor(false)
assert_equal 'c: 1', v.presenta_valor(true)
v.campo.tipo = Mr519Gen::ApplicationHelper::FLOTANTE
assert_equal 1.0, v.presenta_valor(false)
assert_equal 'c: 1.0', v.presenta_valor(true)
v.campo.tipo = Mr519Gen::ApplicationHelper::PRESENTATEXTO
assert_equal 'c', v.presenta_valor(false)
v.campo.tipo = Mr519Gen::ApplicationHelper::BOOLEANO
assert_equal 'SI', v.presenta_valor(false)
o = Mr519Gen::Opcioncs.new(id: 1, campo_id: 1, nombre: 'x', valor: 'x')
o.save
v.campo.tipo = Mr519Gen::ApplicationHelper::SELECCIONMULTIPLE
v.valor_ids = [1, 2]
assert_equal '[1, 2]', v.valor_ids.to_s
assert_equal '[1, 2]', v.presenta_valor(false).to_s
v.campo.tipo = Mr519Gen::ApplicationHelper::SELECCIONSIMPLE
o = Mr519Gen::Opcioncs.new(
id: 1, campo_id: c.id, nombre: 'x', valor: 'x')
o.save
assert_equal 'x', v.presenta_valor(false)
v.campo.tipo = Mr519Gen::ApplicationHelper::SMTABLABASICA
assert_equal 'Problema tablabasica es nil', v.presenta_valor(false)
v.campo.tablabasica = 'Pais'
assert_equal 'Problema con tablabasica Pais porque hay 0', v.presenta_valor(false)
v.campo.tablabasica = 'pais'
v.valor_ids = [170, 686]
assert_equal 'COLOMBIA; SENEGAL', v.presenta_valor(false)
v.campo.tipo = Mr519Gen::ApplicationHelper::SSTABLABASICA
v.campo.tablabasica = nil
assert_equal 'Problema tablabasica es nil', v.presenta_valor(false)
v.campo.tablabasica = 'Pais'
assert_equal 'Problema con tablabasica Pais porque hay 0', v.presenta_valor(false)
v.campo.tablabasica = 'pais'
v.valor = 686
assert_equal 'SENEGAL', v.presenta_valor(false)
v.destroy
r.destroy
c.destroy
f.destroy
end
test "no valido" do
c = Mr519Gen::Valorcampo.new PRUEBA_VALORCAMPO
assert_not c.valid?
c.destroy
end
end
end
| 34.352273 | 89 | 0.665564 |
ab8bc4df4583ac57c4849f7c4b418efb678eef95 | 1,121 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module AimFullProject
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| 41.518519 | 99 | 0.735058 |
1a2559a8d6584238c8ca34bbc995eb404d6de67d | 477 | class Boot2docker < Cask
version '1.1.0'
sha256 '6a98e0311557199a71b23d596a0547e3a7902a1a04f42905c6141a08f2a1bb7d'
url 'https://github.com/boot2docker/osx-installer/releases/download/v1.1.0/Boot2Docker-1.1.0.pkg'
homepage 'https://github.com/boot2docker/osx-installer'
install 'Boot2Docker-1.1.0.pkg'
uninstall :pkgutil => ['io.boot2docker.pkg.boot2docker', 'io.boot2docker.pkg.boot2dockerapp', 'io.boot2dockeriso.pkg.boot2dockeriso', 'io.docker.pkg.docker']
end
| 43.363636 | 159 | 0.779874 |
26726b8bb359656a8e7500dc5c8962c153393934 | 259 | require 'rails_helper'
RSpec.describe User, :type => :model do
it 'is subscribed if there is a subscription with same email address' do
u = create(:user)
sub = create(:subscription,email: u.email)
expect(u).to be_subscribed
end
end
| 18.5 | 74 | 0.679537 |
6ac881dfbe515b08c5c2813a071e01a7d5ab600c | 1,138 | module Fastlane
module Actions
class LaneContextAction < Action
def self.run(params)
Actions.lane_context
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Access lane context values"
end
def self.details
[
"Access the fastlane lane context values",
"More information about how the lane context works: https://docs.fastlane.tools/advanced/#lane-context"
].join("\n")
end
def self.available_options
[]
end
def self.output
[]
end
def self.authors
["KrauseFx"]
end
def self.is_supported?(platform)
true
end
# We don't want to show this as step
def self.step_text
nil
end
def self.example_code
[
'lane_context[SharedValues::BUILD_NUMBER]',
'lane_context[SharedValues::IPA_OUTPUT_PATH]'
]
end
def self.category
:misc
end
end
end
end
| 19.964912 | 113 | 0.502636 |
335c196f60b403e76cb3648ffc86275383a8476c | 564 | =begin
There was a test in your class and you passed it. Congratulations!
But you're an ambitious person. You want to know if you're better than the average student in your class.
You got an array with your colleges' points. Now calculate the average to your points!
Return True if you're better, else False!
Note:
Your points are not included in the array of your classes points. For calculating the average point you may add your point to the given array!
=end
def better_than_average(arr, points)
(arr.sum / arr.length).abs > points ? false : true
end
| 37.6 | 142 | 0.764184 |
6a37b2633007f335cc86e7d2ac035864cc2cedd5 | 4,058 | module ApiBanking
class AccountStatement < JsonClient
SERVICE_VERSION = 1
CODE_NO_TXN_FOUND = '8504'
attr_accessor :request, :result
ReqHeader = Struct.new(:corpID, :approverID)
ReqBody = Struct.new(:accountNo, :transactionType, :fromDate, :toDate)
Request = Struct.new(:header, :body)
Transactions = Struct.new(:transactionDateTime, :transactionType, :amount, :narrative, :referenceNo, :balance)
Result = Struct.new(:transactions)
class << self
attr_accessor :configuration
end
def self.configure
self.configuration ||= Configuration.new
yield(configuration)
end
class Configuration
attr_accessor :environment, :proxy, :timeout
end
def self.get_statement(env, request, callbacks = nil)
dataHash = {}
dataHash[:Acc_Stmt_DtRng_Req] = {}
dataHash[:Acc_Stmt_DtRng_Req][:Header] = {}
dataHash[:Acc_Stmt_DtRng_Req][:Body] = {}
dataHash[:Acc_Stmt_DtRng_Req][:Header][:TranID] = '00'
dataHash[:Acc_Stmt_DtRng_Req][:Header][:Corp_ID] = request.header.corpID
# the tags Maker_ID and Checker_ID have been removed since Schema Validation Error is returned when these are sent in the request.
dataHash[:Acc_Stmt_DtRng_Req][:Header][:Approver_ID] = request.header.approverID
dataHash[:Acc_Stmt_DtRng_Req][:Body][:Acc_No] = request.body.accountNo
dataHash[:Acc_Stmt_DtRng_Req][:Body][:Tran_Type] = request.body.transactionType
dataHash[:Acc_Stmt_DtRng_Req][:Body][:From_Dt] = request.body.fromDate
dataHash[:Acc_Stmt_DtRng_Req][:Body][:Pagination_Details] = {}
dataHash[:Acc_Stmt_DtRng_Req][:Body][:Pagination_Details][:Last_Balance] = {}
dataHash[:Acc_Stmt_DtRng_Req][:Body][:Pagination_Details][:Last_Balance][:Amount_Value] = ''
dataHash[:Acc_Stmt_DtRng_Req][:Body][:Pagination_Details][:Last_Balance][:Currency_Code] = ''
dataHash[:Acc_Stmt_DtRng_Req][:Body][:Pagination_Details][:Last_Pstd_Date] = ''
dataHash[:Acc_Stmt_DtRng_Req][:Body][:Pagination_Details][:Last_Txn_Date] = ''
dataHash[:Acc_Stmt_DtRng_Req][:Body][:Pagination_Details][:Last_Txn_Id] = ''
dataHash[:Acc_Stmt_DtRng_Req][:Body][:Pagination_Details][:Last_Txn_SrlNo] = ''
dataHash[:Acc_Stmt_DtRng_Req][:Body][:To_Dt] = request.body.toDate
reply = do_remote_call(env, dataHash, callbacks)
parse_reply(:getStatement, reply)
end
private
def self.parse_reply(operationName, reply)
if reply.kind_of?Fault
reply.code == CODE_NO_TXN_FOUND ? AccountStatement::Result.new([]) : reply
else
case operationName
when :getStatement
sortedTxnArray = Array.new
txnArray = reply['Acc_Stmt_DtRng_Res']['Body']['transactionDetails'].sort_by { |e| parsed_datetime(e['pstdDate'])}
txnArray.each do |txn|
txnAmt = parsed_money(
txn['transactionSummary']['txnAmt']['amountValue'],
txn['transactionSummary']['txnAmt']['currencyCode']
)
txnBalance = parsed_money(
txn['txnBalance']['amountValue'],
txn['txnBalance']['currencyCode']
)
sortedTxnArray << AccountStatement::Transactions.new(
parsed_datetime(txn['pstdDate']),
txn['transactionSummary']['txnType'],
txnAmt,
txn['transactionSummary']['txnDesc'],
txn['txnId'],
txnBalance
)
end
return AccountStatement::Result.new(
sortedTxnArray
)
end
end
end
def self.parsed_money(amount, currency)
Money.from_amount(amount.to_d, currency)
end
def self.parsed_datetime(datetime)
DateTime.parse(datetime)
end
end
end
| 38.283019 | 136 | 0.614096 |
79da0980e86751b4f09e970b26f60045b0e521d3 | 565 | require_relative "boot"
require "rails/all"
Bundler.require(*Rails.groups)
require "segmentation"
module Dummy
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
| 29.736842 | 82 | 0.768142 |
9112536a010ad1ae8b9b5835a3fb7e6b759ff1d2 | 867 | # Add our main menu override
copy_file "overrides/main_menu.rb", "app/overrides/main_menu.rb"
# Fix uninitialized constant Spree::User::DestroyWithOrdersError
template "initializers/spree_user_error_fix.rb", "config/initializers/spree_user_error_fix.rb"
# remove all stylesheets except core
%w(admin store).each do |ns|
template "assets/javascripts/#{ns}/all.js", "app/assets/javascripts/#{ns}/all.js", :force => true
template "assets/stylesheets/#{ns}/all.css", "app/assets/stylesheets/#{ns}/all.css", :force => true
end
# Fix sass load error by using the converted css file
template "assets/stylesheets/store/screen.css", "app/assets/stylesheets/store/screen.css"
# Enable forgery_protection since we need AUTH_TOKEN to be defined to avoid JS errors
gsub_file "config/environments/test.rb", "forgery_protection = false", "forgery_protection = true"
| 48.166667 | 101 | 0.767013 |
ed2aa3e170919651f0c28cbe00a1040238e862e3 | 83 | require 'rails_helper'
describe Version do
it { should belong_to(:project)}
end
| 13.833333 | 34 | 0.759036 |
3888ff87c8ae3e7a6b51e911d72831a002536558 | 196 | namespace :index_posts do
task default: :environment do
start = Time.now.utc.to_f
ESIndexAllPostsWorker.new.perform
puts "ESIndexAllPostsWorker took #{Time.now.utc.to_f - start}"
end
end
| 24.5 | 64 | 0.765306 |
e978a836cd137d4feb630379f93e090161c7aaea | 1,028 | {
matrix_id: '1391',
name: 'net50',
group: 'Andrianov',
description: 'net50 matrix from Alexander Andrianov, SAS Institute Inc.',
author: 'A. Andrianov',
editor: 'T. Davis',
date: '2006',
kind: 'optimization problem',
problem_2D_or_3D: '0',
num_rows: '16320',
num_cols: '16320',
nonzeros: '945200',
num_explicit_zeros: '0',
num_strongly_connected_components: '2',
num_dmperm_blocks: '2',
structural_full_rank: 'true',
structural_rank: '16320',
pattern_symmetry: '1.000',
numeric_symmetry: '1.000',
rb_type: 'binary',
structure: 'symmetric',
cholesky_candidate: 'yes',
positive_definite: 'no',
norm: '9.244246e+01',
min_singular_value: '3.631464e-206',
condition_number: '2.545598e+207',
svd_rank: '15033',
sprank_minus_rank: '1287',
null_space_dimension: '1287',
full_numerical_rank: 'no',
svd_gap: '11281358103320.898438',
image_files: 'net50.png,net50_dmperm.png,net50_svd.png,net50_graph.gif,',
}
| 29.371429 | 77 | 0.654669 |
f82721c77ae834ef3f87e9e616adc5364afcd507 | 3,319 | # frozen_string_literal: true
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
require 'database_cleaner'
require 'simplecov'
SimpleCov.start
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
# Prevent database truncation if the environment is production
abort('The Rails environment is running in production mode!') if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# Needed for Allinson Flex Metadata
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
AdminSet.find_or_create_default_admin_set_id
@allinson_flex_profile = AllinsonFlex::Importer.load_profile_from_path(path: Rails.root.join('config', 'metadata_profile', 'uc_drc.yml'))
@allinson_flex_profile.save
end
# You can uncomment this line to turn off ActiveRecord support entirely.
# config.use_active_record = false
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, type: :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
| 42.012658 | 141 | 0.756252 |
e2dacece8d46b57eec9eae4f9bebbe4856297ba7 | 572 | # frozen_string_literal: true
module Persistence
module Store
module Operations
# Responsible of building a DELETE Directive.
class Delete < Operation
include Capabilities::Filter
include Capabilities::Retriever
include Capabilities::Requirer
include Capabilities::DiscardedManager
def initialize(source)
exclude_discarded
super(source)
end
def after(results)
return results unless results.size == 1
results.first
end
end
end
end
end
| 21.185185 | 51 | 0.636364 |
1d831c8819de54e945339aa2931dfe5aec548589 | 1,019 | require_relative './../../spec_helper'
describe 'ilo_test::computer_system_set' do
let(:resource_name) { 'computer_system' }
include_context 'chef context'
it 'set asset tag and indicator led' do
expect_any_instance_of(ILO_SDK::Client).to receive(:get_asset_tag).and_return('HP002')
expect_any_instance_of(ILO_SDK::Client).to receive(:get_indicator_led).and_return('On')
expect_any_instance_of(ILO_SDK::Client).to receive(:set_asset_tag).with('HP001').and_return(true)
expect_any_instance_of(ILO_SDK::Client).to receive(:set_indicator_led).with('Off').and_return(true)
expect(real_chef_run).to set_ilo_computer_system('set asset tag and indicator led')
end
it 'do not set asset tag and indicator led' do
expect_any_instance_of(ILO_SDK::Client).to receive(:get_asset_tag).and_return('HP001')
expect_any_instance_of(ILO_SDK::Client).to receive(:get_indicator_led).and_return('Off')
expect(real_chef_run).to set_ilo_computer_system('set asset tag and indicator led')
end
end
| 48.52381 | 103 | 0.773307 |
abae64521b7befeaa53441cc86aee1101c70ff33 | 2,522 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
feature 'Query menu items' do
let(:user) { FactoryGirl.create :admin }
let(:project) { FactoryGirl.create :project }
before do
User.stub(:current).and_return user
end
context 'with identical names' do
let(:query_a) { FactoryGirl.create :public_query, name: 'some query.', project: project }
let(:query_b) { FactoryGirl.create :public_query, name: query_a.name, project: project }
let!(:menu_item_a) { FactoryGirl.create :query_menu_item, query: query_a }
let!(:menu_item_b) { FactoryGirl.create :query_menu_item, query: query_b }
it 'can be shown' do
visit "/projects/#{project.identifier}"
expect(page).to have_selector('a', text: query_a.name, count: 2)
end
end
context 'with dots in their name' do
let(:query) { FactoryGirl.create :public_query, name: 'OP 3.0', project: project }
def check(input_name)
find(:css, "input[name=#{input_name}]").set true
end
it 'can be added', js: true do
visit project_work_packages_path(project, query_id: query.id)
click_on 'Settings'
click_on 'Share ...'
check 'show_in_menu'
click_on 'Save'
expect(page).to have_selector('.flash', text: 'Successful update')
expect(page).to have_selector('a', text: query.name)
end
end
end
| 34.547945 | 93 | 0.715702 |
1a251baefd3efa174abc48d5a47d2b38c205ec7f | 936 | class TenantPhonesController < ApplicationController
before_filter :manager_authorized?, :find_tenant
def create
begin
@tenant.contact.phones.create!(params[:phone])
rescue Exception => e
flash[:notice] = e.message
redirect_to m([@company, @property, @unit, @rental_agreement, @tenant, 'tenant_phones/new'])
else
flash[:notice] = 'New phone successfully created.'
redirect_to m([@company, @property, @unit, @rental_agreement, @tenant])
end
end
def edit
@phone = @tenant.contact.phones.find(params[:id])
end
def update
phone = @tenant.contact.phones.find(params[:id])
phone.update_attributes(params[:phone])
redirect_to m([@company, @property, @unit, @rental_agreement, @tenant])
end
def destroy
phone = @tenant.contact.phones.find(params[:id])
phone.destroy
redirect_to m([@company, @property, @unit, @rental_agreement, @tenant])
end
end
| 27.529412 | 98 | 0.685897 |
e27eb1f1dc4a6ef983bb54d1e2dafd77f5cece57 | 2,068 | # Copyright (c) 2010-2011, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3 or later. See
# the COPYRIGHT file.
class NotificationsController < ApplicationController
include NotificationsHelper
def update
note = Notification.where(:recipient_id => current_user.id, :id => params[:id]).first
if note
note.set_read_state(params[:set_unread] != "true" )
respond_to do |format|
format.json { render :json => { :guid => note.id, :unread => note.unread } }
end
else
respond_to do |format|
format.json { render :json => {}.to_json }
end
end
end
def index
conditions = {:recipient_id => current_user.id}
page = params[:page] || 1
per_page = params[:per_page] || 25
@notifications = WillPaginate::Collection.create(page, per_page, Notification.where(conditions).count ) do |pager|
result = Notification.find(:all,
:conditions => conditions,
:order => 'created_at desc',
:include => [:target, {:actors => :profile}],
:limit => pager.per_page,
:offset => pager.offset
)
pager.replace(result)
end
@notifications.each do |n|
n[:note_html] = render_to_string( :partial => 'notify_popup_item', :locals => { :n => n } )
end
@group_days = @notifications.group_by{|note| I18n.l(note.created_at, :format => I18n.t('date.formats.fullmonth_day')) }
respond_to do |format|
format.html
format.xml { render :xml => @notifications.to_xml }
format.json { render :json => @notifications.to_json }
end
end
def read_all
Notification.where(:recipient_id => current_user.id).update_all(:unread => false)
respond_to do |format|
format.html { redirect_to explore_path }
format.xml { render :xml => {}.to_xml }
format.json { render :json => {}.to_json }
end
end
end
| 33.354839 | 123 | 0.588975 |
5d174d70f01c283ab23ee315e6730a755e2616d1 | 879 | Pod::Spec.new do |s|
s.name = 'AmazonChimeSDK-Bitcode'
s.version = '0.19.2'
s.summary = 'Amazon Chime SDK for iOS with Bitcode support.'
s.description = 'An iOS client library for integrating multi-party communications powered by the Amazon Chime service.'
s.homepage = 'https://github.com/aws/amazon-chime-sdk-ios'
s.license = 'Apache License, Version 2.0'
s.author = { 'Amazon Web Services' => 'amazonwebservices' }
s.source = { :http => "https://amazon-chime-sdk-ios.s3.amazonaws.com/sdk/0.19.2/AmazonChimeSDK-0.19.2.tar.gz" }
s.ios.deployment_target = '10.0'
s.vendored_frameworks = "AmazonChimeSDK.xcframework"
s.swift_version = '5.0'
s.dependency 'AmazonChimeSDKMedia-Bitcode', '~> 0.15.2'
s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
end
| 54.9375 | 126 | 0.650739 |
1a982c226dae4aba583a78615c2496b9e9b5d2ab | 1,467 | begin
require 'puppet_x/sensu/to_type'
rescue LoadError => e
libdir = Pathname.new(__FILE__).parent.parent.parent
require File.join(libdir, 'puppet_x/sensu/to_type')
end
Puppet::Type.newtype(:sensu_client_subscription) do
@doc = ""
def initialize(*args)
super
self[:notify] = [
"Service[sensu-client]",
].select { |ref| catalog.resource(ref) }
end
ensurable do
newvalue(:present) do
provider.create
end
newvalue(:absent) do
provider.destroy
end
defaultto :present
end
newparam(:name) do
desc "The subscription name"
end
newparam(:base_path) do
desc "The base path to the client config file"
defaultto '/etc/sensu/conf.d/'
end
newparam(:subscriptions) do
desc "Subscriptions included"
defaultto :name
munge do |value|
Array(value)
end
end
newproperty(:custom) do
desc "Custom client variables"
include Puppet_X::Sensu::Totype
def is_to_s(hash = @is)
hash.keys.sort.map {|key| "#{key} => #{hash[key]}"}.join(", ")
end
def should_to_s(hash = @should)
hash.keys.sort.map {|key| "#{key} => #{hash[key]}"}.join(", ")
end
def insync?(is)
if defined? @should[0]
if is == @should[0].each { |k, v| value[k] = to_type(v) }
true
else
false
end
else
true
end
end
defaultto {}
end
autorequire(:package) do
['sensu']
end
end
| 18.56962 | 68 | 0.599864 |
2179420f9699391c78a1fc006bcdcc70f2e92c16 | 716 | require 'test_helper'
class ConversationsControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
setup do
sign_in users(:alice)
end
test 'should get index' do
get conversations_url
assert_response :success
end
test 'should create conversation' do
assert_difference('Conversation.count') do
post conversations_url, params: {
conversation: {
user_id: users(:alice).id,
participant_id: users(:alice).id
}
}
end
assert_redirected_to conversation_url(Conversation.last)
end
test 'should show conversation' do
get conversation_url conversations(:one)
assert_response :success
end
end
| 21.69697 | 67 | 0.705307 |
2885bc23b682f0db8a406c8e5b1f8c1c50e80b6b | 2,457 | require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Selma", email: "[email protected]",
password: "foobar", password_confirmation: "foobar")
end
test "should be valid" do
assert @user.valid?
end
test "name should be present" do
@user.name = " "
assert_not @user.valid?
end
test "email should be present" do
@user.email = " "
assert_not @user.valid?
end
test "name should not be too long" do
@user.name = "a" * 51
assert_not @user.valid?
end
test "email should not be too long" do
@user.email = "a" * 244 + "@example.com"
assert_not @user.valid?
end
test "email validation should accept valid addresses" do
valid_addresses = %w[[email protected] [email protected] [email protected]
[email protected] [email protected]]
valid_addresses.each do |valid_address|
@user.email = valid_address
assert @user.valid?, "#{valid_address.inspect} should be valid"
end
end
test "email validation should reject invalid addresses" do
invalid_addresses = %w[user@example,com user_at_foo.org user.name@example.
foo@bar_baz.com foo@bar+baz.com]
invalid_addresses.each do |invalid_address|
@user.email = invalid_address
assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"
end
end
test "email addresses should be unique" do
duplicate_user = @user.dup
duplicate_user.email = @user.email.upcase
@user.save
assert_not duplicate_user.valid?
end
test "email addresses should be saved as lower-case" do
mixed_case_email = "[email protected]"
@user.email = mixed_case_email
@user.save
assert_equal mixed_case_email.downcase, @user.reload.email
end
test "password should be present (nonblank)" do
@user.password = @user.password_confirmation = " " * 6
assert_not @user.valid?
end
test "password should have a minimum length" do
@user.password = @user.password_confirmation = "a" * 5
assert_not @user.valid?
end
test "authenticated? should return false for a user with nil digest" do
assert_not @user.authenticated?(:remember, '')
end
test "associated microposts should be destroyed" do
@user.save
@user.microposts.create!(content: "Lorem ipsum")
assert_difference 'Micropost.count', -1 do
@user.destroy
end
end
end
| 28.241379 | 78 | 0.671144 |
7903c2059524d757c94ec8955d57aabd458efed6 | 1,781 | # Frozen-string-literal: true
# Copyright: 2012 - 2018 - MIT License
# Encoding: utf-8
require "liquid/drop"
require "fastimage"
module Jekyll
module Assets
class Drop < Liquid::Drop
extend Forwardable::Extended
def initialize(path, jekyll:)
@path = path.to_s
@sprockets = jekyll.sprockets
@jekyll = jekyll
@asset = nil
end
rb_delegate :width, to: :dimensions, type: :hash
rb_delegate :height, to: :dimensions, type: :hash
rb_delegate :basename, to: :File, args: :@path
rb_delegate :content_type, to: :asset
rb_delegate :integrity, to: :asset
rb_delegate :filename, to: :asset
# --
# @todo this needs to move to `_url`
# @return [String] the prefixed and digested path.
# The digest path.
# --
def digest_path
@sprockets.prefix_url(asset.digest_path)
end
# --
# Image dimensions if the asest is an image.
# @return [Hash<Integer,Integer>] the dimensions.
# @note this can break easily.
# --
def dimensions
@dimensions ||= begin
img = FastImage.size(asset.filename.to_s)
{
"width" => img[0],
"height" => img[1],
}
rescue => e
Logger.error e
end
end
private
def asset
@asset ||= begin
@sprockets.find_asset!(@path)
end
end
# --
# Register the drop creator.
# @return [nil]
# --
public
def self.register
Jekyll::Hooks.register :site, :pre_render do |s, h|
if s.sprockets
h["assets"] = s.sprockets.to_liquid_payload
end
end
end
end
end
end
| 23.746667 | 61 | 0.542953 |
e9010bbb3a59168b2c5716edc955c1a405566bdf | 605 | git_plugin = self
namespace :puma do
desc 'Setup nginx configuration'
task :nginx_config do
on roles(fetch(:puma_nginx, :web)) do |role|
git_plugin.puma_switch_user(role) do
git_plugin.template_puma('nginx_conf', "/tmp/nginx_#{fetch(:nginx_config_name)}", role)
execute :mv, "/tmp/nginx_#{fetch(:nginx_config_name)} #{fetch(:nginx_sites_available_path)}/#{fetch(:nginx_config_name)}"
execute :ln, '-fs', "#{fetch(:nginx_sites_available_path)}/#{fetch(:nginx_config_name)} #{fetch(:nginx_sites_enabled_path)}/#{fetch(:nginx_config_name)}"
end
end
end
end
| 40.333333 | 161 | 0.702479 |
87a3e15e0a15bd9b65ead8fe7f70e6a86f3bab3b | 867 | require 'test_helper'
class UsersIndexTest < ActionDispatch::IntegrationTest
def setup
@admin = users(:michael)
@non_admin = users(:archer)
end
test "index as admin including pagination and delete links" do
log_in_as @admin
get users_path
assert_template 'users/index'
assert_select 'div.pagination'
first_page_of_users.each do |user|
assert_select 'a[href=?]', user_path(user), text: user.name
unless user == @admin
assert_select 'a[href=?]', user_path(user), text: 'delete'
end
end
assert_difference 'User.count', -1 do
delete user_path @non_admin
end
end
test "index as non-admin" do
log_in_as @non_admin
get users_path
first_page_of_users.each do |user|
assert_select 'a[href=?]', user_path(user), text: 'delete', count: 0
end
end
private
def first_page_of_users
User.paginate(page: 1)
end
end
| 21.675 | 71 | 0.717416 |
6a3223f013de651524b666c3bd36692e8b37e714 | 694 | cask "chia" do
version "1.1.7"
sha256 "0413ebeba010b922bb21ff4630cadfa86096a107cce6ecb37f8902969340e6ba"
url "https://github.com/Chia-Network/chia-blockchain/releases/download/#{version}/Chia-#{version}.dmg",
verified: "github.com/Chia-Network/chia-blockchain/"
name "Chia Blockchain"
desc "GUI Python implementation for the Chia blockchain"
homepage "https://www.chia.net/"
livecheck do
url :url
strategy :github_latest
end
app "Chia.app"
zap trash: [
"~/Library/Application Support/Chia Blockchain",
"~/Library/Preferences/net.chia.blockchain.plist",
"~/Library/Saved Application State/net.chia.blockchain.savedState",
"~/.chia",
]
end
| 27.76 | 105 | 0.71902 |
f8672bec5668b6d1cb089ecc18df6b66af8dcdab | 3,969 | # frozen_string_literal: true
class User < ApplicationRecord
DELETED = "[deleted]"
INVITES_PER_DAY = 10
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
:confirmable, :lockable, authentication_keys: [:username]
enum role: {
member: 0,
moderator: 10,
admin: 20,
deactivated: 100
}
enum ban_type: {
temp: 0,
perma: 1
}, _suffix: :banned
has_many :submissions
has_many :submission_actions
has_many :comments
has_many :votes
has_many :sent_user_invitations, foreign_key: :sender_id, class_name: :UserInvitation
has_many :thread_reply_notifications, foreign_key: :recipient_id
has_many :flattened_thread_reply_notifications, foreign_key: :recipient_id
has_one :received_user_invitation, foreign_key: :recipient_id, class_name: :UserInvitation, required: false
belongs_to :banned_by, class_name: "User", optional: true
validates :username, presence: true
validate :username_not_restricted?
scope :active, -> { where.not(role: :deactivated) }
def self.find_first_by_auth_conditions(warden_conditions)
if warden_conditions.key?(:confirmation_token)
super
else
warden_conditions.fetch(:username, nil).then do |username|
active.where("lower(username) = ?", username.downcase).first if username.present?
end
end
end
def self.include_submission_counts_and_karma
joins(
%{
LEFT JOIN (
SELECT submissions.user_id, COUNT(1) AS submission_count,
SUM(
(
(
SELECT COUNT(votable_id) FROM votes
WHERE votable_type = 'Submission' AND votable_id = submissions.id AND kind = 0
) -
(
SELECT COUNT(votable_id) FROM votes
WHERE votable_type = 'Submission' AND votable_id = submissions.id AND kind = 1
)
)
)::integer AS submission_karma
FROM submissions
GROUP BY submissions.user_id
) scs
ON users.id = scs.user_id
}.squish
)
end
def self.include_comment_counts_and_karma
joins(
%{
LEFT JOIN (
SELECT comments.user_id, COUNT(1) AS comment_count,
SUM(
(
(
SELECT COUNT(votable_id) FROM votes
WHERE votable_type = 'Comment' AND votable_id = comments.id AND kind = 0
) -
(
SELECT COUNT(votable_id) FROM votes
WHERE votable_type = 'Comment' AND votable_id = comments.id AND kind = 1
)
)
)::integer AS comment_karma
FROM comments
GROUP BY comments.user_id
) ccs
ON users.id = ccs.user_id
}.squish
)
end
def banned?
(banned_at.present? && unbanned_at.nil?) ||
(
banned_at.present? && unbanned_at.nil? &&
temp_ban_end_at.present? && Time.current < temp_ban_end_at
)
end
def update_last_submission_at!
update!(last_submission_at: Time.zone.now)
end
def minutes_until_next_submission
if last_submission_at.nil?
0.0
else
last_submitted = last_submission_at.in_time_zone(Time.zone)
[(10.minutes.since(last_submitted) - Time.zone.now) / 1.minute, 0.0].max.round
end
end
def can_invite?
admin? || daily_invites_under_maximum?
end
def has_mod_permissions?
admin? || moderator?
end
private
def daily_invites_under_maximum?
now = Time.zone.now
sent_user_invitations.
where(sent_at: (now.beginning_of_day..now.end_of_day)).
count < INVITES_PER_DAY
end
def username_not_restricted?
if username.present? && username.downcase == DELETED
errors.add(:username, :invalid)
end
end
end
| 27.5625 | 109 | 0.637692 |
b9ede241e0ddb57f6def491eb90d32c86aa9f72b | 2,572 | require "json"
require "date"
require "afip_bill/check_digit"
require "pdfkit"
require "rqrcode"
module AfipBill
class Generator
attr_reader :afip_bill, :bill_type, :user, :line_items, :header_text
AFIP_QR_URL = 'https://www.afip.gob.ar/fe/qr/'
HEADER_PATH = File.dirname(__FILE__) + '/views/shared/_factura_header.html.erb'.freeze
FOOTER_PATH = File.dirname(__FILE__) + '/views/shared/_factura_footer.html.erb'.freeze
BRAVO_CBTE_TIPO = { "01" => "Factura A", "06" => "Factura B", "11" => "Factura C" }.freeze
IVA = 21.freeze
def initialize(bill, user, line_items = [], header_text = 'ORIGINAL')
@afip_bill = JSON.parse(bill)
@user = user
@bill_type = type_a_or_b_bill
@line_items = line_items
@template_header = ERB.new(File.read(HEADER_PATH)).result(binding)
@template_footer = ERB.new(File.read(FOOTER_PATH)).result(binding)
@header_text = header_text
end
def type_a_or_b_bill
BRAVO_CBTE_TIPO[afip_bill["cbte_tipo"]][-1].downcase
end
def qr_code_data_url
@qr_code ||= RQRCode::QRCode.new(qr_code_string).as_png(
bit_depth: 1,
border_modules: 2,
color_mode: ChunkyPNG::COLOR_GRAYSCALE,
color: 'black',
file: nil,
fill: 'white',
module_px_size: 12,
resize_exactly_to: false,
resize_gte_to: false,
size: 120
).to_data_url
end
def generate_pdf_file
tempfile = Tempfile.new(["factura_afip", '.pdf' ])
PDFKit.new(template, disable_smart_shrinking: true).to_file(tempfile.path)
end
def generate_pdf_string
PDFKit.new(template, disable_smart_shrinking: true).to_pdf
end
private
def bill_path
File.dirname(__FILE__) + "/views/bills/factura_#{bill_type}.html.erb"
end
def qr_code_string
"#{AFIP_QR_URL}?p=#{Base64.encode64(qr_hash.to_json)}"
end
def qr_hash
{
ver: 1,
fecha: Date.parse(afip_bill["cbte_fch"]).strftime("%Y-%m-%d"),
cuit: AfipBill.configuration[:business_cuit],
ptoVta: AfipBill.configuration[:sale_point],
tipoCmp: afip_bill["cbte_tipo"],
nroCmp: afip_bill["cbte_hasta"].to_s.rjust(8, "0"),
importe: afip_bill["imp_total"],
moneda: "PES",
ctz: 1,
tipoDocRec: user.afip_document_type,
nroDocRec: afip_bill["doc_num"].tr("-", "").strip,
tipoCodAut: "E",
codAut: afip_bill["cae"]
}
end
def template
ERB.new(File.read(bill_path)).result(binding)
end
end
end
| 29.227273 | 94 | 0.639969 |
b98a9bb89fdeeed3f5cdaf67f218881cdabb9af7 | 1,903 | require 'rspec'
require 'krypt'
require 'stringio'
describe Krypt::Hex::Encoder do
let(:klass) { Krypt::Hex::Encoder }
def write_string(s)
io = StringIO.new
hex = klass.new(io)
hex << s
hex.close
io.string
end
def read_string(s)
io = StringIO.new(s)
hex = klass.new(io)
begin
hex.read
ensure
hex.close
end
end
describe "new" do
it "mandates a single parameter, the underlying IO" do
klass.new(StringIO.new).should be_an_instance_of klass
end
context "takes a block after whose execution the IO is closed" do
specify "successful execution of the block" do
io = StringIO.new
klass.new(io) do |hex|
hex << "test"
end
io.closed?.should == true
end
specify "failed execution of the block" do
io = StringIO.new
begin
klass.new(io) do
raise RuntimeError.new
end
rescue RuntimeError
io.closed?.should == true
end
end
end
end
shared_examples_for "RFC 4648 hex encode" do |meth|
context "RFC 4648 test vectors" do
specify "empty string" do
send(meth, "").should == ""
end
specify "f" do
send(meth, "f").should == "66"
end
specify "fo" do
send(meth, "fo").should == "666f"
end
specify "foo" do
send(meth, "foo").should == "666f6f"
end
specify "foob" do
send(meth, "foob").should == "666f6f62"
end
specify "fooba" do
send(meth, "fooba").should == "666f6f6261"
end
specify "foobar" do
send(meth, "foobar").should == "666f6f626172"
end
end
end
describe "#read" do
it_behaves_like "RFC 4648 hex encode", :read_string
end
describe "#write" do
it_behaves_like "RFC 4648 hex encode", :write_string
end
end
| 20.031579 | 69 | 0.57278 |
61984c378d16fecd4deac5f34aa9fe8ce959509f | 1,167 | require File.expand_path("#{File.dirname(__FILE__)}/../../../spec_helper.rb")
require 'ghost/cli'
describe Ghost::Cli, :type => :cli do
describe "help" do
let(:overview) do
<<-EOF.unindent
USAGE: ghost <task> [<args>]
The ghost tasks are:
add Add a host
bust Clear all ghost-managed hosts
delete Remove a ghost-managed host
export Export all hosts in /etc/hosts format
import Import hosts in /etc/hosts format
list Show all (or a filtered) list of hosts
set Add a host or modify the IP of an existing host
See 'ghost help <task>' for more information on a specific task.
EOF
end
it 'displays help overview when called with no args' do
ghost("").should == overview
end
it 'displays help overview when help task is called with no arguments' do
ghost("help").should == overview
end
context "when no help text for a given topic is available" do
it "prints out a message" do
ghost("help missing").should == "No help for task 'missing'\n"
end
end
end
end
| 30.710526 | 77 | 0.605827 |
0820b79894adb5c70a457b01a19070f1144c4bab | 2,137 | # frozen_string_literal: true
require "noun_project_api/retriever"
module NounProjectApi
# Retrieve icons.
class IconsRetriever < Retriever
API_PATH = "/icons/"
# Finds multiple icons based on the term
# * term - search term
# * limit - limit the amount of results
# * offset - offset the results
# * page - page number
def find(term, limit = nil, offset = nil, page = nil)
cache_key = Digest::MD5.hexdigest("#{term}+#{limit}+#{offset}+#{page}")
cache_ttl = NounProjectApi.configuration.cache_ttl
NounProjectApi.configuration.cache.fetch(cache_key, expires_in: cache_ttl) do
raise ArgumentError, "Missing search term" unless term
search = OAuth::Helper.escape(term)
search += "?limit_to_public_domain=#{NounProjectApi.configuration.public_domain ? 1 : 0}"
args = {
"limit" => limit,
"offset" => offset,
"page" => page
}.reject { |_, v| v.nil? }
args.each { |k, v| search += "&#{k}=#{v}" } unless args.empty?
result = access_token.get("#{API_BASE}#{API_PATH}#{search}")
raise ServiceError.new(result.code, result.body) unless ["200", "404"].include? result.code
if result.code == "200"
JSON.parse(result.body, symbolize_names: true)[:icons].map { |icon| Icon.new(icon) }
else
[]
end
end
end
# List recent uploads
# * limit - limit the amount of results
# * offset - offset the results
# * page - page number
def recent_uploads(limit = nil, offset = nil, page = nil)
args = {
"limit" => limit,
"offset" => offset,
"page" => page
}.reject { |_, v| v.nil? }
if !args.empty?
search = "?"
args.each { |k, v| search += "#{k}=#{v}&" }
else
search = ""
end
result = access_token.get("#{API_BASE}#{API_PATH}recent_uploads#{search}")
raise ServiceError.new(result.code, result.body) unless result.code == "200"
JSON.parse(result.body, symbolize_names: true)[:recent_uploads].map { |icon| Icon.new(icon) }
end
end
end
| 31.895522 | 99 | 0.592887 |
3304cfe11132ef106369291e5be3845108a553fd | 381 | module Sipity
RSpec.describe WorkflowAction, type: :model, no_clean: true do
context 'database configuration' do
subject { described_class }
its(:column_names) { is_expected.to include('workflow_id') }
its(:column_names) { is_expected.to include('resulting_workflow_state_id') }
its(:column_names) { is_expected.to include('name') }
end
end
end
| 34.636364 | 82 | 0.708661 |
4aae0e9f3554897ec57f9c542e1912546b975016 | 2,933 | # frozen_string_literal: true
module RuboCop
module Cop
# Common functionality for modifier cops.
module StatementModifier
include LineLengthHelp
private
def single_line_as_modifier?(node)
return false if non_eligible_node?(node) ||
non_eligible_body?(node.body) ||
non_eligible_condition?(node.condition)
modifier_fits_on_single_line?(node)
end
def non_eligible_node?(node)
node.modifier_form? ||
node.nonempty_line_count > 3 ||
processed_source.line_with_comment?(node.loc.last_line)
end
def non_eligible_body?(body)
body.nil? ||
body.empty_source? ||
body.begin_type? ||
processed_source.contains_comment?(body.source_range)
end
def non_eligible_condition?(condition)
condition.each_node.any?(&:lvasgn_type?)
end
def modifier_fits_on_single_line?(node)
return true unless max_line_length
length_in_modifier_form(node) <= max_line_length
end
def length_in_modifier_form(node)
keyword_element = node.loc.keyword
end_element = node.loc.end
code_before = keyword_element.source_line[0...keyword_element.column]
code_after = end_element.source_line[end_element.last_column..-1]
expression = to_modifier_form(node)
line_length("#{code_before}#{expression}#{code_after}")
end
def to_modifier_form(node)
expression = [node.body.source,
node.keyword,
node.condition.source].compact.join(' ')
parenthesized = parenthesize?(node) ? "(#{expression})" : expression
[parenthesized, first_line_comment(node)].compact.join(' ')
end
def first_line_comment(node)
comment = processed_source.find_comment { |c| c.loc.line == node.loc.line }
return unless comment
comment_source = comment.loc.expression.source
comment_source unless comment_disables_cop?(comment_source)
end
def parenthesize?(node)
# Parenthesize corrected expression if changing to modifier-if form
# would change the meaning of the parent expression
# (due to the low operator precedence of modifier-if)
parent = node.parent
return false if parent.nil?
return true if parent.assignment? || parent.operator_keyword?
return true if %i[array pair].include?(parent.type)
node.parent.send_type?
end
def max_line_length
return unless config.for_cop('Layout/LineLength')['Enabled']
config.for_cop('Layout/LineLength')['Max']
end
def comment_disables_cop?(comment)
regexp_pattern = "# rubocop : (disable|todo) ([^,],)* (all|#{cop_name})"
Regexp.new(regexp_pattern.gsub(' ', '\s*')).match?(comment)
end
end
end
end
| 31.880435 | 83 | 0.642687 |
0367426794931064ff5370ebbb997c305689b85c | 26,422 | # frozen_string_literal: true
require 'spec_helper'
describe "Stealth::Controller replies" do
Stealth::Controller._replies_path = File.expand_path("../replies", __dir__)
let(:facebook_message) { SampleMessage.new(service: 'facebook') }
let(:controller) { MessagesController.new(service_message: facebook_message.message_with_text) }
# Stub out base Facebook integration
module Stealth
module Services
module Facebook
class ReplyHandler
end
class Client
end
end
end
end
class MessagesController < Stealth::Controller
def say_oi
@first_name = "Presley"
send_replies
end
def say_offer
send_replies
end
def say_offer_with_dynamic
send_replies
end
def say_msgs_without_breaks
send_replies
end
def say_uh_oh
send_replies
end
def say_randomize_text
send_replies
end
def say_randomize_speech
send_replies
end
def say_custom_reply
send_replies custom_reply: 'messages/say_offer'
end
def say_howdy_with_dynamic
send_replies
end
def say_nested_custom_reply
send_replies custom_reply: 'messages/sub1/sub2/say_nested'
end
def say_inline_reply
reply = [
{ 'reply_type' => 'text', 'text' => 'Hi, Morty. Welcome to Stealth bot...' },
{ 'reply_type' => 'delay', 'duration' => 2 },
{ 'reply_type' => 'text', 'text' => 'We offer users an awesome Ruby framework for building chat bots.' }
]
send_replies inline: reply
end
end
describe "missing reply" do
it "should raise a Stealth::Errors::ReplyNotFound" do
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_uh_oh")
expect {
controller.send_replies
}.to raise_error(Stealth::Errors::ReplyNotFound)
end
end
describe "class attributes" do
it "should have altered the _replies_path class attribute" do
expect(MessagesController._replies_path).to eq(File.expand_path("../replies", __dir__))
end
it "should have altered the _preprocessors class attribute" do
expect(MessagesController._preprocessors).to eq([:erb])
end
end
describe "action_replies" do
it "should select the :erb preprocessor when reply extension is .yml" do
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_oi")
file_contents, selected_preprocessor = controller.send(:action_replies)
expect(selected_preprocessor).to eq(:erb)
end
it "should select the :none preprocessor when there is no reply extension" do
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_offer")
file_contents, selected_preprocessor = controller.send(:action_replies)
expect(selected_preprocessor).to eq(:none)
end
it "should read the reply's file contents" do
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_offer")
file_contents, selected_preprocessor = controller.send(:action_replies)
expect(file_contents).to eq(File.read(File.expand_path("../replies/messages/say_offer.yml", __dir__)))
end
end
describe "reply with ERB" do
let(:stubbed_handler) { double("handler") }
let(:stubbed_client) { double("client") }
before(:each) do
allow(Stealth::Services::Facebook::ReplyHandler).to receive(:new).and_return(stubbed_handler)
allow(Stealth::Services::Facebook::Client).to receive(:new).and_return(stubbed_client)
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_oi")
Stealth.config.auto_insert_delays = false
end
after(:each) do
Stealth.config.auto_insert_delays = true
end
it "should translate each reply_type in the reply" do
allow(stubbed_client).to receive(:transmit).and_return(true)
allow(controller).to receive(:sleep).and_return(true)
expect(stubbed_handler).to receive(:text).exactly(3).times
expect(stubbed_handler).to receive(:delay).exactly(2).times
controller.say_oi
end
it "should transmit each reply_type in the reply" do
allow(stubbed_handler).to receive(:text).exactly(3).times
allow(stubbed_handler).to receive(:delay).exactly(2).times
allow(controller).to receive(:sleep).and_return(true)
expect(stubbed_client).to receive(:transmit).exactly(5).times
controller.say_oi
end
it "should sleep on delays" do
allow(stubbed_handler).to receive(:text).exactly(3).times
allow(stubbed_handler).to receive(:delay).exactly(2).times
allow(stubbed_client).to receive(:transmit).exactly(5).times
expect(controller).to receive(:sleep).exactly(2).times
controller.say_oi
end
end
describe "plain reply" do
let(:stubbed_handler) { double("handler") }
let(:stubbed_client) { double("client") }
before(:each) do
allow(Stealth::Services::Facebook::ReplyHandler).to receive(:new).and_return(stubbed_handler)
allow(Stealth::Services::Facebook::Client).to receive(:new).and_return(stubbed_client)
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_offer")
Stealth.config.auto_insert_delays = false
end
after(:each) do
Stealth.config.auto_insert_delays = true
end
it "should translate each reply_type in the reply" do
allow(stubbed_client).to receive(:transmit).and_return(true)
allow(controller).to receive(:sleep).and_return(true).with(2.0)
expect(stubbed_handler).to receive(:text).exactly(2).times
expect(stubbed_handler).to receive(:delay).exactly(1).times
controller.say_offer
end
it "should transmit each reply_type in the reply" do
allow(stubbed_handler).to receive(:text).exactly(2).times
allow(stubbed_handler).to receive(:delay).exactly(1).times
allow(controller).to receive(:sleep).and_return(true).with(2.0)
expect(stubbed_client).to receive(:transmit).exactly(3).times
controller.say_offer
end
it "should sleep on delays" do
allow(stubbed_handler).to receive(:text).exactly(2).times
allow(stubbed_handler).to receive(:delay).exactly(1).times
allow(stubbed_client).to receive(:transmit).exactly(3).times
expect(controller).to receive(:sleep).exactly(1).times.with(2.0)
controller.say_offer
end
end
describe "custom_reply" do
let(:stubbed_handler) { double("handler") }
let(:stubbed_client) { double("client") }
before(:each) do
allow(Stealth::Services::Facebook::ReplyHandler).to receive(:new).and_return(stubbed_handler)
allow(Stealth::Services::Facebook::Client).to receive(:new).and_return(stubbed_client)
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_custom_reply")
Stealth.config.auto_insert_delays = false
end
after(:each) do
Stealth.config.auto_insert_delays = true
end
it "should translate each reply_type in the reply" do
allow(stubbed_client).to receive(:transmit).and_return(true)
allow(controller).to receive(:sleep).and_return(true).with(2.0)
expect(stubbed_handler).to receive(:text).exactly(2).times
expect(stubbed_handler).to receive(:delay).exactly(1).times
controller.say_custom_reply
end
it "should transmit each reply_type in the reply" do
allow(stubbed_handler).to receive(:text).exactly(2).times
allow(stubbed_handler).to receive(:delay).exactly(1).times
allow(controller).to receive(:sleep).and_return(true).with(2.0)
expect(stubbed_client).to receive(:transmit).exactly(3).times
controller.say_custom_reply
end
it "should sleep on delays" do
allow(stubbed_handler).to receive(:text).exactly(2).times
allow(stubbed_handler).to receive(:delay).exactly(1).times
allow(stubbed_client).to receive(:transmit).exactly(3).times
expect(controller).to receive(:sleep).exactly(1).times.with(2.0)
controller.say_custom_reply
end
it "should correctly load from sub-dirs" do
expect(stubbed_handler).to receive(:text).exactly(3).times
expect(stubbed_handler).to receive(:delay).exactly(2).times
expect(stubbed_client).to receive(:transmit).exactly(5).times
expect(controller).to receive(:sleep).exactly(2).times.with(2.0)
controller.say_nested_custom_reply
end
end
describe "inline replies" do
let(:stubbed_handler) { double("handler") }
let(:stubbed_client) { double("client") }
before(:each) do
allow(Stealth::Services::Facebook::ReplyHandler).to receive(:new).and_return(stubbed_handler)
allow(Stealth::Services::Facebook::Client).to receive(:new).and_return(stubbed_client)
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_inline_reply")
Stealth.config.auto_insert_delays = false
end
after(:each) do
Stealth.config.auto_insert_delays = true
end
it "should translate each reply_type in the reply" do
allow(stubbed_client).to receive(:transmit).and_return(true)
allow(controller).to receive(:sleep).and_return(true).with(2.0)
expect(stubbed_handler).to receive(:text).exactly(2).times
expect(stubbed_handler).to receive(:delay).exactly(1).times
controller.say_inline_reply
end
it "should transmit each reply_type in the reply" do
allow(stubbed_handler).to receive(:text).exactly(2).times
allow(stubbed_handler).to receive(:delay).exactly(1).times
allow(controller).to receive(:sleep).and_return(true).with(2.0)
expect(stubbed_client).to receive(:transmit).exactly(3).times
controller.say_inline_reply
end
it "should sleep on delays" do
allow(stubbed_handler).to receive(:text).exactly(2).times
allow(stubbed_handler).to receive(:delay).exactly(1).times
allow(stubbed_client).to receive(:transmit).exactly(3).times
expect(controller).to receive(:sleep).exactly(1).times.with(2.0)
controller.say_inline_reply
end
end
describe "auto delays" do
let(:stubbed_handler) { double("handler") }
let(:stubbed_client) { double("client") }
before(:each) do
allow(Stealth::Services::Facebook::ReplyHandler).to receive(:new).and_return(stubbed_handler)
allow(Stealth::Services::Facebook::Client).to receive(:new).and_return(stubbed_client)
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_msgs_without_breaks")
end
it "should add two additional delays to a reply without delays" do
allow(stubbed_client).to receive(:transmit).and_return(true)
allow(controller).to receive(:sleep).and_return(true)
expect(stubbed_handler).to receive(:text).exactly(2).times
expect(stubbed_handler).to receive(:delay).exactly(2).times
controller.say_msgs_without_breaks
end
it "should only add a single delay to a reply that already contains a delay" do
allow(stubbed_client).to receive(:transmit).and_return(true)
allow(controller).to receive(:sleep).and_return(true)
expect(stubbed_handler).to receive(:text).exactly(2).times
expect(stubbed_handler).to receive(:delay).exactly(2).times
controller.say_offer
end
it "should not add delays if auto_insert_delays = false" do
allow(stubbed_client).to receive(:transmit).and_return(true)
allow(controller).to receive(:sleep).and_return(true)
expect(stubbed_handler).to receive(:text).exactly(2).times
expect(stubbed_handler).to_not receive(:delay)
Stealth.config.auto_insert_delays = false
controller.say_msgs_without_breaks
Stealth.config.auto_insert_delays = true
end
end
describe "session locking" do
let(:stubbed_handler) { double("handler") }
let(:stubbed_client) { double("client") }
before(:each) do
allow(Stealth::Services::Facebook::ReplyHandler).to receive(:new).and_return(stubbed_handler)
allow(Stealth::Services::Facebook::Client).to receive(:new).and_return(stubbed_client)
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_offer")
Stealth.config.auto_insert_delays = false
end
after(:each) do
Stealth.config.auto_insert_delays = true
end
it "should update the lock for each reply_type in the reply" do
allow(stubbed_client).to receive(:transmit).and_return(true)
allow(controller).to receive(:sleep).and_return(true).with(2.0)
expect(controller).to receive(:lock_session!).exactly(3).times
expect(stubbed_handler).to receive(:text).exactly(2).times
expect(stubbed_handler).to receive(:delay).exactly(1).times
controller.say_offer
end
it "should update the lock position for each reply_type in the reply" do
allow(stubbed_client).to receive(:transmit).and_return(true)
allow(controller).to receive(:sleep).and_return(true).with(2.0)
expect(controller).to receive(
:lock_session!
).with(
session_slug: controller.current_session.get_session,
position: 0
).exactly(1).times
expect(controller).to receive(
:lock_session!
).with(
session_slug: controller.current_session.get_session,
position: 1
).exactly(1).times
expect(controller).to receive(
:lock_session!
).with(
session_slug: controller.current_session.get_session,
position: 2
).exactly(1).times
expect(stubbed_handler).to receive(:text).exactly(2).times
expect(stubbed_handler).to receive(:delay).exactly(1).times
controller.say_offer
end
it "should update the lock position with an offset for each reply_type in the reply" do
allow(stubbed_client).to receive(:transmit).and_return(true)
allow(controller).to receive(:sleep).and_return(true)
controller.pos = 17 # set the offset
expect(controller).to receive(
:lock_session!
).with(
session_slug: controller.current_session.get_session,
position: 17
).exactly(1).times
expect(controller).to receive(
:lock_session!
).with(
session_slug: controller.current_session.get_session,
position: 18
).exactly(1).times
expect(controller).to receive(
:lock_session!
).with(
session_slug: controller.current_session.get_session,
position: 19
).exactly(1).times
expect(controller).to receive(
:lock_session!
).with(
session_slug: controller.current_session.get_session,
position: 20
).exactly(1).times
expect(stubbed_handler).to receive(:cards).exactly(1).time
expect(stubbed_handler).to receive(:list).exactly(1).time
expect(stubbed_handler).to receive(:delay).exactly(2).times
allow(controller.current_session).to receive(:state_string).and_return("say_howdy_with_dynamic")
controller.say_howdy_with_dynamic
end
end
describe "dynamic delays" do
let(:stubbed_handler) { double("handler") }
let(:stubbed_client) { double("client") }
before(:each) do
allow(Stealth::Services::Facebook::ReplyHandler).to receive(:new).and_return(stubbed_handler)
allow(Stealth::Services::Facebook::Client).to receive(:new).and_return(stubbed_client)
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_offer_with_dynamic")
end
it "should use the default multiplier if none is set" do
allow(stubbed_handler).to receive(:text).exactly(2).times
allow(stubbed_handler).to receive(:delay).exactly(2).times
allow(stubbed_client).to receive(:transmit).exactly(4).times
delay = Stealth.config.dynamic_delay_muliplier * Stealth::Controller::DynamicDelay::SHORT_DELAY
expect(controller).to receive(:sleep).exactly(2).times.with(delay)
controller.say_offer_with_dynamic
end
it "should slow down SHORT_DELAY if dynamic_delay_muliplier > 1" do
allow(stubbed_handler).to receive(:text).exactly(2).times
allow(stubbed_handler).to receive(:delay).exactly(2).times
allow(stubbed_client).to receive(:transmit).exactly(4).times
Stealth.config.dynamic_delay_muliplier = 5
delay = Stealth.config.dynamic_delay_muliplier * Stealth::Controller::DynamicDelay::SHORT_DELAY
expect(controller).to receive(:sleep).exactly(2).times.with(delay)
controller.say_offer_with_dynamic
end
it "should speed up SHORT_DELAY if dynamic_delay_muliplier < 1" do
allow(stubbed_handler).to receive(:text).exactly(2).times
allow(stubbed_handler).to receive(:delay).exactly(2).times
allow(stubbed_client).to receive(:transmit).exactly(4).times
Stealth.config.dynamic_delay_muliplier = 0.1
delay = Stealth.config.dynamic_delay_muliplier * Stealth::Controller::DynamicDelay::SHORT_DELAY
expect(controller).to receive(:sleep).exactly(2).times.with(delay)
controller.say_offer_with_dynamic
end
end
describe "variants" do
let(:twilio_message) { SampleMessage.new(service: 'twilio') }
let(:twilio_controller) { MessagesController.new(service_message: twilio_message.message_with_text) }
let(:epsilon_message) { SampleMessage.new(service: 'epsilon') }
let(:epsilon_controller) { MessagesController.new(service_message: epsilon_message.message_with_text) }
let(:gamma_message) { SampleMessage.new(service: 'twitter') }
let(:gamma_controller) { MessagesController.new(service_message: gamma_message.message_with_text) }
it "should load the Facebook reply variant if current_service == facebook" do
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_hola")
file_contents, selected_preprocessor = controller.send(:action_replies)
expect(file_contents).to eq(File.read(File.expand_path("../replies/messages/say_hola.yml+facebook.erb", __dir__)))
end
it "should load the Twilio reply variant if current_service == twilio" do
allow(twilio_controller.current_session).to receive(:flow_string).and_return("message")
allow(twilio_controller.current_session).to receive(:state_string).and_return("say_hola")
file_contents, selected_preprocessor = twilio_controller.send(:action_replies)
expect(file_contents).to eq(File.read(File.expand_path("../replies/messages/say_hola.yml+twilio.erb", __dir__)))
end
it "should load the base reply variant if current_service does not have a custom variant" do
allow(epsilon_controller.current_session).to receive(:flow_string).and_return("message")
allow(epsilon_controller.current_session).to receive(:state_string).and_return("say_hola")
file_contents, selected_preprocessor = epsilon_controller.send(:action_replies)
expect(file_contents).to eq(File.read(File.expand_path("../replies/messages/say_hola.yml.erb", __dir__)))
end
it "should load the correct variant when there is no preprocessor" do
allow(gamma_controller.current_session).to receive(:flow_string).and_return("message")
allow(gamma_controller.current_session).to receive(:state_string).and_return("say_yo")
file_contents, selected_preprocessor = gamma_controller.send(:action_replies)
expect(file_contents).to eq(File.read(File.expand_path("../replies/messages/say_yo.yml+twitter", __dir__)))
end
end
describe "randomized replies" do
let(:stubbed_handler) { double("handler") }
let(:stubbed_client) { double("client") }
before(:each) do
allow(Stealth::Services::Facebook::Client).to receive(:new).and_return(stubbed_client)
end
describe "text replies" do
before(:each) do
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_randomize_text")
Stealth.config.auto_insert_delays = false
end
after(:each) do
Stealth.config.auto_insert_delays = true
end
it "should receive a single text string" do
allow(Stealth::Services::Facebook::ReplyHandler).to receive(:new) do |*args|
expect(args.first[:reply]['text']).to be_a(String)
stubbed_handler
end
allow(stubbed_handler).to receive(:text).exactly(1).time
expect(stubbed_client).to receive(:transmit).exactly(1).time
controller.say_randomize_text
end
end
end
describe "sub-state replies" do
let(:stubbed_handler) { double("handler") }
let(:stubbed_client) { double("client") }
before(:each) do
allow(Stealth::Services::Facebook::ReplyHandler).to receive(:new).and_return(stubbed_handler)
allow(Stealth::Services::Facebook::Client).to receive(:new).and_return(stubbed_client)
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_offer")
allow(stubbed_client).to receive(:transmit).and_return(true)
allow(controller).to receive(:sleep).and_return(true)
end
it "should transmit only the last reply in the file when @pos = -1" do
expect(stubbed_handler).to receive(:text).exactly(1).time
expect(stubbed_handler).to receive(:delay).exactly(1).time # auto-delay
controller.pos = -1
controller.say_offer
end
it "should transmit the last two replies in the file when @pos = -2" do
expect(stubbed_handler).to receive(:text).exactly(1).time
expect(stubbed_handler).to receive(:delay).exactly(1).time
controller.pos = -2
controller.say_offer
end
it "should transmit all the replies in the file when @pos = 0" do
expect(stubbed_handler).to receive(:text).exactly(2).times
expect(stubbed_handler).to receive(:delay).exactly(2).times
controller.pos = 0
controller.say_offer
end
it "should transmit all the replies in the file when @pos = nil" do
expect(stubbed_handler).to receive(:text).exactly(2).times
expect(stubbed_handler).to receive(:delay).exactly(2).times
expect(controller.pos).to be_nil
controller.say_offer
end
end
describe "client errors" do
let(:stubbed_handler) { double("handler") }
let(:stubbed_client) { double("client") }
before(:each) do
allow(Stealth::Services::Facebook::ReplyHandler).to receive(:new).and_return(stubbed_handler)
allow(Stealth::Services::Facebook::Client).to receive(:new).and_return(stubbed_client)
allow(controller.current_session).to receive(:flow_string).and_return("message")
allow(controller.current_session).to receive(:state_string).and_return("say_offer")
allow(stubbed_handler).to receive(:delay).exactly(1).time
allow(stubbed_handler).to receive(:text).exactly(1).time
end
describe "Stealth::Errors::UserOptOut" do
before(:each) do
expect(stubbed_client).to receive(:transmit).and_raise(
Stealth::Errors::UserOptOut.new('boom')
).once # Retuns early; doesn't send the remaining replies in the file
end
it "should log the unhandled exception if the controller does not have a handle_opt_out method" do
expect(Stealth::Logger).to receive(:l).with(
topic: :err,
message: "User #{facebook_message.sender_id} unhandled exception due to opt-out."
)
expect(controller).to receive(:do_nothing)
controller.say_offer
end
it "should call handle_opt_out method" do
expect(controller).to receive(:handle_opt_out)
expect(Stealth::Logger).to receive(:l).with(
topic: 'facebook',
message: "User #{facebook_message.sender_id} opted out. [boom]"
)
expect(controller).to receive(:do_nothing)
controller.say_offer
end
end
describe "Stealth::Errors::InvalidSessionID" do
before(:each) do
expect(stubbed_client).to receive(:transmit).and_raise(
Stealth::Errors::InvalidSessionID.new('boom')
).once # Retuns early; doesn't send the remaining replies in the file
end
it "should log the unhandled exception if the controller does not have a handle_invalid_session_id method" do
expect(Stealth::Logger).to receive(:l).with(
topic: :err,
message: "User #{facebook_message.sender_id} unhandled exception due to invalid session_id."
)
expect(controller).to receive(:do_nothing)
controller.say_offer
end
it "should call handle_invalid_session_id method" do
expect(controller).to receive(:handle_invalid_session_id)
expect(Stealth::Logger).to receive(:l).with(
topic: 'facebook',
message: "User #{facebook_message.sender_id} has an invalid session_id. [boom]"
)
expect(controller).to receive(:do_nothing)
controller.say_offer
end
end
describe 'an unknown client error' do
before(:each) do
allow(stubbed_client).to receive(:transmit).and_raise(
StandardError
)
end
it 'should raise the error' do
expect {
controller.say_offer
}.to raise_error(StandardError)
end
end
end
end
| 38.017266 | 120 | 0.705738 |
116178eb87ee34f8d72e174ccaa466b8cadb0be8 | 177 | module DP
module ForceErrors
def self.included(base)
base.alias_method_chain :raise_errors?, :dp
end
def raise_errors_with_dp?
true
end
end
end | 14.75 | 49 | 0.672316 |
01cbe01dc6a6fc5f8621f6e6a9971fa0edc4105c | 1,861 | # -*- encoding: utf-8 -*-
# stub: activerecord 5.0.7.2 ruby lib
Gem::Specification.new do |s|
s.name = "activerecord".freeze
s.version = "5.0.7.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["David Heinemeier Hansson".freeze]
s.date = "2019-03-13"
s.description = "Databases on Rails. Build a persistent domain model by mapping database tables to Ruby classes. Strong conventions for associations, validations, aggregations, migrations, and testing come baked-in.".freeze
s.email = "[email protected]".freeze
s.extra_rdoc_files = ["README.rdoc".freeze]
s.files = ["README.rdoc".freeze]
s.homepage = "http://rubyonrails.org".freeze
s.licenses = ["MIT".freeze]
s.rdoc_options = ["--main".freeze, "README.rdoc".freeze]
s.required_ruby_version = Gem::Requirement.new(">= 2.2.2".freeze)
s.rubygems_version = "2.5.2.1".freeze
s.summary = "Object-relational mapper framework (part of Rails).".freeze
s.installed_by_version = "2.5.2.1" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<activesupport>.freeze, ["= 5.0.7.2"])
s.add_runtime_dependency(%q<activemodel>.freeze, ["= 5.0.7.2"])
s.add_runtime_dependency(%q<arel>.freeze, ["~> 7.0"])
else
s.add_dependency(%q<activesupport>.freeze, ["= 5.0.7.2"])
s.add_dependency(%q<activemodel>.freeze, ["= 5.0.7.2"])
s.add_dependency(%q<arel>.freeze, ["~> 7.0"])
end
else
s.add_dependency(%q<activesupport>.freeze, ["= 5.0.7.2"])
s.add_dependency(%q<activemodel>.freeze, ["= 5.0.7.2"])
s.add_dependency(%q<arel>.freeze, ["~> 7.0"])
end
end
| 43.27907 | 225 | 0.679205 |
08bbe4cb9c5cfa7fe27fd9e6829664c23a09716b | 609 | require "benchmark"
class Foo
def ping
end
end
block = Proc.new {
ping
}
Foo.send(:define_method, "pong", &block)
object = Foo.new
method = object.method("pong")
TESTS = 100_000
Benchmark.bmbm do |results|
results.report("noop:") { TESTS.times { } }
results.report("method:") { TESTS.times { object.ping } }
results.report("instance_eval:") { TESTS.times { object.instance_eval &block } }
results.report("define_method:") { TESTS.times { object.pong } }
results.report("method.call:") { TESTS.times { method.call } }
results.report("send:") { TESTS.times { object.send("pong") } }
end
| 22.555556 | 82 | 0.671593 |
79e3f3f05474cb5d1412e50a7f0d6caf01f7a8d3 | 2,269 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "helper"
describe Google::Cloud::Bigtable::Instance, :mock_bigtable do
let(:instance_id) { "test-instance-id" }
let(:display_name) { "Test instance" }
it "knows the identifiers" do
instance_grpc = Google::Bigtable::Admin::V2::Instance.new(
instance_hash(
name: instance_id,
display_name: display_name,
state: :READY,
type: :PRODUCTION
))
instance = Google::Cloud::Bigtable::Instance.from_grpc(instance_grpc, bigtable.service)
instance.must_be_kind_of Google::Cloud::Bigtable::Instance
instance.project_id.must_equal project_id
instance.instance_id.must_equal instance_id
instance.display_name.must_equal display_name
instance.state.must_equal :READY
instance.must_be :ready?
instance.wont_be :creating?
instance.type.must_equal :PRODUCTION
instance.must_be :production?
instance.wont_be :development?
end
describe "#labels=" do
let(:instance){
Google::Cloud::Bigtable::Instance.from_grpc(
Google::Bigtable::Admin::V2::Instance.new(name: instance_id),
bigtable.service
)
}
it "set labels using hash" do
instance.labels = { "env" => "test1" }
instance.labels.to_h.must_equal({"env" => "test1"})
instance.labels = { :env => "test2" }
instance.labels.to_h.must_equal({"env" => "test2"})
instance.labels = { data: "users", appprofile: 12345 }
instance.labels.to_h.must_equal({ "data" => "users", "appprofile" => "12345" })
end
it "clear lables if labels value is nil" do
instance.labels = { "env" => "test" }
instance.labels = nil
instance.labels.length.must_equal 0
end
end
end
| 31.513889 | 91 | 0.690613 |
b9a7cd09327e4d7932d22c735811b6f0f33b5647 | 1,588 | #
# Author:: Matthew Kent (<[email protected]>)
# Copyright:: Copyright (c) 2011 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
require 'chef/mash'
describe Mash do
it "should duplicate a simple key/value mash to a new mash" do
data = {:x=>"one", :y=>"two", :z=>"three"}
@orig = Mash.new(data)
@copy = @orig.dup
@copy.to_hash.should == Mash.new(data).to_hash
@copy[:x] = "four"
@orig[:x].should == "one"
end
it "should duplicate a mash with an array to a new mash" do
data = {:x=>"one", :y=>"two", :z=>[1,2,3]}
@orig = Mash.new(data)
@copy = @orig.dup
@copy.to_hash.should == Mash.new(data).to_hash
@copy[:z] << 4
@orig[:z].should == [1,2,3]
end
it "should duplicate a nested mash to a new mash" do
data = {:x=>"one", :y=>"two", :z=>Mash.new({:a=>[1,2,3]})}
@orig = Mash.new(data)
@copy = @orig.dup
@copy.to_hash.should == Mash.new(data).to_hash
@copy[:z][:a] << 4
@orig[:z][:a].should == [1,2,3]
end
# add more!
end
| 30.538462 | 74 | 0.639798 |
919c34947018e1a7932d6abb5a7b48dae4614ad9 | 893 | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "<%= name %>/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "<%= name %>"
s.version = <%= camelized %>::VERSION
s.authors = ["<%= author %>"]
s.email = ["<%= email %>"]
s.homepage = "TODO"
s.summary = "TODO: Summary of <%= camelized %>."
s.description = "TODO: Description of <%= camelized %>."
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
<% unless options.skip_test_unit? -%>
s.test_files = Dir["test/**/*"]
<% end -%>
<%= '# ' if options.dev? || options.edge? -%>s.add_dependency "rails", "~> <%= Rails::VERSION::STRING %>"
<% unless options[:skip_active_record] -%>
s.add_development_dependency "<%= gem_for_database %>"
<% end -%>
end
| 31.892857 | 107 | 0.585666 |
384e3481ab4145adf384a6a9d34bbc3f37366b2c | 69 | require_relative '../test_init'
include Metrics::Stream::Divergence
| 17.25 | 35 | 0.797101 |
18e985564752c1a0725b9f14d29855d72be5220f | 11,192 |
module Logging
# A Mapped Diagnostic Context, or MDC in short, is an instrument used to
# distinguish interleaved log output from different sources. Log output is
# typically interleaved when a server handles multiple clients
# near-simultaneously.
#
# Interleaved log output can still be meaningful if each log entry from
# different contexts had a distinctive stamp. This is where MDCs come into
# play.
#
# The MDC provides a hash of contextual messages that are identified by
# unique keys. These unique keys are set by the application and appended
# to log messages to identify groups of log events. One use of the Mapped
# Diagnostic Context is to store HTTP request headers associated with a Rack
# request. These headers can be included with all log messages emitted while
# generating the HTTP response.
#
# When configured to do so, PatternLayout instances will automatically
# retrieve the mapped diagnostic context for the current thread with out any
# user intervention. This context information can be used to track user
# sessions in a Rails application, for example.
#
# Note that MDCs are managed on a per thread basis. MDC operations such as
# `[]`, `[]=`, and `clear` affect the MDC of the current thread only. MDCs
# of other threads remain unaffected.
#
# By default, when a new thread is created it will inherit the context of
# its parent thread. However, the `inherit` method may be used to inherit
# context for any other thread in the application.
#
module MappedDiagnosticContext
extend self
# The name used to retrieve the MDC from thread-local storage.
NAME = 'logging.mapped-diagnostic-context'.freeze
# Public: Put a context value as identified with the key parameter into
# the current thread's context map.
#
# key - The String identifier for the context.
# value - The String value to store.
#
# Returns the value.
#
def []=( key, value )
context.store(key.to_s, value)
end
# Public: Get the context value identified with the key parameter.
#
# key - The String identifier for the context.
#
# Returns the value associated with the key or nil if there is no value
# present.
#
def []( key )
context.fetch(key.to_s, nil)
end
# Public: Remove the context value identified with the key parameter.
#
# key - The String identifier for the context.
#
# Returns the value associated with the key or nil if there is no value
# present.
#
def delete( key )
context.delete(key.to_s)
end
# Public: Clear all mapped diagnostic information if any. This method is
# useful in cases where the same thread can be potentially used over and
# over in different unrelated contexts.
#
# Returns the MappedDiagnosticContext.
#
def clear
context.clear if Thread.current[NAME]
self
end
# Public: Inherit the diagnostic context of another thread. In the vast
# majority of cases the other thread will the parent that spawned the
# current thread. The diagnostic context from the parent thread is cloned
# before being inherited; the two diagnostic contexts can be changed
# independently.
#
# Returns the MappedDiagnosticContext.
#
def inherit( obj )
case obj
when Hash
Thread.current[NAME] = obj.dup
when Thread
return if Thread.current == obj
Thread.exclusive {
Thread.current[NAME] = obj[NAME].dup if obj[NAME]
}
end
self
end
# Returns the Hash acting as the storage for this NestedDiagnosticContext.
# A new storage Hash is created for each Thread running in the
# application.
#
def context
Thread.current[NAME] ||= Hash.new
end
end # MappedDiagnosticContext
# A Nested Diagnostic Context, or NDC in short, is an instrument to
# distinguish interleaved log output from different sources. Log output is
# typically interleaved when a server handles multiple clients
# near-simultaneously.
#
# Interleaved log output can still be meaningful if each log entry from
# different contexts had a distinctive stamp. This is where NDCs come into
# play.
#
# The NDC is a stack of contextual messages that are pushed and popped by
# the client as different contexts are encountered in the application. When a
# new context is entered, the client will `push` a new message onto the NDC
# stack. This message appears in all log messages. When this context is
# exited, the client will call `pop` to remove the message.
#
# * Contexts can be nested
# * When entering a context, call `Logging.ndc.push`
# * When leaving a context, call `Logging.ndc.pop`
# * Configure the PatternLayout to log context information
#
# There is no penalty for forgetting to match each push operation with a
# corresponding pop, except the obvious mismatch between the real
# application context and the context set in the NDC.
#
# When configured to do so, PatternLayout instance will automatically
# retrieve the nested diagnostic context for the current thread with out any
# user intervention. This context information can be used to track user
# sessions in a Rails application, for example.
#
# Note that NDCs are managed on a per thread basis. NDC operations such as
# `push`, `pop`, and `clear` affect the NDC of the current thread only. NDCs
# of other threads remain unaffected.
#
# By default, when a new thread is created it will inherit the context of
# its parent thread. However, the `inherit` method may be used to inherit
# context for any other thread in the application.
#
module NestedDiagnosticContext
extend self
# The name used to retrieve the NDC from thread-local storage.
NAME = 'logging.nested-diagnostic-context'.freeze
# Public: Push new diagnostic context information for the current thread.
# The contents of the message parameter is determined solely by the
# client.
#
# message - The message String to add to the current context.
#
# Returns the current NestedDiagnosticContext.
#
def push( message )
context.push(message)
self
end
alias :<< :push
# Public: Clients should call this method before leaving a diagnostic
# context. The returned value is the last pushed message. If no
# context is available then `nil` is returned.
#
# Returns the last pushed diagnostic message String or nil if no messages
# exist.
#
def pop
context.pop
end
# Public: Looks at the last diagnostic context at the top of this NDC
# without removing it. The returned value is the last pushed message. If
# no context is available then `nil` is returned.
#
# Returns the last pushed diagnostic message String or nil if no messages
# exist.
#
def peek
context.last
end
# Public: Clear all nested diagnostic information if any. This method is
# useful in cases where the same thread can be potentially used over and
# over in different unrelated contexts.
#
# Returns the NestedDiagnosticContext.
#
def clear
context.clear if Thread.current[NAME]
self
end
# Public: Inherit the diagnostic context of another thread. In the vast
# majority of cases the other thread will the parent that spawned the
# current thread. The diagnostic context from the parent thread is cloned
# before being inherited; the two diagnostic contexts can be changed
# independently.
#
# Returns the NestedDiagnosticContext.
#
def inherit( obj )
case obj
when Array
Thread.current[NAME] = obj.dup
when Thread
return if Thread.current == obj
Thread.exclusive {
Thread.current[NAME] = obj[NAME].dup if obj[NAME]
}
end
self
end
# Returns the Array acting as the storage stack for this
# NestedDiagnosticContext. A new storage Array is created for each Thread
# running in the application.
#
def context
Thread.current[NAME] ||= Array.new
end
end # NestedDiagnosticContext
# Public: Accessor method for getting the current Thread's
# MappedDiagnosticContext.
#
# Returns MappedDiagnosticContext
#
def self.mdc() MappedDiagnosticContext end
# Public: Accessor method for getting the current Thread's
# NestedDiagnosticContext.
#
# Returns NestedDiagnosticContext
#
def self.ndc() NestedDiagnosticContext end
# Public: Convenience method that will clear both the Mapped Diagnostic
# Context and the Nested Diagnostic Context of the current thread. If the
# `all` flag passed to this method is true, then the diagnostic contexts for
# _every_ thread in the application will be cleared.
#
# all - Boolean flag used to clear the context of every Thread (default is false)
#
# Returns the Logging module.
#
def self.clear_diagnostic_contexts( all = false )
if all
Thread.exclusive {
Thread.list.each { |thread|
thread[MappedDiagnosticContext::NAME].clear if thread[MappedDiagnosticContext::NAME]
thread[NestedDiagnosticContext::NAME].clear if thread[NestedDiagnosticContext::NAME]
}
}
else
MappedDiagnosticContext.clear
NestedDiagnosticContext.clear
end
self
end
end # module Logging
# :stopdoc:
class Thread
class << self
%w[new start fork].each do |m|
class_eval <<-__, __FILE__, __LINE__
alias :_orig_#{m} :#{m}
private :_orig_#{m}
def #{m}( *a, &b )
create_with_logging_context(:_orig_#{m}, *a ,&b)
end
__
end
private
# In order for the diagnostic contexts to behave properly we need to
# inherit state from the parent thread. The only way I have found to do
# this in Ruby is to override `new` and capture the contexts from the
# parent Thread at the time the child Thread is created. The code below does
# just this. If there is a more idiomatic way of accomplishing this in Ruby,
# please let me know!
#
# Also, great care is taken in this code to ensure that a reference to the
# parent thread does not exist in the binding associated with the block
# being executed in the child thread. The same is true for the parent
# thread's mdc and ndc. If any of those references end up in the binding,
# then they cannot be garbage collected until the child thread exits.
#
def create_with_logging_context( m, *a, &b )
mdc, ndc = nil
if Thread.current[Logging::MappedDiagnosticContext::NAME]
mdc = Thread.current[Logging::MappedDiagnosticContext::NAME].dup
end
if Thread.current[Logging::NestedDiagnosticContext::NAME]
ndc = Thread.current[Logging::NestedDiagnosticContext::NAME].dup
end
self.send(m, *a) { |*args|
Logging::MappedDiagnosticContext.inherit(mdc)
Logging::NestedDiagnosticContext.inherit(ndc)
b.call(*args)
}
end
end
end # Thread
# :startdoc:
| 33.812689 | 94 | 0.693174 |
610e07594424f0b0c3cc6f1ef993be408f5b893d | 866 | module Paymill
class Base
include Paymill::Operations::All
include Paymill::Operations::Create
include Paymill::Operations::Find
attr_accessor :created_at, :updated_at
# Initializes the object using the given attributes
#
# @param [Hash] attributes The attributes to use for initialization
def initialize(attributes = {})
set_attributes(attributes)
parse_timestamps
end
# Sets the attributes
#
# @param [Hash] attributes The attributes to initialize
def set_attributes(attributes)
attributes.each_pair do |key, value|
instance_variable_set("@#{key}", value)
end
end
# Parses UNIX timestamps and creates Time objects.
def parse_timestamps
@created_at = Time.at(created_at) if created_at
@updated_at = Time.at(updated_at) if updated_at
end
end
end
| 26.242424 | 71 | 0.692841 |
e819873a1bf2c08367fc0214c56c7cfc8bbc7a3a | 317 | with_driver "azure"
machine_options = {
bootstrap_options: {
cloud_service_name: "jkeisercloudtest",
storage_account_name: "jkeiserstorage",
#:vm_size => "A7"
location: "West US",
},
#:image_id => 'foobar'
password: 'chefm3t4l\m/',
}
machine "koopa" do
machine_options machine_options
end
| 18.647059 | 43 | 0.687697 |
acb7905a232cc2d68abdb55b70bc9b1d1a3cb892 | 5,141 | # typed: false
# frozen_string_literal: true
require 'active_support/core_ext/integer/time'
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Include generic and useful information about system operation, but avoid logging too much
# information to avoid inadvertent exposure of personally identifiable information (PII).
config.log_level = :info
# Prepend all log lines with the following tags.
config.log_tags = [:request_id]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "tasker_rails_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Log disallowed deprecations.
config.active_support.disallowed_deprecation = :log
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require "syslog/logger"
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV['RAILS_LOG_TO_STDOUT'].present?
logger = ActiveSupport::Logger.new($stdout)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
| 43.940171 | 114 | 0.766582 |
91c9c3e6810158bb725860f144dbebd809322b63 | 1,133 | # frozen_string_literal: true
require 'forwardable'
require 'dopp/document/context'
require 'dopp/document/structure'
module Dopp
# PDF document.
class Document
extend Forwardable
def_delegators(
:@context,
:page_size=, :landscape=, :rotate=,
:page_size, :landscape, :rotate,
:page_width, :page_height,
:fill_color=, :stroke_color=,
:fill_color, :stroke_color
)
def_delegators(
:@structure,
:pdf_version=,
:title=, :mod_date=,
:page_layout=, :page_mode=
)
attr_reader :context
# Initialize.
def initialize(opts = {})
@context = Context.new(opts)
@structure = Structure.new(self, opts)
end
# Add new page.
def add_page(opts = {})
@structure.add_page(opts)
end
# Render to string.
# @return [String] Content.
def render
@structure.render
end
# Detailed description of this object.
# @return [String] Descritption.
def inspect
String.new('#<').concat(
self.class.name, ':',
object_id.to_s, ' ', @structure.to_s, '>'
)
end
end
end
| 20.232143 | 49 | 0.603707 |
7a3fb5e5a414683a60e634640d5cefd01f147697 | 50 | module CertificateFactory
VERSION = "0.1.0"
end
| 12.5 | 25 | 0.74 |
5d5646f2d62d720d1592d0962bd5d53e720c3dda | 922 | Pod::Spec.new do |s|
s.name = "TeamupKit"
s.platform = :ios, "9.0"
s.requires_arc = true
s.version = "0.2.3"
s.summary = "Swift framework for Teamup services."
s.description = <<-DESC
Swift framework for communicating with Teamup, a service to super charge your fitness business.
DESC
s.homepage = "https://github.com/amrap-labs/TeamupKit"
s.license = "MIT"
s.author = { "Merrick Sapsford" => "[email protected]" }
s.social_media_url = "http://twitter.com/MerrickSapsford"
s.source = { :git => "https://github.com/amrap-labs/TeamupKit.git", :tag => s.version.to_s }
s.source_files = "Sources/TeamupKit/**/*.{h,m,swift}"
s.resource_bundle = {
'TeamupKit' => [
'Sources/TeamupKit/Resources/**/*'
]
}
s.dependency 'KeychainSwift', '~> 8.0'
s.dependency 'Alamofire', '~> 4.5.0'
end
| 30.733333 | 102 | 0.591106 |
395c43a40adac3523665a582d6735d726e873905 | 1,253 | class EmacsClangCompleteAsync < Formula
desc "Emacs plugin using libclang to complete C/C++ code"
homepage "https://github.com/Golevka/emacs-clang-complete-async"
url "https://github.com/Golevka/emacs-clang-complete-async/archive/v0.5.tar.gz"
sha256 "151a81ae8dd9181116e564abafdef8e81d1e0085a1e85e81158d722a14f55c76"
head "https://github.com/Golevka/emacs-clang-complete-async.git"
stable do
# https://github.com/Golevka/emacs-clang-complete-async/issues/65
patch :DATA
end
option "with-elisp", "Include Emacs lisp package"
depends_on "llvm" => "with-clang"
# https://github.com/Golevka/emacs-clang-complete-async/pull/59
patch do
url "https://github.com/yocchi/emacs-clang-complete-async/commit/5ce197b15d7b8c9abfc862596bf8d902116c9efe.diff"
sha256 "6f638c473781a8f86a0ab970303579256f49882744863e36924748c010e7c1ed"
end
def install
system "make"
bin.install "clang-complete"
share.install "auto-complete-clang-async.el" if build.with? "elisp"
end
end
__END__
--- a/src/completion.h 2013-05-26 17:27:46.000000000 +0200
+++ b/src/completion.h 2014-02-11 21:40:18.000000000 +0100
@@ -3,6 +3,7 @@
#include <clang-c/Index.h>
+#include <stdio.h>
typedef struct __completion_Session_struct
| 29.833333 | 115 | 0.750998 |
62c70038a36566881cb80f6757da6b77097b2803 | 404 | # Be sure to restart your server when you modify this file.
Revs::Application.config.session_store :cookie_store, key: '_revs_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# Revs::Application.config.session_store :active_record_store
| 44.888889 | 74 | 0.806931 |
edb3a2484cf332220e4bf144e3729b9a6f57d2a7 | 3,096 | class Protobuf < Formula
desc "Protocol buffers (Google's data interchange format)"
homepage "https://github.com/protocolbuffers/protobuf/"
url "https://github.com/protocolbuffers/protobuf.git",
:tag => "v3.6.1.3",
:revision => "66dc42d891a4fc8e9190c524fd67961688a37bbe"
head "https://github.com/protocolbuffers/protobuf.git"
bottle do
cellar :any
sha256 "f299e4a5e34e5795eb3d89ca0aaae018e476c17d92f98dd93eeebeb47dbb17c5" => :mojave
sha256 "d8f2a28e7e99f5046472992f41fe59c3344f2336435f21b6cfa57c433cf20fc8" => :high_sierra
sha256 "52eedfd81a251dbbc72d2ddbe78e1a54c651792bed0601b57c5ef31a53a6b62d" => :sierra
end
option "without-python@2", "Build without python2 support"
deprecated_option "without-python" => "with-python@2"
deprecated_option "with-python3" => "with-python"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "python@2" => :recommended
depends_on "python" => :optional
resource "six" do
url "https://files.pythonhosted.org/packages/16/d8/bc6316cf98419719bd59c91742194c111b6f2e85abac88e496adefaf7afe/six-1.11.0.tar.gz"
sha256 "70e8a77beed4562e7f14fe23a786b54f6296e34344c23bc42f07b15018ff98e9"
end
needs :cxx11
def install
# Don't build in debug mode. See:
# https://github.com/Homebrew/homebrew/issues/9279
# https://github.com/protocolbuffers/protobuf/blob/5c24564811c08772d090305be36fae82d8f12bbe/configure.ac#L61
ENV.prepend "CXXFLAGS", "-DNDEBUG"
ENV.cxx11
system "./autogen.sh"
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}", "--with-zlib"
system "make"
system "make", "check" if build.bottle?
system "make", "install"
# Install editor support and examples
doc.install "editors", "examples"
Language::Python.each_python(build) do |python, version|
resource("six").stage do
system python, *Language::Python.setup_install_args(libexec)
end
chdir "python" do
ENV.append_to_cflags "-I#{include}"
ENV.append_to_cflags "-L#{lib}"
args = Language::Python.setup_install_args libexec
args << "--cpp_implementation"
system python, *args
end
site_packages = "lib/python#{version}/site-packages"
pth_contents = "import site; site.addsitedir('#{libexec/site_packages}')\n"
(prefix/site_packages/"homebrew-protobuf.pth").write pth_contents
end
end
def caveats; <<~EOS
Editor support and examples have been installed to:
#{doc}
EOS
end
test do
testdata = <<~EOS
syntax = "proto3";
package test;
message TestCase {
string name = 4;
}
message Test {
repeated TestCase case = 1;
}
EOS
(testpath/"test.proto").write testdata
system bin/"protoc", "test.proto", "--cpp_out=."
system "python2.7", "-c", "import google.protobuf" if build.with? "python@2"
system "python3", "-c", "import google.protobuf" if build.with? "python"
end
end
| 34.021978 | 134 | 0.684755 |
b9dbc0844384d5f69ffad732a7a45204b024656b | 272 | module SignInSupport
def sign_in(user)
visit root_path
click_on('ログイン')
sleep 0.1
fill_in 'メールアドレス', with: user.email
sleep 0.1
fill_in 'パスワード', with: user.password
find('.login__hover').hover
find('input[name="commit"]').click
end
end
| 20.923077 | 40 | 0.658088 |
7ab5215867834398ec70c2b5c3fd047040b5382f | 1,234 | require_relative 'lib/tweetbot/version'
Gem::Specification.new do |spec|
spec.name = "tweetbot"
spec.version = Tweetbot::VERSION
spec.authors = ["Corey Haines"]
spec.email = ["[email protected]"]
spec.summary = %q{Tweetbot makes writing twitter bots twivial!}
spec.description = %q{Using tweetbot, you can easily create twitter bots that respond to key phrases that people say on the twitters}
spec.homepage = "https://github.com/coreyhaines/tweetbot"
spec.license = "MIT"
spec.required_ruby_version = Gem::Requirement.new(">= 2.7.0")
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/coreyhaines/tweetbot"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_runtime_dependency "twitter"
end
| 42.551724 | 135 | 0.675041 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.