_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 { file.close type = FastImage.type(file.path) if %i(jpeg png gif).include?(type) send_image(file.path, refer, &callback) else fail_back(&callback) end } rescue Exception => e logger.error("An error occurred during the image downloading: #{e.inspect} #{e.backtrace}") fail_back(&callback) end end
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') target.method(:send_image_url).call(content, option, self, &callback) else target.method(:send_image).call(content, self, &callback) end when :video target.send_video(content, self, &callback) end end
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 { if done @starts_at = Time.now cb.call unless cb.nil? logger.info("Successfully loaded all information") else EM.next_tick(&check_done) end } EM.add_timer(0, &check_done) end
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.include?(contact) @profile = contact else raise "Couldn't fetch the user profile." end end callback end
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, contact) @contacts << contact unless self.contacts.include?(contact) } else raise "Couldn't fetch the contact list." end end callback end
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| @connection.communicate(['chat_info', "chat\##{id}"]) do |success, data| collect_done.call(id, data, count) if success end end @chats = [] @connection.communicate('dialog_list') do |success, data| if success and data.class == Array chatsize = data.count { |chat| chat['peer_type'] == 'chat' } data.each do |chat| if chat['peer_type'] == 'chat' collect.call(chat['peer_id'], chatsize) elsif chat['peer_type'] == 'user' @chats << TelegramChat.new(self, chat) end end callback.trigger(:success) if chatsize == 0 else raise "Couldn't fetch the dialog(chat) list." end end callback end
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'] message.raw_to = @raw_data['to']['peer_id'] message.to_type = @raw_data['to']['peer_type'] from = @client.contacts.find { |c| c.id == message.raw_from } to = @client.contacts.find { |c| c.id == message.raw_to } to = @client.chats.find { |c| c.id == message.raw_to } if to.nil? message.from = from message.to = to @message = message if @message.from.nil? user = @raw_data['from'] user = TelegramContact.pick_or_new(@client, user) @client.contacts << user unless @client.contacts.include?(user) @message.from = user end if @message.to.nil? type = @raw_data['to']['peer_type'] case type when 'chat', 'encr_chat' chat = TelegramChat.pick_or_new(@client, @raw_data['to']) @client.chats << chat unless @client.chats.include?(chat) if type == 'encr_chat' then @message.to = chat else @message.from = chat end when 'user' user = TelegramContact.pick_or_new(@client, @raw_data['to']) @client.contacts << user unless @client.contacts.include?(user) @message.to = user end end end
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 } EM.add_timer(0, &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 codec Protocol::MessagesForPartition.new(partition, message_set.compress(codec)) else Protocol::MessagesForPartition.new(partition, message_set) end end Protocol::MessagesForTopic.new(topic, messages_for_partitions) end end
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, topic, partition. messages_for_broker_ids[broker_id] ||= MessagesForBroker.new(broker_id) messages_for_broker_ids[broker_id].add(message, partition_id) end messages_for_broker_ids.values end
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 required_acks != 0 read_response(ProduceResponse) else true end end
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_request(req) read_response(FetchResponse) end
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 = NO_PARTITION broker_id = NO_BROKER end return partition_id, broker_id end
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}" end topic_fetches = build_topic_fetch_request(fetch_max_bytes) fetch_response = @connection.fetch(fetch_max_wait, fetch_min_bytes, topic_fetches) topic_response = fetch_response.topic_fetch_responses.first partition_response = topic_response.partition_fetch_responses.first unless partition_response.error == Errors::NO_ERROR_CODE if @offset < 0 && Errors::ERROR_CODES[partition_response.error] == Errors::OffsetOutOfRange @offset = :earliest_offset return fetch(options) end raise Errors::ERROR_CODES[partition_response.error] else @highwater_mark = partition_response.highwater_mark_offset messages = partition_response.message_set.flatten.map do |m| FetchedMessage.new(topic_response.topic, m.value, m.key, m.offset) end if messages.any? @offset = messages.last.offset + 1 end messages end end
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 end
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['GetConsoleScreenBufferInfo'], [Fiddle::TYPE_LONG, Fiddle::TYPE_VOIDP], Fiddle::TYPE_INT) format = 'SSSSSssssSS' buffer = ([0] * format.size).pack(format) stdout_handle = get_std_handle.(STDOUT_HANDLE) get_console_buffer_info.(stdout_handle, buffer) _, _, _, _, _, left, top, right, bottom, = buffer.unpack(format) size = [bottom - top + 1, right - left + 1] return size if nonzero_column?(size[1] - 1) rescue LoadError warn 'no native fiddle module found' if verbose rescue Fiddle::DLError # non windows platform or no kernel32 lib end
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 package' if verbose end
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_column?(cols) end end
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(&:to_s).sort.join(', ')}" end if !recognizes.empty? && raise_error_if_unrecognized unrecognized = options.keys - requirements - recognized unless unrecognized.empty? raise ArgumentError, "Unrecognized arguments: #{unrecognized.map(&:to_s).sort.join(', ')}" end end end
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 == :semicolon break elsif node === :'{' # Note: The spec says the block should _be_ the consumed simple # block, but Simon Sapin's CSS parsing tests and tinycss2 expect # only the _value_ of the consumed simple block here. I assume I'm # interpreting the spec too literally, so I'm going with the # tinycss2 behavior. rule[:block] = consume_simple_block(input)[:value] break elsif node == :simple_block && token[:start] == '{' # Note: The spec says the block should _be_ the simple block, but # Simon Sapin's CSS parsing tests and tinycss2 expect only the # _value_ of the simple block here. I assume I'm interpreting the # spec too literally, so I'm going with the tinycss2 behavior. rule[:block] = token[:value] break else input.reconsume rule[:prelude] << consume_component_value(input) end end end create_node(:at_rule, rule) end
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 # mentioned in the spec, but it's necessary to avoid re-parsing # functions that have already been parsed. token else consume_function(input) end else token end end
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_token = input.peek end unless next_token && next_token[:node] == :colon # Parse error. # # Note: The spec explicitly says to return nothing here, but Simon # Sapin's CSS parsing tests expect an error node. return create_node(:error, :value => 'invalid') end input.consume until input.peek.nil? value << consume_component_value(input) end end # Look for !important. important_tokens = value.reject {|token| node = token[:node] node == :whitespace || node == :comment || node == :semicolon }.last(2) if important_tokens.size == 2 && important_tokens[0][:node] == :delim && important_tokens[0][:value] == '!' && important_tokens[1][:node] == :ident && important_tokens[1][:value].downcase == 'important' declaration[:important] = true excl_index = value.index(important_tokens[0]) # Technically the spec doesn't require us to trim trailing tokens after # the !important, but Simon Sapin's CSS parsing tests expect it and # tinycss2 does it, so we'll go along with the cool kids. value.slice!(excl_index, value.size - excl_index) else declaration[:important] = false end declaration[:value] = value create_node(:declaration, declaration) end
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] when :at_keyword # When parsing a style rule, this is a parse error. Otherwise it's # not. input.reconsume declarations << consume_at_rule(input) when :ident decl_tokens = [token] while next_token = input.peek break if next_token[:node] == :semicolon decl_tokens << consume_component_value(input) end if decl = consume_declaration(TokenScanner.new(decl_tokens)) declarations << decl end else # Parse error (invalid property name, etc.). # # Note: The spec doesn't say we should append anything to the list of # declarations here, but Simon Sapin's CSS parsing tests expect an # error node. declarations << create_node(:error, :value => 'invalid') input.reconsume while next_token = input.peek break if next_token[:node] == :semicolon consume_component_value(input) end end end declarations end
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] when :')' break # Non-standard. when :comment next else input.reconsume function[:value] << consume_component_value(input) end end }) create_node(:function, function) end
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 parsing tests expect an error node. return create_node(:error, :value => 'invalid') end if token[:node] == :'{' # Note: The spec says the block should _be_ the consumed simple # block, but Simon Sapin's CSS parsing tests and tinycss2 expect # only the _value_ of the consumed simple block here. I assume I'm # interpreting the spec too literally, so I'm going with the # tinycss2 behavior. rule[:block] = consume_simple_block(input)[:value] break elsif token[:node] == :simple_block && token[:start] == '{' # Note: The spec says the block should _be_ the simple block, but # Simon Sapin's CSS parsing tests and tinycss2 expect only the # _value_ of the simple block here. I assume I'm interpreting the # spec too literally, so I'm going with the tinycss2 behavior. rule[:block] = token[:value] break else input.reconsume rule[:prelude] << consume_component_value(input) end end end create_node(:qualified_rule, rule) end
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 :cdc, :cdo unless flags[:top_level] @tokens.reconsume rule = consume_qualified_rule rules << rule if rule end when :at_keyword @tokens.reconsume rule = consume_at_rule rules << rule if rule else @tokens.reconsume rule = consume_qualified_rule rules << rule if rule end end rules end
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. } block[:tokens].concat(input.collect do while token = input.consume break if token[:node] == end_token input.reconsume block[:value] << consume_component_value(input) end end) create_node(:simple_block, block) end
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_component_value(input) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? value else create_node(:error, :value => 'extra-input') end end
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 input.peek[:node] != :ident # Syntax error. return create_node(:error, :value => 'invalid') end if decl = consume_declaration(input) return decl end # Syntax error. create_node(:error, :value => 'invalid') end
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.peek[:node] == :at_keyword rule = consume_at_rule(input) else rule = consume_qualified_rule(input) end while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? rule else # Syntax error. create_node(:error, :value => 'extra-input') end end
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_a?(String) string << node[:value] string << '(' else string << parse_value(node[:tokens]) end else if node.key?(:raw) string << node[:raw] elsif node.key?(:tokens) string << parse_value(node[:tokens]) end end end string.strip end
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 text << char end end end text end
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 nil 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" else return codepoint.chr(Encoding::UTF_8) end end @s.consume end
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 consume_url end else create_token(:function, :value => value) end else create_token(:ident, :value => value) end end
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[:preserve_hacks] result << @s.consume else @s.reconsume return result end end result end
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(:percentage, :repr => number[0], :type => number[2], :value => number[1]) else create_token(:number, :repr => number[0], :type => number[2], :value => number[1]) end end
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 => true, :value => value) when '\\' case @s.peek when '' # End of the input, so do nothing. next when "\n" @s.consume else value << consume_escaped end else value << char end end create_token(:string, :value => value) end
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 return create_token(:unicode_range, range) end range[:start] = value.hex if @s.peek(2) =~ RE_UNICODE_RANGE_END @s.consume range[:end] = (@s.scan(RE_HEX) || '').hex else range[:end] = range[:start] end create_token(:unicode_range, range) end
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 return create_token(:bad_url, :value => value + consume_bad_url) end when '"', "'", '(', RE_NON_PRINTABLE # Parse error. return create_token(:bad_url, :error => true, :value => value + consume_bad_url) when '\\' if valid_escape? value << consume_escaped else # Parse error. return create_token(:bad_url, :error => true, :value => value + consume_bad_url ) end else value << char end end create_token(:url, :value => value) end
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[:exponent].to_i # I know this looks nutty, but it's exactly what's defined in the spec, # and it works. s * (i + f * 10**-d) * 10**(t * e) end
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]) else false end end
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( field.to_sym, Mongoid::Autoinc::Incrementor.new(model_name, field, options).inc ) end
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 it has a namespace. if args.all? { |node| not node.is_namespaced? } or args.any? { |node| node.is_character_data? } return true end href1 = node_1.namespace_uri || '' href2 = node_2.namespace_uri || '' return href1 == href2 end
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 = File.open(files.at(Kernel.rand(files.size))) session[:captcha] = File.basename(file.path, '.*') if file.mtime < EasyCaptcha.cache_expire.ago File.unlink(file.path) # remove speech version File.unlink(file.path.gsub(/png\z/, "wav")) if File.exists?(file.path.gsub(/png\z/, "wav")) else return file.readlines.join end end generated_code = generate_captcha_code image = Captcha.new(generated_code).image # write captcha for caching File.open(captcha_cache_path(generated_code), 'w') { |f| f.write image } # write speech file if u create a new captcha image EasyCaptcha.espeak.generate(generated_code, speech_captcha_cache_path(generated_code)) if EasyCaptcha.espeak? # return image image else Captcha.new(generate_captcha_code).image end end
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_code, wav_file.path) File.read(wav_file.path) end end
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_lifetime modules << :brute_force if @max_consecutive_bad_logins_allowed modules end
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, @current_user, self, event: :authentication) end status = message.present? ? Failure.new(message) : Success.new if status.success? @current_user.save write_cookie if @current_user.session_token else @current_user = nil end yield(status) if block_given? end
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, authenticate_session, event: :set_user) end unauthorized(message) if message end
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/ instance_variable_get("@#{ $1 }") else super end when 1 # config.client= if name =~ /\A(\w+)=\z/ instance_variable_set("@#{ $1 }", args.first) else super end else super end end
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 } version. Perhaps, the problem with Node.js runtime.} end end
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 #{ npm_package_name }"?} end nil end
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) # arg_count is set to 0 end
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 == TTABLE "(# is #{Lib.lua_objlen(@pointer, i)})" else '' end a << "#{i} : #{tname} (#{type}) #{val}" a }.reverse.join("\n") s += "\n" if s.length > 0 s end
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, o) when Float then Lib.lua_pushnumber(@pointer, o) when String then Lib.lua_pushlstring(@pointer, o, o.bytesize) when Symbol then Lib.lua_pushlstring(@pointer, o.to_s, o.to_s.bytesize) when Hash then stack_push_hash(o) when Array then stack_push_array(o) else raise( ArgumentError.new( "don't know how to pass Ruby instance of #{o.class} to Lua")) end end
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[action.to_sym] || seamless_database_pool_options[:all] if read_pool_method SeamlessDatabasePool.set_read_only_connection_type(read_pool_method) do yield end else yield end end
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?(Ref) stack_unstack # leave key on top h[key] = value end h end
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 << (a_keys.include?(k) ? h[k] : [ k, h[k] ]) a } end
ruby
{ "resource": "" }