_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q20400 | Podio.Client.authenticate_with_sso | train | def authenticate_with_sso(attributes)
response = @oauth_connection.post do |req|
req.url '/oauth/token', :grant_type => 'sso', :client_id => api_key, :client_secret => api_secret
req.body = attributes
end
@oauth_token = OAuthToken.new(response.body)
configure_oauth
[@oauth_token, response.body['new_user_created']]
end | ruby | {
"resource": ""
} |
q20401 | Podio.Client.authenticate_with_openid | train | def authenticate_with_openid(identifier, type)
response = @trusted_connection.post do |req|
req.url '/oauth/token_by_openid'
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.body = {:grant_type => type, :client_id => api_key, :client_secret => api_secret, :identifier => identifier}
end
@oauth_token = OAuthToken.new(response.body)
configure_oauth
@oauth_token
end | ruby | {
"resource": ""
} |
q20402 | Podio.Client.authenticate_with_activation_code | train | def authenticate_with_activation_code(activation_code)
response = @oauth_connection.post do |req|
req.url '/oauth/token'
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.body = {:grant_type => 'activation_code', :client_id => api_key, :client_secret => api_secret, :activation_code => activation_code}
end
@oauth_token = OAuthToken.new(response.body)
configure_oauth
@oauth_token
end | ruby | {
"resource": ""
} |
q20403 | Podio.Client.oauth_token= | train | def oauth_token=(new_oauth_token)
@oauth_token = new_oauth_token.is_a?(Hash) ? OAuthToken.new(new_oauth_token) : new_oauth_token
configure_oauth
end | ruby | {
"resource": ""
} |
q20404 | Loc.LocationCollection.distance | train | def distance
return nil unless @locations.size > 1
locations.each_cons(2).reduce(0) do |acc, (loc1, loc2)|
acc + loc1.distance_to(loc2)
end
end | ruby | {
"resource": ""
} |
q20405 | Codebot.Integration.update! | train | def update!(params)
self.name = params[:name]
self.endpoint = params[:endpoint]
self.secret = params[:secret]
self.gitlab = params[:gitlab] || false
self.shortener_url = params[:shortener_url]
self.shortener_secret = params[:shortener_secret]
set_channels params[:channels], params[:config]
end | ruby | {
"resource": ""
} |
q20406 | Codebot.Integration.add_channels! | train | def add_channels!(channels, conf)
channels.each_key do |identifier|
if @channels.any? { |chan| chan.identifier_eql?(identifier) }
raise CommandError, "channel #{identifier.inspect} already exists"
end
end
new_channels = Channel.deserialize_all(channels, conf)
@channels.push(*new_channels)
end | ruby | {
"resource": ""
} |
q20407 | Codebot.Integration.delete_channels! | train | def delete_channels!(identifiers)
identifiers.each do |identifier|
channel = @channels.find { |chan| chan.identifier_eql? identifier }
if channel.nil?
raise CommandError, "channel #{identifier.inspect} does not exist"
end
@channels.delete channel
end
end | ruby | {
"resource": ""
} |
q20408 | Codebot.Integration.set_channels | train | def set_channels(channels, conf)
if channels.nil?
@channels = [] if @channels.nil?
return
end
@channels = valid!(channels, Channel.deserialize_all(channels, conf),
:@channels,
invalid_error: 'invalid channel list %s') { [] }
end | ruby | {
"resource": ""
} |
q20409 | Codebot.Integration.serialize | train | def serialize(conf)
check_channel_networks!(conf)
[name, {
'endpoint' => endpoint,
'secret' => secret,
'gitlab' => gitlab,
'shortener_url' => shortener_url,
'shortener_secret' => shortener_secret,
'channels' => Channel.serialize_all(channels, conf)
}]
end | ruby | {
"resource": ""
} |
q20410 | Codebot.IPCClient.command | train | def command(cmd, explicit)
return false unless check_pipe_exist(explicit)
Timeout.timeout 5 do
File.open @pipe, 'w' do |p|
p.puts cmd
end
end
true
rescue Timeout::Error
communication_error! 'no response'
end | ruby | {
"resource": ""
} |
q20411 | Codebot.IntegrationManager.create | train | def create(params)
integration = Integration.new(
params.merge(config: { networks: @config.networks })
)
@config.transaction do
check_available!(integration.name, integration.endpoint)
NetworkManager.new(@config).check_channels!(integration)
@config.integrations << integration
integration_feedback(integration, :created) unless params[:quiet]
end
end | ruby | {
"resource": ""
} |
q20412 | Codebot.IntegrationManager.update | train | def update(name, params)
@config.transaction do
integration = find_integration!(name)
check_available_except!(params[:name], params[:endpoint], integration)
update_channels!(integration, params)
NetworkManager.new(@config).check_channels!(integration)
integration.update!(params)
integration_feedback(integration, :updated) unless params[:quiet]
end
end | ruby | {
"resource": ""
} |
q20413 | Codebot.IntegrationManager.destroy | train | def destroy(name, params)
@config.transaction do
integration = find_integration!(name)
@config.integrations.delete integration
integration_feedback(integration, :destroyed) unless params[:quiet]
end
end | ruby | {
"resource": ""
} |
q20414 | Codebot.IntegrationManager.list | train | def list(search)
@config.transaction do
integrations = @config.integrations.dup
unless search.nil?
integrations.select! do |intg|
intg.name.downcase.include? search.downcase
end
end
puts 'No integrations found' if integrations.empty?
integrations.each { |intg| show_integration intg }
end
end | ruby | {
"resource": ""
} |
q20415 | Codebot.IntegrationManager.find_integration! | train | def find_integration!(name)
integration = find_integration(name)
return integration unless integration.nil?
raise CommandError, "an integration with the name #{name.inspect} " \
'does not exist'
end | ruby | {
"resource": ""
} |
q20416 | Codebot.IntegrationManager.check_available! | train | def check_available!(name, endpoint)
check_name_available!(name) unless name.nil?
check_endpoint_available!(endpoint) unless endpoint.nil?
end | ruby | {
"resource": ""
} |
q20417 | Codebot.IntegrationManager.check_available_except! | train | def check_available_except!(name, endpoint, intg)
check_name_available!(name) unless name.nil? || intg.name_eql?(name)
return if endpoint.nil? || intg.endpoint_eql?(endpoint)
check_endpoint_available!(endpoint)
end | ruby | {
"resource": ""
} |
q20418 | Codebot.IntegrationManager.update_channels! | train | def update_channels!(integration, params)
integration.channels.clear if params[:clear_channels]
if params[:delete_channel]
integration.delete_channels!(params[:delete_channel])
end
return unless params[:add_channel]
integration.add_channels!(params[:add_channel],
networks: @config.networks)
end | ruby | {
"resource": ""
} |
q20419 | Codebot.IntegrationManager.show_integration | train | def show_integration(integration)
puts "Integration: #{integration.name}"
puts "\tEndpoint: #{integration.endpoint}"
puts "\tSecret: #{show_integration_secret(integration)}"
if integration.channels.empty?
puts "\tChannels: (none)"
else
puts "\tChannels:"
show_integration_channels(integration)
end
end | ruby | {
"resource": ""
} |
q20420 | Codebot.IntegrationManager.show_integration_channels | train | def show_integration_channels(integration)
integration.channels.each do |channel|
puts "\t\t- #{channel.name} on #{channel.network.name}"
puts "\t\t\tKey: #{channel.key}" if channel.key?
puts "\t\t\tMessages are sent without joining" if channel.send_external
end
end | ruby | {
"resource": ""
} |
q20421 | Codebot.NetworkManager.create | train | def create(params)
network = Network.new(params.merge(config: {}))
@config.transaction do
check_name_available!(network.name)
@config.networks << network
network_feedback(network, :created) unless params[:quiet]
end
end | ruby | {
"resource": ""
} |
q20422 | Codebot.NetworkManager.update | train | def update(name, params)
@config.transaction do
network = find_network!(name)
unless params[:name].nil?
check_name_available_except!(params[:name], network)
end
network.update!(params)
network_feedback(network, :updated) unless params[:quiet]
end
end | ruby | {
"resource": ""
} |
q20423 | Codebot.NetworkManager.destroy | train | def destroy(name, params)
@config.transaction do
network = find_network!(name)
@config.networks.delete network
network_feedback(network, :destroyed) unless params[:quiet]
end
end | ruby | {
"resource": ""
} |
q20424 | Codebot.NetworkManager.list | train | def list(search)
@config.transaction do
networks = @config.networks.dup
unless search.nil?
networks.select! { |net| net.name.downcase.include? search.downcase }
end
puts 'No networks found' if networks.empty?
networks.each { |net| show_network net }
end
end | ruby | {
"resource": ""
} |
q20425 | Codebot.NetworkManager.find_network! | train | def find_network!(name)
network = find_network(name)
return network unless network.nil?
raise CommandError, "a network with the name #{name.inspect} " \
'does not exist'
end | ruby | {
"resource": ""
} |
q20426 | Codebot.NetworkManager.check_channels! | train | def check_channels!(integration)
integration.channels.map(&:network).map(&:name).each do |network|
find_network!(network)
end
end | ruby | {
"resource": ""
} |
q20427 | Codebot.NetworkManager.check_name_available_except! | train | def check_name_available_except!(name, network)
return if name.nil? || network.name_eql?(name) || !find_network(name)
raise CommandError, "a network with the name #{name.inspect} " \
'already exists'
end | ruby | {
"resource": ""
} |
q20428 | Codebot.NetworkManager.show_network | train | def show_network(network) # rubocop:disable Metrics/AbcSize
puts "Network: #{network.name}"
security = "#{network.secure ? 'secure' : 'insecure'} connection"
password = network.server_password
puts "\tServer: #{network.host}:#{network.real_port} (#{security})"
puts "\tPassword: #{'*' * password.length}" unless password.to_s.empty?
puts "\tNickname: #{network.nick}"
puts "\tBind to: #{network.bind}" unless network.bind.to_s.empty?
puts "\tUser modes: #{network.modes}" unless network.modes.to_s.empty?
show_network_sasl(network)
show_network_nickserv(network)
end | ruby | {
"resource": ""
} |
q20429 | Codebot.Core.join | train | def join
ipc = Thread.new { @ipc_server.join && stop }
web = Thread.new { @web_server.join && stop }
ipc.join
web.join
@irc_client.join
end | ruby | {
"resource": ""
} |
q20430 | Codebot.Core.trap_signals | train | def trap_signals
shutdown = proc do |signal|
STDERR.puts "\nReceived #{signal}, shutting down..."
stop
join
exit 1
end
trap('INT') { shutdown.call 'SIGINT' }
trap('TERM') { shutdown.call 'SIGTERM' }
end | ruby | {
"resource": ""
} |
q20431 | Codebot.WebServer.create_server | train | def create_server
core = @core
Sinatra.new do
include WebListener
configure { instance_eval(&WebServer.configuration) }
post('/*') { handle_post(core, request, params) }
error(Sinatra::NotFound) { [405, 'Method not allowed'] }
end
end | ruby | {
"resource": ""
} |
q20432 | Codebot.WebListener.handle_post | train | def handle_post(core, request, params)
payload = params['payload'] || request.body.read
dispatch(core, request, *params['splat'], payload)
rescue JSON::ParserError
[400, 'Invalid JSON payload']
end | ruby | {
"resource": ""
} |
q20433 | Codebot.WebListener.dispatch | train | def dispatch(core, request, endpoint, payload)
intg = integration_for(core.config, endpoint)
return [404, 'Endpoint not registered'] if intg.nil?
return [403, 'Invalid signature'] unless valid?(request, intg, payload)
req = create_request(intg, request, payload)
return req if req.is_a? Array
core.irc_client.dispatch(req)
[202, 'Accepted']
end | ruby | {
"resource": ""
} |
q20434 | Codebot.WebListener.create_request | train | def create_request(integration, request, payload)
event = if integration.gitlab
create_gitlab_event(request)
else
create_github_event(request)
end
return event if event.is_a? Array
return [501, 'Event not yet supported'] if event.nil?
Request.new(integration, event, payload)
end | ruby | {
"resource": ""
} |
q20435 | Codebot.WebListener.valid? | train | def valid?(request, integration, payload)
return true unless integration.verify_payloads?
secret = integration.secret
if integration.gitlab
secret == request.env['HTTP_X_GITLAB_TOKEN']
else
request_signature = request.env['HTTP_X_HUB_SIGNATURE']
Cryptography.valid_signature?(payload, secret, request_signature)
end
end | ruby | {
"resource": ""
} |
q20436 | Codebot.IRCClient.dispatch | train | def dispatch(request)
request.each_network do |network, channels|
connection = connection_to(network)
next if connection.nil?
channels.each do |channel|
message = request.to_message_for channel
connection.enqueue message
end
end
end | ruby | {
"resource": ""
} |
q20437 | Codebot.IRCClient.migrate! | train | def migrate!
@semaphore.synchronize do
return unless @active
networks = @core.config.networks
(@checkpoint - networks).each { |network| disconnect_from network }
(networks - @checkpoint).each { |network| connect_to network }
@checkpoint = networks
end
end | ruby | {
"resource": ""
} |
q20438 | Codebot.IRCClient.disconnect_from | train | def disconnect_from(network)
connection = @connections.delete connection_to(network)
connection.tap(&:stop).tap(&:join) unless connection.nil?
end | ruby | {
"resource": ""
} |
q20439 | Codebot.Formatter.format_number | train | def format_number(num, singular = nil, plural = nil)
bold_num = ::Cinch::Formatting.format(:bold, num.to_s)
(bold_num + ' ' + (num == 1 ? singular : plural).to_s).strip
end | ruby | {
"resource": ""
} |
q20440 | Codebot.Formatter.ary_to_sentence | train | def ary_to_sentence(ary, empty_sentence = nil)
case ary.length
when 0 then empty_sentence.to_s
when 1 then ary.first
when 2 then ary.join(' and ')
else
*ary, last_element = ary
ary_to_sentence([ary.join(', '), last_element])
end
end | ruby | {
"resource": ""
} |
q20441 | Codebot.Formatter.abbreviate | train | def abbreviate(text, suffix: ' ...', length: 200)
content_length = length - suffix.length
short = text.to_s.lines.first.to_s.strip[0...content_length].strip
yield text if block_given?
short << suffix unless short.eql? text.to_s.strip
short
end | ruby | {
"resource": ""
} |
q20442 | Codebot.Formatter.prettify | train | def prettify(text)
pretty = abbreviate(text) { |short| short.sub!(/[[:punct:]]+\z/, '') }
sanitize pretty
end | ruby | {
"resource": ""
} |
q20443 | Codebot.Formatter.extract | train | def extract(*path)
node = payload
node if path.all? do |sub|
break unless node.is_a? Hash
node = node[sub.to_s]
end
end | ruby | {
"resource": ""
} |
q20444 | Codebot.IPCServer.run | train | def run(*)
create_pipe
file = File.open @pipe, 'r+'
while (line = file.gets.strip)
handle_command line
end
ensure
delete_pipe
end | ruby | {
"resource": ""
} |
q20445 | Codebot.IPCServer.handle_command | train | def handle_command(command)
case command
when 'REHASH' then @core.config.load!
when 'STOP' then Thread.new { @core.stop }
else STDERR.puts "Unknown IPC command: #{command.inspect}"
end
end | ruby | {
"resource": ""
} |
q20446 | Codebot.Sanitizers.valid_network | train | def valid_network(name, conf)
return if name.nil?
conf[:networks].find { |net| net.name_eql? name }
end | ruby | {
"resource": ""
} |
q20447 | Codebot.Channel.update! | train | def update!(params)
set_identifier params[:identifier], params[:config] if params[:identifier]
self.name = params[:name]
self.key = params[:key]
self.send_external = params[:send_external]
set_network params[:network], params[:config]
end | ruby | {
"resource": ""
} |
q20448 | Codebot.Channel.set_network | train | def set_network(network, conf)
@network = valid! network, valid_network(network, conf), :@network,
required: true,
required_error: 'channels must have a network',
invalid_error: 'invalid channel network %s'
end | ruby | {
"resource": ""
} |
q20449 | Codebot.Channel.set_identifier | train | def set_identifier(identifier, conf)
network_name, self.name = identifier.split('/', 2) if identifier
set_network(network_name, conf)
end | ruby | {
"resource": ""
} |
q20450 | Codebot.Config.load_from_file! | train | def load_from_file!(file)
data = Psych.safe_load(File.read(file)) if File.file? file
data = {} unless data.is_a? Hash
conf = {}
conf[:networks] = Network.deserialize_all data['networks'], conf
conf[:integrations] = Integration.deserialize_all data['integrations'],
conf
conf
end | ruby | {
"resource": ""
} |
q20451 | Codebot.Config.save_to_file! | train | def save_to_file!(file)
data = {}
data['networks'] = Network.serialize_all @conf[:networks], @conf
data['integrations'] = Integration.serialize_all @conf[:integrations],
@conf
File.write file, Psych.dump(data)
end | ruby | {
"resource": ""
} |
q20452 | Codebot.Network.update! | train | def update!(params)
self.name = params[:name]
self.server_password = params[:server_password]
self.nick = params[:nick]
self.bind = params[:bind]
self.modes = params[:modes]
update_complicated!(params)
end | ruby | {
"resource": ""
} |
q20453 | Codebot.Network.update_connection | train | def update_connection(host, port, secure)
@host = valid! host, valid_host(host), :@host,
required: true,
required_error: 'networks must have a hostname',
invalid_error: 'invalid hostname %s'
@port = valid! port, valid_port(port), :@port,
invalid_error: 'invalid port number %s'
@secure = valid!(secure, valid_boolean(secure), :@secure,
invalid_error: 'secure must be a boolean') { false }
end | ruby | {
"resource": ""
} |
q20454 | Codebot.Network.update_sasl | train | def update_sasl(disable, user, pass)
@sasl_username = valid! user, valid_string(user), :@sasl_username,
invalid_error: 'invalid SASL username %s'
@sasl_password = valid! pass, valid_string(pass), :@sasl_password,
invalid_error: 'invalid SASL password %s'
return unless disable
@sasl_username = nil
@sasl_password = nil
end | ruby | {
"resource": ""
} |
q20455 | Codebot.Network.update_nickserv | train | def update_nickserv(disable, user, pass)
@nickserv_username = valid! user, valid_string(user), :@nickserv_username,
invalid_error: 'invalid NickServ username %s'
@nickserv_password = valid! pass, valid_string(pass), :@nickserv_password,
invalid_error: 'invalid NickServ password %s'
return unless disable
@nickserv_username = nil
@nickserv_password = nil
end | ruby | {
"resource": ""
} |
q20456 | Codebot.Network.serialize | train | def serialize(_conf)
[name, Network.fields.map { |sym| [sym.to_s, send(sym)] }.to_h]
end | ruby | {
"resource": ""
} |
q20457 | Codebot.ThreadController.start | train | def start(arg = nil)
return if running?
@thread = Thread.new do
Thread.current.abort_on_exception = true
run(arg)
end
end | ruby | {
"resource": ""
} |
q20458 | Codebot.IRCConnection.run | train | def run(connection)
@connection = connection
bot = create_bot(connection)
thread = Thread.new { bot.start }
@ready.pop
loop { deliver bot, dequeue }
ensure
thread.exit unless thread.nil?
end | ruby | {
"resource": ""
} |
q20459 | Codebot.IRCConnection.deliver | train | def deliver(bot, message)
channel = bot.Channel(message.channel.name)
message.format.to_a.each do |msg|
channel.send msg
end
end | ruby | {
"resource": ""
} |
q20460 | Codebot.IRCConnection.channels | train | def channels(config, network)
config.integrations.map(&:channels).flatten.select do |channel|
network == channel.network
end
end | ruby | {
"resource": ""
} |
q20461 | Codebot.IRCConnection.create_bot | train | def create_bot(con) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
net = con.network
chan_ary = channel_array(con.core.config, network)
cc = self
Cinch::Bot.new do
configure do |c|
c.channels = chan_ary
c.local_host = net.bind
c.modes = net.modes.to_s.gsub(/\A\+/, '').chars.uniq
c.nick = net.nick
c.password = net.server_password
c.port = net.real_port
c.realname = Codebot::WEBSITE
if net.sasl?
c.sasl.username = net.sasl_username
c.sasl.password = net.sasl_password
end
c.server = net.host
c.ssl.use = net.secure
c.ssl.verify = net.secure
c.user = Codebot::PROJECT.downcase
cc.configure_nickserv_identification(net, c)
end
on(:join) { con.set_ready! }
end
end | ruby | {
"resource": ""
} |
q20462 | Tinder.Room.user | train | def user(id)
if id
cached_user = users.detect {|u| u[:id] == id }
user = cached_user || fetch_user(id)
self.users << user
user
end
end | ruby | {
"resource": ""
} |
q20463 | Tinder.Room.fetch_user | train | def fetch_user(id)
user_data = connection.get("/users/#{id}.json")
user = user_data && user_data[:user]
user[:created_at] = Time.parse(user[:created_at])
user
end | ruby | {
"resource": ""
} |
q20464 | MailRoom.CLI.start | train | def start
Signal.trap(:INT) do
coordinator.running = false
end
Signal.trap(:TERM) do
exit
end
coordinator.run
end | ruby | {
"resource": ""
} |
q20465 | MailRoom.MailboxWatcher.run | train | def run
@running = true
connection.on_new_message do |message|
@mailbox.deliver(message)
end
self.watching_thread = Thread.start do
while(running?) do
connection.wait
end
end
watching_thread.abort_on_exception = true
end | ruby | {
"resource": ""
} |
q20466 | Processing.Watcher.start_watching | train | def start_watching
start_original
Kernel.loop do
if @files.find { |file| FileTest.exist?(file) && File.stat(file).mtime > @time }
puts 'reloading sketch...'
Processing.app && Processing.app.close
java.lang.System.gc
@time = Time.now
start_runner
reload_files_to_watch
end
sleep SLEEP_TIME
end
end | ruby | {
"resource": ""
} |
q20467 | Processing.Watcher.report_errors | train | def report_errors
yield
rescue Exception => e
wformat = 'Exception occured while running sketch %s...'
tformat = "Backtrace:\n\t%s"
warn format(wformat, File.basename(SKETCH_PATH))
puts format(tformat, e.backtrace.join("\n\t"))
end | ruby | {
"resource": ""
} |
q20468 | Processing.App.close | train | def close
control_panel.remove if respond_to?(:control_panel)
surface.stopThread
surface.setVisible(false) if surface.isStopped
dispose
Processing.app = nil
end | ruby | {
"resource": ""
} |
q20469 | Processing.HelperMethods.buffer | train | def buffer(buf_width = width, buf_height = height, renderer = @render_mode)
create_graphics(buf_width, buf_height, renderer).tap do |buffer|
buffer.begin_draw
yield buffer
buffer.end_draw
end
end | ruby | {
"resource": ""
} |
q20470 | Processing.HelperMethods.hsb_color | train | def hsb_color(hue, sat, brightness)
Java::Monkstone::ColorUtil.hsbToRgB(hue, sat, brightness)
end | ruby | {
"resource": ""
} |
q20471 | Processing.HelperMethods.dist | train | def dist(*args)
case args.length
when 4
return dist2d(*args)
when 6
return dist3d(*args)
else
raise ArgumentError, 'takes 4 or 6 parameters'
end
end | ruby | {
"resource": ""
} |
q20472 | Processing.HelperMethods.blend_color | train | def blend_color(c1, c2, mode)
Java::ProcessingCore::PImage.blendColor(c1, c2, mode)
end | ruby | {
"resource": ""
} |
q20473 | Processing.HelperMethods.find_method | train | def find_method(method_name)
reg = Regexp.new(method_name.to_s, true)
methods.sort.select { |meth| reg.match(meth) }
end | ruby | {
"resource": ""
} |
q20474 | Processing.HelperMethods.proxy_java_fields | train | def proxy_java_fields
fields = %w(key frameRate mousePressed keyPressed)
methods = fields.map { |field| java_class.declared_field(field) }
@declared_fields = Hash[fields.zip(methods)]
end | ruby | {
"resource": ""
} |
q20475 | Processing.Runner.execute! | train | def execute!
show_help if options.empty?
show_version if options[:version]
run_sketch if options[:run]
watch_sketch if options[:watch]
live if options[:live]
create if options[:create]
check if options[:check]
install if options[:install]
end | ruby | {
"resource": ""
} |
q20476 | Processing.Runner.parse_options | train | def parse_options(args)
opt_parser = OptionParser.new do |opts|
# Set a banner, displayed at the top
# of the help screen.
opts.banner = 'Usage: k9 [options] [<filename.rb>]'
# Define the options, and what they do
options[:version] = false
opts.on('-v', '--version', 'JRubyArt Version') do
options[:version] = true
end
options[:install] = false
opts.on('-i', '--install', 'Installs jruby-complete and examples') do
options[:install] = true
end
options[:check] = false
opts.on('-?', '--check', 'Prints configuration') do
options[:check] = true
end
options[:app] = false
opts.on('-a', '--app', 'Export as app NOT IMPLEMENTED YET') do
options[:export] = true
end
options[:watch] = false
opts.on('-w', '--watch', 'Watch/run the sketch') do
options[:watch] = true
end
options[:run] = false
opts.on('-r', '--run', 'Run the sketch') do
options[:run] = true
end
options[:live] = false
opts.on('-l', '--live', 'As above, with pry console bound to Processing.app') do
options[:live] = true
end
options[:create] = false
opts.on('-c', '--create', 'Create new outline sketch') do
options[:create] = true
end
# This displays the help screen, all programs are
# assumed to have this option.
opts.on('-h', '--help', 'Display this screen') do
puts opts
exit
end
end
@argc = opt_parser.parse(args)
@filename = argc.shift
end | ruby | {
"resource": ""
} |
q20477 | WillFilter.Filter.model_class | train | def model_class
if WillFilter::Config.require_filter_extensions?
raise WillFilter::FilterException.new("model_class method must be overloaded in the extending class.")
end
if model_class_name.blank?
raise WillFilter::FilterException.new("model_class_name was not specified.")
end
@model_class ||= model_class_name.constantize
end | ruby | {
"resource": ""
} |
q20478 | WillFilter.Filter.condition_title_for | train | def condition_title_for(key)
title_parts = key.to_s.split('.')
title = key.to_s.gsub(".", ": ").gsub("_", " ")
title = title.split(" ").collect{|part| part.split("/").last.capitalize}.join(" ")
if title_parts.size > 1
"#{JOIN_NAME_INDICATOR} #{title}"
else
title
end
end | ruby | {
"resource": ""
} |
q20479 | WillFilter.Filter.export_formats | train | def export_formats
formats = []
formats << ["-- Generic Formats --", -1]
WillFilter::Config.default_export_formats.each do |frmt|
formats << [frmt, frmt]
end
if custom_formats.size > 0
formats << ["-- Custom Formats --", -2]
custom_formats.each do |frmt|
formats << frmt
end
end
formats
end | ruby | {
"resource": ""
} |
q20480 | WillFilter.Filter.joins | train | def joins
return nil if inner_joins.empty?
inner_joins.collect do |inner_join|
join_table_name = association_class(inner_join).table_name
join_on_field = inner_join.last.to_s
"INNER JOIN #{join_table_name} ON #{join_table_name}.id = #{table_name}.#{join_on_field}"
end
end | ruby | {
"resource": ""
} |
q20481 | Bandwidth.Client.make_request | train | def make_request(method, path, data = {}, api_version = 'v1', api_endpoint = '')
d = camelcase(data)
build_path = lambda {|path| "/#{api_version}" + (if path[0] == "/" then path else "/#{path}" end) }
# A somewhat less ideal solution to the V1/V2 endpoint split
# If no endpoint is defined, use default connection
if api_endpoint.length == 0
create_connection = @create_connection
# Otherwise retrieve (or create if needed) the connection based on the given api_endpoint
else
if not @created_connections.key?(api_endpoint)
new_connection = lambda{||
Faraday.new(api_endpoint) { |faraday|
faraday.basic_auth(@api_token, @api_secret)
faraday.headers['Accept'] = 'application/json'
faraday.headers['User-Agent'] = "ruby-bandwidth/v#{Bandwidth::VERSION}"
@set_adapter.call(faraday)
@configure_connection.call(faraday) if @configure_connection
}
}
@created_connections[api_endpoint] = new_connection
end
create_connection = @created_connections[api_endpoint]
end
connection = create_connection.call()
response = if method == :get || method == :delete
connection.run_request(method, build_path.call(path), nil, nil) do |req|
req.params = d unless d == nil || d.empty?
end
else
connection.run_request(method, build_path.call(path), d.to_json(), {'Content-Type' => 'application/json'})
end
check_response(response)
r = if response.body.strip().size > 0 then symbolize(JSON.parse(response.body)) else {} end
[r, symbolize(response.headers || {})]
end | ruby | {
"resource": ""
} |
q20482 | Bandwidth.Client.check_response | train | def check_response(response)
if response.status >= 400
parsed_body = JSON.parse(response.body)
raise Errors::GenericError.new(parsed_body['code'], parsed_body['message'])
end
end | ruby | {
"resource": ""
} |
q20483 | Bandwidth.Client.camelcase | train | def camelcase v
case
when v.is_a?(Array)
v.map {|i| camelcase(i)}
when v.is_a?(Hash)
result = {}
v.each do |k, val|
result[k.to_s().camelcase(:lower)] = camelcase(val)
end
result
else
v
end
end | ruby | {
"resource": ""
} |
q20484 | Bandwidth.Client.symbolize | train | def symbolize v
case
when v.is_a?(Array)
v.map {|i| symbolize(i)}
when v.is_a?(Hash)
result = {}
v.each do |k, val|
result[k.underscore().to_sym()] = symbolize(val)
end
result
else
v
end
end | ruby | {
"resource": ""
} |
q20485 | Uploader.Asset.to_fileupload | train | def to_fileupload
{
id: id,
name: filename,
content_type: content_type,
size: size,
url: url,
thumb_url: thumb_url
}
end | ruby | {
"resource": ""
} |
q20486 | Bandwidth.Recording.create_transcription | train | def create_transcription()
headers = @client.make_request(:post, @client.concat_user_path("#{RECORDING_PATH}/#{id}/transcriptions"), {})[1]
id = Client.get_id_from_location_header(headers[:location])
get_transcription(id)
end | ruby | {
"resource": ""
} |
q20487 | Uploader.Authorization.uploader_authorization_adapter | train | def uploader_authorization_adapter
adapter = Uploader.authorization_adapter
if adapter.is_a? String
ActiveSupport::Dependencies.constantize(adapter)
else
adapter
end
end | ruby | {
"resource": ""
} |
q20488 | Uploader.FileuploadGlue.multiple? | train | def multiple?(method_name)
return false if association(method_name).nil?
name = association(method_name).respond_to?(:many?) ? :many? : :collection?
association(method_name).send(name)
end | ruby | {
"resource": ""
} |
q20489 | Bandwidth.Conference.create_member | train | def create_member(data)
headers = @client.make_request(:post, @client.concat_user_path("#{CONFERENCE_PATH}/#{id}/members"), data)[1]
id = Client.get_id_from_location_header(headers[:location])
get_member(id)
end | ruby | {
"resource": ""
} |
q20490 | Bandwidth.Conference.get_member | train | def get_member(member_id)
member = ConferenceMember.new(@client.make_request(:get, @client.concat_user_path("#{CONFERENCE_PATH}/#{id}/members/#{member_id}"))[0],
@client)
member.conference_id = id
member
end | ruby | {
"resource": ""
} |
q20491 | Bandwidth.Conference.get_members | train | def get_members()
@client.make_request(:get, @client.concat_user_path("#{CONFERENCE_PATH}/#{id}/members"))[0].map do |i|
member = ConferenceMember.new(i, @client)
member.conference_id = id
member
end
end | ruby | {
"resource": ""
} |
q20492 | Prawn.QRCode.print_qr_code | train | def print_qr_code(content, level: :m, dot: DEFAULT_DOTSIZE, pos: [0,cursor], stroke: true, margin: 4, **options)
qr_version = 0
dot_size = dot
begin
qr_version += 1
qr_code = RQRCode::QRCode.new(content, size: qr_version, level: level)
dot = options[:extent] / (2*margin + qr_code.modules.length) if options[:extent]
render_qr_code(qr_code, dot: dot, pos: pos, stroke: stroke, margin: margin, **options)
rescue RQRCode::QRCodeRunTimeError
if qr_version < 40
retry
else
raise
end
end
end | ruby | {
"resource": ""
} |
q20493 | Bandwidth.Domain.create_endpoint | train | def create_endpoint(data)
headers = @client.make_request(:post, @client.concat_user_path("#{DOMAIN_PATH}/#{id}/endpoints"), data)[1]
id = Client.get_id_from_location_header(headers[:location])
get_endpoint(id)
end | ruby | {
"resource": ""
} |
q20494 | Bandwidth.Domain.get_endpoint | train | def get_endpoint(endpoint_id)
endpoint = EndPoint.new(@client.make_request(:get, @client.concat_user_path("#{DOMAIN_PATH}/#{id}/endpoints/#{endpoint_id}"))[0],
@client)
endpoint.domain_id = id
endpoint
end | ruby | {
"resource": ""
} |
q20495 | Bandwidth.Domain.get_endpoints | train | def get_endpoints(query = nil)
@client.make_request(:get, @client.concat_user_path("#{DOMAIN_PATH}/#{id}/endpoints"), query)[0].map do |i|
endpoint = EndPoint.new(i, @client)
endpoint.domain_id = id
endpoint
end
end | ruby | {
"resource": ""
} |
q20496 | Bandwidth.Domain.delete_endpoint | train | def delete_endpoint(endpoint_id)
endpoint = EndPoint.new({:id => endpoint_id}, @client)
endpoint.domain_id = id
endpoint.delete()
end | ruby | {
"resource": ""
} |
q20497 | Bandwidth.Call.create_gather | train | def create_gather(data)
d = if data.is_a?(String)
{
:tag => id, :max_digits => 1,
:prompt => {:locale => 'en_US', :gender => 'female', :sentence => data, :voice => 'kate', :bargeable => true }
}
else
data
end
headers = @client.make_request(:post, @client.concat_user_path("#{CALL_PATH}/#{id}/gather"), d)[1]
id = Client.get_id_from_location_header(headers[:location])
get_gather(id)
end | ruby | {
"resource": ""
} |
q20498 | Bandwidth.PlayAudioExtensions.speak_sentence | train | def speak_sentence(sentence, tag = nil, gender = "female", voice = "kate")
play_audio({:gender => gender || "female", :locale => "en_US",
:voice => voice || "kate", :sentence => sentence, :tag => tag})
end | ruby | {
"resource": ""
} |
q20499 | HQMF2CQL.Document.extract_criteria | train | def extract_criteria
# Grab each data criteria entry from the HQMF
extracted_data_criteria = []
@doc.xpath('cda:QualityMeasureDocument/cda:component/cda:dataCriteriaSection/cda:entry', NAMESPACES).each do |entry|
extracted_data_criteria << entry
dc = HQMF2CQL::DataCriteria.new(entry) # Create new data criteria
sdc = dc.clone # Clone data criteria
sdc.id += '_source' # Make it a source
@data_criteria << dc
@source_data_criteria << sdc
end
make_positive_entry
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.