_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q900 | ActionAccess.UserUtilities.can? | train | def can?(action, resource, options = {})
keeper = ActionAccess::Keeper.instance
clearance_levels = Array(clearance_levels())
clearance_levels.any? { |c| keeper.lets? c, action, resource, options }
end | ruby | {
"resource": ""
} |
q901 | Telegram.TelegramBase.send_image | train | def send_image(path, refer, &callback)
if @type == 'encr_chat'
logger.warn("Currently telegram-cli has a bug with send_typing, then prevent this for safety")
return
end
fail_back(&callback) if not File.exist?(path)
@client.send_photo(targetize, path, &callback)
end | ruby | {
"resource": ""
} |
q902 | Telegram.TelegramBase.send_image_url | train | def send_image_url(url, opt, refer, &callback)
begin
opt = {} if opt.nil?
http = EM::HttpRequest.new(url, :connect_timeout => 2, :inactivity_timeout => 5).get opt
file = Tempfile.new(['image', 'jpg'])
http.stream { |chunk|
file.write(chunk)
}
http.callback... | ruby | {
"resource": ""
} |
q903 | Telegram.TelegramBase.send_video | train | def send_video(path, refer, &callback)
fail_back(&callback) if not File.exist?(path)
@client.send_video(targetize, path, &callback)
end | ruby | {
"resource": ""
} |
q904 | Telegram.TelegramMessage.reply | train | def reply(type, content, target=nil, &callback)
target = @target if target.nil?
case type
when :text
target.send_message(content, self, &callback)
when :image
option = nil
content, option = content if content.class == Array
if content.include?('http')
t... | ruby | {
"resource": ""
} |
q905 | Telegram.API.update! | train | def update!(&cb)
done = false
EM.synchrony do
multi = EM::Synchrony::Multi.new
multi.add :profile, update_profile!
multi.add :contacts, update_contacts!
multi.add :chats, update_chats!
multi.perform
done = true
end
check_done = Proc.new {
... | ruby | {
"resource": ""
} |
q906 | Telegram.API.update_profile! | train | def update_profile!
assert!
callback = Callback.new
@profile = nil
@connection.communicate('get_self') do |success, data|
if success
callback.trigger(:success)
contact = TelegramContact.pick_or_new(self, data)
@contacts << contact unless self.contacts.includ... | ruby | {
"resource": ""
} |
q907 | Telegram.API.update_contacts! | train | def update_contacts!
assert!
callback = Callback.new
@contacts = []
@connection.communicate('contact_list') do |success, data|
if success and data.class == Array
callback.trigger(:success)
data.each { |contact|
contact = TelegramContact.pick_or_new(self, c... | ruby | {
"resource": ""
} |
q908 | Telegram.API.update_chats! | train | def update_chats!
assert!
callback = Callback.new
collected = 0
collect_done = Proc.new do |id, data, count|
collected += 1
@chats << TelegramChat.new(self, data)
callback.trigger(:success) if collected == count
end
collect = Proc.new do |id, count|
... | ruby | {
"resource": ""
} |
q909 | Telegram.API.send_contact | train | def send_contact(peer, phone, first_name, last_name)
assert!
@connection.communicate(['send_contact', peer, phone, first_name, last_name])
end | ruby | {
"resource": ""
} |
q910 | Telegram.API.download_attachment | train | def download_attachment(type, seq, &callback)
assert!
raise "Type mismatch" unless %w(photo video audio).include?(type)
@connection.communicate(["load_#{type.to_s}", seq], &callback)
end | ruby | {
"resource": ""
} |
q911 | Telegram.Event.format_message | train | def format_message
message = Message.new
message.id = @id
message.text = @raw_data['text'] ||= ''
media = @raw_data['media']
message.type = media ? media['type'] : 'text'
message.raw_from = @raw_data['from']['peer_id']
message.from_type = @raw_data['from']['peer_type']
m... | ruby | {
"resource": ""
} |
q912 | Telegram.Connection.communicate | train | def communicate(*messages, &callback)
@available = false
@data = ''
@callback = callback
messages = messages.first if messages.size == 1 and messages.first.is_a?(Array)
messages = messages.join(' ') << "\n"
send_data(messages)
end | ruby | {
"resource": ""
} |
q913 | Telegram.Connection.receive_data | train | def receive_data(data)
@data << data
return unless data.index("\n\n")
begin
result = _receive_data(@data)
rescue
raise
result = nil
end
@callback.call(!result.nil?, result) unless @callback.nil?
@callback = nil
@available = true
end | ruby | {
"resource": ""
} |
q914 | Telegram.ConnectionPool.acquire | train | def acquire(&callback)
acq = Proc.new {
conn = self.find { |conn| conn.available? }
if not conn.nil? and conn.connected?
callback.call(conn)
else
logger.warn("Failed to acquire available connection, retry after 0.1 second")
EM.add_timer(0.1, &acq)
end
... | ruby | {
"resource": ""
} |
q915 | Telegram.Client.execute | train | def execute
cli_arguments = Telegram::CLIArguments.new(@config)
command = "'#{@config.daemon}' #{cli_arguments.to_s}"
@stdout = IO.popen(command, 'a+')
initialize_stdout_reading
end | ruby | {
"resource": ""
} |
q916 | Telegram.Client.poll | train | def poll
logger.info("Start polling for events")
while (data = @stdout.gets)
begin
brace = data.index('{')
data = data[brace..-2]
data = Oj.load(data, mode: :compat)
@events << data
rescue
end
end
end | ruby | {
"resource": ""
} |
q917 | Telegram.Client.connect | train | def connect(&block)
logger.info("Trying to start telegram-cli and then connect")
@connect_callback = block
process_data
EM.defer(method(:execute), method(:create_pool), method(:execution_failed))
end | ruby | {
"resource": ""
} |
q918 | Poseidon.MessageSet.flatten | train | def flatten
messages = struct.messages.map do |message|
if message.compressed?
s = message.decompressed_value
MessageSet.read_without_size(Protocol::ResponseBuffer.new(s)).flatten
else
message
end
end.flatten
end | ruby | {
"resource": ""
} |
q919 | Poseidon.MessagesForBroker.add | train | def add(message, partition_id)
@messages << message
@topics[message.topic] ||= {}
@topics[message.topic][partition_id] ||= []
@topics[message.topic][partition_id] << message
end | ruby | {
"resource": ""
} |
q920 | Poseidon.MessagesForBroker.build_protocol_objects | train | def build_protocol_objects(compression_config)
@topics.map do |topic, messages_by_partition|
codec = compression_config.compression_codec_for_topic(topic)
messages_for_partitions = messages_by_partition.map do |partition, messages|
message_set = MessageSet.new(messages)
if cod... | ruby | {
"resource": ""
} |
q921 | Poseidon.MessagesToSendBatch.messages_for_brokers | train | def messages_for_brokers
messages_for_broker_ids = {}
@messages.each do |message|
partition_id, broker_id = @message_conductor.destination(message.topic,
message.key)
# Create a nested hash to group messages by broker_id, topi... | ruby | {
"resource": ""
} |
q922 | Poseidon.Connection.produce | train | def produce(required_acks, timeout, messages_for_topics)
ensure_connected
req = ProduceRequest.new( request_common(:produce),
required_acks,
timeout,
messages_for_topics)
send_request(req)
if require... | ruby | {
"resource": ""
} |
q923 | Poseidon.Connection.fetch | train | def fetch(max_wait_time, min_bytes, topic_fetches)
ensure_connected
req = FetchRequest.new( request_common(:fetch),
REPLICA_ID,
max_wait_time,
min_bytes,
topic_fetches)
send... | ruby | {
"resource": ""
} |
q924 | Poseidon.Connection.topic_metadata | train | def topic_metadata(topic_names)
ensure_connected
req = MetadataRequest.new( request_common(:metadata),
topic_names)
send_request(req)
read_response(MetadataResponse)
end | ruby | {
"resource": ""
} |
q925 | Poseidon.ClusterMetadata.update | train | def update(topic_metadata_response)
update_brokers(topic_metadata_response.brokers)
update_topics(topic_metadata_response.topics)
@last_refreshed_at = Time.now
nil
end | ruby | {
"resource": ""
} |
q926 | Poseidon.MessageConductor.destination | train | def destination(topic, key = nil)
topic_metadata = topic_metadatas[topic]
if topic_metadata && topic_metadata.leader_available?
partition_id = determine_partition(topic_metadata, key)
broker_id = topic_metadata.partition_leader(partition_id) || NO_BROKER
else
partition_id =... | ruby | {
"resource": ""
} |
q927 | Poseidon.PartitionConsumer.fetch | train | def fetch(options = {})
fetch_max_wait = options.delete(:max_wait_ms) || max_wait_ms
fetch_max_bytes = options.delete(:max_bytes) || max_bytes
fetch_min_bytes = options.delete(:min_bytes) || min_bytes
if options.keys.any?
raise ArgumentError, "Unknown options: #{options.keys.inspect}"
... | ruby | {
"resource": ""
} |
q928 | Poseidon.Producer.send_messages | train | def send_messages(messages)
raise Errors::ProducerShutdownError if @shutdown
if !messages.respond_to?(:each)
raise ArgumentError, "messages must respond to #each"
end
@producer.send_messages(convert_to_messages_objects(messages))
end | ruby | {
"resource": ""
} |
q929 | TTY.Screen.size | train | def size
size = size_from_java
size ||= size_from_win_api
size ||= size_from_ioctl
size ||= size_from_io_console
size ||= size_from_readline
size ||= size_from_tput
size ||= size_from_stty
size ||= size_from_env
size ||= size_from_ansicon
size || DEFAULT_SIZE... | ruby | {
"resource": ""
} |
q930 | TTY.Screen.size_from_win_api | train | def size_from_win_api(verbose: nil)
require 'fiddle'
kernel32 = Fiddle::Handle.new('kernel32')
get_std_handle = Fiddle::Function.new(kernel32['GetStdHandle'],
[-Fiddle::TYPE_INT], Fiddle::TYPE_INT)
get_console_buffer_info = Fiddle::Function.new(
kernel32['GetCons... | ruby | {
"resource": ""
} |
q931 | TTY.Screen.size_from_java | train | def size_from_java(verbose: nil)
return unless jruby?
require 'java'
java_import 'jline.TerminalFactory'
terminal = TerminalFactory.get
size = [terminal.get_height, terminal.get_width]
return size if nonzero_column?(size[1])
rescue
warn 'failed to import java terminal packa... | ruby | {
"resource": ""
} |
q932 | TTY.Screen.size_from_ioctl | train | def size_from_ioctl
return if jruby?
return unless @output.respond_to?(:ioctl)
format = 'SSSS'
buffer = ([0] * format.size).pack(format)
if ioctl?(TIOCGWINSZ, buffer) || ioctl?(TIOCGWINSZ_PPC, buffer)
rows, cols, = buffer.unpack(format)[0..1]
return [rows, cols] if nonzero... | ruby | {
"resource": ""
} |
q933 | TTY.Screen.size_from_readline | train | def size_from_readline
if defined?(Readline) && Readline.respond_to?(:get_screen_size)
size = Readline.get_screen_size
size if nonzero_column?(size[1])
end
rescue NotImplementedError
end | ruby | {
"resource": ""
} |
q934 | TTY.Screen.size_from_tput | train | def size_from_tput
return unless @output.tty?
lines = run_command('tput', 'lines').to_i
cols = run_command('tput', 'cols').to_i
[lines, cols] if nonzero_column?(lines)
rescue IOError, SystemCallError
end | ruby | {
"resource": ""
} |
q935 | TTY.Screen.size_from_stty | train | def size_from_stty
return unless @output.tty?
out = run_command('stty', 'size')
return unless out
size = out.split.map(&:to_i)
size if nonzero_column?(size[1])
rescue IOError, SystemCallError
end | ruby | {
"resource": ""
} |
q936 | TTY.Screen.run_command | train | def run_command(*args)
require 'tempfile'
out = Tempfile.new('tty-screen')
result = system(*args, out: out.path, err: File::NULL)
return if result.nil?
out.rewind
out.read
ensure
out.close if out
end | ruby | {
"resource": ""
} |
q937 | MultiMail.Service.validate_options | train | def validate_options(options, raise_error_if_unrecognized = true)
keys = []
for key, value in options
unless value.nil?
keys << key
end
end
missing = requirements - keys
unless missing.empty?
raise ArgumentError, "Missing required arguments: #{missing.map... | ruby | {
"resource": ""
} |
q938 | Crass.Parser.consume_at_rule | train | def consume_at_rule(input = @tokens)
rule = {}
rule[:tokens] = input.collect do
rule[:name] = input.consume[:value]
rule[:prelude] = []
while token = input.consume
node = token[:node]
if node == :comment # Non-standard.
next
elsif node... | ruby | {
"resource": ""
} |
q939 | Crass.Parser.consume_component_value | train | def consume_component_value(input = @tokens)
return nil unless token = input.consume
case token[:node]
when :'{', :'[', :'('
consume_simple_block(input)
when :function
if token.key?(:name)
# This is a parsed function, not a function token. This step isn't
# ... | ruby | {
"resource": ""
} |
q940 | Crass.Parser.consume_declaration | train | def consume_declaration(input = @tokens)
declaration = {}
value = []
declaration[:tokens] = input.collect do
declaration[:name] = input.consume[:value]
next_token = input.peek
while next_token && next_token[:node] == :whitespace
input.consume
next_t... | ruby | {
"resource": ""
} |
q941 | Crass.Parser.consume_declarations | train | def consume_declarations(input = @tokens, options = {})
declarations = []
while token = input.consume
case token[:node]
# Non-standard: Preserve comments, semicolons, and whitespace.
when :comment, :semicolon, :whitespace
declarations << token unless options[:strict]
... | ruby | {
"resource": ""
} |
q942 | Crass.Parser.consume_function | train | def consume_function(input = @tokens)
function = {
:name => input.current[:value],
:value => [],
:tokens => [input.current] # Non-standard, used for serialization.
}
function[:tokens].concat(input.collect {
while token = input.consume
case token[:node]
... | ruby | {
"resource": ""
} |
q943 | Crass.Parser.consume_qualified_rule | train | def consume_qualified_rule(input = @tokens)
rule = {:prelude => []}
rule[:tokens] = input.collect do
while true
unless token = input.consume
# Parse error.
#
# Note: The spec explicitly says to return nothing here, but Simon
# Sapin's CSS pa... | ruby | {
"resource": ""
} |
q944 | Crass.Parser.consume_rules | train | def consume_rules(flags = {})
rules = []
while token = @tokens.consume
case token[:node]
# Non-standard. Spec says to discard comments and whitespace, but we
# keep them so we can serialize faithfully.
when :comment, :whitespace
rules << token
when :cd... | ruby | {
"resource": ""
} |
q945 | Crass.Parser.consume_simple_block | train | def consume_simple_block(input = @tokens)
start_token = input.current[:node]
end_token = BLOCK_END_TOKENS[start_token]
block = {
:start => start_token.to_s,
:end => end_token.to_s,
:value => [],
:tokens => [input.current] # Non-standard. Used for serialization.
... | ruby | {
"resource": ""
} |
q946 | Crass.Parser.parse_component_value | train | def parse_component_value(input = @tokens)
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
while input.peek && input.peek[:node] == :whitespace
input.consume
end
if input.peek.nil?
return create_node(:error, :value => 'empty')
end
value = consume_c... | ruby | {
"resource": ""
} |
q947 | Crass.Parser.parse_component_values | train | def parse_component_values(input = @tokens)
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
tokens = []
while token = consume_component_value(input)
tokens << token
end
tokens
end | ruby | {
"resource": ""
} |
q948 | Crass.Parser.parse_declaration | train | def parse_declaration(input = @tokens)
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
while input.peek && input.peek[:node] == :whitespace
input.consume
end
if input.peek.nil?
# Syntax error.
return create_node(:error, :value => 'empty')
elsif in... | ruby | {
"resource": ""
} |
q949 | Crass.Parser.parse_declarations | train | def parse_declarations(input = @tokens, options = {})
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
consume_declarations(input, options)
end | ruby | {
"resource": ""
} |
q950 | Crass.Parser.parse_rule | train | def parse_rule(input = @tokens)
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
while input.peek && input.peek[:node] == :whitespace
input.consume
end
if input.peek.nil?
# Syntax error.
return create_node(:error, :value => 'empty')
elsif input.pee... | ruby | {
"resource": ""
} |
q951 | Crass.Parser.parse_value | train | def parse_value(nodes)
nodes = [nodes] unless nodes.is_a?(Array)
string = String.new
nodes.each do |node|
case node[:node]
when :comment, :semicolon
next
when :at_keyword, :ident
string << node[:value]
when :function
if node[:value].is_... | ruby | {
"resource": ""
} |
q952 | Crass.Tokenizer.consume_bad_url | train | def consume_bad_url
text = String.new
until @s.eos?
if valid_escape?
text << consume_escaped
elsif valid_escape?(@s.peek(2))
@s.consume
text << consume_escaped
else
char = @s.consume
if char == ')'
break
else
... | ruby | {
"resource": ""
} |
q953 | Crass.Tokenizer.consume_comments | train | def consume_comments
if @s.peek(2) == '/*'
@s.consume
@s.consume
if text = @s.scan_until(RE_COMMENT_CLOSE)
text.slice!(-2, 2)
else
# Parse error.
text = @s.consume_rest
end
return create_token(:comment, :value => text)
end
... | ruby | {
"resource": ""
} |
q954 | Crass.Tokenizer.consume_escaped | train | def consume_escaped
return "\ufffd" if @s.eos?
if hex_str = @s.scan(RE_HEX)
@s.consume if @s.peek =~ RE_WHITESPACE
codepoint = hex_str.hex
if codepoint == 0 ||
codepoint.between?(0xD800, 0xDFFF) ||
codepoint > 0x10FFFF
return "\ufffd"
els... | ruby | {
"resource": ""
} |
q955 | Crass.Tokenizer.consume_ident | train | def consume_ident
value = consume_name
if @s.peek == '('
@s.consume
if value.downcase == 'url'
@s.consume while @s.peek(2) =~ RE_WHITESPACE_ANCHORED
if @s.peek(2) =~ RE_QUOTED_URL_START
create_token(:function, :value => value)
else
con... | ruby | {
"resource": ""
} |
q956 | Crass.Tokenizer.consume_name | train | def consume_name
result = String.new
until @s.eos?
if match = @s.scan(RE_NAME)
result << match
next
end
char = @s.consume
if valid_escape?
result << consume_escaped
# Non-standard: IE * hack
elsif char == '*' && @options[:pres... | ruby | {
"resource": ""
} |
q957 | Crass.Tokenizer.consume_numeric | train | def consume_numeric
number = consume_number
if start_identifier?(@s.peek(3))
create_token(:dimension,
:repr => number[0],
:type => number[2],
:unit => consume_name,
:value => number[1])
elsif @s.peek == '%'
@s.consume
create_token(:... | ruby | {
"resource": ""
} |
q958 | Crass.Tokenizer.consume_string | train | def consume_string(ending = nil)
ending = @s.current if ending.nil?
value = String.new
until @s.eos?
case char = @s.consume
when ending
break
when "\n"
# Parse error.
@s.reconsume
return create_token(:bad_string,
:error => ... | ruby | {
"resource": ""
} |
q959 | Crass.Tokenizer.consume_unicode_range | train | def consume_unicode_range
value = @s.scan(RE_HEX) || String.new
while value.length < 6
break unless @s.peek == '?'
value << @s.consume
end
range = {}
if value.include?('?')
range[:start] = value.gsub('?', '0').hex
range[:end] = value.gsub('?', 'F').hex
... | ruby | {
"resource": ""
} |
q960 | Crass.Tokenizer.consume_url | train | def consume_url
value = String.new
@s.scan(RE_WHITESPACE)
until @s.eos?
case char = @s.consume
when ')'
break
when RE_WHITESPACE
@s.scan(RE_WHITESPACE)
if @s.eos? || @s.peek == ')'
@s.consume
break
else
... | ruby | {
"resource": ""
} |
q961 | Crass.Tokenizer.convert_string_to_number | train | def convert_string_to_number(str)
matches = RE_NUMBER_STR.match(str)
s = matches[:sign] == '-' ? -1 : 1
i = matches[:integer].to_i
f = matches[:fractional].to_i
d = matches[:fractional] ? matches[:fractional].length : 0
t = matches[:exponent_sign] == '-' ? -1 : 1
e = matches[:... | ruby | {
"resource": ""
} |
q962 | Crass.Tokenizer.preprocess | train | def preprocess(input)
input = input.to_s.encode('UTF-8',
:invalid => :replace,
:undef => :replace)
input.gsub!(/(?:\r\n|[\r\f])/, "\n")
input.gsub!("\u0000", "\ufffd")
input
end | ruby | {
"resource": ""
} |
q963 | Crass.Tokenizer.start_identifier? | train | def start_identifier?(text = nil)
text = @s.current + @s.peek(2) if text.nil?
case text[0]
when '-'
nextChar = text[1]
!!(nextChar == '-' || nextChar =~ RE_NAME_START || valid_escape?(text[1, 2]))
when RE_NAME_START
true
when '\\'
valid_escape?(text[0, 2]... | ruby | {
"resource": ""
} |
q964 | Crass.Tokenizer.start_number? | train | def start_number?(text = nil)
text = @s.current + @s.peek(2) if text.nil?
case text[0]
when '+', '-'
!!(text[1] =~ RE_DIGIT || (text[1] == '.' && text[2] =~ RE_DIGIT))
when '.'
!!(text[1] =~ RE_DIGIT)
when RE_DIGIT
true
else
false
end
end | ruby | {
"resource": ""
} |
q965 | Mongoid.Autoinc.assign! | train | def assign!(field)
options = self.class.incrementing_fields[field]
fail AutoIncrementsError if options[:auto]
fail AlreadyAssignedError if send(field).present?
increment!(field, options)
end | ruby | {
"resource": ""
} |
q966 | Mongoid.Autoinc.update_auto_increments | train | def update_auto_increments
self.class.incrementing_fields.each do |field, options|
increment!(field, options) if options[:auto]
end && true
end | ruby | {
"resource": ""
} |
q967 | Mongoid.Autoinc.increment! | train | def increment!(field, options)
options = options.dup
model_name = (options.delete(:model_name) || self.class.model_name).to_s
options[:scope] = evaluate_scope(options[:scope]) if options[:scope]
options[:step] = evaluate_step(options[:step]) if options[:step]
write_attribute(
fie... | ruby | {
"resource": ""
} |
q968 | Mongoid.Autoinc.evaluate_scope | train | def evaluate_scope(scope)
return send(scope) if scope.is_a? Symbol
return instance_exec(&scope) if scope.is_a? Proc
fail ArgumentError, 'scope is not a Symbol or a Proc'
end | ruby | {
"resource": ""
} |
q969 | Mongoid.Autoinc.evaluate_step | train | def evaluate_step(step)
return step if step.is_a? Integer
return evaluate_step_proc(step) if step.is_a? Proc
fail ArgumentError, 'step is not an Integer or a Proc'
end | ruby | {
"resource": ""
} |
q970 | Mongoid.Autoinc.evaluate_step_proc | train | def evaluate_step_proc(step_proc)
result = instance_exec(&step_proc)
return result if result.is_a? Integer
fail 'step Proc does not evaluate to an Integer'
end | ruby | {
"resource": ""
} |
q971 | EquivalentXml.Processor.same_namespace? | train | def same_namespace?(node_1, node_2)
args = [node_1,node_2]
# CharacterData nodes shouldn't have namespaces. But in Nokogiri,
# they do. And they're invisible. And they get corrupted easily.
# So let's wilfully ignore them. And while we're at it, let's
# ignore any class that doesn't know ... | ruby | {
"resource": ""
} |
q972 | EasyCaptcha.ControllerHelpers.generate_captcha | train | def generate_captcha
if EasyCaptcha.cache
# create cache dir
FileUtils.mkdir_p(EasyCaptcha.cache_temp_dir)
# select all generated captchas from cache
files = Dir.glob(EasyCaptcha.cache_temp_dir + "*.png")
unless files.size < EasyCaptcha.cache_size
file ... | ruby | {
"resource": ""
} |
q973 | EasyCaptcha.ControllerHelpers.generate_speech_captcha | train | def generate_speech_captcha
raise RuntimeError, "espeak disabled" unless EasyCaptcha.espeak?
if EasyCaptcha.cache
File.read(speech_captcha_cache_path(current_captcha_code))
else
wav_file = Tempfile.new("#{current_captcha_code}.wav")
EasyCaptcha.espeak.generate(current_captcha_c... | ruby | {
"resource": ""
} |
q974 | EasyCaptcha.ControllerHelpers.generate_captcha_code | train | def generate_captcha_code
session[:captcha] = EasyCaptcha.length.times.collect { EasyCaptcha.chars[rand(EasyCaptcha.chars.size)] }.join
end | ruby | {
"resource": ""
} |
q975 | EasyCaptcha.ControllerHelpers.captcha_valid? | train | def captcha_valid?(code)
return false if session[:captcha].blank? or code.blank?
session[:captcha].to_s.upcase == code.to_s.upcase
end | ruby | {
"resource": ""
} |
q976 | EasyCaptcha.ViewHelpers.captcha_tag | train | def captcha_tag(*args)
options = { :alt => 'captcha', :width => EasyCaptcha.image_width, :height => EasyCaptcha.image_height }
options.merge! args.extract_options!
image_tag(captcha_url(:i => Time.now.to_i), options)
end | ruby | {
"resource": ""
} |
q977 | RGallery.Photo.source_photos | train | def source_photos
return [] unless sources.kind_of? Array
@source_photos ||= sources.map do |source|
RGallery::Photo.new source.src, options.merge(:sizing => source.sizing)
end
end | ruby | {
"resource": ""
} |
q978 | RGallery.Photo.sources= | train | def sources= sources = []
return unless sources.kind_of? Array
@sources = sources.map{|source| Hashie::Mash.new source }
end | ruby | {
"resource": ""
} |
q979 | Authenticate.Configuration.modules | train | def modules
modules = @modules.dup # in case the user pushes any on
modules << @authentication_strategy
modules << :db_password
modules << :password_reset
modules << :trackable # needs configuration
modules << :timeoutable if @timeout_in
modules << :lifetimed if @max_session_l... | ruby | {
"resource": ""
} |
q980 | Authenticate.Session.login | train | def login(user)
@current_user = user
@current_user.generate_session_token if user.present?
message = catch(:failure) do
Authenticate.lifecycle.run_callbacks(:after_set_user, @current_user, self, event: :authentication)
Authenticate.lifecycle.run_callbacks(:after_authentication, @curre... | ruby | {
"resource": ""
} |
q981 | Authenticate.Controller.require_login | train | def require_login
debug "!!!!!!!!!!!!!!!!!! controller#require_login " # logged_in? #{logged_in?}"
unauthorized unless logged_in?
message = catch(:failure) do
current_user = authenticate_session.current_user
Authenticate.lifecycle.run_callbacks(:after_set_user, current_user, authentica... | ruby | {
"resource": ""
} |
q982 | Authenticate.Controller.unauthorized | train | def unauthorized(msg = t('flashes.failure_when_not_signed_in'))
authenticate_session.logout
respond_to do |format|
format.any(:js, :json, :xml) { head :unauthorized }
format.any { redirect_unauthorized(msg) }
end
end | ruby | {
"resource": ""
} |
q983 | JadePug.Config.method_missing | train | def method_missing(name, *args, &block)
return super if block
case args.size
when 0
# config.client?
if name =~ /\A(\w+)\?\z/
!!(respond_to?($1) ? send($1) : instance_variable_get("@#{ $1 }"))
# config.client
elsif name =~ /\A(\w+)\z/
... | ruby | {
"resource": ""
} |
q984 | JadePug.Config.to_hash | train | def to_hash
instance_variables.each_with_object({}) do |var, h|
h[var[1..-1].to_sym] = instance_variable_get(var)
end
end | ruby | {
"resource": ""
} |
q985 | JadePug.Compiler.prepare_options | train | def prepare_options(options)
options = engine.config.to_hash.merge(options)
options.keys.each { |k| options[k.to_s.gsub(/_([a-z])/) { $1.upcase }.to_sym] = options[k] }
options.delete_if { |k, v| v.nil? }
end | ruby | {
"resource": ""
} |
q986 | JadePug.ShippedCompiler.read_compiler_source | train | def read_compiler_source(path)
raise engine::CompilerError, "Couldn't read compiler source: #{ path }" unless File.readable?(path)
File.read(path)
end | ruby | {
"resource": ""
} |
q987 | JadePug.SystemCompiler.version | train | def version
stdout, exit_status = Open3.capture2 "node", "--eval", \
"console.log(require(#{ JSON.dump(File.join(npm_package_path, "package.json")) }).version)"
if exit_status.success?
stdout.strip
else
raise engine::CompilerError, \
%{Failed to get #{ engine.name } ... | ruby | {
"resource": ""
} |
q988 | JadePug.SystemCompiler.check_npm_package! | train | def check_npm_package!
exit_status = Open3.capture2("node", "--eval", npm_package_require_snippet)[1]
unless exit_status.success?
raise engine::CompilerError, \
%{No #{ engine.name } NPM package has been found in your system. } +
%{Have you forgotten to "npm install --global #{ ... | ruby | {
"resource": ""
} |
q989 | Rufus::Lua.StateMixin.loadstring_and_call | train | def loadstring_and_call(s, bndng, filename, lineno)
bottom = stack_top
chunk = filename ? "#{filename}:#{lineno}" : 'line'
err = Lib.luaL_loadbuffer(@pointer, s, s.bytesize, chunk)
fail_if_error('eval:compile', err, bndng, filename, lineno)
pcall(bottom, 0, bndng, filename, lineno) # ar... | ruby | {
"resource": ""
} |
q990 | Rufus::Lua.StateMixin.stack_to_s | train | def stack_to_s
# warning : don't touch at stack[0]
s = (1..stack_top).inject([]) { |a, i|
type, tname = stack_type_at(i)
val =
if type == TSTRING
"\"#{stack_fetch(i)}\""
elsif SIMPLE_TYPES.include?(type)
stack_fetch(i).to_s
elsif type... | ruby | {
"resource": ""
} |
q991 | Rufus::Lua.StateMixin.stack_push | train | def stack_push(o)
return stack_push(o.to_lua) if o.respond_to?(:to_lua)
case o
when NilClass then Lib.lua_pushnil(@pointer)
when TrueClass then Lib.lua_pushboolean(@pointer, 1)
when FalseClass then Lib.lua_pushboolean(@pointer, 0)
when Integer then Lib.lua_pushinteger(@pointer, ... | ruby | {
"resource": ""
} |
q992 | Rufus::Lua.StateMixin.stack_push_hash | train | def stack_push_hash(h)
Lib.lua_createtable(@pointer, 0, h.size)
# since we already know the size of the table...
h.each do |k, v|
stack_push(k)
stack_push(v)
Lib.lua_settable(@pointer, -3)
end
end | ruby | {
"resource": ""
} |
q993 | Rufus::Lua.StateMixin.stack_push_array | train | def stack_push_array(a)
Lib.lua_createtable(@pointer, a.size, 0)
# since we already know the size of the table...
a.each_with_index do |e, i|
stack_push(i + 1)
stack_push(e)
Lib.lua_settable(@pointer, -3)
end
end | ruby | {
"resource": ""
} |
q994 | SeamlessDatabasePool.ControllerFilter.set_read_only_connection_for_block | train | def set_read_only_connection_for_block(action)
read_pool_method = nil
if session
read_pool_method = session[:next_request_db_connection]
session.delete(:next_request_db_connection) if session[:next_request_db_connection]
end
read_pool_method ||= seamless_database_pool_options[ac... | ruby | {
"resource": ""
} |
q995 | Rufus::Lua.Function.call | train | def call(*args)
bottom = stack_top
load_onto_stack
# load function on stack
args.each { |arg| stack_push(arg) }
# push arguments on stack
pcall(bottom, args.length, nil, nil, nil)
end | ruby | {
"resource": ""
} |
q996 | Rufus::Lua.Coroutine.resume | train | def resume(*args)
bottom = stack_top
fetch_library_method('coroutine.resume').load_onto_stack
load_onto_stack
args.each { |arg| stack_push(arg) }
pcall(bottom, args.length + 1, nil, nil, nil)
end | ruby | {
"resource": ""
} |
q997 | Rufus::Lua.Table.[]= | train | def []=(k, v)
load_onto_stack
stack_push(k)
stack_push(v)
Lib.lua_settable(@pointer, -3)
v
end | ruby | {
"resource": ""
} |
q998 | Rufus::Lua.Table.to_h | train | def to_h
load_onto_stack
table_pos = stack_top
Lib.lua_pushnil(@pointer)
h = {}
while Lib.lua_next(@pointer, table_pos) != 0 do
value = stack_fetch(-1)
value.load_onto_stack if value.is_a?(Ref)
key = stack_fetch(-2)
key.load_onto_stack if key.is_a?(Re... | ruby | {
"resource": ""
} |
q999 | Rufus::Lua.Table.to_a | train | def to_a(pure=true)
h = self.to_h
pure && h.keys.find { |k| not [ Float ].include?(k.class) } &&
fail('cannot turn hash into array, some keys are not numbers')
a_keys = (1..objlen).to_a.collect { |k| k.to_f }
keys = a_keys + (h.keys - a_keys)
keys.inject([]) { |a, k|
a ... | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.