_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q6500
KeytechKit.ElementFileHandler.load
train
def load(element_key) parameter = { basic_auth: @auth } response = self.class.get("/elements/#{element_key}/files", parameter) parse_files(response['FileInfos']) if response.success? end
ruby
{ "resource": "" }
q6501
KeytechKit.ElementFileHandler.load_masterfile
train
def load_masterfile(element_key) parameter = { basic_auth: @auth } response = self.class.get("/elements/#{element_key}/files/masterfile", parameter) return response if response.success? end
ruby
{ "resource": "" }
q6502
KeytechKit.ElementFileHandler.upload_masterfile
train
def upload_masterfile(element_key, file, original_filename) # file, elementkey , name?? content_length = file.size content_type = 'application/octet-stream; charset=utf-8' parameter = { basic_auth: @auth, headers: { 'Content-Type' => content_type, ...
ruby
{ "resource": "" }
q6503
Shells.ShellBase.change_quit
train
def change_quit(quit_command) raise Shells::NotRunning unless running? self.options = options.dup.merge( quit: quit_command ).freeze self end
ruby
{ "resource": "" }
q6504
Taaze.TaazeComments.url_get_html
train
def url_get_html(url_str) url = URI.parse(URI.encode(url_str)) # first get total size req = Net::HTTP::Get.new(url.to_s) res = Net::HTTP.start(url.host, url.port) { |http| http.request(req) } res.body end
ruby
{ "resource": "" }
q6505
Taaze.TaazeComments.extract_comments
train
def extract_comments(content, user_id) # Json format~ # "content":"勇氣就是熱誠,來自於我們對自己工作的自信心;.....", # "title":"", # "status":"C", # "stars":"5", # "prodId":"11100597685", # "titleMain":"行銷之神原一平全集(精裝版)", # "orgProdId":"11100597685", # "pkNo":"1000243977", # "mdf_t...
ruby
{ "resource": "" }
q6506
Model.ClassMethods.find!
train
def find!( *args ) raise_not_found_error_was = Mongoid.raise_not_found_error begin Mongoid.raise_not_found_error = true self.find( *args ) ensure Mongoid.raise_not_found_error = raise_not_found_error_was end end
ruby
{ "resource": "" }
q6507
ThinkFeelDoDashboard.ApplicationHelper.breadcrumbs
train
def breadcrumbs return unless show_breadcrumbs? content_for( :breadcrumbs, content_tag(:ol, class: "breadcrumb") do concat(content_tag(:li, link_to("Home", root_path))) if can_view_resource_index? concat( content_tag( :li, contr...
ruby
{ "resource": "" }
q6508
Sndacs.Bucket.put_bucket_policy
train
def put_bucket_policy(bucket_policy) if bucket_policy && bucket_policy.is_a?(String) && bucket_policy.strip != '' bucket_request(:put,:body => bucket_policy,:subresource=>"policy") true else false end end
ruby
{ "resource": "" }
q6509
Bebox.ProfileWizard.create_new_profile
train
def create_new_profile(project_root, profile_name, profile_base_path) # Clean the profile_path to make it a valid path profile_base_path = Bebox::Profile.cleanpath(profile_base_path) # Check if the profile name is valid return unless name_valid?(profile_name, profile_base_path) # Check if ...
ruby
{ "resource": "" }
q6510
Bebox.ProfileWizard.name_valid?
train
def name_valid?(profile_name, profile_base_path) unless valid_puppet_class_name?(profile_name) error _('wizard.profile.invalid_name')%{words: Bebox::RESERVED_WORDS.join(', ')} return false end return true if profile_base_path.empty? # Check if the path name is valid unless ...
ruby
{ "resource": "" }
q6511
Bebox.ProfileWizard.remove_profile
train
def remove_profile(project_root) # Choose a profile from the availables profiles = Bebox::Profile.list(project_root) # Get a profile if exist if profiles.count > 0 profile = choose_option(profiles, _('wizard.choose_remove_profile')) else return error _('wizard.profile.no_de...
ruby
{ "resource": "" }
q6512
Remi.DataSubject.field_symbolizer
train
def field_symbolizer(arg = nil) return @field_symbolizer unless arg @field_symbolizer = if arg.is_a? Symbol Remi::FieldSymbolizers[arg] else arg end end
ruby
{ "resource": "" }
q6513
Remi.DataSubject.df=
train
def df=(new_dataframe) dsl_eval if new_dataframe.respond_to? :df_type @dataframe = new_dataframe else @dataframe = Remi::DataFrame.create(df_type, new_dataframe) end end
ruby
{ "resource": "" }
q6514
Jinx.MultiEnumerator.method_missing
train
def method_missing(symbol, *args) self.class.new(@components.map { |enum|enum.send(symbol, *args) }) end
ruby
{ "resource": "" }
q6515
Gogetit.GogetLXD.generate_user_data
train
def generate_user_data(lxd_params, options) logger.info("Calling <#{__method__.to_s}>") lxd_params[:config] = {} if options[:'no-maas'] lxd_params[:config][:"user.user-data"] = {} else sshkeys = maas.get_sshkeys pkg_repos = maas.get_package_repos lxd_params[:co...
ruby
{ "resource": "" }
q6516
Pyrite.Dsl.fill_in
train
def fill_in(element, value) if element.match /date/ # Try to guess at date selects select_date(element, value) else browser.type("jquery=#{element}", value) end end
ruby
{ "resource": "" }
q6517
Pyrite.Dsl.select_date
train
def select_date(element, value) suffixes = { :year => '1i', :month => '2i', :day => '3i', :hour => '4i', :minute => '5i' } date = value.respond_to?(:year) ? value : Date.parse(value) browser.select "jquery=#{element}_#{suffixes[:year]}", date.year ...
ruby
{ "resource": "" }
q6518
Pyrite.Dsl.wait_for
train
def wait_for(element) case element when :page_load browser.wait_for(:wait_for => :page) when :ajax browser.wait_for(:wait_for => :ajax, :javascript_framework => Pyrite.js_framework) else browser.wait_for(:element => "jquery=#{element}") end end
ruby
{ "resource": "" }
q6519
Maguro.Features.create_database_files
train
def create_database_files username = builder.options['database-username'] password = builder.options['database-password'] builder.remove_file "config/database.yml" create_database_yml_file("config/database.sample.yml", "username", "pass") create_database_yml_file("config/database.yml", us...
ruby
{ "resource": "" }
q6520
Kamaze::Project::Concern::Observable.ClassMethods.add_observer
train
def add_observer(observer_class, func = :handle_event) func = func.to_sym unless observer_class.instance_methods.include?(func) m = "#<#{observer_class}> does not respond to `#{func}'" raise NoMethodError, m end observer_peers[observer_class] = func self end
ruby
{ "resource": "" }
q6521
MuckEngine.SslRequirement.ssl_required?
train
def ssl_required? return ENV['SSL'] == 'on' ? true : false if defined? ENV['SSL'] return false if local_request? return false if RAILS_ENV == 'test' ((self.class.read_inheritable_attribute(:ssl_required_actions) || []).include?(action_name.to_sym)) && (::Rails.env == 'production' || ::Ra...
ruby
{ "resource": "" }
q6522
RootedTree.Node.ancestors
train
def ancestors return to_enum(__callee__) unless block_given? node = self loop do node = node.parent yield node end end
ruby
{ "resource": "" }
q6523
RootedTree.Node.child
train
def child(index = nil) unless index raise ArgumentError, 'No index for node with degree != 1' if degree != 1 return first end rtl, index = wrap_index index raise RangeError, 'Child index out of range' if index >= degree children(rtl: rtl).each do |c| break c if i...
ruby
{ "resource": "" }
q6524
RootedTree.Node.edges
train
def edges(&block) return to_enum(__callee__) unless block_given? children do |v| yield self, v v.edges(&block) end end
ruby
{ "resource": "" }
q6525
RootedTree.Node.+
train
def +(other) unless root? && other.root? raise StructureException, 'Only roots can be added' end a = frozen? ? dup : self b = other.frozen? ? other.dup : other ab = self.class.new ab << a << b end
ruby
{ "resource": "" }
q6526
SwaggerDocsGenerator.Methods.swagger_doc
train
def swagger_doc(action, &block) parse = ParserAction.new(action, &block) parse.adding_path end
ruby
{ "resource": "" }
q6527
SwaggerDocsGenerator.Methods.swagger_definition
train
def swagger_definition(name, &block) parse = ParserDefinition.new(name, &block) parse.adding_definition end
ruby
{ "resource": "" }
q6528
Whenner.Conversions.Promise
train
def Promise(obj) return obj.to_promise if obj.respond_to?(:to_promise) Deferred.new.fulfill(obj) end
ruby
{ "resource": "" }
q6529
RogerEslint.Lint.normalize_path
train
def normalize_path(test, path) Pathname.new(path).relative_path_from(test.project.path.realpath).to_s end
ruby
{ "resource": "" }
q6530
MMETools.ArgsProc.assert_valid_keys
train
def assert_valid_keys(options, valid_options) unknown_keys = options.keys - valid_options.keys raise(ArgumentError, "Unknown options(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty? end
ruby
{ "resource": "" }
q6531
CLIntegracon.Formatter.describe_file_diff
train
def describe_file_diff(diff, max_width=80) description = [] description << "File comparison error `#{diff.relative_path}` for #{spec.spec_folder}:" description << "--- DIFF ".ljust(max_width, '-') description += diff.map do |line| case line when /^\+/ then line.green ...
ruby
{ "resource": "" }
q6532
Gitkite.GitkitController.sign_in_success
train
def sign_in_success g_user = signed_in? if g_user user = { :email => g_user.email, :user_id => g_user.user_id, :name => g_user.name, :photo_url => g_user.photo_url, :provider_id => g_user.provider_id } @user = User.find_by(user_id: ...
ruby
{ "resource": "" }
q6533
Bebox.FilesHelper.render_erb_template
train
def render_erb_template(template_path, options) require 'tilt' Tilt::ERBTemplate.new(template_path).render(nil, options) end
ruby
{ "resource": "" }
q6534
Bebox.FilesHelper.write_content_to_file
train
def write_content_to_file(file_path, content) File.open(file_path, 'w') do |f| f.write content end end
ruby
{ "resource": "" }
q6535
TriglavClient.ResourcesApi.create_resource
train
def create_resource(resource, opts = {}) data, _status_code, _headers = create_resource_with_http_info(resource, opts) return data end
ruby
{ "resource": "" }
q6536
TriglavClient.ResourcesApi.get_resource
train
def get_resource(id_or_uri, opts = {}) data, _status_code, _headers = get_resource_with_http_info(id_or_uri, opts) return data end
ruby
{ "resource": "" }
q6537
TriglavClient.ResourcesApi.list_aggregated_resources
train
def list_aggregated_resources(uri_prefix, opts = {}) data, _status_code, _headers = list_aggregated_resources_with_http_info(uri_prefix, opts) return data end
ruby
{ "resource": "" }
q6538
TriglavClient.ResourcesApi.update_resource
train
def update_resource(id_or_uri, resource, opts = {}) data, _status_code, _headers = update_resource_with_http_info(id_or_uri, resource, opts) return data end
ruby
{ "resource": "" }
q6539
Coinstack.UserPair.add_list_data
train
def add_list_data(data) raise symbol.to_s if data.nil? self.exchange_rate = data['price_usd'].to_f self.perchant_change_week = data['percent_change_7d'].to_f self.perchant_change_day = data['percent_change_24h'].to_f end
ruby
{ "resource": "" }
q6540
Poster.Forum.new_topic
train
def new_topic board: 92, subj: 'test', msg: 'msg', icon: "exclamation" board = board.instance_of?(Symbol) ? @opts[:boards][board] : board # Check board posting page first (to get sequence numbers) get "/index.php?action=post;board=#{board}.0" raise "Not logged, cannot post!" unless logged? ...
ruby
{ "resource": "" }
q6541
Tangle.BaseGraphPrivate.each_vertex_breadth_first
train
def each_vertex_breadth_first(start_vertex, walk_method) remaining = [start_vertex] remaining.each_with_object([]) do |vertex, history| history << vertex yield vertex send(walk_method, vertex).each do |other| remaining << other unless history.include?(other) end ...
ruby
{ "resource": "" }
q6542
RequiresApproval.ClassMethods.create_versions_class
train
def create_versions_class versions_table_name = self.versions_table_name self.const_set self.versions_class_name, Class.new(ActiveRecord::Base) self.versions_class.class_eval do self.table_name = versions_table_name # Whitelist public attributes # Everything since this class...
ruby
{ "resource": "" }
q6543
Aims.Geometry.make_bonds
train
def make_bonds(bond_length = 3.0) # initialize an empty array @bonds = Array.new # Make bonds between all atoms # stack = atoms.dup atoms_extended = atoms.dup if periodic? v1 = lattice_vectors[0] v2 = lattice_vectors[1] atoms.each{|a| [-1, 0, 1].each{|n1| ...
ruby
{ "resource": "" }
q6544
Aims.Geometry.recache_visible_atoms
train
def recache_visible_atoms(makeBonds = false) plane_count = (@clip_planes ? @clip_planes.length : 0) return if plane_count == 0 if @visibleAtoms @visibleAtoms.clear else @visibleAtoms = [] end @atoms.each{|a| i = plane_count @clip_planes.each{|p| ...
ruby
{ "resource": "" }
q6545
Aims.Geometry.center
train
def center(visible_only = true) if atoms.empty? return Atom.new(0,0,0) else bounds = bounding_box(visible_only) x = (bounds[0].x + bounds[1].x)/2.0 y = (bounds[0].y + bounds[1].y)/2.0 z = (bounds[0].z + bounds[1].z)/2.0 return Atom.new(x,y,z) end end
ruby
{ "resource": "" }
q6546
Aims.Geometry.displace
train
def displace(x,y,z) Geometry.new(atoms(:all).collect{|a| a.displace(x,y,z) }, self.lattice_vectors) #TODO copy miller indices end
ruby
{ "resource": "" }
q6547
Aims.Geometry.repeat
train
def repeat(nx=1, ny=1, nz=1) raise "Not a periodic system." if self.lattice_vectors.nil? u = self.copy v1 = self.lattice_vectors[0] v2 = self.lattice_vectors[1] v3 = self.lattice_vectors[2] nx_sign = (0 < nx) ? 1 : -1 ny_sign = (0 < ny) ? 1 : -1 nz_sign = (...
ruby
{ "resource": "" }
q6548
Aims.Geometry.format_geometry_in
train
def format_geometry_in output = "" if self.lattice_vectors output << self.lattice_vectors.collect{|v| "lattice_vector #{v[0]} #{v[1]} #{v[2]}"}.join("\n") output << "\n" end output << self.atoms.collect{|a| a.format_geometry_in}.join("\n") output end
ruby
{ "resource": "" }
q6549
Aims.Geometry.format_xyz
train
def format_xyz(title = "Aims Geoemtry") output = self.atoms.size.to_s + "\n" output << "#{title} \n" self.atoms.each{ |a| output << [a.species, a.x.to_s, a.y.to_s, a.z.to_s].join("\t") + "\n" } output end
ruby
{ "resource": "" }
q6550
Aims.Geometry.delta
train
def delta(aCell) raise "Cells do not have the same number of atoms" unless self.atoms.size == aCell.atoms.size pseudo_atoms = [] self.atoms.size.times {|i| a1 = self.atoms[i] a2 = aCell.atoms[i] raise "Species do not match" unless a1.species == a2.species a = Atom.new ...
ruby
{ "resource": "" }
q6551
Dynabix.Metadata.has_metadata
train
def has_metadata(serializer=:metadata, *attributes) serialize(serializer, HashWithIndifferentAccess) if RUBY_VERSION < '1.9' raise "has_metadata serializer must be named ':metadata', this restriction is lifted in Ruby 1.9+" unless serializer == :metadata else # we can safely define ad...
ruby
{ "resource": "" }
q6552
Shells.ShellBase.queue_input
train
def queue_input(data) #:doc: sync do if options[:unbuffered_input] data = data.chars input_fifo.push *data else input_fifo.push data end end end
ruby
{ "resource": "" }
q6553
CLIntegracon::Adapter::Bacon.Context.subject
train
def subject &block @subject ||= CLIntegracon::shared_config.subject.dup return @subject if block.nil? instance_exec(@subject, &block) end
ruby
{ "resource": "" }
q6554
CLIntegracon::Adapter::Bacon.Context.file_tree_spec_context
train
def file_tree_spec_context &block @file_tree_spec_context ||= CLIntegracon.shared_config.file_tree_spec_context.dup return @file_tree_spec_context if block.nil? instance_exec(@file_tree_spec_context, &block) end
ruby
{ "resource": "" }
q6555
Garcon.ReadWriteLock.acquire_read_lock
train
def acquire_read_lock while(true) c = @counter.value raise ResourceLimitError, 'Too many reader threads' if max_readers?(c) if waiting_writer?(c) @reader_mutex.synchronize do @reader_q.wait(@reader_mutex) if waiting_writer? end while(true) ...
ruby
{ "resource": "" }
q6556
Garcon.ReadWriteLock.release_read_lock
train
def release_read_lock while(true) c = @counter.value if @counter.compare_and_swap(c,c-1) if waiting_writer?(c) && running_readers(c) == 1 @writer_mutex.synchronize { @writer_q.signal } end break end end true end
ruby
{ "resource": "" }
q6557
Garcon.ReadWriteLock.acquire_write_lock
train
def acquire_write_lock while(true) c = @counter.value raise ResourceLimitError, 'Too many writer threads' if max_writers?(c) if c == 0 break if @counter.compare_and_swap(0,RUNNING_WRITER) elsif @counter.compare_and_swap(c,c+WAITING_WRITER) while(true) ...
ruby
{ "resource": "" }
q6558
Garcon.ReadWriteLock.release_write_lock
train
def release_write_lock while(true) c = @counter.value if @counter.compare_and_swap(c,c-RUNNING_WRITER) @reader_mutex.synchronize { @reader_q.broadcast } if waiting_writers(c) > 0 @writer_mutex.synchronize { @writer_q.signal } end break en...
ruby
{ "resource": "" }
q6559
CommandModel.Model.parameters
train
def parameters self.class.parameters.each_with_object({}) do |parameter, hash| hash[parameter.name] = send(parameter.name) end end
ruby
{ "resource": "" }
q6560
ModelsAuditor.Controller.user_for_models_auditor
train
def user_for_models_auditor user = case when defined?(current_user) current_user when defined?(current_employee) current_employee else return end ActiveSupport::VERSION::MAJOR >= 4 ? user.try!(:id) : user.try(:id) rescue N...
ruby
{ "resource": "" }
q6561
ModelsAuditor.Controller.info_for_models_auditor
train
def info_for_models_auditor { ip: request.remote_ip, user_agent: request.user_agent, controller: self.class.name, action: action_name, path: request.path_info } end
ruby
{ "resource": "" }
q6562
AuthRocket.Credential.verify
train
def verify(code, attribs={}) params = parse_request_params(attribs.merge(code: code), json_root: json_root).merge credentials: api_creds parsed, _ = request(:post, url+'/verify', params) load(parsed) errors.empty? ? self : false end
ruby
{ "resource": "" }
q6563
Bullring.RhinoServer.fetch_library
train
def fetch_library(name) library_script = @server_registry['library', name] logger.debug {"#{logname}: Tried to fetch script '#{name}' from the registry and it " + "was #{'not ' if library_script.nil?}found."} raise NameError, "Server cannot find a script named #{name}" if l...
ruby
{ "resource": "" }
q6564
RailsExtension::ActionControllerExtension::AccessibleViaUser.ClassMethods.assert_access_without_login
train
def assert_access_without_login(*actions) user_options = actions.extract_options! options = {} if ( self.constants.include?('ASSERT_ACCESS_OPTIONS') ) options.merge!(self::ASSERT_ACCESS_OPTIONS) end options.merge!(user_options) actions += options[:actions]||[] m_key = options[:model].try(:und...
ruby
{ "resource": "" }
q6565
Jinx.Collection.to_json
train
def to_json(state=nil) # Make a new State from the options if this is a top-level call. state = JSON::State.for(state) unless JSON::State === state to_a.to_json(state) end
ruby
{ "resource": "" }
q6566
Myreplicator.Export.export
train
def export Log.run(:job_type => "export", :name => schedule_name, :file => filename, :export_id => id) do |log| exporter = MysqlExporter.new exporter.export_table self # pass current object to exporter end end
ruby
{ "resource": "" }
q6567
Myreplicator.Export.is_running?
train
def is_running? return false if state != "exporting" begin Process.getpgid(exporter_pid) raise Exceptions::ExportIgnored.new("Ignored") rescue Errno::ESRCH return false end end
ruby
{ "resource": "" }
q6568
Furnish.SSH.run
train
def run(cmd) ret = { :exit_status => 0, :stdout => "", :stderr => "" } port = ssh_args[:port] Net::SSH.start(host, username, ssh_args) do |ssh| ssh.open_channel do |ch| if stdin ch.send_data(stdin) ch.eof! en...
ruby
{ "resource": "" }
q6569
TrackableTasks.TaskRun.run_time_or_time_elapsed
train
def run_time_or_time_elapsed if self.end_time return Time.at(self.end_time - self.start_time) else return Time.at(Time.now - self.start_time) end end
ruby
{ "resource": "" }
q6570
BarkestCore.DatabaseConfig.extra_label
train
def extra_label(index) return nil if index < 1 || index > 5 txt = send("extra_#{index}_label") txt = extra_name(index).to_s.humanize.capitalize if txt.blank? txt end
ruby
{ "resource": "" }
q6571
BarkestCore.DatabaseConfig.extra_field_type
train
def extra_field_type(index) t = extra_type(index).to_s case t when 'password' 'password' when 'integer', 'float' 'number' when 'boolean' 'checkbox' else if t.downcase.index('in:') 'select' else ...
ruby
{ "resource": "" }
q6572
BarkestCore.DatabaseConfig.extra_value
train
def extra_value(index, convert = false) return nil if index < 1 || index > 5 val = send "extra_#{index}_value" if convert case extra_type(index) when 'boolean' BarkestCore::BooleanParser.parse_for_boolean_column(val) when 'integer' BarkestCor...
ruby
{ "resource": "" }
q6573
MailRelay.Base.resend_to
train
def resend_to(destinations) if destinations.size > 0 message.smtp_envelope_to = destinations # Set envelope from and sender to local server to satisfy SPF: # http://www.openspf.org/Best_Practices/Webgenerated message.sender = envelope_sender message.smtp_envelope_from = en...
ruby
{ "resource": "" }
q6574
MailRelay.Base.receiver_from_received_header
train
def receiver_from_received_header if received = message.received received = received.first if received.respond_to?(:first) received.info[/ for .*?([^\s<>]+)@[^\s<>]+/, 1] end end
ruby
{ "resource": "" }
q6575
HttpMonkey.Client::Environment.uri=
train
def uri=(uri) self['SERVER_NAME'] = uri.host self['SERVER_PORT'] = uri.port.to_s self['QUERY_STRING'] = (uri.query || "") self['PATH_INFO'] = (!uri.path || uri.path.empty?) ? "/" : uri.path self['rack.url_scheme'] = uri.scheme self['HTTPS'] = (uri.scheme == "https" ? "on" : "off") ...
ruby
{ "resource": "" }
q6576
HttpMonkey.Client::Environment.uri
train
def uri uri = %Q{#{self['rack.url_scheme']}://#{self['SERVER_NAME']}:#{self['SERVER_PORT']}#{self['REQUEST_URI']}} begin URI.parse(uri) rescue StandardError => e raise ArgumentError, "Invalid #{uri}", e.backtrace end end
ruby
{ "resource": "" }
q6577
Roroacms.Admin::MenusController.edit
train
def edit @menu = Menu.find(params[:id]) # add breadcrumb and set title add_breadcrumb I18n.t("controllers.admin.menus.edit.breadcrumb", menu_name: @menu.name) set_title(I18n.t("controllers.admin.menus.edit.title", menu_name: @menu.name)) end
ruby
{ "resource": "" }
q6578
Roroacms.Admin::MenusController.destroy
train
def destroy @menu = Menu.find(params[:id]) @menu.destroy respond_to do |format| format.html { redirect_to admin_menus_path, notice: I18n.t("controllers.admin.menus.destroy.flash.success") } end end
ruby
{ "resource": "" }
q6579
Chap.Hook.symlink_configs
train
def symlink_configs paths = Dir.glob("#{shared_path}/config/**/*"). select {|p| File.file?(p) } paths.each do |src| relative_path = src.gsub(%r{.*config/},'config/') dest = "#{release_path}/#{relative_path}" # make sure the directory exist for symlink creation ...
ruby
{ "resource": "" }
q6580
MotionMastr.MastrBuilder.apply_attributes
train
def apply_attributes(attributed_string, start, length, styles) return unless attributed_string && start && length && styles # sanity return unless start >= 0 && length > 0 && styles.length > 0 # minimums return unless start + length <= attributed_string.length # maximums range = [start, le...
ruby
{ "resource": "" }
q6581
TransactionReliability.Helpers.with_transaction_retry
train
def with_transaction_retry(options = {}) retry_count = options.fetch(:retry_count, 4) backoff = options.fetch(:backoff, 0.25) exit_on_fail = options.fetch(:exit_on_fail, false) exit_on_disconnect = options.fetch(:exit_on_disconnect, true)...
ruby
{ "resource": "" }
q6582
TransactionReliability.Helpers.transaction_with_retry
train
def transaction_with_retry(txn_options = {}, retry_options = {}) base_obj = self.respond_to?(:transaction) ? self : ActiveRecord::Base with_transaction_retry(retry_options) do base_obj.transaction(txn_options) do yield end end end
ruby
{ "resource": "" }
q6583
GoogleAnymote.TV.connect_to_unit
train
def connect_to_unit puts "Connecting to '#{@host}..." begin tcp_client = TCPSocket.new @host, @port @ssl_client = OpenSSL::SSL::SSLSocket.new tcp_client, @context @ssl_client.connect rescue Exception => e puts "Could not connect to '#{@host}: #{e}" end end
ruby
{ "resource": "" }
q6584
GoogleAnymote.TV.fling_uri
train
def fling_uri(uri) send_request RequestMessage.new(fling_message: Fling.new(uri: uri)) end
ruby
{ "resource": "" }
q6585
GoogleAnymote.TV.send_keycode
train
def send_keycode(keycode) send_request RequestMessage.new(key_event_message: KeyEvent.new(keycode: keycode, action: Action::DOWN)) send_request RequestMessage.new(key_event_message: KeyEvent.new(keycode: keycode, action: Action::UP)) end
ruby
{ "resource": "" }
q6586
GoogleAnymote.TV.send_data
train
def send_data(msg) send_request RequestMessage.new(data_message: Data1.new(type: "com.google.tv.string", data: msg)) end
ruby
{ "resource": "" }
q6587
GoogleAnymote.TV.move_mouse
train
def move_mouse(x_delta, y_delta) send_request RequestMessage.new(mouse_event_message: MouseEvent.new(x_delta: x_delta, y_delta: y_delta)) end
ruby
{ "resource": "" }
q6588
GoogleAnymote.TV.scroll_mouse
train
def scroll_mouse(x_amount, y_amount) send_request RequestMessage.new(mouse_wheel_message: MouseWheel.new(x_scroll: x_amount, y_scroll: y_amount)) end
ruby
{ "resource": "" }
q6589
GoogleAnymote.TV.send_request
train
def send_request(request) message = RemoteMessage.new(request_message: request).serialize_to_string message_size = [message.length].pack('N') @ssl_client.write(message_size + message) end
ruby
{ "resource": "" }
q6590
GoogleAnymote.TV.send_message
train
def send_message(msg) # Build the message and get it's size message = msg.serialize_to_string message_size = [message.length].pack('N') # Try to send the message try_again = true begin data = "" @ssl_client.write(message_size + message) @ssl_client.readpartia...
ruby
{ "resource": "" }
q6591
CabooseStore.CabooseStoreHelper.init_routes
train
def init_routes puts "Adding the caboose store routes..." filename = File.join(@app_path,'config','routes.rb') return if !File.exists?(filename) return if !@force str = "" str << "\t# Catch everything with caboose\n" str << "\tmount CabooseStore::Engine => '/'\n" ...
ruby
{ "resource": "" }
q6592
Cashboard.BadRequest.errors
train
def errors parsed_errors = XmlSimple.xml_in(response.response.body) error_hash = {} parsed_errors['error'].each do |e| error_hash[e['field']] = e['content'] end return error_hash end
ruby
{ "resource": "" }
q6593
Tickspot.Client.clients
train
def clients(options = {}) post("/clients", options)["clients"].map {|obj| Hashie::Mash.new obj } end
ruby
{ "resource": "" }
q6594
Tickspot.Client.projects
train
def projects(options = {}) post("/projects", options)["projects"].map {|obj| Hashie::Mash.new obj } end
ruby
{ "resource": "" }
q6595
Tickspot.Client.tasks
train
def tasks(options = {}) post("/tasks", options)["tasks"].map {|obj| Hashie::Mash.new obj } end
ruby
{ "resource": "" }
q6596
Tickspot.Client.entries
train
def entries(options = {}) post("/entries", options)["entries"].map {|obj| Hashie::Mash.new obj } end
ruby
{ "resource": "" }
q6597
Tickspot.Client.users
train
def users(options = {}) post("/users", options)['users'].map {|obj| Hashie::Mash.new obj } end
ruby
{ "resource": "" }
q6598
BasicCache.TimeCache.cache
train
def cache(key = nil) key ||= BasicCache.caller_name key = key.to_sym if include? key @store[key].value else value = yield @store[key] = TimeCacheItem.new Time.now, value value end end
ruby
{ "resource": "" }
q6599
BasicCache.TimeCache.include?
train
def include?(key = nil) key ||= BasicCache.caller_name key = key.to_sym @store.include?(key) && Time.now - @store[key].stamp < @lifetime end
ruby
{ "resource": "" }