_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q24500
Zlib.ZStream.get_bits
train
def get_bits need val = @bit_bucket while @bit_count < need val |= (@input_buffer[@in_pos+=1] << @bit_count) @bit_count += 8 end @bit_bucket = val >> need @bit_count -= need val & ((1 << need) - 1) end
ruby
{ "resource": "" }
q24501
Zlib.Inflate.inflate
train
def inflate zstring=nil @zstring = zstring unless zstring.nil? #We can't use unpack, IronRuby doesn't have it yet. @zstring.each_byte {|b| @input_buffer << b} unless @rawdeflate then compression_method_and_flags = @input_buffer[@in_pos+=1] flags = @input_buffer[@in_pos+=1] #CMF and FLG, when viewed as a 16-bit unsigned integer stored inMSB order (CMF*256 + FLG), is a multiple of 31 if ((compression_method_and_flags << 0x08) + flags) % 31 != 0 then raise Zlib::DataError.new("incorrect header check") end #CM = 8 denotes the ìdeflateî compression method with a window size up to 32K. (RFC's only specify CM 8) compression_method = compression_method_and_flags & 0x0F if compression_method != Z_DEFLATED then raise Zlib::DataError.new("unknown compression method") end #For CM = 8, CINFO is the base-2 logarithm of the LZ77 window size,minus eight (CINFO=7 indicates a 32K window size) compression_info = compression_method_and_flags >> 0x04 if (compression_info + 8) > @w_bits then raise Zlib::DataError.new("invalid window size") end preset_dictionary_flag = ((flags & 0x20) >> 0x05) == 1 compression_level = (flags & 0xC0) >> 0x06 if preset_dictionary_flag and @dict.nil? then raise Zlib::NeedDict.new "Preset dictionary needed!" end #TODO: Add Preset dictionary support if preset_dictionary_flag then @dict_crc = @input_buffer[@in_pos+=1] << 24 | @input_buffer[@in_pos+=1] << 16 | @input_buffer[@in_pos+=1] << 8 | @input_buffer[@in_pos+=1] end end last_block = false #Begin processing DEFLATE stream until last_block last_block = (get_bits(1) == 1) block_type = get_bits(2) case block_type when 0 then no_compression when 1 then fixed_codes when 2 then dynamic_codes when 3 then raise Zlib::DataError.new("invalid block type") end end finish end
ruby
{ "resource": "" }
q24502
Jekyll.Convertible.do_layout
train
def do_layout(payload, layouts) pre_render if respond_to?(:pre_render) && hooks if respond_to?(:merge_payload) && hooks old_do_layout(merge_payload(payload.dup), layouts) else old_do_layout(payload, layouts) end post_render if respond_to?(:post_render) && hooks end
ruby
{ "resource": "" }
q24503
Jekyll.Site.site_payload
train
def site_payload @cached_payload = begin payload = old_site_payload site_hooks.each do |hook| p = hook.merge_payload(payload, self) next unless p && p.is_a?(Hash) payload = Jekyll::Utils.deep_merge_hashes(payload, p) end payload end end
ruby
{ "resource": "" }
q24504
KnnBall.Ball.distance
train
def distance(coordinates) coordinates = coordinates.center if coordinates.respond_to?(:center) Math.sqrt([center, coordinates].transpose.map {|a,b| (b - a)**2}.reduce {|d1,d2| d1 + d2}) end
ruby
{ "resource": "" }
q24505
Tool.Decoration.decorate
train
def decorate(block = nil, name: "generated", &callback) @decorations << callback if block alias_name = "__" << name.to_s.downcase.gsub(/[^a-z]+/, ?_) << ?1 alias_name = alias_name.succ while private_method_defined? alias_name or method_defined? alias_name without_decorations { define_method(name, &block) } alias_method(alias_name, name) remove_method(name) private(alias_name) end end
ruby
{ "resource": "" }
q24506
Scrapix.VBulletin.find
train
def find reset; return @images unless @url @page_no = @options["start"] until @images.count > @options["total"] || thread_has_ended? page = @agent.get "#{@url}&page=#{@page_no}" puts "[VERBOSE] Searching: #{@url}&page=#{@page_no}" if @options["verbose"] && options["cli"] sources = page.image_urls.map{|x| x.to_s} sources = filter_images sources # hook for sub-classes @page_no += 1 continue if sources.empty? sources.each do |source| hash = Digest::MD5.hexdigest(source) unless @images.has_key?(hash) @images[hash] = {url: source} puts source if options["cli"] end end end @images = @images.map{|x, y| y} end
ruby
{ "resource": "" }
q24507
Danger.DangerKotlinDetekt.detekt
train
def detekt(inline_mode: false) unless skip_gradle_task || gradlew_exists? fail("Could not find `gradlew` inside current directory") return end unless SEVERITY_LEVELS.include?(severity) fail("'#{severity}' is not a valid value for `severity` parameter.") return end system "./gradlew #{gradle_task || 'detektCheck'}" unless skip_gradle_task unless File.exist?(report_file) fail("Detekt report not found at `#{report_file}`. "\ "Have you forgot to add `xmlReport true` to your `build.gradle` file?") end issues = read_issues_from_report filtered_issues = filter_issues_by_severity(issues) if inline_mode # Report with inline comment send_inline_comment(filtered_issues) else message = message_for_issues(filtered_issues) markdown("### Detekt found issues\n\n" + message) unless message.to_s.empty? end end
ruby
{ "resource": "" }
q24508
WinRM.WinRMWebService.get_builder_obj
train
def get_builder_obj(shell_id, command_id, &block) body = { "#{NS_WIN_SHELL}:DesiredStream" => 'stdout stderr', :attributes! => {"#{NS_WIN_SHELL}:DesiredStream" => {'CommandId' => command_id}}} builder = Builder::XmlMarkup.new builder.instruct!(:xml, :encoding => 'UTF-8') builder.tag! :env, :Envelope, namespaces do |env| env.tag!(:env, :Header) { |h| h << Gyoku.xml(merge_headers(header,resource_uri_cmd,action_receive,selector_shell_id(shell_id))) } env.tag!(:env, :Body) do |env_body| env_body.tag!("#{NS_WIN_SHELL}:Receive") { |cl| cl << Gyoku.xml(body) } end end builder end
ruby
{ "resource": "" }
q24509
WinRM.WinRMWebService.get_command_output
train
def get_command_output(shell_id, command_id, &block) done_elems = [] output = Output.new while done_elems.empty? resp_doc = nil builder = get_builder_obj(shell_id, command_id, &block) request_msg = builder.target! resp_doc = send_get_output_message(request_msg) REXML::XPath.match(resp_doc, "//#{NS_WIN_SHELL}:Stream").each do |n| next if n.text.nil? || n.text.empty? stream = { n.attributes['Name'].to_sym => Base64.decode64(n.text).force_encoding('utf-8').sub("\xEF\xBB\xBF", "") } output[:data] << stream yield stream[:stdout], stream[:stderr] if block_given? end # We may need to get additional output if the stream has not finished. # The CommandState will change from Running to Done like so: # @example # from... # <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Running"/> # to... # <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done"> # <rsp:ExitCode>0</rsp:ExitCode> # </rsp:CommandState> done_elems = REXML::XPath.match(resp_doc, "//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']") end output[:exitcode] = REXML::XPath.first(resp_doc, "//#{NS_WIN_SHELL}:ExitCode").text.to_i output end
ruby
{ "resource": "" }
q24510
Hippo::Concerns.ApiAttributeAccess.setting_attribute_is_allowed?
train
def setting_attribute_is_allowed?(name, user) return false unless user.can_write?(self, name) (self.whitelisted_attributes && self.whitelisted_attributes.has_key?( name.to_sym)) || ( self.attribute_names.include?( name.to_s ) && ( self.blacklisted_attributes.nil? || ! self.blacklisted_attributes.has_key?( name.to_sym ) ) ) end
ruby
{ "resource": "" }
q24511
Turbot.Helpers.turbot_api_parameters
train
def turbot_api_parameters uri = URI.parse(host) { :host => uri.host, :port => uri.port, :scheme => uri.scheme, } end
ruby
{ "resource": "" }
q24512
Pling.Gateway.handles?
train
def handles?(device) device = Pling._convert(device, :device) self.class.handled_types.include?(device.type) end
ruby
{ "resource": "" }
q24513
Elparser.SExpList.to_h
train
def to_h ret = Hash.new @list.each do |i| ret[i.car.to_ruby] = i.cdr.to_ruby end ret end
ruby
{ "resource": "" }
q24514
Elparser.Parser.parse
train
def parse(str) if str.nil? || str == "" raise ParserError.new("Empty input",0,"") end s = StringScanner.new str @tokens = [] until s.eos? s.skip(/\s+/) ? nil : s.scan(/\A[-+]?[0-9]*\.[0-9]+(e[-+]?[0-9]+)?/i) ? (@tokens << [:FLOAT, s.matched]) : s.scan(/\A[-+]?(0|[1-9]\d*)/) ? (@tokens << [:INTEGER, s.matched]) : s.scan(/\A\.(?=\s)/) ? (@tokens << ['.', '.']) : s.scan(/\A[a-z\-.\/_:*<>+=$#][a-z\-.\/_:$*<>+=0-9]*/i) ? (@tokens << [:SYMBOL, s.matched]) : s.scan(/\A"(([^\\"]|\\.)*)"/) ? (@tokens << [:STRING, _unescape_string(s.matched.slice(1...-1))]) : s.scan(/\A./) ? (a = s.matched; @tokens << [a, a]) : (raise ParserError.new("Scanner error",s.pos,s.peek(5))) end @tokens.push [false, 'END'] return do_parse.map do |i| normalize(i) end end
ruby
{ "resource": "" }
q24515
Elparser.Parser.normalize
train
def normalize(ast) if ast.class == SExpSymbol case ast.name when "nil" return SExpNil.new else return ast end elsif ast.cons? then ast.visit do |i| normalize(i) end end return ast end
ruby
{ "resource": "" }
q24516
MemoryIO.IO.write
train
def write(objects, from: nil, as: nil) stream.pos = from if from as ||= objects.class if objects.class.ancestors.include?(MemoryIO::Types::Type) return stream.write(objects) if as.nil? conv = to_proc(as, :write) Array(objects).map { |o| conv.call(stream, o) } end
ruby
{ "resource": "" }
q24517
MemoryIO.Util.underscore
train
def underscore(str) return '' if str.empty? str = str.gsub('::', '/') str.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2') str.gsub!(/([a-z\d])([A-Z])/, '\1_\2') str.downcase! str end
ruby
{ "resource": "" }
q24518
MemoryIO.Util.safe_eval
train
def safe_eval(str, **vars) return str if str.is_a?(Integer) # dentaku 2 doesn't support hex str = str.gsub(/0x[0-9a-zA-Z]+/) { |c| c.to_i(16) } Dentaku::Calculator.new.store(vars).evaluate(str) end
ruby
{ "resource": "" }
q24519
MemoryIO.Util.unpack
train
def unpack(str) str.bytes.reverse.reduce(0) { |s, c| s * 256 + c } end
ruby
{ "resource": "" }
q24520
MemoryIO.Util.pack
train
def pack(val, b) Array.new(b) { |i| (val >> (i * 8)) & 0xff }.pack('C*') end
ruby
{ "resource": "" }
q24521
KnnBall.KDTree.nearest
train
def nearest(coord, options = {}) return nil if root.nil? return nil if coord.nil? results = (options[:results] ? options[:results] : ResultSet.new({limit: options[:limit] || 1})) root_ball = options[:root] || root # keep the stack while finding the leaf best match. parents = [] best_balls = [] in_target = [] # Move down to best match current_best = nil current = root_ball while current_best.nil? dim = current.dimension-1 if(current.complete?) next_ball = (coord[dim] <= current.center[dim] ? current.left : current.right) elsif(current.leaf?) next_ball = nil else next_ball = (current.left.nil? ? current.right : current.left) end if ( next_ball.nil? ) current_best = current else parents.push current current = next_ball end end # Move up to check split parents.reverse! results.add(current_best.quick_distance(coord), current_best.value) parents.each do |current_node| dist = current_node.quick_distance(coord) if results.eligible?( dist ) results.add(dist, current_node.value) end dim = current_node.dimension-1 if current_node.complete? # retrieve the splitting node. split_node = (coord[dim] <= current_node.center[dim] ? current_node.right : current_node.left) best_dist = results.barrier_value if( (coord[dim] - current_node.center[dim]).abs <= best_dist) # potential match, need to investigate subtree nearest(coord, root: split_node, results: results) end end end return results.limit == 1 ? results.items.first : results.items end
ruby
{ "resource": "" }
q24522
KnnBall.KDTree.parent_ball
train
def parent_ball(coord) current = root d_idx = current.dimension-1 result = nil while(result.nil?) if(coord[d_idx] <= current.center[d_idx]) if current.left.nil? result = current else current = current.left end else if current.right.nil? result = current else current = current.right end end d_idx = current.dimension-1 end return result end
ruby
{ "resource": "" }
q24523
Teamspeak.Client.command
train
def command(cmd, params = {}, options = '') flood_control out = '' response = '' out += cmd params.each_pair do |key, value| out += " #{key}=#{encode_param(value.to_s)}" end out += ' ' + options @sock.puts out if cmd == 'servernotifyregister' 2.times { response += @sock.gets } return parse_response(response) end loop do response += @sock.gets break if response.index(' msg=') end # Array of commands that are expected to return as an array. # Not sure - clientgetids should_be_array = %w( bindinglist serverlist servergrouplist servergroupclientlist servergroupsbyclientid servergroupclientlist logview channellist channelfind channelgrouplist channelgroupclientlist channelgrouppermlist channelpermlist clientlist clientfind clientdblist clientdbfind channelclientpermlist permissionlist permoverview privilegekeylist messagelist complainlist banlist ftlist custominfo permfind ) parsed_response = parse_response(response) should_be_array.include?(cmd) ? parsed_response : parsed_response.first end
ruby
{ "resource": "" }
q24524
TmlRails.ActionViewExtension.trh
train
def trh(tokens = {}, options = {}, &block) return '' unless block_given? label = capture(&block) tokenizer = Tml::Tokenizers::Dom.new(tokens, options) tokenizer.translate(label).html_safe end
ruby
{ "resource": "" }
q24525
TmlRails.ActionViewExtension.tml_language_flag_tag
train
def tml_language_flag_tag(lang = tml_current_language, opts = {}) return '' unless tml_application.feature_enabled?(:language_flags) html = image_tag(lang.flag_url, :style => (opts[:style] || 'vertical-align:middle;'), :title => lang.native_name) html << '&nbsp;&nbsp;'.html_safe html.html_safe end
ruby
{ "resource": "" }
q24526
TmlRails.ActionViewExtension.tml_language_name_tag
train
def tml_language_name_tag(lang = tml_current_language, opts = {}) show_flag = opts[:flag].nil? ? true : opts[:flag] name_type = opts[:language].nil? ? :english : opts[:language].to_sym # :full, :native, :english, :locale, :both html = [] html << "<span style='white-space: nowrap'>" html << tml_language_flag_tag(lang, opts) if show_flag html << "<span dir='ltr'>" if name_type == :both html << lang.english_name.to_s html << '<span class="trex-native-name">' html << lang.native_name html << '</span>' else name = case name_type when :native then lang.native_name when :full then lang.full_name when :locale then lang.locale else lang.english_name end html << name.to_s end html << '</span></span>' html.join.html_safe end
ruby
{ "resource": "" }
q24527
TmlRails.ActionViewExtension.tml_language_selector_tag
train
def tml_language_selector_tag(type = nil, opts = {}) return unless Tml.config.enabled? type ||= :default type = :dropdown if type == :select opts = opts.collect{|key, value| "data-tml-#{key}='#{value}'"}.join(' ') "<div data-tml-language-selector='#{type}' #{opts}></div>".html_safe end
ruby
{ "resource": "" }
q24528
TmlRails.ActionViewExtension.tml_style_attribute_tag
train
def tml_style_attribute_tag(attr_name = 'float', default = 'right', lang = tml_current_language) return "#{attr_name}:#{default}".html_safe if Tml.config.disabled? "#{attr_name}:#{lang.align(default)}".html_safe end
ruby
{ "resource": "" }
q24529
Effigy.ExampleElementTransformer.clone_and_transform_each
train
def clone_and_transform_each(collection, &block) collection.inject(element_to_clone) do |sibling, item| item_element = clone_with_item(item, &block) sibling.add_next_sibling(item_element) end end
ruby
{ "resource": "" }
q24530
Effigy.ExampleElementTransformer.clone_with_item
train
def clone_with_item(item, &block) item_element = element_to_clone.dup view.find(item_element) { yield(item) } item_element end
ruby
{ "resource": "" }
q24531
Effigy.View.text
train
def text(selector, content) select(selector).each do |node| node.content = content end end
ruby
{ "resource": "" }
q24532
Effigy.View.attr
train
def attr(selector, attributes_or_attribute_name, value = nil) attributes = attributes_or_attribute_name.to_effigy_attributes(value) select(selector).each do |element| element.merge!(attributes) end end
ruby
{ "resource": "" }
q24533
Effigy.View.replace_each
train
def replace_each(selector, collection, &block) selected_elements = select(selector) ExampleElementTransformer.new(self, selected_elements).replace_each(collection, &block) end
ruby
{ "resource": "" }
q24534
Effigy.View.add_class
train
def add_class(selector, *class_names) select(selector).each do |element| class_list = ClassList.new(element) class_list.add class_names end end
ruby
{ "resource": "" }
q24535
Effigy.View.remove_class
train
def remove_class(selector, *class_names) select(selector).each do |element| class_list = ClassList.new(element) class_list.remove(class_names) end end
ruby
{ "resource": "" }
q24536
Effigy.View.html
train
def html(selector, inner_html) select(selector).each do |node| node.inner_html = inner_html end end
ruby
{ "resource": "" }
q24537
Effigy.View.append
train
def append(selector, html_to_append) select(selector).each { |node| node.append_fragment html_to_append } end
ruby
{ "resource": "" }
q24538
Effigy.View.find
train
def find(selector) if block_given? old_context = @current_context @current_context = select(selector) yield @current_context = old_context else Selection.new(self, selector) end end
ruby
{ "resource": "" }
q24539
Effigy.View.clone_element_with_item
train
def clone_element_with_item(original_element, item, &block) item_element = original_element.dup find(item_element) { yield(item) } item_element end
ruby
{ "resource": "" }
q24540
RETerm.ComponentInput.handle_input
train
def handle_input(*input) while ch = next_ch(input) quit = QUIT_CONTROLS.include?(ch) enter = ENTER_CONTROLS.include?(ch) inc = INC_CONTROLS.include?(ch) dec = DEC_CONTROLS.include?(ch) break if shutdown? || (quit && (!enter || quit_on_enter?)) if enter on_enter elsif inc on_inc elsif dec on_dec end if key_bound?(ch) invoke_key_bindings(ch) end on_key(ch) end ch end
ruby
{ "resource": "" }
q24541
BabelBridge.RuleNode.match
train
def match(pattern_element) @num_match_attempts += 1 return :no_pattern_element unless pattern_element return :skipped if pattern_element.delimiter && ( if last_match last_match.delimiter # don't match two delimiters in a row else @num_match_attempts > 1 # don't match a delimiter as the first element unless this is the first match attempt end ) if result = pattern_element.parse(self) add_match result, pattern_element.name # success, but don't keep EmptyNodes end end
ruby
{ "resource": "" }
q24542
BabelBridge.RuleNode.attempt_match
train
def attempt_match matches_before = matches.length match_length_before = match_length (yield && match_length > match_length_before).tap do |success| # match_length test returns failure if no progress is made (our source position isn't advanced) unless success @matches = matches[0..matches_before-1] update_match_length end end end
ruby
{ "resource": "" }
q24543
PeoplePlacesThings.StreetAddress.to_canonical_s
train
def to_canonical_s parts = [] parts << self.number.upcase if self.number parts << StreetAddress.string_for(self.pre_direction, :short).upcase if self.pre_direction parts << StreetAddress.string_for(StreetAddress.find_token(self.ordinal, ORDINALS), :short).upcase if self.ordinal canonical_name = self.name.gsub(/[(,?!\'":.#)]/, '').gsub(PO_BOX_PATTERN, 'PO BOX').upcase if self.name canonical_name.gsub!(/(rr|r.r.)/i, 'RR') if canonical_name =~ RR_PATTERN # remove the original ordinal and box from the name, they are output in canonical form separately canonical_name.gsub!(self.ordinal.upcase, '') if self.ordinal canonical_name.gsub!(self.box_number, '') if self.box_number parts << canonical_name.chomp(' ') if canonical_name parts << self.box_number if self.box_number parts << StreetAddress.string_for(self.suffix, :short).upcase if self.suffix parts << StreetAddress.string_for(self.post_direction, :short).upcase if self.post_direction # make all unit type as the canoncial number "#" parts << StreetAddress.string_for(:number, :short).upcase if self.unit_type parts << self.unit.upcase if self.unit parts.delete('') parts.join(' ') end
ruby
{ "resource": "" }
q24544
ActiveCucumber.Cucumparer.to_horizontal_table
train
def to_horizontal_table mortadella = Mortadella::Horizontal.new headers: @cucumber_table.headers @database_content = @database_content.all if @database_content.respond_to? :all @database_content.each do |record| cucumberator = cucumberator_for record mortadella << @cucumber_table.headers.map do |header| cucumberator.value_for header end end mortadella.table end
ruby
{ "resource": "" }
q24545
ActiveCucumber.Cucumparer.to_vertical_table
train
def to_vertical_table object mortadella = Mortadella::Vertical.new cucumberator = cucumberator_for object @cucumber_table.rows_hash.each do |key, _| mortadella[key] = cucumberator.value_for key end mortadella.table end
ruby
{ "resource": "" }
q24546
Barrister.Server.handle_json
train
def handle_json(json_str) begin req = JSON::parse(json_str) resp = handle(req) rescue JSON::ParserError => e resp = err_resp({ }, -32700, "Unable to parse JSON: #{e.message}") end # Note the `:ascii_only` usage here. Important. return JSON::generate(resp, { :ascii_only=>true }) end
ruby
{ "resource": "" }
q24547
Barrister.Server.handle
train
def handle(req) if req.kind_of?(Array) resp_list = [ ] req.each do |r| resp_list << handle_single(r) end return resp_list else return handle_single(req) end end
ruby
{ "resource": "" }
q24548
Barrister.Server.handle_single
train
def handle_single(req) method = req["method"] if !method return err_resp(req, -32600, "No method provided on request") end # Special case - client is requesting the IDL bound to this server, so # we return it verbatim. No further validation is needed in this case. if method == "barrister-idl" return ok_resp(req, @contract.idl) end # Make sure we can find an interface and function on the IDL for this # request method string err_resp, iface, func = @contract.resolve_method(req) if err_resp != nil return err_resp end # Make sure that the params on the request match the IDL types err_resp = @contract.validate_params(req, func) if err_resp != nil return err_resp end params = [ ] if req["params"] params = req["params"] end # Make sure we have a handler bound to this Server for the interface. # If not, that means `server.add_handler` was not called for this interface # name. That's likely a misconfiguration. handler = @handlers[iface.name] if !handler return err_resp(req, -32000, "Server error. No handler is bound to interface #{iface.name}") end # Make sure that the handler has a method for the given function. if !handler.respond_to?(func.name) return err_resp(req, -32000, "Server error. Handler for #{iface.name} does not implement #{func.name}") end begin # Call the handler function. This is where your code gets invoked. result = handler.send(func.name, *params) # Verify that the handler function's return value matches the # correct type as specified in the IDL err_resp = @contract.validate_result(req, result, func) if err_resp != nil return err_resp else return ok_resp(req, result) end rescue RpcException => e # If the handler raised a RpcException, that's ok - return it unmodified. return err_resp(req, e.code, e.message, e.data) rescue => e # If any other error was raised, print it and return a generic error to the client puts e.inspect puts e.backtrace return err_resp(req, -32000, "Unknown error: #{e}") end end
ruby
{ "resource": "" }
q24549
Barrister.Client.init_proxies
train
def init_proxies singleton = class << self; self end @contract.interfaces.each do |iface| proxy = InterfaceProxy.new(self, iface) singleton.send :define_method, iface.name do return proxy end end end
ruby
{ "resource": "" }
q24550
Barrister.Client.request
train
def request(method, params) req = { "jsonrpc" => "2.0", "id" => Barrister::rand_str(22), "method" => method } if params req["params"] = params end # We always validate that the method is valid err_resp, iface, func = @contract.resolve_method(req) if err_resp != nil return err_resp end if @validate_req err_resp = @contract.validate_params(req, func) if err_resp != nil return err_resp end end # This makes the request to the server resp = @trans.request(req) if @validate_result && resp != nil && resp.key?("result") err_resp = @contract.validate_result(req, resp["result"], func) if err_resp != nil resp = err_resp end end return resp end
ruby
{ "resource": "" }
q24551
Barrister.HttpTransport.request
train
def request(req) json_str = JSON::generate(req, { :ascii_only=>true }) http = Net::HTTP.new(@uri.host, @uri.port) request = Net::HTTP::Post.new(@uri.request_uri) request.body = json_str request["Content-Type"] = "application/json" response = http.request(request) if response.code != "200" raise RpcException.new(-32000, "Non-200 response #{response.code} from #{@url}") else return JSON::parse(response.body) end end
ruby
{ "resource": "" }
q24552
Barrister.BatchClient.send
train
def send if @trans.sent raise "Batch has already been sent!" end @trans.sent = true requests = @trans.requests if requests.length < 1 raise RpcException.new(-32600, "Batch cannot be empty") end # Send request batch to server resp_list = @parent.trans.request(requests) # Build a hash for the responses so we can re-order them # in request order. sorted = [ ] by_req_id = { } resp_list.each do |resp| by_req_id[resp["id"]] = resp end # Iterate through the requests in the batch and assemble # the sorted result array requests.each do |req| id = req["id"] resp = by_req_id[id] if !resp msg = "No result for request id: #{id}" resp = { "id" => id, "error" => { "code"=>-32603, "message" => msg } } end sorted << RpcResponse.new(req, resp) end return sorted end
ruby
{ "resource": "" }
q24553
Barrister.Contract.resolve_method
train
def resolve_method(req) method = req["method"] iface_name, func_name = Barrister::parse_method(method) if iface_name == nil return err_resp(req, -32601, "Method not found: #{method}") end iface = interface(iface_name) if !iface return err_resp(req, -32601, "Interface not found on IDL: #{iface_name}") end func = iface.function(func_name) if !func return err_resp(req, -32601, "Function #{func_name} does not exist on interface #{iface_name}") end return nil, iface, func end
ruby
{ "resource": "" }
q24554
Barrister.Contract.validate_params
train
def validate_params(req, func) params = req["params"] if !params params = [] end e_params = func.params.length r_params = params.length if e_params != r_params msg = "Function #{func.name}: Param length #{r_params} != expected length: #{e_params}" return err_resp(req, -32602, msg) end for i in (0..(e_params-1)) expected = func.params[i] invalid = validate("Param[#{i}]", expected, expected["is_array"], params[i]) if invalid != nil return err_resp(req, -32602, invalid) end end # valid return nil end
ruby
{ "resource": "" }
q24555
Barrister.Contract.validate_result
train
def validate_result(req, result, func) invalid = validate("", func.returns, func.returns["is_array"], result) if invalid == nil return nil else return err_resp(req, -32001, invalid) end end
ruby
{ "resource": "" }
q24556
Barrister.Contract.validate
train
def validate(name, expected, expect_array, val) # If val is nil, then check if the IDL allows this type to be optional if val == nil if expected["optional"] return nil else return "#{name} cannot be null" end else exp_type = expected["type"] # If we expect an array, make sure that val is an Array, and then # recursively validate the elements in the array if expect_array if val.kind_of?(Array) stop = val.length - 1 for i in (0..stop) invalid = validate("#{name}[#{i}]", expected, false, val[i]) if invalid != nil return invalid end end return nil else return type_err(name, "[]"+expected["type"], val) end # Check the built in Barrister primitive types elsif exp_type == "string" if val.class == String return nil else return type_err(name, exp_type, val) end elsif exp_type == "bool" if val.class == TrueClass || val.class == FalseClass return nil else return type_err(name, exp_type, val) end elsif exp_type == "int" || exp_type == "float" if val.class == Integer || val.class == Fixnum || val.class == Bignum return nil elsif val.class == Float && exp_type == "float" return nil else return type_err(name, exp_type, val) end # Expected type is not an array or a Barrister primitive. # It must be a struct or an enum. else # Try to find a struct struct = @structs[exp_type] if struct if !val.kind_of?(Hash) return "#{name} #{exp_type} value must be a map/hash. not: " + val.class.name end s_field_keys = { } # Resolve all fields on the struct and its ancestors s_fields = all_struct_fields([], struct) # Validate that each field on the struct has a valid value s_fields.each do |f| fname = f["name"] invalid = validate("#{name}.#{fname}", f, f["is_array"], val[fname]) if invalid != nil return invalid end s_field_keys[fname] = 1 end # Validate that there are no extraneous elements on the value val.keys.each do |k| if !s_field_keys.key?(k) return "#{name}.#{k} is not a field in struct '#{exp_type}'" end end # Struct is valid return nil end # Try to find an enum enum = @enums[exp_type] if enum if val.class != String return "#{name} enum value must be a string. got: " + val.class.name end # Try to find an enum value that matches this val enum["values"].each do |en| if en["value"] == val return nil end end # Invalid return "#{name} #{val} is not a value in enum '#{exp_type}'" end # Unlikely branch - suggests the IDL is internally inconsistent return "#{name} unknown type: #{exp_type}" end # Panic if we have a branch unaccounted for. Indicates a Barrister bug. raise "Barrister ERROR: validate did not return for: #{name} #{expected}" end end
ruby
{ "resource": "" }
q24557
Barrister.Contract.all_struct_fields
train
def all_struct_fields(arr, struct) struct["fields"].each do |f| arr << f end if struct["extends"] parent = @structs[struct["extends"]] if parent return all_struct_fields(arr, parent) end end return arr end
ruby
{ "resource": "" }
q24558
Rusen.Notifier.notify
train
def notify(exception, request = {}, environment = {}, session = {}) begin notification = Notification.new(exception, request, environment, session) @notifiers.each do |notifier| notifier.notify(notification) end # We need to ignore all the exceptions thrown by the notifiers. rescue Exception warn('Rusen: Some or all the notifiers failed to sent the notification.') end end
ruby
{ "resource": "" }
q24559
Hashie.Mash.[]=
train
def []=(key, value) coerced_value = coercion(key).present? ? coercion(key).call(value) : value old_setter(key, coerced_value) end
ruby
{ "resource": "" }
q24560
RETerm.Panel.show
train
def show Ncurses::Panel.top_panel(@panel) update_reterm @@registry.values.each { |panel| if panel == self dispatch :panel_show else panel.dispatch :panel_hide end } end
ruby
{ "resource": "" }
q24561
Related.Helpers.generate_id
train
def generate_id Base64.encode64( Digest::MD5.digest("#{Time.now}-#{rand}") ).gsub('/','x').gsub('+','y').gsub('=','').strip end
ruby
{ "resource": "" }
q24562
Chozo::Mixin.ParamsValidate._pv_opts_lookup
train
def _pv_opts_lookup(opts, key) if opts.has_key?(key.to_s) opts[key.to_s] elsif opts.has_key?(key.to_sym) opts[key.to_sym] else nil end end
ruby
{ "resource": "" }
q24563
Chozo::Mixin.ParamsValidate._pv_required
train
def _pv_required(opts, key, is_required=true) if is_required if (opts.has_key?(key.to_s) && !opts[key.to_s].nil?) || (opts.has_key?(key.to_sym) && !opts[key.to_sym].nil?) true else raise ValidationFailed, "Required argument #{key} is missing!" end end end
ruby
{ "resource": "" }
q24564
Chozo::Mixin.ParamsValidate._pv_respond_to
train
def _pv_respond_to(opts, key, method_name_list) value = _pv_opts_lookup(opts, key) unless value.nil? Array(method_name_list).each do |method_name| unless value.respond_to?(method_name) raise ValidationFailed, "Option #{key} must have a #{method_name} method!" end end end end
ruby
{ "resource": "" }
q24565
Chozo::Mixin.ParamsValidate._pv_default
train
def _pv_default(opts, key, default_value) value = _pv_opts_lookup(opts, key) if value == nil opts[key] = default_value end end
ruby
{ "resource": "" }
q24566
Chozo::Mixin.ParamsValidate._pv_regex
train
def _pv_regex(opts, key, regex) value = _pv_opts_lookup(opts, key) if value != nil passes = false [ regex ].flatten.each do |r| if value != nil if r.match(value.to_s) passes = true end end end unless passes raise ValidationFailed, "Option #{key}'s value #{value} does not match regular expression #{regex.inspect}" end end end
ruby
{ "resource": "" }
q24567
Chozo::Mixin.ParamsValidate._pv_callbacks
train
def _pv_callbacks(opts, key, callbacks) raise ArgumentError, "Callback list must be a hash!" unless callbacks.kind_of?(Hash) value = _pv_opts_lookup(opts, key) if value != nil callbacks.each do |message, zeproc| if zeproc.call(value) != true raise ValidationFailed, "Option #{key}'s value #{value} #{message}!" end end end end
ruby
{ "resource": "" }
q24568
Chozo::Mixin.ParamsValidate._pv_name_attribute
train
def _pv_name_attribute(opts, key, is_name_attribute=true) if is_name_attribute if opts[key] == nil opts[key] = self.instance_variable_get("@name") end end end
ruby
{ "resource": "" }
q24569
BeakerAnswers.Version20162.answer_hiera
train
def answer_hiera # Render pretty JSON, because it is a subset of HOCON json = JSON.pretty_generate(answers) hocon = Hocon::Parser::ConfigDocumentFactory.parse_string(json) hocon.render end
ruby
{ "resource": "" }
q24570
TripIt.Base.convertDT
train
def convertDT(tpitDT) return nil if tpitDT.nil? date = tpitDT["date"] time = tpitDT["time"] offset = tpitDT["utc_offset"] if time.nil? # Just return a date Date.parse(date) elsif date.nil? # Or just a time Time.parse(time) else # Ideally both DateTime.parse("#{date}T#{time}#{offset}") end end
ruby
{ "resource": "" }
q24571
Rscons.Builder.standard_build
train
def standard_build(short_cmd_string, target, command, sources, env, cache) unless cache.up_to_date?(target, command, sources, env) unless Rscons.phony_target?(target) cache.mkdir_p(File.dirname(target)) FileUtils.rm_f(target) end return false unless env.execute(short_cmd_string, command) cache.register_build(target, command, sources, env) end target end
ruby
{ "resource": "" }
q24572
RETerm.Window.finalize!
train
def finalize! erase @@registry.delete(self) children.each { |c| del_child c } cdk_scr.destroy if cdk? component.finalize! if component? end
ruby
{ "resource": "" }
q24573
RETerm.Window.child_containing
train
def child_containing(x, y, z) found = nil children.find { |c| next if found # recursively descend into layout children if c.component.kind_of?(Layout) found = c.child_containing(x, y, z) else found = c.total_x <= x && c.total_y <= y && # c.z >= z (c.total_x + c.cols) >= x && (c.total_y + c.rows) >= y found = c if found end } found end
ruby
{ "resource": "" }
q24574
RETerm.Window.erase
train
def erase children.each { |c| c.erase } @win.werase if @win component.component.erase if cdk? && component? && component.init? end
ruby
{ "resource": "" }
q24575
RETerm.Window.no_border!
train
def no_border! @win.border(' '.ord, ' '.ord, ' '.ord, ' '.ord, ' '.ord, ' '.ord, ' '.ord, ' '.ord) end
ruby
{ "resource": "" }
q24576
RETerm.Window.sync_getch
train
def sync_getch return self.getch unless sync_enabled? c = -1 while c == -1 && !shutdown? c = self.getch run_sync! end c end
ruby
{ "resource": "" }
q24577
RETerm.Window.colors=
train
def colors=(c) @colors = c.is_a?(ColorPair) ? c : ColorPair.for(c).first @win.bkgd(Ncurses.COLOR_PAIR(@colors.id)) unless @win.nil? component.colors = @colors if component? children.each { |ch| ch.colors = c } end
ruby
{ "resource": "" }
q24578
RETerm.Window.dimensions
train
def dimensions rows = [] cols = [] @win.getmaxyx(rows, cols) rows = rows.first cols = cols.first [rows, cols] end
ruby
{ "resource": "" }
q24579
ChefWorkflow.IPSupport.next_ip
train
def next_ip(arg) octets = arg.split(/\./, 4).map(&:to_i) octets[3] += 1 raise "out of ips!" if octets[3] > 255 return octets.map(&:to_s).join(".") end
ruby
{ "resource": "" }
q24580
SanitizeAttributes.InstanceMethods.sanitize!
train
def sanitize! self.class.sanitizable_attributes.each do |attr_name| cleaned_text = process_text_via_sanitization_method(self.send(attr_name), attr_name) self.send((attr_name.to_s + '='), cleaned_text) end end
ruby
{ "resource": "" }
q24581
ActiveCucumber.Creator.factorygirl_attributes
train
def factorygirl_attributes symbolize_attributes! @attributes.each do |key, value| next unless respond_to?(method = method_name(key)) if (result = send method, value) || value.nil? @attributes[key] = result if @attributes.key? key else @attributes.delete key end end end
ruby
{ "resource": "" }
q24582
Configurate.LookupChain.add_provider
train
def add_provider(provider, *args) unless provider.respond_to?(:instance_methods) && provider.instance_methods.include?(:lookup) raise ArgumentError, "the given provider does not respond to lookup" end @provider << provider.new(*args) end
ruby
{ "resource": "" }
q24583
Configurate.LookupChain.lookup
train
def lookup(setting, *args) setting = SettingPath.new setting if setting.is_a? String @provider.each do |provider| begin return special_value_or_string(provider.lookup(setting.clone, *args)) rescue SettingNotFoundError; end end nil end
ruby
{ "resource": "" }
q24584
Rscons.Environment.build_dir
train
def build_dir(src_dir, obj_dir) if src_dir.is_a?(String) src_dir = src_dir.gsub("\\", "/").sub(%r{/*$}, "") end @build_dirs.unshift([src_dir, obj_dir]) end
ruby
{ "resource": "" }
q24585
Rscons.Environment.process
train
def process cache = Cache.instance failure = nil begin while @job_set.size > 0 or @threaded_commands.size > 0 if failure @job_set.clear! job = nil else targets_still_building = @threaded_commands.map do |tc| tc.build_operation[:target] end job = @job_set.get_next_job_to_run(targets_still_building) end # TODO: have Cache determine when checksums may be invalid based on # file size and/or timestamp. cache.clear_checksum_cache! if job result = run_builder(job[:builder], job[:target], job[:sources], cache, job[:vars], allow_delayed_execution: true, setup_info: job[:setup_info]) unless result failure = "Failed to build #{job[:target]}" Ansi.write($stderr, :red, failure, :reset, "\n") next end end completed_tcs = Set.new # First do a non-blocking wait to pick up any threads that have # completed since last time. while tc = wait_for_threaded_commands(nonblock: true) completed_tcs << tc end # If needed, do a blocking wait. if (@threaded_commands.size > 0) and ((completed_tcs.empty? and job.nil?) or (@threaded_commands.size >= n_threads)) completed_tcs << wait_for_threaded_commands end # Process all completed {ThreadedCommand} objects. completed_tcs.each do |tc| result = finalize_builder(tc) if result @build_hooks[:post].each do |build_hook_block| build_hook_block.call(tc.build_operation) end else unless @echo == :command print_failed_command(tc.command) end failure = "Failed to build #{tc.build_operation[:target]}" Ansi.write($stderr, :red, failure, :reset, "\n") break end end end ensure cache.write end if failure raise BuildError.new(failure) end end
ruby
{ "resource": "" }
q24586
Rscons.Environment.expand_varref
train
def expand_varref(varref, extra_vars = nil) vars = if extra_vars.nil? @varset else @varset.merge(extra_vars) end lambda_args = [env: self, vars: vars] vars.expand_varref(varref, lambda_args) end
ruby
{ "resource": "" }
q24587
Rscons.Environment.execute
train
def execute(short_desc, command, options = {}) print_builder_run_message(short_desc, command) env_args = options[:env] ? [options[:env]] : [] options_args = options[:options] ? [options[:options]] : [] system(*env_args, *Rscons.command_executer, *command, *options_args).tap do |result| unless result or @echo == :command print_failed_command(command) end end end
ruby
{ "resource": "" }
q24588
Rscons.Environment.method_missing
train
def method_missing(method, *args) if @builders.has_key?(method.to_s) target, sources, vars, *rest = args vars ||= {} unless vars.is_a?(Hash) or vars.is_a?(VarSet) raise "Unexpected construction variable set: #{vars.inspect}" end builder = @builders[method.to_s] target = expand_path(expand_varref(target)) sources = Array(sources).map do |source| expand_path(expand_varref(source)) end.flatten build_target = builder.create_build_target(env: self, target: target, sources: sources, vars: vars) add_target(build_target.to_s, builder, sources, vars, rest) build_target else super end end
ruby
{ "resource": "" }
q24589
Rscons.Environment.depends
train
def depends(target, *user_deps) target = expand_varref(target.to_s) user_deps = user_deps.map {|ud| expand_varref(ud)} @user_deps[target] ||= [] @user_deps[target] = (@user_deps[target] + user_deps).uniq build_after(target, user_deps) end
ruby
{ "resource": "" }
q24590
Rscons.Environment.build_sources
train
def build_sources(sources, suffixes, cache, vars) sources.map do |source| if source.end_with?(*suffixes) source else converted = nil suffixes.each do |suffix| converted_fname = get_build_fname(source, suffix) if builder = find_builder_for(converted_fname, source, []) converted = run_builder(builder, converted_fname, [source], cache, vars) return nil unless converted break end end converted or raise "Could not find a builder to handle #{source.inspect}." end end end
ruby
{ "resource": "" }
q24591
Rscons.Environment.register_builds
train
def register_builds(target, sources, suffixes, vars, options = {}) options[:features] ||= [] @registered_build_dependencies[target] ||= Set.new sources.map do |source| if source.end_with?(*suffixes) source else output_fname = nil suffixes.each do |suffix| attempt_output_fname = get_build_fname(source, suffix, features: options[:features]) if builder = find_builder_for(attempt_output_fname, source, options[:features]) output_fname = attempt_output_fname self.__send__(builder.name, output_fname, source, vars) @registered_build_dependencies[target] << output_fname break end end output_fname or raise "Could not find a builder for #{source.inspect}." end end end
ruby
{ "resource": "" }
q24592
Rscons.Environment.run_builder
train
def run_builder(builder, target, sources, cache, vars, options = {}) vars = @varset.merge(vars) build_operation = { builder: builder, target: target, sources: sources, cache: cache, env: self, vars: vars, setup_info: options[:setup_info] } call_build_hooks = lambda do |sec| @build_hooks[sec].each do |build_hook_block| build_hook_block.call(build_operation) end end # Invoke pre-build hooks. call_build_hooks[:pre] # Call the builder's #run method. if builder.method(:run).arity == 5 rv = builder.run(*build_operation.values_at(:target, :sources, :cache, :env, :vars)) else rv = builder.run(build_operation) end if rv.is_a?(ThreadedCommand) # Store the build operation so the post-build hooks can be called # with it when the threaded command completes. rv.build_operation = build_operation start_threaded_command(rv) unless options[:allow_delayed_execution] # Delayed command execution is not allowed, so we need to execute # the command and finalize the builder now. tc = wait_for_threaded_commands(which: [rv]) rv = finalize_builder(tc) if rv call_build_hooks[:post] else unless @echo == :command print_failed_command(tc.command) end end end else call_build_hooks[:post] if rv end rv end
ruby
{ "resource": "" }
q24593
Rscons.Environment.expand_path
train
def expand_path(path) if Rscons.phony_target?(path) path elsif path.is_a?(Array) path.map do |path| expand_path(path) end else path.sub(%r{^\^(?=[\\/])}, @build_root).gsub("\\", "/") end end
ruby
{ "resource": "" }
q24594
Rscons.Environment.shell
train
def shell(command) shell_cmd = if self["SHELL"] flag = self["SHELLFLAG"] || (self["SHELL"] == "cmd" ? "/c" : "-c") [self["SHELL"], flag] else Rscons.get_system_shell end IO.popen([*shell_cmd, command]) do |io| io.read end end
ruby
{ "resource": "" }
q24595
Rscons.Environment.merge_flags
train
def merge_flags(flags) flags.each_pair do |key, val| if self[key].is_a?(Array) and val.is_a?(Array) self[key] += val else self[key] = val end end end
ruby
{ "resource": "" }
q24596
Rscons.Environment.dump
train
def dump varset_hash = @varset.to_h varset_hash.keys.sort_by(&:to_s).each do |var| var_str = var.is_a?(Symbol) ? var.inspect : var Ansi.write($stdout, :cyan, var_str, :reset, " => #{varset_hash[var].inspect}\n") end end
ruby
{ "resource": "" }
q24597
Rscons.Environment.print_builder_run_message
train
def print_builder_run_message(short_description, command) case @echo when :command if command.is_a?(Array) message = command_to_s(command) elsif command.is_a?(String) message = command elsif short_description.is_a?(String) message = short_description end when :short message = short_description if short_description end Ansi.write($stdout, :cyan, message, :reset, "\n") if message end
ruby
{ "resource": "" }
q24598
Rscons.Environment.add_target
train
def add_target(target, builder, sources, vars, args) setup_info = builder.setup( target: target, sources: sources, env: self, vars: vars) @job_set.add_job( builder: builder, target: target, sources: sources, vars: vars, setup_info: setup_info) end
ruby
{ "resource": "" }
q24599
Rscons.Environment.start_threaded_command
train
def start_threaded_command(tc) print_builder_run_message(tc.short_description, tc.command) env_args = tc.system_env ? [tc.system_env] : [] options_args = tc.system_options ? [tc.system_options] : [] system_args = [*env_args, *Rscons.command_executer, *tc.command, *options_args] tc.thread = Thread.new do system(*system_args) end @threaded_commands << tc end
ruby
{ "resource": "" }