_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q2300
LIFX.LightTarget.set_power
train
def set_power(state) level = case state when :on 1 when :off 0 else raise ArgumentError.new("Must pass in either :on or :off") end send_message(Protocol::Device::SetPower.new(level: level)) self end
ruby
{ "resource": "" }
q2301
LIFX.LightTarget.set_site_id
train
def set_site_id(site_id) send_message(Protocol::Device::SetSite.new(site: [site_id].pack('H*'))) end
ruby
{ "resource": "" }
q2302
LIFX.LightTarget.set_time
train
def set_time(time = Time.now) send_message(Protocol::Device::SetTime.new(time: (time.to_f * NSEC_IN_SEC).round)) end
ruby
{ "resource": "" }
q2303
GemUpdater.RubyGemsFetcher.query_rubygems
train
def query_rubygems(tries = 0) JSON.parse(open("https://rubygems.org/api/v1/gems/#{gem_name}.json").read) rescue OpenURI::HTTPError => e # We may trigger too many requests, in which case give rubygems a break if e.io.status.include?(HTTP_TOO_MANY_REQUESTS) if (tries += 1) < 2 sleep 1 && retry end end end
ruby
{ "resource": "" }
q2304
GemUpdater.RubyGemsFetcher.uri_from_other_sources
train
def uri_from_other_sources uri = nil source.remotes.each do |remote| break if uri uri = case remote.host when 'rubygems.org' then next # already checked when 'rails-assets.org' uri_from_railsassets else Bundler.ui.error "Source #{remote} is not supported, ' \ 'feel free to open a PR or an issue on https://github.com/MaximeD/gem_updater" end end uri end
ruby
{ "resource": "" }
q2305
DirectedGraph.Graph.compute_key
train
def compute_key(external_identifier) x = [external_identifier].flatten x.map! {|xx| xx.to_s} x.join("_") end
ruby
{ "resource": "" }
q2306
DirectedGraph.Graph.to_graphml
train
def to_graphml() builder = Builder::XmlMarkup.new(:indent => 1) builder.instruct! :xml, :version => "1.0" graphml_attribs = { "xmlns" => "http://graphml.graphdrawing.org/xmlns", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xmlns:y" => "http://www.yworks.com/xml/graphml", "xmlns:yed" => "http://www.yworks.com/xml/yed/3", "xsi:schemaLocation" => "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd", :directed => "1", :label => "test" } builder.graphml(graphml_attribs) do # Define key id's at top of graphml file builder.key({:for=>"node", :id=>"d3", "yfiles.type"=>"nodegraphics"}) # Build Graph # builder.graph({:id=>"G"}) do vertices.each do |vertex| builder.node(:id => compute_key([vertex.name, vertex.object_id])) do builder.data({:key=>"d3"}) do builder.tag!("y:ShapeNode") do graphics = vertex.data.fetch(:graphics, {}) graphics.fetch(:fill, []).each {|f| builder.tag! "y:Fill", {:color=>f, :transparent=>"false"}} graphics.fetch(:shape,[]).each {|s| builder.tag! "y:Shape", {:type=>s}} graphics.fetch(:geometry,[]).each {|s| builder.tag! "y:Geometry", s} graphics.fetch(:label,[]).each {|l| builder.tag! "y:NodeLabel", l} end end end end edges.each do |edge| source = edge.origin_vertex target = edge.destination_vertex options = edge.data[:options] label = "" builder.edge( :source => s = compute_key([source.name, source.object_id]), :target => t = compute_key([target.name, target.object_id]), :id => compute_key([source.name, target.name, edge.object_id]), :label => "#{label}" ) do #edge[:attributes].each_pair { |k, v| # id_str = compute_key([k,:edge_attr]) # builder.data(v.to_s, {:key=>@guid[id_str]}) #} end end end end builder.target! end
ruby
{ "resource": "" }
q2307
LIFX.Color.to_hsbk
train
def to_hsbk Protocol::Light::Hsbk.new( hue: (hue / 360.0 * UINT16_MAX).to_i, saturation: (saturation * UINT16_MAX).to_i, brightness: (brightness * UINT16_MAX).to_i, kelvin: [KELVIN_MIN, kelvin.to_i, KELVIN_MAX].sort[1] ) end
ruby
{ "resource": "" }
q2308
LIFX.Color.similar_to?
train
def similar_to?(other, threshold: DEFAULT_SIMILAR_THRESHOLD) return false unless other.is_a?(Color) conditions = [] conditions << (((hue - other.hue).abs < (threshold * 360)) || begin # FIXME: Surely there's a better way. hues = [hue, other.hue].sort hues[0] += 360 (hues[0] - hues[1]).abs < (threshold * 360) end) conditions << ((saturation - other.saturation).abs < threshold) conditions << ((brightness - other.brightness).abs < threshold) conditions.all? end
ruby
{ "resource": "" }
q2309
Nominatim.Reverse.fetch
train
def fetch body = get(Nominatim.config.reverse_url, @criteria).body return nil if body.empty? Nominatim::Place.new(body) end
ruby
{ "resource": "" }
q2310
Signature.Request.sign
train
def sign(token) @auth_hash = { :auth_version => "1.0", :auth_key => token.key, :auth_timestamp => Time.now.to_i.to_s } @auth_hash[:auth_signature] = signature(token) @signed = true return @auth_hash end
ruby
{ "resource": "" }
q2311
Signature.Request.authenticate_by_token!
train
def authenticate_by_token!(token, timestamp_grace = 600) # Validate that your code has provided a valid token. This does not # raise an AuthenticationError since passing tokens with empty secret is # a code error which should be fixed, not reported to the API's consumer if token.secret.nil? || token.secret.empty? raise "Provided token is missing secret" end validate_version! validate_timestamp!(timestamp_grace) validate_signature!(token) true end
ruby
{ "resource": "" }
q2312
Signature.Request.authenticate
train
def authenticate(timestamp_grace = 600) raise ArgumentError, "Block required" unless block_given? key = @auth_hash['auth_key'] raise AuthenticationError, "Missing parameter: auth_key" unless key token = yield key unless token raise AuthenticationError, "Unknown auth_key" end authenticate_by_token!(token, timestamp_grace) return token end
ruby
{ "resource": "" }
q2313
Signature.Request.authenticate_async
train
def authenticate_async(timestamp_grace = 600) raise ArgumentError, "Block required" unless block_given? df = EM::DefaultDeferrable.new key = @auth_hash['auth_key'] unless key df.fail(AuthenticationError.new("Missing parameter: auth_key")) return end token_df = yield key token_df.callback { |token| begin authenticate_by_token!(token, timestamp_grace) df.succeed(token) rescue AuthenticationError => e df.fail(e) end } token_df.errback { df.fail(AuthenticationError.new("Unknown auth_key")) } ensure return df end
ruby
{ "resource": "" }
q2314
Signature.Request.identical?
train
def identical?(a, b) return true if a.nil? && b.nil? return false if a.nil? || b.nil? return false unless a.bytesize == b.bytesize a.bytes.zip(b.bytes).reduce(0) { |memo, (a, b)| memo += a ^ b } == 0 end
ruby
{ "resource": "" }
q2315
Sottolio.Script.method_missing
train
def method_missing(m, *args, &block) if args.any? args = args.first if args.length == 1 @var << { m.to_sym => args } instance_variable_set "@#{m}", args else instance_variable_get "@#{m}" end end
ruby
{ "resource": "" }
q2316
LIFX.TagManager.purge_unused_tags!
train
def purge_unused_tags! unused_tags.each do |tag| logger.info("Purging tag '#{tag}'") entries_with(label: tag).each do |entry| payload = Protocol::Device::SetTagLabels.new(tags: id_to_tags_field(entry.tag_id), label: '') context.send_message(target: Target.new(site_id: entry.site_id), payload: payload, acknowledge: true) end end Timeout.timeout(5) do while !unused_tags.empty? sleep 0.1 end end end
ruby
{ "resource": "" }
q2317
GemUpdater.Updater.format_diff
train
def format_diff gemfile.changes.map do |gem, details| ERB.new(template, nil, '<>').result(binding) end end
ruby
{ "resource": "" }
q2318
GemUpdater.Updater.fill_changelogs
train
def fill_changelogs [].tap do |threads| gemfile.changes.each do |gem_name, details| threads << Thread.new { retrieve_gem_changes(gem_name, details) } end end.each(&:join) end
ruby
{ "resource": "" }
q2319
GemUpdater.Updater.find_source
train
def find_source(gem, source) case source when Bundler::Source::Rubygems GemUpdater::RubyGemsFetcher.new(gem, source).source_uri when Bundler::Source::Git source.uri.gsub(/^git/, 'http').chomp('.git') end end
ruby
{ "resource": "" }
q2320
GemUpdater.Updater.template
train
def template File.read("#{Dir.home}/.gem_updater_template.erb") rescue Errno::ENOENT File.read(File.expand_path('../lib/gem_updater_template.erb', __dir__)) end
ruby
{ "resource": "" }
q2321
OmniCat.Classifier.strategy=
train
def strategy=(classifier) is_interchangeable?(classifier) if @strategy && classifier.category_count == 0 previous_strategy = @strategy @strategy = classifier convert_categories_with_docs(previous_strategy) else @strategy = classifier end end
ruby
{ "resource": "" }
q2322
OmniCat.Result.add_score
train
def add_score(score) @total_score += score.value @scores[score.key] = score if @top_score_key.nil? || @scores[@top_score_key].value < score.value @top_score_key = score.key end end
ruby
{ "resource": "" }
q2323
LIFX.Light.add_hook
train
def add_hook(payload_class, hook_arg = nil, &hook_block) hook = block_given? ? hook_block : hook_arg if !hook || !hook.is_a?(Proc) raise "Must pass a proc either as an argument or a block" end @message_hooks[payload_class] << hook end
ruby
{ "resource": "" }
q2324
LIFX.Light.color
train
def color(refresh: false, fetch: true) @color = nil if refresh send_message!(Protocol::Light::Get.new, wait_for: Protocol::Light::State) if fetch && !@color @color end
ruby
{ "resource": "" }
q2325
LIFX.Light.set_label
train
def set_label(label) if label.bytes.length > MAX_LABEL_LENGTH raise LabelTooLong.new("Label length in bytes must be below or equal to #{MAX_LABEL_LENGTH}") end while self.label != label send_message!(Protocol::Device::SetLabel.new(label: label.encode('utf-8')), wait_for: Protocol::Device::StateLabel) end self end
ruby
{ "resource": "" }
q2326
LIFX.Light.set_power!
train
def set_power!(state) level = case state when :on 1 when :off 0 else raise ArgumentError.new("Must pass in either :on or :off") end send_message!(Protocol::Device::SetPower.new(level: level), wait_for: Protocol::Device::StatePower) do |payload| if level == 0 payload.level == 0 else payload.level > 0 end end self end
ruby
{ "resource": "" }
q2327
LIFX.Light.time
train
def time send_message!(Protocol::Device::GetTime.new, wait_for: Protocol::Device::StateTime) do |payload| Time.at(payload.time.to_f / NSEC_IN_SEC) end end
ruby
{ "resource": "" }
q2328
LIFX.Light.latency
train
def latency start = Time.now.to_f send_message!(Protocol::Device::GetTime.new, wait_for: Protocol::Device::StateTime) Time.now.to_f - start end
ruby
{ "resource": "" }
q2329
LIFX.Light.mesh_firmware
train
def mesh_firmware(fetch: true) @mesh_firmware ||= begin send_message!(Protocol::Device::GetMeshFirmware.new, wait_for: Protocol::Device::StateMeshFirmware) do |payload| Firmware.new(payload) end if fetch end end
ruby
{ "resource": "" }
q2330
LIFX.Light.wifi_firmware
train
def wifi_firmware(fetch: true) @wifi_firmware ||= begin send_message!(Protocol::Device::GetWifiFirmware.new, wait_for: Protocol::Device::StateWifiFirmware) do |payload| Firmware.new(payload) end if fetch end end
ruby
{ "resource": "" }
q2331
LIFX.Light.temperature
train
def temperature send_message!(Protocol::Light::GetTemperature.new, wait_for: Protocol::Light::StateTemperature) do |payload| payload.temperature / 100.0 end end
ruby
{ "resource": "" }
q2332
LIFX.Light.mesh_info
train
def mesh_info send_message!(Protocol::Device::GetMeshInfo.new, wait_for: Protocol::Device::StateMeshInfo) do |payload| { signal: payload.signal, # This is in Milliwatts tx: payload.tx, rx: payload.rx } end end
ruby
{ "resource": "" }
q2333
LIFX.Light.wifi_info
train
def wifi_info send_message!(Protocol::Device::GetWifiInfo.new, wait_for: Protocol::Device::StateWifiInfo) do |payload| { signal: payload.signal, # This is in Milliwatts tx: payload.tx, rx: payload.rx } end end
ruby
{ "resource": "" }
q2334
LIFX.Light.version
train
def version send_message!(Protocol::Device::GetVersion.new, wait_for: Protocol::Device::StateVersion) do |payload| { vendor: payload.vendor, product: payload.product, version: payload.version } end end
ruby
{ "resource": "" }
q2335
LIFX.Light.uptime
train
def uptime send_message!(Protocol::Device::GetInfo.new, wait_for: Protocol::Device::StateInfo) do |payload| payload.uptime.to_f / NSEC_IN_SEC end end
ruby
{ "resource": "" }
q2336
LIFX.Light.last_downtime
train
def last_downtime send_message!(Protocol::Device::GetInfo.new, wait_for: Protocol::Device::StateInfo) do |payload| payload.downtime.to_f / NSEC_IN_SEC end end
ruby
{ "resource": "" }
q2337
LIFX.Light.send_message
train
def send_message(payload, acknowledge: true, at_time: nil) context.send_message(target: Target.new(device_id: id), payload: payload, acknowledge: acknowledge, at_time: at_time) end
ruby
{ "resource": "" }
q2338
LIFX.Light.send_message!
train
def send_message!(payload, wait_for: wait_for, wait_timeout: Config.message_wait_timeout, retry_interval: Config.message_retry_interval, &block) if Thread.current[:sync_enabled] raise "Cannot use synchronous methods inside a sync block" end result = nil begin block ||= Proc.new { |msg| true } proc = -> (payload) { result = block.call(payload) } add_hook(wait_for, proc) try_until -> { result }, timeout: wait_timeout, timeout_exception: TimeoutError, action_interval: retry_interval, signal: @message_signal do send_message(payload) end result rescue TimeoutError backtrace = caller_locations(2).map { |c| c.to_s } caller_method = caller_locations(2, 1).first.label ex = MessageTimeout.new("#{caller_method}: Timeout exceeded waiting for response from #{self}") ex.device = self ex.set_backtrace(backtrace) raise ex ensure remove_hook(wait_for, proc) end end
ruby
{ "resource": "" }
q2339
Nexus.Client.gav_data
train
def gav_data(gav) res = {} request = Typhoeus::Request.new( "#{host_url}/service/local/artifact/maven/resolve", :params => gav.to_hash,:connecttimeout => 5, :headers => { 'Accept' => 'application/json' } ) request.on_failure do |response| raise("Failed to get gav data for #{gav.to_s}") end request.on_complete do |response| res = JSON.parse(response.response_body) end request.run res['data'] end
ruby
{ "resource": "" }
q2340
Nexus.Client.sha
train
def sha(file, use_sha_file=false) if use_sha_file and File.exists?("#{file}.sha1") # reading the file is faster than doing a hash, so we keep the hash in the file # then we read back and compare. There is no reason to perform sha1 everytime begin File.open("#{file}.sha1", 'r') { |f| f.read().strip} rescue Digest::SHA1.file(File.expand_path(file)).hexdigest end else Digest::SHA1.file(File.expand_path(file)).hexdigest end end
ruby
{ "resource": "" }
q2341
Nexus.Client.sha_match?
train
def sha_match?(file, gav, use_sha_file=false) if File.exists?(file) if gav.sha1.nil? gav.sha1 = gav_data(gav)['sha1'] end sha(file,use_sha_file) == gav.sha1 else false end end
ruby
{ "resource": "" }
q2342
Nexus.Client.write_sha1
train
def write_sha1(file,sha1) shafile = "#{file}.sha1" File.open(shafile, 'w') { |f| f.write(sha1) } end
ruby
{ "resource": "" }
q2343
GemUpdater.SourcePageParser.known_https
train
def known_https(uri) case uri.host when HOSTS[:github] # remove possible subdomain like 'wiki.github.com' URI "https://github.com#{uri.path}" when HOSTS[:bitbucket] URI "https://#{uri.host}#{uri.path}" when HOSTS[:rubygems] URI "https://#{uri.host}#{uri.path}" else uri end end
ruby
{ "resource": "" }
q2344
GemUpdater.SourcePageParser.changelog_names
train
def changelog_names CHANGELOG_NAMES.flat_map do |name| [name, name.upcase, name.capitalize] end.uniq end
ruby
{ "resource": "" }
q2345
Kss.ApplicationHelper.styleguide_block
train
def styleguide_block(section, &block) raise ArgumentError, "Missing block" unless block_given? @section = styleguide.section(section) if [email protected] raise "KSS styleguide section is nil, is section '#{section}' defined in your css?" end content = capture(&block) render 'kss/shared/styleguide_block', :section => @section, :example_html => content end
ruby
{ "resource": "" }
q2346
AkamaiApi::ECCU.SoapBody.array
train
def array name, values array_attrs = { 'soapenc:arrayType' => "xsd:string[#{values.length}]", 'xsi:type' => 'wsdl:ArrayOfString' } builder.tag! name, array_attrs do |tag| values.each { |value| tag.item value } end self end
ruby
{ "resource": "" }
q2347
AkamaiApi::CCU::PurgeStatus.Request.execute
train
def execute purge_id_or_progress_uri purge_id_or_progress_uri = normalize_progress_uri purge_id_or_progress_uri response = self.class.get purge_id_or_progress_uri, basic_auth: AkamaiApi.auth parse_response response end
ruby
{ "resource": "" }
q2348
AkamaiApi::ECCU.FindRequest.execute
train
def execute retrieve_content = false with_soap_error_handling do response = client_call :get_info, message: request_body(retrieve_content).to_s FindResponse.new response[:eccu_info] end end
ruby
{ "resource": "" }
q2349
AkamaiApi::CCU::Purge.Request.execute
train
def execute *items akamai = Akamai::Edgegrid::HTTP.new(address=baseuri.host, port=baseuri.port) akamai.setup_edgegrid(creds) http = Net::HTTP.new(address=baseuri.host, port=baseuri.port) http.use_ssl = true items = Array.wrap(items.first) if items.length == 1 req = Net::HTTP::Post.new(resource, initheader = @@headers).tap do |pq| if for_ccu_v2? pq.body = request_body items else pq.body = {"objects" => items}.to_json end end timestamp = Akamai::Edgegrid::HTTP.eg_timestamp() nonce = Akamai::Edgegrid::HTTP.new_nonce() req['Authorization'] = akamai.make_auth_header(req, timestamp, nonce) parse_response http.request(req) end
ruby
{ "resource": "" }
q2350
AkamaiApi::CCU::Purge.Request.request_body
train
def request_body items { type: type, action: action, domain: domain, objects: items }.to_json end
ruby
{ "resource": "" }
q2351
AkamaiApi.CCU.purge
train
def purge action, type, items, opts = {} request = Purge::Request.new action, type, domain: opts[:domain] request.execute items end
ruby
{ "resource": "" }
q2352
StringDirection.DominantStrategy.run
train
def run(string) string = string.to_s ltr_count = chars_count(string, ltr_regex) rtl_count = chars_count(string, rtl_regex) diff = ltr_count - rtl_count return ltr if diff > 0 return rtl if diff < 0 nil end
ruby
{ "resource": "" }
q2353
AkamaiApi::ECCU.FindResponse.file
train
def file content64 = get_if_handleable(raw[:contents]) { :content => content64 ? Base64.decode64(content64) : nil, :size => raw[:file_size].to_i, :name => get_if_handleable(raw[:filename]), :md5 => get_if_handleable(raw[:md5_digest]) }.reject { |k, v| v.nil? } end
ruby
{ "resource": "" }
q2354
AkamaiApi::ECCU.FindResponse.property
train
def property { :name => get_if_handleable(raw[:property_name]), :exact_match => (raw[:property_name_exact_match] == true), :type => get_if_handleable(raw[:property_type]) }.reject { |k, v| v.nil? } end
ruby
{ "resource": "" }
q2355
AkamaiApi::ECCU.FindResponse.get_if_handleable
train
def get_if_handleable value case value when String then value when DateTime then value.to_time.utc.xmlschema(3) else nil end end
ruby
{ "resource": "" }
q2356
StringDirection.MarksStrategy.run
train
def run(string) string = string.to_s if ltr_mark?(string) && rtl_mark?(string) bidi elsif ltr_mark?(string) ltr elsif rtl_mark?(string) rtl end end
ruby
{ "resource": "" }
q2357
AhoC.Trie.add
train
def add pattern node = @root # If this is a string process each character if String(pattern) == pattern pattern.each_char do |char| if node.goto(char) == nil node = node.add(char) else node = node.goto(char) end end else # Otherwise, pattern should support "each" method. for item in pattern if node.goto(item) == nil node = node.add(item) else node = node.goto(item) end end end if block_given? node.output = yield pattern else node.output = [pattern] end end
ruby
{ "resource": "" }
q2358
Draper.CanCanCan.can?
train
def can?(action, subject, *extra_args) while subject.is_a?(Draper::Decorator) subject = subject.model end super(action, subject, *extra_args) end
ruby
{ "resource": "" }
q2359
Celerity.Element.method_missing
train
def method_missing(meth, *args, &blk) assert_exists meth = selector_to_attribute(meth) if self.class::ATTRIBUTES.include?(meth) || (self.class == Element && @object.hasAttribute(meth.to_s)) return @object.getAttribute(meth.to_s) end Log.warn "Element\#method_missing calling super with #{meth.inspect}" super end
ruby
{ "resource": "" }
q2360
ImageRuby.RubyBitmapModl.get_pixel
train
def get_pixel(x,y) index = (y*@width + x) pointindex = index*3 Color.from_rgba( @array[pointindex+2].ord, @array[pointindex+1].ord, @array[pointindex].ord, @alpha ? @alpha[index].ord : 255 ) end
ruby
{ "resource": "" }
q2361
ImageRuby.RubyBitmapModl.set_pixel
train
def set_pixel(x,y,color) index = (y*@width + x) pointindex = index*3 @array[pointindex+2] = color.r.chr @array[pointindex+1] = color.g.chr @array[pointindex] = color.b.chr if color.a != 255 then @alpha = 255.chr*(@height * @width) unless @alpha @alpha[index] = color.a.chr end self end
ruby
{ "resource": "" }
q2362
Rley.ParseTreeVisitor.traverse_subnodes
train
def traverse_subnodes(aParentNode) subnodes = aParentNode.subnodes broadcast(:before_subnodes, aParentNode, subnodes) # Let's proceed with the visit of subnodes subnodes.each { |a_node| a_node.accept(self) } broadcast(:after_subnodes, aParentNode, subnodes) end
ruby
{ "resource": "" }
q2363
Rley.ParseTreeVisitor.broadcast
train
def broadcast(msg, *args) subscribers.each do |subscr| next unless subscr.respond_to?(msg) || subscr.respond_to?(:accept_all) subscr.send(msg, *args) end end
ruby
{ "resource": "" }
q2364
Celerity.Browser.goto
train
def goto(uri, headers = nil) uri = "http://#{uri}" unless uri =~ %r{://} request = HtmlUnit::WebRequest.new(::Java::JavaNet::URL.new(uri)) request.setAdditionalHeaders(headers) if headers request.setCharset(@charset) rescue_status_code_exception do self.page = @webclient.getPage(request) end url() end
ruby
{ "resource": "" }
q2365
Celerity.Browser.send_keys
train
def send_keys(keys) keys = keys.gsub(/\s*/, '').scan(/((?:\{[A-Z]+?\})|.)/u).flatten keys.each do |key| element = @page.getFocusedElement case key when "{TAB}" @page.tabToNextElement when /\w/ element.type(key) else raise NotImplementedError end end end
ruby
{ "resource": "" }
q2366
Celerity.Browser.resynchronized
train
def resynchronized(&block) old_controller = @webclient.ajaxController @webclient.setAjaxController(::HtmlUnit::NicelyResynchronizingAjaxController.new) yield self @webclient.setAjaxController(old_controller) end
ruby
{ "resource": "" }
q2367
Celerity.Browser.confirm
train
def confirm(bool, &block) blk = lambda { bool } listener.add_listener(:confirm, &blk) yield listener.remove_listener(:confirm, blk) end
ruby
{ "resource": "" }
q2368
Celerity.Browser.add_checker
train
def add_checker(checker = nil, &block) if block_given? @error_checkers << block elsif Proc === checker @error_checkers << checker else raise ArgumentError, "argument must be a Proc or block" end end
ruby
{ "resource": "" }
q2369
Celerity.Browser.page=
train
def page=(value) return if @page == value @page = value if @page.respond_to?("getDocumentElement") @object = @page.getDocumentElement || @object elsif @page.is_a? HtmlUnit::UnexpectedPage raise UnexpectedPageException, @page.getWebResponse.getContentType end render unless @viewer == DefaultViewer run_error_checks value end
ruby
{ "resource": "" }
q2370
Celerity.Browser.enable_event_listener
train
def enable_event_listener @event_listener ||= lambda do |event| self.page = @page ? @page.getEnclosingWindow.getEnclosedPage : event.getNewPage end listener.add_listener(:web_window_event, &@event_listener) end
ruby
{ "resource": "" }
q2371
Celerity.Browser.render
train
def render @viewer.render_html(self.send(@render_type), url) rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EPIPE @viewer = DefaultViewer end
ruby
{ "resource": "" }
q2372
ImageRuby.PureRubyImageMethods.[]
train
def [] (x,y) if x.instance_of? Fixnum and y.instance_of? Fixnum get_pixel(fixx(x),fixy(y)) else x = (fixx(x)..fixx(x)) if x.instance_of? Fixnum y = (fixy(y)..fixy(y)) if y.instance_of? Fixnum if x.instance_of? Range x = (fixx(x.first)..fixx(x.last)) end if y.instance_of? Range y = (fixy(y.first)..fixy(y.last)) end newimg = Image.new(x.last + 1 - x.first, y.last + 1 - y.first) width = x.count (0..y.count).each do |y_| destpointer = y_*width*3 origpointer = ((y.first + y_)*self.width + x.first)*3 newimg.pixel_data[destpointer..destpointer+width*3] = self.pixel_data[origpointer..origpointer+width*3] end newimg end end
ruby
{ "resource": "" }
q2373
ImageRuby.PureRubyImageMethods.[]=
train
def []= (x,y,obj) if x.instance_of? Fixnum and y.instance_of? Fixnum set_pixel(x,y,obj) else x = (x..x) if x.instance_of? Fixnum y = (y..y) if y.instance_of? Fixnum width = x.count (0..y.count-1).each do |y_| origpointer = y_*obj.width*3 destpointer = ((y.first + y_)*self.width + x.first)*3 self.pixel_data[destpointer..destpointer+obj.width*3-1] = obj.pixel_data[origpointer..origpointer+obj.width*3-1] end end end
ruby
{ "resource": "" }
q2374
ImageRuby.PureRubyImageMethods.each_pixel
train
def each_pixel (0..@width-1).each do |x| (0..@height-1).each do |y| yield(x,y,get_pixel(x,y)) end end end
ruby
{ "resource": "" }
q2375
ImageRuby.PureRubyImageMethods.map_pixel
train
def map_pixel Image.new(@width, @height) do |x,y| yield(x,y,get_pixel(x,y)) end end
ruby
{ "resource": "" }
q2376
ImageRuby.PureRubyImageMethods.map_pixel!
train
def map_pixel! each_pixel do |x,y,color| set_pixel(x,y, yield(x,y,get_pixel(x,y))) end self end
ruby
{ "resource": "" }
q2377
ImageRuby.PureRubyImageMethods.color_replace
train
def color_replace(color1, color2) newimage = self.dup newimage.color_replace!(color1,color2) newimage end
ruby
{ "resource": "" }
q2378
ImageRuby.PureRubyImageMethods.color_replace!
train
def color_replace!( color1, color2) strcolor1 = color1.to_s strcolor2 = color2.to_s a = color2.a.chr (0..width*height).each do |i| if pixel_data[i*3..i*3+2] == strcolor1 then pixel_data[i*3..i*3+2] = strcolor2 alpha_data[i] = a end end end
ruby
{ "resource": "" }
q2379
ImageRuby.PureRubyImageMethods.mask
train
def mask(color1 = nil) color1 = color1 || Color.from_rgb(255,255,255) color2 = color1.dup color2.a = 0 color_replace(color1,color2) end
ruby
{ "resource": "" }
q2380
TDiff.Unordered.tdiff_unordered
train
def tdiff_unordered(tree,&block) return enum_for(:tdiff_unordered,tree) unless block # check if the nodes differ unless tdiff_equal(tree) yield '-', self yield '+', tree return self end yield ' ', self tdiff_recursive_unordered(tree,&block) return self end
ruby
{ "resource": "" }
q2381
TDiff.Unordered.tdiff_recursive_unordered
train
def tdiff_recursive_unordered(tree,&block) x = enum_for(:tdiff_each_child,self) y = enum_for(:tdiff_each_child,tree) unchanged = {} changes = [] x.each_with_index do |xi,i| y.each_with_index do |yj,j| if (!unchanged.has_value?(yj) && xi.tdiff_equal(yj)) unchanged[xi] = yj changes << [i, ' ', xi] break end end unless unchanged.has_key?(xi) changes << [i, '-', xi] end end y.each_with_index do |yj,j| unless unchanged.has_value?(yj) changes << [j, '+', yj] end end # order the changes by index to match the behavior of `tdiff` changes.sort_by { |change| change[0] }.each do |index,change,node| yield change, node end # explicitly release the changes variable changes = nil # recurse down the unchanged nodes unchanged.each do |xi,yj| xi.tdiff_recursive_unordered(yj,&block) end unchanged = nil end
ruby
{ "resource": "" }
q2382
OneDrive.V1.get_drive
train
def get_drive drive_id url = base_api_url + "/drives/#{drive_id}" @drives = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
ruby
{ "resource": "" }
q2383
OneDrive.V1.get_users_drive
train
def get_users_drive id_or_user_principal_name url = base_api_url + "/users/#{id_or_user_principal_name}/drive" @drives = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
ruby
{ "resource": "" }
q2384
OneDrive.V1.get_my_drive
train
def get_my_drive url = base_api_url + "/me/drive" @my_drive = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
ruby
{ "resource": "" }
q2385
OneDrive.V1.get_library_for_site
train
def get_library_for_site site_id url = base_api_url + "/sites/#{site_id}/drive" @drives = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
ruby
{ "resource": "" }
q2386
OneDrive.V1.get_special_folder_by_name
train
def get_special_folder_by_name name url = base_api_url + "/me/drive/special/#{name}" @special_drive = JSON.parse(HTTParty.get(url,headers: set_headers).body) end
ruby
{ "resource": "" }
q2387
Celerity.TableRow.child_cell
train
def child_cell(index) assert_exists if (index - Celerity.index_offset) >= @cells.length raise UnknownCellException, "Unable to locate a cell at index #{index}" end TableCell.new(self, :object, @cells[index - Celerity.index_offset]) end
ruby
{ "resource": "" }
q2388
Celerity.Table.to_a
train
def to_a assert_exists # @object.getRows.map do |table_row| # table_row.getCells.map { |td| td.asText.strip } # end rows.map do |table_row| table_row.map { |td| td.text } end end
ruby
{ "resource": "" }
q2389
Skinny.Websocket.start!
train
def start! # Steal any remaining data from rack.input @buffer = @env[Thin::Request::RACK_INPUT].read + @buffer # Remove references to Thin connection objects, freeing memory @env.delete Thin::Request::RACK_INPUT @env.delete Thin::Request::ASYNC_CALLBACK @env.delete Thin::Request::ASYNC_CLOSE # Figure out which version we're using @version = @env['HTTP_SEC_WEBSOCKET_VERSION'] @version ||= "hixie-76" if @env.has_key?('HTTP_SEC_WEBSOCKET_KEY1') and @env.has_key?('HTTP_SEC_WEBSOCKET_KEY2') @version ||= "hixie-75" # Pull out the details we care about @origin ||= @env['HTTP_SEC_WEBSOCKET_ORIGIN'] || @env['HTTP_ORIGIN'] @location ||= "ws#{secure? ? 's' : ''}://#{@env['HTTP_HOST']}#{@env['REQUEST_PATH']}" @protocol ||= @env['HTTP_SEC_WEBSOCKET_PROTOCOL'] || @env['HTTP_WEBSOCKET_PROTOCOL'] EM.next_tick { callback :on_start, self rescue error! "Error in start callback" } # Queue up the actual handshake EM.next_tick method :handshake! @state = :started # Return self so we can be used as a response self rescue error! "Error starting connection" end
ruby
{ "resource": "" }
q2390
Skinny.Websocket.send_frame
train
def send_frame opcode, payload="", masked=false payload = payload.dup.force_encoding("ASCII-8BIT") if payload.respond_to? :force_encoding payload_length = payload.bytesize # We don't support continuations (yet), so always send fin fin_byte = 0x80 send_data [fin_byte | opcode].pack("C") # We shouldn't be sending mask, we're a server only masked_byte = masked ? 0x80 : 0x00 if payload_length <= 125 send_data [masked_byte | payload_length].pack("C") elsif payload_length < 2 ** 16 send_data [masked_byte | 126].pack("C") send_data [payload_length].pack("n") else send_data [masked_byte | 127].pack("C") send_data [payload_length / (2 ** 32), payload_length % (2 ** 32)].pack("NN") end if payload_length if masked mask_key = Array.new(4) { rand(256) }.pack("C*") send_data mask_key payload = mask payload, mask_key end send_data payload end end
ruby
{ "resource": "" }
q2391
Skinny.Websocket.finish!
train
def finish! if hixie_75? or hixie_76? send_data "\xff\x00" else send_frame OPCODE_CLOSE end EM.next_tick { callback(:on_finish, self) rescue error! "Error in finish callback" } EM.next_tick { close_connection_after_writing } @state = :finished rescue error! "Error finishing WebSocket connection" end
ruby
{ "resource": "" }
q2392
Celerity.XpathSupport.elements_by_xpath
train
def elements_by_xpath(xpath) assert_exists objects = @page.getByXPath(xpath) # should use an ElementCollection here? objects.map { |o| element_from_dom_node(o) } end
ruby
{ "resource": "" }
q2393
Celerity.XpathSupport.element_from_dom_node
train
def element_from_dom_node(obj, identifier_string = nil) element_class = Util.htmlunit2celerity(obj.class) || Element element = element_class.new(self, :object, obj) element.identifier_string = identifier_string element.extend(ClickableElement) unless element.is_a?(ClickableElement) element end
ruby
{ "resource": "" }
q2394
Celerity.TextField.contains_text
train
def contains_text(expected_text) assert_exists case expected_text when Regexp value() =~ expected_text when String value().index(expected_text) else raise TypeError, "expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}" end end
ruby
{ "resource": "" }
q2395
SimpleCov.ArrayMergeHelper.merge_resultset
train
def merge_resultset(array) new_array = dup array.each_with_index do |element, i| pair = [element, new_array[i]] new_array[i] = if pair.any?(&:nil?) && pair.map(&:to_i).all?(&:zero?) nil else element.to_i + new_array[i].to_i end end new_array end
ruby
{ "resource": "" }
q2396
Celerity.Image.file_created_date
train
def file_created_date assert_exists web_response = @object.getWebResponse(true) Time.parse(web_response.getResponseHeaderValue("Last-Modified").to_s) end
ruby
{ "resource": "" }
q2397
Celerity.Image.save
train
def save(filename) assert_exists image_reader = @object.getImageReader file = java.io.File.new(filename) buffered_image = image_reader.read(0); javax.imageio.ImageIO.write(buffered_image, image_reader.getFormatName(), file); end
ruby
{ "resource": "" }
q2398
Celerity.Util.matches?
train
def matches?(string, what) Regexp === what ? string.strip =~ what : string == what.to_s end
ruby
{ "resource": "" }
q2399
Celerity.Listener.add_listener
train
def add_listener(type, &block) case type when :status @webclient.setStatusHandler(self) when :alert @webclient.setAlertHandler(self) when :attachment @webclient.setAttachmentHandler(self) when :web_window_event @webclient.addWebWindowListener(self) when :html_parser @webclient.setHTMLParserListener(self) when :incorrectness @webclient.setIncorrectnessListener(self) when :confirm @webclient.setConfirmHandler(self) when :prompt @webclient.setPromptHandler(self) else raise ArgumentError, "unknown listener type #{type.inspect}" end @procs[type] << block end
ruby
{ "resource": "" }