_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q3700
SadPanda.Emotion.call
train
def call words = stems_for(remove_stopwords_in(@words)) score_words(frequencies_for(words)) scores.key(scores.values.max) end
ruby
{ "resource": "" }
q3701
SadPanda.Emotion.method_missing
train
def method_missing(emotion) return scores[emotion] || 0 if scores.keys.include? emotion raise NoMethodError, "#{emotion} is not defined" end
ruby
{ "resource": "" }
q3702
SadPanda.Emotion.ambiguous_score
train
def ambiguous_score unq_scores = scores.values.uniq scores[:ambiguous] = 1 if unq_scores.length == 1 && unq_scores.first.zero? end
ruby
{ "resource": "" }
q3703
SadPanda.Emotion.score_emotions
train
def score_emotions(emotion, term, frequency) return unless SadPanda::Bank::EMOTIONS[emotion].include?(term) scores[emotion] += frequency end
ruby
{ "resource": "" }
q3704
SadPanda.Emotion.set_emotions
train
def set_emotions(word, frequency) SadPanda::Bank::EMOTIONS.keys.each do |emotion| score_emotions(emotion, word, frequency) end end
ruby
{ "resource": "" }
q3705
SadPanda.Emotion.score_words
train
def score_words(word_frequencies) word_frequencies.each do |word, frequency| set_emotions(word, frequency) end score_emoticons ambiguous_score end
ruby
{ "resource": "" }
q3706
Autoversion.DSL.parse_file
train
def parse_file path, matcher File.open(path) do |f| f.each do |line| if m = matcher.call(line) return m end end end raise "#{path}: found no matching lines." end
ruby
{ "resource": "" }
q3707
Autoversion.DSL.update_file
train
def update_file path, matcher, currentVersion, nextVersion temp_path = "#{path}.autoversion" begin File.open(path) do |source| File.open(temp_path, 'w') do |target| source.each do |line| if matcher.call(line) target.write line.gsub currentVersion....
ruby
{ "resource": "" }
q3708
Autoversion.DSL.update_files
train
def update_files paths, matcher, currentVersion, nextVersion paths.each do |path| update_file path, matcher, currentVersion, nextVersion end end
ruby
{ "resource": "" }
q3709
RightScale.BundleRunner.echo
train
def echo(options) which = options[:id] ? "with ID #{options[:id].inspect}" : "named #{format_script_name(options[:name])}" scope = options[:scope] == :all ? "'all' servers" : "a 'single' server" where = options[:tags] ? "on #{scope} with tags #{options[:tags].inspect}" : "locally on this server" ...
ruby
{ "resource": "" }
q3710
RightScale.BundleRunner.to_forwarder_options
train
def to_forwarder_options(options) result = {} if options[:tags] result[:tags] = options[:tags] result[:selector] = options[:scope] end if options[:thread] result[:thread] = options[:thread] end if options[:policy] result[:policy] = options[:policy] ...
ruby
{ "resource": "" }
q3711
Ruyml.Data.render
train
def render(template, output = nil) result = ERB.new(File.read(template), 0, '-').result(binding) if !output.nil? File.open(output, "w") do |file| file.write(result) end else puts result end end
ruby
{ "resource": "" }
q3712
Outpost.Application.add_scout
train
def add_scout(scout_description, &block) config = ScoutConfig.new config.instance_eval(&block) scout_description.each do |scout, description| @scouts[scout] << { :description => description, :config => config } end end
ruby
{ "resource": "" }
q3713
Outpost.Application.notify
train
def notify if reports.any? @notifiers.each do |notifier, options| # .dup is NOT reliable options_copy = Marshal.load(Marshal.dump(options)) notifier.new(options_copy).notify(self) end end end
ruby
{ "resource": "" }
q3714
RightScale.AuditProxy.append_output
train
def append_output(text) @mutex.synchronize do @buffer << RightScale::AuditProxy.force_utf8(text) end EM.next_tick do buffer_size = nil @mutex.synchronize do buffer_size = @buffer.size end if buffer_size > MAX_AUDIT_SIZE flush_buffer ...
ruby
{ "resource": "" }
q3715
RightScale.AuditProxy.internal_send_audit
train
def internal_send_audit(options) RightScale::AuditProxy.force_utf8!(options[:text]) opts = { :audit_id => @audit_id, :category => options[:category], :offset => @size } opts[:category] ||= EventCategories::CATEGORY_NOTIFICATION unless EventCategories::CATEGORIES.include?(opts[:category]) ...
ruby
{ "resource": "" }
q3716
RightScale.AuditProxy.flush_buffer
train
def flush_buffer # note we must discard cancelled timer or else we never create a new timer and stay cancelled. if @timer @timer.cancel @timer = nil end to_send = nil @mutex.synchronize do unless @buffer.empty? to_send = @buffer @buffer = '' ...
ruby
{ "resource": "" }
q3717
Emcee.Document.htmlify_except
train
def htmlify_except(nodes) nodes.reduce(to_html) do |output, node| output.gsub(node.to_html, node.to_xhtml) end end
ruby
{ "resource": "" }
q3718
RightScale.Reenroller.run
train
def run(options) check_privileges AgentConfig.root_dir = AgentConfig.right_link_root_dirs if RightScale::Platform.windows? cleanup_certificates(options) # Write state file to indicate to RightScaleService that it should not # enter the rebooting state (which is the default beh...
ruby
{ "resource": "" }
q3719
RightScale.Reenroller.process_running?
train
def process_running?(pid) return false unless pid Process.getpgid(pid) != -1 rescue Errno::ESRCH false end
ruby
{ "resource": "" }
q3720
RightScale.AgentChecker.start
train
def start(options) begin setup_traps @state_serializer = Serializer.new(:json) # Retrieve instance agent configuration options @agent = AgentConfig.agent_options('instance') error("No instance agent configured", nil, abort = true) if @agent.empty? # Apply agent's ...
ruby
{ "resource": "" }
q3721
RightScale.AgentChecker.check
train
def check begin checker_identity = "#{@agent[:identity]}-rchk" pid_file = PidFile.new(checker_identity, @agent[:pid_dir]) if @options[:stop] # Stop checker pid_data = pid_file.read_pid if pid_data[:pid] info("Stopping checker daemon") ...
ruby
{ "resource": "" }
q3722
RightScale.AgentChecker.check_communication
train
def check_communication(attempt, must_try = false) attempt += 1 begin if !must_try && (time = time_since_last_communication) < @options[:time_limit] @retry_timer.cancel if @retry_timer elapsed = elapsed(time) info("Passed communication check with activity as recently as...
ruby
{ "resource": "" }
q3723
RightScale.AgentChecker.time_since_last_communication
train
def time_since_last_communication state_file = @options[:state_path] || File.join(AgentConfig.agent_state_dir, 'state.js') state = @state_serializer.load(File.read(state_file)) if File.file?(state_file) state.nil? ? (@options[:time_limit] + 1) : (Time.now.to_i - state["last_communication"]) end
ruby
{ "resource": "" }
q3724
RightScale.AgentChecker.try_communicating
train
def try_communicating(attempt) begin send_command({:name => "check_connectivity"}, @options[:verbose], COMMAND_IO_TIMEOUT) do |r| @command_io_failures = 0 res = serialize_operation_result(r) rescue nil if res && res.success? info("Successful agent communication" +...
ruby
{ "resource": "" }
q3725
RightScale.AgentChecker.reenroll!
train
def reenroll! unless @reenrolling @reenrolling = true begin info("Triggering re-enroll after unsuccessful communication check", to_console = true) cmd = "rs_reenroll" cmd += " -v" if @options[:verbose] cmd += '&' unless RightScale::Platform.windows? ...
ruby
{ "resource": "" }
q3726
RightScale.AgentChecker.error
train
def error(description, error = nil, abort = false) if @logging_enabled msg = "[check] #{description}" msg += ", aborting" if abort msg = Log.format(msg, error, :trace) if error Log.error(msg) end msg = description msg += ": #{error}" if error puts "** #{msg...
ruby
{ "resource": "" }
q3727
RightScale.AgentChecker.elapsed
train
def elapsed(time) time = time.to_i if time <= MINUTE "#{time} sec" elsif time <= HOUR minutes = time / MINUTE seconds = time - (minutes * MINUTE) "#{minutes} min #{seconds} sec" elsif time <= DAY hours = time / HOUR minutes = (time - (hours * HOUR)...
ruby
{ "resource": "" }
q3728
RightScale.InstanceCommands.run_recipe_command
train
def run_recipe_command(opts) payload = opts[:options] || {} target = {} target[:tags] = payload.delete(:tags) if payload[:tags] target[:scope] = payload.delete(:scope) if payload[:scope] target[:selector] = payload.delete(:selector) if payload[:selector] if (target[:tags] && !target[...
ruby
{ "resource": "" }
q3729
RightScale.InstanceCommands.run_right_script_command
train
def run_right_script_command(opts) payload = opts[:options] || {} target = {} target[:tags] = payload.delete(:tags) if payload[:tags] target[:scope] = payload.delete(:scope) if payload[:scope] target[:selector] = payload.delete(:selector) if payload[:selector] if (target[:tags] && !t...
ruby
{ "resource": "" }
q3730
RightScale.InstanceCommands.send_retryable_request_command
train
def send_retryable_request_command(opts) options = opts[:options] options[:timeout] ||= opts[:timeout] send_retryable_request(opts[:type], opts[:conn], opts[:payload], options) end
ruby
{ "resource": "" }
q3731
RightScale.InstanceCommands.get_instance_state_agent_command
train
def get_instance_state_agent_command(opts) result = RightScale::InstanceState.value CommandIO.instance.reply(opts[:conn], JSON.dump({ :result => result }) ) rescue Exception => e CommandIO.instance.reply(opts[:conn], JSON.dump({ :error => e.message }) ) end
ruby
{ "resource": "" }
q3732
RightScale.InstanceCommands.get_instance_state_run_command
train
def get_instance_state_run_command(opts) value = RightScale::InstanceState.value result = case value when 'booting' "booting#{InstanceState.reboot? ? ':reboot' : ''}" when 'operational', 'stranded' value when 'decommissioning', '...
ruby
{ "resource": "" }
q3733
RightScale.InstanceCommands.get_tags_command
train
def get_tags_command(opts) AgentTagManager.instance.tags(opts) { |tags| CommandIO.instance.reply(opts[:conn], tags) } end
ruby
{ "resource": "" }
q3734
RightScale.InstanceCommands.add_tag_command
train
def add_tag_command(opts) AgentTagManager.instance.add_tags(opts[:tag], opts) do |raw_response| reply = @serializer.dump(raw_response) rescue raw_response CommandIO.instance.reply(opts[:conn], reply) end end
ruby
{ "resource": "" }
q3735
RightScale.InstanceCommands.remove_tag_command
train
def remove_tag_command(opts) AgentTagManager.instance.remove_tags(opts[:tag], opts) do |raw_response| reply = @serializer.dump(raw_response) rescue raw_response CommandIO.instance.reply(opts[:conn], reply) end end
ruby
{ "resource": "" }
q3736
RightScale.InstanceCommands.query_tags_command
train
def query_tags_command(opts) AgentTagManager.instance.query_tags_raw(opts[:tags], opts[:hrefs], opts) do |raw_response| reply = @serializer.dump(raw_response) rescue raw_response CommandIO.instance.reply(opts[:conn], reply) end end
ruby
{ "resource": "" }
q3737
RightScale.InstanceCommands.audit_create_entry_command
train
def audit_create_entry_command(opts) payload = { :agent_identity => @agent_identity, :summary => opts[:summary], :category => opts[:category] || RightScale::EventCategories::NONE, :user_email => opts[:user_email], :detail => opts[:detail] } ...
ruby
{ "resource": "" }
q3738
RightScale.InstanceCommands.audit_update_status_command
train
def audit_update_status_command(opts) AuditCookStub.instance.forward_audit(:update_status, opts[:content], opts[:thread_name], opts[:options]) CommandIO.instance.reply(opts[:conn], 'OK', close_after_writing=false) end
ruby
{ "resource": "" }
q3739
RightScale.InstanceCommands.set_inputs_patch_command
train
def set_inputs_patch_command(opts) payload = {:agent_identity => @agent_identity, :patch => opts[:patch]} send_push("/updater/update_inputs", opts[:conn], payload) CommandIO.instance.reply(opts[:conn], 'OK') end
ruby
{ "resource": "" }
q3740
RightScale.InstanceCommands.send_push
train
def send_push(type, conn, payload = nil, target = nil, options = {}) payload ||= {} payload[:agent_identity] = @agent_identity Sender.instance.send_push(type, payload, target, options) CommandIO.instance.reply(conn, 'OK') true end
ruby
{ "resource": "" }
q3741
RightScale.InstanceCommands.send_request
train
def send_request(type, conn, payload = nil, target = nil, options = {}) payload ||= {} payload[:agent_identity] = @agent_identity Sender.instance.send_request(type, payload, target, options) do |r| reply = @serializer.dump(r) rescue '\"Failed to serialize response\"' CommandIO.instance...
ruby
{ "resource": "" }
q3742
RightScale.InstanceCommands.send_retryable_request
train
def send_retryable_request(type, conn, payload = nil, opts = {}) req = RetryableRequest.new(type, payload, opts) callback = Proc.new do |content| result = OperationResult.success(content) reply = @serializer.dump(result) rescue '\"Failed to serialize response\"' CommandIO.instance.r...
ruby
{ "resource": "" }
q3743
RightScale.InstanceCommands.run_request
train
def run_request(type, conn, payload) payload ||= {} payload[:agent_identity] = @agent_identity Sender.instance.send_request(type, payload) do |r| r = OperationResult.from_results(r) if r && r.success? && r.content.is_a?(RightScale::ExecutableBundle) @scheduler.schedule_bundle...
ruby
{ "resource": "" }
q3744
RightScale.InstanceCommands.get_shutdown_request_command
train
def get_shutdown_request_command(opts) shutdown_request = ShutdownRequest.instance CommandIO.instance.reply(opts[:conn], { :level => shutdown_request.level, :immediately => shutdown_request.immediately? }) rescue Exception => e CommandIO.instance.reply(opts[:conn], { :error => e.message }) end
ruby
{ "resource": "" }
q3745
RightScale.InstanceCommands.set_shutdown_request_command
train
def set_shutdown_request_command(opts) shutdown_request = ShutdownRequest.submit(opts) CommandIO.instance.reply(opts[:conn], { :level => shutdown_request.level, :immediately => shutdown_request.immediately? }) rescue Exception => e CommandIO.instance.reply(opts[:conn], { :error => e.message }) ...
ruby
{ "resource": "" }
q3746
Streamio.Video.add_transcoding
train
def add_transcoding(parameters) response = self.class.resource.post("#{id}/transcodings", parameters) reload response.code.to_i == 201 end
ruby
{ "resource": "" }
q3747
RightScale.ServerImporter.http_get
train
def http_get(path, keep_alive = true) uri = safe_parse_http_uri(path) history = [] loop do Log.debug("http_get(#{uri})") # keep history of live connections for more efficient redirection. host = uri.host connection = Rightscale::HttpConnection.new(:logger => Log, :exce...
ruby
{ "resource": "" }
q3748
RightScale.ServerImporter.safe_parse_http_uri
train
def safe_parse_http_uri(path) raise ArgumentError.new("URI path cannot be empty") if path.to_s.empty? begin uri = URI.parse(path) rescue URI::InvalidURIError => e # URI raises an exception for paths like "<IP>:<port>" # (e.g. "127.0.0.1:123") unless they also have scheme (e.g. ...
ruby
{ "resource": "" }
q3749
Mago.Detector.process_file
train
def process_file(path) code = File.read(path) sexp_node = RubyParser.new.parse(code) file = Mago::RubyFile.new(path) sexp_processor = Mago::SexpProcessor.new(file, @ignore) sexp_processor.process(sexp_node) @report.files << file @on_file.call(file) if @on_file r...
ruby
{ "resource": "" }
q3750
RightScale.ShutdownRequest.process
train
def process(errback = nil, audit = nil, &block) # yield if not shutting down (continuing) or if already requested shutdown. if continue? || @shutdown_scheduled block.call if block return true end # ensure we have an audit, creating a temporary audit if necessary. sender = ...
ruby
{ "resource": "" }
q3751
RightScale.ShutdownRequest.fail
train
def fail(errback, audit, msg, res = nil) if msg.kind_of?(Exception) e = msg detailed = Log.format("Could not process shutdown state #{self}", e, :trace) msg = e.message else detailed = nil end msg += ": #{res.content}" if res && res.content audit.append_erro...
ruby
{ "resource": "" }
q3752
Netzke::Basepack::DataAdapters.ActiveRecordAdapter.predicates_for_and_conditions
train
def predicates_for_and_conditions(conditions) return nil if conditions.empty? predicates = conditions.map do |q| q = HashWithIndifferentAccess.new(Netzke::Support.permit_hash_params(q)) attr = q[:attr] method, assoc = method_and_assoc(attr) arel_table = assoc ? Arel::Table...
ruby
{ "resource": "" }
q3753
RightScale.AuditStub.send_command
train
def send_command(cmd, content, options) begin options ||= {} cmd = { :name => cmd, :content => RightScale::AuditProxy.force_utf8(content), :options => options } EM.next_tick { @agent_connection.send_command(cmd) } rescue Exception => e $stderr.puts 'Failed to audit' $...
ruby
{ "resource": "" }
q3754
Webpacked.Helper.webpacked_tags
train
def webpacked_tags(entries, kind) common_entry = ::Rails.configuration.webpacked.common_entry_name common_bundle = asset_tag(common_entry, kind) page_bundle = Array(entries).reduce('') do |memo, entry| tag = asset_tag(entry, kind) memo << tag if tag end common_bundle ? [com...
ruby
{ "resource": "" }
q3755
Webpacked.Helper.asset_tag
train
def asset_tag(entry, kind) path = webpacked_asset_path(entry, kind) if path case kind when :js then javascript_include_tag path when :css then stylesheet_link_tag path end end end
ruby
{ "resource": "" }
q3756
RightScale.ExecutableSequenceProxy.cook_path
train
def cook_path relative_path = File.join(File.dirname(__FILE__), '..', '..', 'bin', 'cook_runner') return File.normalize_path(relative_path) end
ruby
{ "resource": "" }
q3757
RightScale.ExecutableSequenceProxy.report_failure
train
def report_failure(title, msg=nil) @context.audit.append_error(title, :category => RightScale::EventCategories::CATEGORY_ERROR) @context.audit.append_error(msg) unless msg.nil? @context.succeeded = false fail true end
ruby
{ "resource": "" }
q3758
RightScale::Clouds.Azure.get_updated_userdata
train
def get_updated_userdata(data) result = RightScale::CloudUtilities.parse_rightscale_userdata(data) api_url = "https://#{result['RS_server']}/api" client_id = result['RS_rn_id'] client_secret = result['RS_rn_auth'] new_userdata = retrieve_updated_data(api_url, client_id , client_s...
ruby
{ "resource": "" }
q3759
RightScale.ExternalParameterGatherer.run
train
def run if done? #we might not have ANY external parameters! report_success return true end @audit.create_new_section('Retrieving credentials') #Preflight to check validity of cred objects ok = true @executables_inputs.each_pair do |exe, inputs| inpu...
ruby
{ "resource": "" }
q3760
RightScale.ExternalParameterGatherer.handle_response
train
def handle_response(exe, name, location, response) result = @serializer.load(response) if result.success? if result.content # Since we only ask for one credential at a time, we can do this... secure_document = result.content.first if secure_document.envelope_mime_type...
ruby
{ "resource": "" }
q3761
RightScale.ExternalParameterGatherer.count_remaining
train
def count_remaining count = @executables_inputs.values.map { |a| a.values.count { |p| not p.is_a?(RightScale::SecureDocument) } } return count.inject { |sum,x| sum + x } || 0 end
ruby
{ "resource": "" }
q3762
RightScale.ExternalParameterGatherer.substitute_parameters
train
def substitute_parameters @executables_inputs.each_pair do |exe, inputs| inputs.each_pair do |name, value| case exe when RightScale::RecipeInstantiation exe.attributes[name] = value.content when RightScale::RightScriptInstantiation exe.paramete...
ruby
{ "resource": "" }
q3763
RightScale.ExternalParameterGatherer.report_failure
train
def report_failure(title, message, exception = nil) if exception Log.error("ExternalParameterGatherer failed due to " + "#{exception.class.name}: #{exception.message} (#{exception.backtrace.first})") end @failure_title = title @failure_message = message EM.next...
ruby
{ "resource": "" }
q3764
RightScale.ExternalParameterGatherer.send_retryable_request
train
def send_retryable_request(operation, payload, options = {}, &callback) connection = EM.connect('127.0.0.1', @listen_port, AgentConnection, @cookie, @thread_name, callback) EM.next_tick do connection.send_command(:name => :send_retryable_request, :type => operation, :...
ruby
{ "resource": "" }
q3765
RightScale.CookbookRepoRetriever.should_be_linked?
train
def should_be_linked?(repo_sha, position) @dev_cookbooks.has_key?(repo_sha) && @dev_cookbooks[repo_sha].positions && @dev_cookbooks[repo_sha].positions.detect { |dev_position| dev_position.position == position } end
ruby
{ "resource": "" }
q3766
RightScale.CookbookRepoRetriever.checkout_cookbook_repos
train
def checkout_cookbook_repos(&callback) @dev_cookbooks.each_pair do |repo_sha, dev_repo| repo = dev_repo.to_scraper_hash # get the root dir this repo should be, or was, checked out to repo_dir = @scraper.repo_dir(repo) if File.directory?(repo_dir) # repo was already chec...
ruby
{ "resource": "" }
q3767
RightScale.CookbookRepoRetriever.link
train
def link(repo_sha, position) # symlink to the checked out cookbook only if it was actually checked out if repo_dir = @registered_checkouts[repo_sha] checkout_path = CookbookPathMapping.checkout_path(repo_dir, position) raise ArgumentError.new("Missing directory cannot be linked: #{checkout_p...
ruby
{ "resource": "" }
q3768
RightScale.AgentConnection.send_command
train
def send_command(options) return if @stopped_callback @pending += 1 command = options.dup command[:cookie] = @cookie command[:thread_name] = @thread_name send_data(CommandSerializer.dump(command)) true end
ruby
{ "resource": "" }
q3769
RightScale.AgentConnection.stop
train
def stop(&callback) send_command(:name => :close_connection) @stopped_callback = callback Log.info("[cook] Disconnecting from agent (#{@pending} response#{@pending > 1 ? 's' : ''} pending)") @stop_timeout = EM::Timer.new(STOP_TIMEOUT) do Log.warning("[cook] Time out waiting for responses...
ruby
{ "resource": "" }
q3770
RightScale.LoginUserManager.uuid_to_uid
train
def uuid_to_uid(uuid) uuid = Integer(uuid) if uuid >= 0 && uuid <= MAX_UUID 10_000 + uuid else raise RangeError, "#{uuid} is not within (0..#{MAX_UUID})" end end
ruby
{ "resource": "" }
q3771
RightScale.LoginUserManager.pick_username
train
def pick_username(ideal) name = ideal i = 0 while user_exists?(name) i += 1 name = "#{ideal}_#{i}" end name end
ruby
{ "resource": "" }
q3772
RightScale.LoginUserManager.create_user
train
def create_user(username, uuid, superuser) uid = LoginUserManager.uuid_to_uid(uuid) if uid_exists?(uid, ['rightscale']) username = uid_to_username(uid) elsif !uid_exists?(uid) username = pick_username(username) yield(username) if block_given? add_user(username, uid) ...
ruby
{ "resource": "" }
q3773
RightScale.LoginUserManager.manage_user
train
def manage_user(uuid, superuser, options={}) uid = LoginUserManager.uuid_to_uid(uuid) username = uid_to_username(uid) force = options[:force] || false disable = options[:disable] || false if ( force && uid_exists?(uid) ) || uid_exists?(uid, ['rightscale']) modify_user(use...
ruby
{ "resource": "" }
q3774
RightScale.LoginUserManager.add_user
train
def add_user(username, uid, shell=nil) uid = Integer(uid) shell ||= DEFAULT_SHELLS.detect { |sh| File.exists?(sh) } useradd = find_sbin('useradd') unless shell.nil? dash_s = "-s #{Shellwords.escape(shell)}" end result = sudo("#{useradd} #{dash_s} -u #{uid} -p #{random_pass...
ruby
{ "resource": "" }
q3775
RightScale.LoginUserManager.modify_user
train
def modify_user(username, locked=false, shell=nil) shell ||= DEFAULT_SHELLS.detect { |sh| File.exists?(sh) } usermod = find_sbin('usermod') if locked # the man page claims that "1" works here, but testing proves that it doesn't. # use 1970 instead. dash_e = "-e 1970-01-01 -L"...
ruby
{ "resource": "" }
q3776
RightScale.LoginUserManager.modify_group
train
def modify_group(group, operation, username) #Ensure group/user exist; this raises ArgumentError if either does not exist Etc.getgrnam(group) Etc.getpwnam(username) groups = Set.new Etc.group { |g| groups << g.name if g.mem.include?(username) } case operation when :add ...
ruby
{ "resource": "" }
q3777
RightScale.LoginUserManager.uid_exists?
train
def uid_exists?(uid, groups=[]) uid = Integer(uid) user_exists = Etc.getpwuid(uid).uid == uid if groups.empty? user_belongs = true else mem = Set.new username = Etc.getpwuid(uid).name Etc.group { |g| mem << g.name if g.mem.include?(username) } user_belongs...
ruby
{ "resource": "" }
q3778
RightScale.LoginUserManager.group_exists?
train
def group_exists?(name) groups = Set.new Etc.group { |g| groups << g.name } groups.include?(name) end
ruby
{ "resource": "" }
q3779
RightScale.LoginUserManager.find_sbin
train
def find_sbin(cmd) path = SBIN_PATHS.detect do |dir| File.exists?(File.join(dir, cmd)) end raise RightScale::LoginManager::SystemConflict, "Failed to find a suitable implementation of '#{cmd}'." unless path File.join(path, cmd) end
ruby
{ "resource": "" }
q3780
RightScale.FlatMetadataFormatter.recursive_flatten_metadata
train
def recursive_flatten_metadata(tree_metadata, flat_metadata = {}, metadata_path = [], path_index = 0) unless tree_metadata.empty? tree_metadata.each do |key, value| metadata_path[path_index] = key if value.respond_to?(:has_key?) recursive_flatten_metadata(value, flat_metada...
ruby
{ "resource": "" }
q3781
RightScale.FlatMetadataFormatter.flatten_metadata_path
train
def flatten_metadata_path(metadata_path) flat_path = transform_path(metadata_path) if @formatted_path_prefix && !(flat_path.start_with?(RS_METADATA_PREFIX) || flat_path.start_with?(@formatted_path_prefix)) return @formatted_path_prefix + flat_path end return flat_path end
ruby
{ "resource": "" }
q3782
RightScale.RightScriptsCookbook.script_path
train
def script_path(nickname) base_path = nickname.gsub(/[^0-9a-zA-Z_]/,'_') base_path = File.join(@recipes_dir, base_path) candidate_path = RightScale::Platform.shell.format_script_file_name(base_path) i = 1 path = candidate_path path = candidate_path + (i += 1).to_s while File.exists?(...
ruby
{ "resource": "" }
q3783
RightScale.RightScriptsCookbook.cache_dir
train
def cache_dir(script) # prefix object ID with a text constant to make a legal directory name # in case object id is negative (Ubuntu, etc.). this method will be called # more than once and must return the same directory each time for a given # script instantiation. path = File.normalize_pa...
ruby
{ "resource": "" }
q3784
Yourub.MetaSearch.search
train
def search(criteria) begin @api_options= { :part => 'snippet', :type => 'video', :order => 'relevance', :safeSearch => 'none', } @categories = [] @count_filter = {} @criteria = Yourub::Validator.c...
ruby
{ "resource": "" }
q3785
Yourub.MetaSearch.get_views
train
def get_views(video_id) params = { :id => video_id, :part => 'statistics' } request = Yourub::REST::Videos.list(self,params) v = Yourub::Result.format(request).first v ? Yourub::CountFilter.get_views_count(v) : nil end
ruby
{ "resource": "" }
q3786
Yourub.MetaSearch.get
train
def get(video_id) params = {:id => video_id, :part => 'snippet,statistics'} request = Yourub::REST::Videos.list(self,params) Yourub::Result.format(request).first end
ruby
{ "resource": "" }
q3787
Hamlet.Parser.parse_text_block
train
def parse_text_block(text_indent = nil, from = nil) empty_lines = 0 first_line = true embedded = nil case from when :from_tag first_line = true when :from_embedded embedded = true end close_bracket = false until @lines.empty? if @lines.first...
ruby
{ "resource": "" }
q3788
Emcee.DirectiveProcessor.render
train
def render(context, locals) @context = context @pathname = context.pathname @directory = File.dirname(@pathname) @header = data[HEADER_PATTERN, 0] || "" @body = $' || data # Ensure body ends in a new line @body += "\n" if @body != "" && @body !~ /\n\Z/m @included_pa...
ruby
{ "resource": "" }
q3789
RightScale.SpecHelper.cleanup_state
train
def cleanup_state # intentionally not deleting entire temp dir to preserve localized # executable directories between tests on Windows. see how we reference # RS_RIGHT_RUN_EXE below. delete_if_exists(state_file_path) delete_if_exists(chef_file_path) delete_if_exists(past_scripts_path...
ruby
{ "resource": "" }
q3790
RightScale.SpecHelper.delete_if_exists
train
def delete_if_exists(file) # Windows cannot delete open files, but we only have a path at this point # so it's too late to close the file. report failure to delete files but # otherwise continue without failing test. begin File.delete(file) if File.file?(file) rescue Exception => e...
ruby
{ "resource": "" }
q3791
RightScale.SpecHelper.setup_script_execution
train
def setup_script_execution Dir.glob(File.join(RIGHT_LINK_SPEC_HELPER_TEMP_PATH, '__TestScript*')).should be_empty Dir.glob(File.join(RIGHT_LINK_SPEC_HELPER_TEMP_PATH, '[0-9]*')).should be_empty AgentConfig.cache_dir = File.join(RIGHT_LINK_SPEC_HELPER_TEMP_PATH, 'cache') end
ruby
{ "resource": "" }
q3792
Prowler.Application.verify
train
def verify(api_key = nil) raise ConfigurationError, "You must provide an API key to verify" if api_key.nil? && self.api_key.nil? perform(:verify, { :providerkey => provider_key, :apikey => api_key || self.api_key }, :get, Success) end
ruby
{ "resource": "" }
q3793
PgComment.SchemaDumper.tables_with_comments
train
def tables_with_comments(stream) tables_without_comments(stream) @connection.tables.sort.each do |table_name| dump_comments(table_name, stream) end unless (index_comments = @connection.index_comments).empty? index_comments.each_pair do |index_name, comment| stream.puts...
ruby
{ "resource": "" }
q3794
PgComment.SchemaDumper.dump_comments
train
def dump_comments(table_name, stream) unless (comments = @connection.comments(table_name)).empty? comment_statements = comments.map do |row| column_name = row[0] comment = format_comment(row[1]) if column_name " set_column_comment '#{table_name}', '#{column_name}...
ruby
{ "resource": "" }
q3795
RightScale.CommandHelper.send_command
train
def send_command(cmd, verbose, timeout=20) config_options = ::RightScale::AgentConfig.agent_options('instance') listen_port = config_options[:listen_port] raise ::ArgumentError.new('Could not retrieve agent listen port') unless listen_port client = ::RightScale::CommandClient.new(listen_port, co...
ruby
{ "resource": "" }
q3796
RightScale.CommandHelper.default_logger
train
def default_logger(verbose=false) if verbose logger = Logger.new(STDOUT) logger.level = Logger::DEBUG logger.formatter = PlainLoggerFormatter.new else logger = RightScale::Log end return logger end
ruby
{ "resource": "" }
q3797
RightScale.OhaiRunner.run
train
def run $0 = "rs_ohai" # to prevent showing full path to executalbe in help banner Log.program_name = 'RightLink' init_logger RightScale::OhaiSetup.configure_ohai Ohai::Application.new.run true end
ruby
{ "resource": "" }
q3798
RightScale.VolumeManagementHelper.manage_planned_volumes
train
def manage_planned_volumes(&block) # state may have changed since timer calling this method was added, so # ensure we are still booting (and not stranded). return if InstanceState.value == 'stranded' # query for planned volume mappings belonging to instance. last_mappings = InstanceState....
ruby
{ "resource": "" }
q3799
RightScale.VolumeManagementHelper.detach_planned_volume
train
def detach_planned_volume(mapping) payload = {:agent_identity => @agent_identity, :device_name => mapping[:device_name]} Log.info("Detaching volume #{mapping[:volume_id]} for management purposes.") req = RetryableRequest.new("/storage_valet/detach_volume", payload, :retry_delay => VolumeManagement::VO...
ruby
{ "resource": "" }