_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q23500
FcrepoWrapper.Instance.status
train
def status return true unless config.managed? return false if pid.nil? begin Process.getpgid(pid) rescue Errno::ESRCH return false end begin TCPSocket.new(host, port).close Net::HTTP.start(host, port) do |http| http.request(Net::HTTP::Get.new('/')) end true rescue Errno::ECONNREFUSED, Errno::EINVAL false end end
ruby
{ "resource": "" }
q23501
FcrepoWrapper.Instance.clean!
train
def clean! stop remove_instance_dir! FileUtils.remove_entry(config.download_path) if File.exists?(config.download_path) FileUtils.remove_entry(config.tmp_save_dir, true) if File.exists? config.tmp_save_dir md5.clean! FileUtils.remove_entry(config.version_file) if File.exists? config.version_file end
ruby
{ "resource": "" }
q23502
FcrepoWrapper.Instance.remove_instance_dir!
train
def remove_instance_dir! FileUtils.remove_entry(config.instance_dir, true) if File.exists? config.instance_dir end
ruby
{ "resource": "" }
q23503
FcrepoWrapper.Instance.extract
train
def extract return config.instance_dir if extracted? jar_file = download FileUtils.mkdir_p config.instance_dir FileUtils.cp jar_file, config.binary_path self.extracted_version = config.version config.instance_dir end
ruby
{ "resource": "" }
q23504
Rbkb::Cli.Executable.exit
train
def exit(ret) @exit_status = ret if defined? Rbkb::Cli::TESTING throw(((ret==0)? :exit_zero : :exit_err), ret) else Kernel.exit(ret) end end
ruby
{ "resource": "" }
q23505
Rbkb::Cli.Executable.add_range_opts
train
def add_range_opts(fkey, lkey) @oparse.on("-r", "--range=START[:END]", "Start and optional end range") do |r| raise "-x and -r are mutually exclusive" if @parser_got_range @parser_got_range=true unless /^(-?[0-9]+)(?::(-?[0-9]+))?$/.match(r) raise "invalid range #{r.inspect}" end @opts[fkey] = $1.to_i @opts[lkey] = $2.to_i if $2 end @oparse.on("-x", "--hexrange=START[:END]", "Start and optional end range in hex") do |r| raise "-x and -r are mutually exclusive" if @parser_got_range @parser_got_range=true unless /^(-?[0-9a-f]+)(?::(-?[0-9a-f]+))?$/i.match(r) raise "invalid range #{r.inspect}" end @opts[fkey] = if ($1[0,1] == '-') ($1[1..-1]).hex_to_num * -1 else $1.hex_to_num end if $2 @opts[lkey] = if($2[0,1] == '-') $2[1..-1].hex_to_num * -1 else $2.hex_to_num end end end end
ruby
{ "resource": "" }
q23506
EwayRapid.RapidClient.create_transaction
train
def create_transaction(payment_method, transaction) unless get_valid? return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), CreateTransactionResponse) end begin case payment_method when Enums::PaymentMethod::DIRECT url = @web_url + Constants::DIRECT_PAYMENT_METHOD_NAME + Constants::JSON_SUFFIX request = Message::TransactionProcess::TransDirectPaymentMsgProcess.create_request(transaction) response = Message::TransactionProcess::TransDirectPaymentMsgProcess.send_request(url, @api_key, @password, @version, request) Message::TransactionProcess::TransDirectPaymentMsgProcess.make_result(response) when Enums::PaymentMethod::RESPONSIVE_SHARED url = @web_url + Constants::RESPONSIVE_SHARED_METHOD_NAME + Constants::JSON_SUFFIX request = Message::TransactionProcess::TransResponsiveSharedMsgProcess.create_request(transaction) response = Message::TransactionProcess::TransResponsiveSharedMsgProcess.send_request(url, @api_key, @password, @version, request) Message::TransactionProcess::TransResponsiveSharedMsgProcess.make_result(response) when Enums::PaymentMethod::TRANSPARENT_REDIRECT url = @web_url + Constants::TRANSPARENT_REDIRECT_METHOD_NAME + Constants::JSON_SUFFIX request = Message::TransactionProcess::TransTransparentRedirectMsgProcess.create_request(transaction) response = Message::TransactionProcess::TransTransparentRedirectMsgProcess.send_request(url, @api_key, @password, @version, request) Message::TransactionProcess::TransTransparentRedirectMsgProcess.make_result(response) when Enums::PaymentMethod::WALLET if transaction.capture url = @web_url + Constants::DIRECT_PAYMENT_METHOD_NAME + Constants::JSON_SUFFIX request = Message::TransactionProcess::TransDirectPaymentMsgProcess.create_request(transaction) response = Message::TransactionProcess::TransDirectPaymentMsgProcess.send_request(url, @api_key, @password, @version, request) Message::TransactionProcess::TransDirectPaymentMsgProcess.make_result(response) else url = @web_url + Constants::CAPTURE_PAYMENT_METHOD request = Message::TransactionProcess::CapturePaymentMsgProcess.create_request(transaction) response = Message::TransactionProcess::CapturePaymentMsgProcess.send_request(url, @api_key, @password, @version, request) Message::TransactionProcess::CapturePaymentMsgProcess.make_result(response) end when Enums::PaymentMethod::AUTHORISATION url = @web_url + Constants::CAPTURE_PAYMENT_METHOD request = Message::TransactionProcess::CapturePaymentMsgProcess.create_request(transaction) response = Message::TransactionProcess::CapturePaymentMsgProcess.send_request(url, @api_key, @password, @version, request) Message::TransactionProcess::CapturePaymentMsgProcess.make_result(response) else make_response_with_exception(Exceptions::ParameterInvalidException.new('Unsupported payment type'), CreateTransactionResponse) end rescue => e @logger.error(e.to_s) if @logger make_response_with_exception(e, CreateTransactionResponse) end end
ruby
{ "resource": "" }
q23507
EwayRapid.RapidClient.query_transaction_by_filter
train
def query_transaction_by_filter(filter) index_of_value = filter.calculate_index_of_value if index_of_value.nil? return make_response_with_exception(Exceptions::APIKeyInvalidException.new('Invalid transaction filter'), QueryTransactionResponse) end case index_of_value when Enums::TransactionFilter::TRANSACTION_ID_INDEX query_transaction_by_id(filter.transaction_id.to_s) when Enums::TransactionFilter::ACCESS_CODE_INDEX query_transaction_by_access_code(filter.access_code) when Enums::TransactionFilter::INVOICE_NUMBER_INDEX query_transaction_with_path(filter.invoice_number, Constants::TRANSACTION_METHOD + '/' + Constants::TRANSACTION_QUERY_WITH_INVOICE_NUM_METHOD) when Enums::TransactionFilter::INVOICE_REFERENCE_INDEX query_transaction_with_path(filter.invoice_reference, Constants::TRANSACTION_METHOD + '/' + Constants::TRANSACTION_QUERY_WITH_INVOICE_REF_METHOD) else make_response_with_exception(Exceptions::APIKeyInvalidException.new('Invalid transaction filter'), QueryTransactionResponse) end end
ruby
{ "resource": "" }
q23508
EwayRapid.RapidClient.refund
train
def refund(refund) unless @is_valid return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), RefundResponse) end begin url = @web_url + Constants::TRANSACTION_METHOD request = Message::RefundProcess::RefundMsgProcess.create_request(refund) response = Message::RefundProcess::RefundMsgProcess.send_request(url, @api_key, @password, @version, request) Message::RefundProcess::RefundMsgProcess.make_result(response) rescue => e @logger.error(e.to_s) if @logger make_response_with_exception(e, RefundResponse) end end
ruby
{ "resource": "" }
q23509
EwayRapid.RapidClient.create_customer
train
def create_customer(payment_method, customer) unless get_valid? return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), CreateCustomerResponse) end begin case payment_method when Enums::PaymentMethod::DIRECT url = @web_url + Constants::DIRECT_PAYMENT_METHOD_NAME + Constants::JSON_SUFFIX request = Message::CustomerProcess::CustDirectPaymentMsgProcess.create_request(customer) response = Message::CustomerProcess::CustDirectPaymentMsgProcess.send_request(url, @api_key, @password, @version, request) Message::CustomerProcess::CustDirectPaymentMsgProcess.make_result(response) when Enums::PaymentMethod::RESPONSIVE_SHARED url = @web_url + Constants::RESPONSIVE_SHARED_METHOD_NAME + Constants::JSON_SUFFIX request = Message::CustomerProcess::CustResponsiveSharedMsgProcess.create_request(customer) response = Message::CustomerProcess::CustResponsiveSharedMsgProcess.send_request(url, @api_key, @password, @version, request) Message::CustomerProcess::CustResponsiveSharedMsgProcess.make_result(response) when Enums::PaymentMethod::TRANSPARENT_REDIRECT url = @web_url + Constants::TRANSPARENT_REDIRECT_METHOD_NAME + Constants::JSON_SUFFIX request = Message::CustomerProcess::CustTransparentRedirectMsgProcess.create_request(customer) response = Message::CustomerProcess::CustTransparentRedirectMsgProcess.send_request(url, @api_key, @password, @version, request) Message::CustomerProcess::CustTransparentRedirectMsgProcess.make_result(response) else make_response_with_exception(Exceptions::ParameterInvalidException.new('Unsupported payment type'), CreateCustomerResponse) end rescue => e @logger.error(e.to_s) if @logger make_response_with_exception(e, CreateCustomerResponse) end end
ruby
{ "resource": "" }
q23510
EwayRapid.RapidClient.update_customer
train
def update_customer(payment_method, customer) unless get_valid? return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), CreateCustomerResponse) end begin case payment_method when Enums::PaymentMethod::DIRECT url = @web_url + Constants::DIRECT_PAYMENT_METHOD_NAME + Constants::JSON_SUFFIX request = Message::CustomerProcess::CustDirectUpdateMsgProcess.create_request(customer) response = Message::CustomerProcess::CustDirectUpdateMsgProcess.send_request(url, @api_key, @password, @version, request) Message::CustomerProcess::CustDirectUpdateMsgProcess.make_result(response) when Enums::PaymentMethod::RESPONSIVE_SHARED url = @web_url + Constants::RESPONSIVE_SHARED_METHOD_NAME + Constants::JSON_SUFFIX request = Message::CustomerProcess::CustResponsiveUpdateMsgProcess.create_request(customer) response = Message::CustomerProcess::CustResponsiveUpdateMsgProcess.send_request(url, @api_key, @password, @version, request) Message::CustomerProcess::CustResponsiveUpdateMsgProcess.make_result(response) when Enums::PaymentMethod::TRANSPARENT_REDIRECT url = @web_url + Constants::TRANSPARENT_REDIRECT_METHOD_NAME + Constants::JSON_SUFFIX request = Message::CustomerProcess::CustTransparentUpdateMsgProcess.create_request(customer) response = Message::CustomerProcess::CustTransparentUpdateMsgProcess.send_request(url, @api_key, @password, @version, request) Message::CustomerProcess::CustTransparentUpdateMsgProcess.make_result(response) else return make_response_with_exception(Exceptions::ParameterInvalidException.new('Unsupported payment type'), CreateCustomerResponse) end rescue => e @logger.error(e.to_s) if @logger make_response_with_exception(e, CreateCustomerResponse) end end
ruby
{ "resource": "" }
q23511
EwayRapid.RapidClient.query_customer
train
def query_customer(token_customer_id) @logger.debug('Query customer with id:' + token_customer_id.to_s) if @logger unless @is_valid return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), QueryCustomerResponse) end begin url = @web_url + Constants::DIRECT_CUSTOMER_SEARCH_METHOD + Constants::JSON_SUFFIX url = URI.encode(url) request = Message::CustomerProcess::QueryCustomerMsgProcess.create_request(token_customer_id.to_s) response = Message::CustomerProcess::QueryCustomerMsgProcess.send_request(url, @api_key, @password, @version, request) Message::CustomerProcess::QueryCustomerMsgProcess.make_result(response) rescue => e @logger.error(e.to_s) if @logger make_response_with_exception(e, QueryCustomerResponse) end end
ruby
{ "resource": "" }
q23512
EwayRapid.RapidClient.settlement_search
train
def settlement_search(search_request) unless @is_valid return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), QueryCustomerResponse) end begin request = Message::TransactionProcess::SettlementSearchMsgProcess.create_request(search_request) url = @web_url + Constants::SETTLEMENT_SEARCH_METHOD + request response = Message::TransactionProcess::SettlementSearchMsgProcess.send_request(url, @api_key, @password, @version) Message::TransactionProcess::SettlementSearchMsgProcess.make_result(response) rescue => e @logger.error(e.to_s) if @logger make_response_with_exception(e, SettlementSearchResponse) end end
ruby
{ "resource": "" }
q23513
EwayRapid.RapidClient.query_transaction_with_path
train
def query_transaction_with_path(request, request_path) unless @is_valid return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), QueryTransactionResponse) end begin if request.nil? || request == '' url = @web_url + request_path + '/' + '0' else url = @web_url + request_path + '/' + request end url = URI.encode(url) response = Message::TransactionProcess::TransQueryMsgProcess.process_post_msg(url, @api_key, @password, @version) Message::TransactionProcess::TransQueryMsgProcess.make_result(response) rescue => e @logger.error(e.to_s) if @logger make_response_with_exception(e, QueryTransactionResponse) end end
ruby
{ "resource": "" }
q23514
EwayRapid.RapidClient.validate_api_param
train
def validate_api_param set_valid(true) if @api_key.nil? || @api_key.empty? || @password.nil? || @password.empty? add_error_code(Constants::API_KEY_INVALID_ERROR_CODE) set_valid(false) end if @rapid_endpoint.nil? || @rapid_endpoint.empty? add_error_code(Constants::LIBRARY_NOT_HAVE_ENDPOINT_ERROR_CODE) set_valid(false) end if @is_valid begin parser_endpoint_to_web_url unless @list_error.nil? @list_error.clear end set_valid(true) @logger.info "Initiate client using [#{@web_url}] successful!" if @logger rescue => e @logger.error "Error setting Rapid endpoint #{e.backtrace.inspect}" if @logger set_valid(false) add_error_code(Constants::LIBRARY_NOT_HAVE_ENDPOINT_ERROR_CODE) end else @logger.warn 'Invalid parameter passed to Rapid client' if @logger end end
ruby
{ "resource": "" }
q23515
EwayRapid.RapidClient.parser_endpoint_to_web_url
train
def parser_endpoint_to_web_url # @type [String] prop_name = nil if Constants::RAPID_ENDPOINT_PRODUCTION.casecmp(@rapid_endpoint).zero? prop_name = Constants::GLOBAL_RAPID_PRODUCTION_REST_URL_PARAM elsif Constants::RAPID_ENDPOINT_SANDBOX.casecmp(@rapid_endpoint).zero? prop_name = Constants::GLOBAL_RAPID_SANDBOX_REST_URL_PARAM end if prop_name.nil? set_web_url(@rapid_endpoint) else property_array = YAML.load_file(File.join(File.dirname(__FILE__), 'resources', 'rapid-api.yml')) property_array.each do |h| if prop_name.casecmp(h.keys.first).zero? set_web_url(h[h.keys.first]) end end if @web_url.nil? fail Exception, "The endpoint #{prop_name} is invalid." end end # verify_endpoint_url(@web_url) # this is unreliable end
ruby
{ "resource": "" }
q23516
EwayRapid.RapidClient.verify_endpoint_url
train
def verify_endpoint_url(web_url) begin resource = RestClient::Resource.new web_url resource.get rescue RestClient::Exception => e if e.http_code == 404 set_valid(false) end end end
ruby
{ "resource": "" }
q23517
WePay.Client.call
train
def call(call, access_token = false, params = {}, risk_token = false, client_ip = false) path = call.start_with?('/') ? call : call.prepend('/') url = URI.parse(api_endpoint + path) call = Net::HTTP::Post.new(url.path, { 'Content-Type' => 'application/json', 'User-Agent' => 'WePay Ruby SDK' }) unless params.empty? call.body = params.to_json end if access_token then call.add_field('Authorization', "Bearer #{access_token}"); end if @api_version then call.add_field('Api-Version', @api_version); end if risk_token then call.add_field('WePay-Risk-Token', risk_token); end if client_ip then call.add_field('Client-IP', client_ip); end make_request(call, url) end
ruby
{ "resource": "" }
q23518
WePay.Client.make_request
train
def make_request(call, url) request = Net::HTTP.new(url.host, url.port) request.read_timeout = 30 request.use_ssl = true response = request.start { |http| http.request(call) } JSON.parse(response.body) end
ruby
{ "resource": "" }
q23519
RailsApiBenchmark.Configuration.all
train
def all instance_variables.inject({}) do |h, v| var = v.to_s.sub('@', '') h.merge(var.to_sym => send(var)) end end
ruby
{ "resource": "" }
q23520
Textoken.Searcher.match_keys
train
def match_keys values.each do |v| Textoken.expression_err("#{v}: is not permitted.") unless yaml.key?(v) add_regexps(yaml[v]) end end
ruby
{ "resource": "" }
q23521
Plex.Season.episode
train
def episode(number) episodes.detect { |epi| epi.index.to_i == number.to_i } end
ruby
{ "resource": "" }
q23522
Marmot.Client.convert
train
def convert input_io, options={} @exception = nil #1 iam "Retrieving cookies... ", false do response = self.class.get '/tools/webfont-generator' @cookies = (response.headers.get_fields("Set-Cookie") || []).join(";") fail "Failed to retrieve cookies" if @cookies.empty? self.class.headers({"Cookie" => @cookies}) @@headers_set = true response end unless @@headers_set #2 iam "Uploading font... " do response = self.class.post '/uploadify/fontfacegen_uploadify.php', :query => { "Filedata" => File.new(input_io) } @path_data = response.body @id, @original_filename = @path_data.split("|") fail "Failed to upload the file. Is it a valid font?" if @id.nil? || @original_filename.nil? response end #3 iam "Confirming upload... " do response = self.class.post "/tools/insert", :query => { "original_filename" => @original_filename, "path_data" => @path_data } json = JSON.parse response.body fail (json["message"] || "Failed to confirm the upload. Is it a valid font?") if !json["name"] || !json["id"] response end #4 iam "Generating webfont... " do custom_options = options.delete :custom_options options[:id] = @id @params = OptionsSanitizer.sanitize(options, custom_options) logger.debug "HTTP Params:\n#{@params.collect{|k,v| "#{k}: #{v.inspect}" }.join("\n")}" response = self.class.post "/tools/generate", :query => @params fail "Failed to generate webfont kit" if !response.body.empty? response end #5 counter = 0 while response = self.class.get("/tools/progress/#{@id}") do p = JSON.parse(response.body)["progress"].to_i logger.info "Progress: #{p} " if p == 100 break elsif p == 0 fail "Progress timeout" if (counter += 1) > 10 end sleep 2 end #6 iam "Downloading fonts... ", false do response = self.class.post "/tools/download", :query => @params end #7 if !options[:output_io] filename = response.headers["Content-Disposition"].gsub(/attachment; filename=\"(.*)\"/,'\1') options[:output_io] = File.new(filename, "wb") end options[:output_io] << response.response.body end
ruby
{ "resource": "" }
q23523
Plex.Client.play_media
train
def play_media(key, user_agent = nil, http_cookies = nil, view_offset = nil) if !key.is_a?(String) && key.respond_to?(:key) key = key.key end url = player_url+'/application/playMedia?' url += "path=#{CGI::escape(server.url+key)}" url += "&key=#{CGI::escape(key)}" url += "&userAgent=#{user_agent}" if user_agent url += "&httpCookies=#{http_cookies}" if http_cookies url += "&viewOffset=#{view_offset}" if view_offset ping url end
ruby
{ "resource": "" }
q23524
Plex.Client.screenshot
train
def screenshot(width, height, quality) url = player_url+'/application/screenshot?' url += "width=#{width}" url += "&height=#{height}" url += "&quality=#{quality}" ping url end
ruby
{ "resource": "" }
q23525
Plex.Show.season
train
def season(number) seasons.detect { |sea| sea.index.to_i == number.to_i } end
ruby
{ "resource": "" }
q23526
Plex.Show.first_season
train
def first_season seasons.inject { |a, b| a.index.to_i < b.index.to_i && a.index.to_i > 0 ? a : b } end
ruby
{ "resource": "" }
q23527
Textoken.Base.tokens
train
def tokens options.collection.each do |option| if @findings.nil? @findings = option.tokenize(self) else @findings &= option.tokenize(self) end end Tokenizer.new(self).tokens end
ruby
{ "resource": "" }
q23528
Orientdb4r.RestClient.gremlin
train
def gremlin(gremlin) raise ArgumentError, 'gremlin query is blank' if blank? gremlin response = call_server(:method => :post, :uri => "command/#{@database}/gremlin/#{CGI::escape(gremlin)}") entries = process_response(response) do raise NotFoundError, 'record not found' if response.body =~ /ORecordNotFoundException/ end rslt = entries['result'] # mixin all document entries (they have '@class' attribute) rslt.each { |doc| doc.extend Orientdb4r::DocumentMetadata unless doc['@class'].nil? } rslt end
ruby
{ "resource": "" }
q23529
Orientdb4r.RestClient.process_response
train
def process_response(response) raise ArgumentError, 'response is null' if response.nil? if block_given? yield end # return code if 401 == response.code raise UnauthorizedError, compose_error_message(response) elsif 500 == response.code raise ServerError, compose_error_message(response) elsif 2 != (response.code / 100) raise OrientdbError, "unexpected return code, code=#{response.code}, body=#{compose_error_message(response)}" end content_type = response.headers[:content_type] if connection_library == :restclient content_type = response.headers['Content-Type'] if connection_library == :excon content_type ||= 'text/plain' rslt = case when content_type.start_with?('text/plain') response.body when content_type.start_with?('application/x-gzip') response.body when content_type.start_with?('application/json') ::JSON.parse(response.body) else raise OrientdbError, "unsuported content type: #{content_type}" end rslt end
ruby
{ "resource": "" }
q23530
Orientdb4r.RestClient.compose_error_message
train
def compose_error_message(http_response, max_len=200) msg = http_response.body.gsub("\n", ' ') msg = "#{msg[0..max_len]} ..." if msg.size > max_len msg end
ruby
{ "resource": "" }
q23531
WLang.Dialect.dialects_for
train
def dialects_for(symbols) info = self.class.tag_dispatching_name(symbols, "_diatag") raise ArgumentError, "No tag for #{symbols}" unless respond_to?(info) send(info) end
ruby
{ "resource": "" }
q23532
WLang.Dialect.render
train
def render(fn, scope = nil, buffer = "") if scope.nil? case fn when String then buffer << fn when Proc then fn.call(self, buffer) when Template then fn.call(@scope, buffer) when TiltTemplate then buffer << fn.render(@scope) else raise ArgumentError, "Unable to render `#{fn}`" end buffer else with_scope(scope){ render(fn, nil, buffer) } end end
ruby
{ "resource": "" }
q23533
WLang.Dialect.evaluate
train
def evaluate(expr, *default, &bl) case expr when Symbol, String catch(:fail) do return scope.evaluate(expr, self, *default, &bl) end raise NameError, "Unable to find `#{expr}` on #{scope}" else evaluate(render(expr), *default, &bl) end end
ruby
{ "resource": "" }
q23534
Forger.Network.security_group_id
train
def security_group_id resp = ec2.describe_security_groups(filters: [ {name: "vpc-id", values: [vpc_id]}, {name: "group-name", values: ["default"]} ]) resp.security_groups.first.group_id end
ruby
{ "resource": "" }
q23535
Sunspot.IndexQueue.process
train
def process count = 0 loop do entries = Entry.next_batch!(self) if entries.nil? || entries.empty? break if Entry.ready_count(self) == 0 else batch = Batch.new(self, entries) if defined?(@batch_handler) && @batch_handler @batch_handler.call(batch) else batch.submit! end count += entries.select{|e| e.processed? }.size end end count end
ruby
{ "resource": "" }
q23536
Orientdb4r.HashExtension.get_mandatory_attribute
train
def get_mandatory_attribute(name) key = name.to_s raise ::ArgumentError, "unknown attribute, name=#{key}" unless self.include? key self[key] end
ruby
{ "resource": "" }
q23537
Orientdb4r.OClass.property
train
def property(name) raise ArgumentError, 'no properties defined on class' if properties.nil? props = properties.select { |i| i['name'] == name.to_s } raise ::ArgumentError, "unknown property, name=#{name}" if props.empty? raise ::ArgumentError, "too many properties found, name=#{name}" if props.size > 1 # just to be sure props[0] end
ruby
{ "resource": "" }
q23538
Orientdb4r.Utils.blank?
train
def blank?(str) str.nil? or (str.is_a? String and str.strip.empty?) end
ruby
{ "resource": "" }
q23539
Forger::Template.Context.load_custom_helpers
train
def load_custom_helpers Dir.glob("#{Forger.root}/app/helpers/**/*_helper.rb").each do |path| filename = path.sub(%r{.*/},'').sub('.rb','') module_name = filename.classify # Prepend a period so require works FORGER_ROOT is set to a relative path # without a period. # # Example: FORGER_ROOT=tmp/project first_char = path[0..0] path = "./#{path}" unless %w[. /].include?(first_char) require path self.class.send :include, module_name.constantize end end
ruby
{ "resource": "" }
q23540
Wayback.Base.attrs
train
def attrs @attrs.inject({}) do |attrs, (key, value)| attrs.merge!(key => respond_to?(key) ? send(key) : value) end end
ruby
{ "resource": "" }
q23541
Orientdb4r.Client.database_exists?
train
def database_exists?(options) rslt = true begin get_database options rescue OrientdbError rslt = false end rslt end
ruby
{ "resource": "" }
q23542
Orientdb4r.Client.class_exists?
train
def class_exists?(name) rslt = true begin get_class name rescue OrientdbError => e raise e if e.is_a? ConnectionError and e.message == 'not connected' # workaround for AOP2 (unable to decorate already existing methods) rslt = false end rslt end
ruby
{ "resource": "" }
q23543
Orientdb4r.Client.drop_class
train
def drop_class(name, options={}) raise ArgumentError, 'class name is blank' if blank?(name) # :mode=>:strict forbids to drop a class that is a super class for other one opt_pattern = { :mode => :nil } verify_options(options, opt_pattern) if :strict == options[:mode] response = get_database children = response['classes'].select { |i| i['superClass'] == name } unless children.empty? raise OrientdbError, "class is super-class, cannot be deleted, name=#{name}" end end command "DROP CLASS #{name}" end
ruby
{ "resource": "" }
q23544
Orientdb4r.Client.create_property
train
def create_property(clazz, property, type, options={}) raise ArgumentError, "class name is blank" if blank?(clazz) raise ArgumentError, "property name is blank" if blank?(property) opt_pattern = { :mandatory => :optional , :notnull => :optional, :min => :optional, :max => :optional, :readonly => :optional, :linked_class => :optional } verify_options(options, opt_pattern) cmd = "CREATE PROPERTY #{clazz}.#{property} #{type.to_s}" # link? if [:link, :linklist, :linkset, :linkmap].include? type.to_s.downcase.to_sym raise ArgumentError, "defined linked-type, but not linked-class" unless options.include? :linked_class cmd << " #{options[:linked_class]}" end command cmd # ALTER PROPERTY ... options.delete :linked_class # it's not option for ALTER unless options.empty? options.each do |k,v| command "ALTER PROPERTY #{clazz}.#{property} #{k.to_s.upcase} #{v}" end end end
ruby
{ "resource": "" }
q23545
Orientdb4r.Client.time_around
train
def time_around(&block) start = Time.now rslt = block.call query_log("#{aop_context[:class].name}##{aop_context[:method]}", "elapsed time = #{Time.now - start} [s]") rslt end
ruby
{ "resource": "" }
q23546
AwesomeXML.ClassMethods.constant_node
train
def constant_node(name, value, options = {}) attr_reader name.to_sym define_method("parse_#{name}".to_sym) do instance_variable_set("@#{name}", value) end register(name, options[:private]) end
ruby
{ "resource": "" }
q23547
AwesomeXML.ClassMethods.node
train
def node(name, type, options = {}, &block) attr_reader name.to_sym options[:local_context] = @local_context xpath = NodeXPath.new(name, options).xpath define_method("parse_#{name}".to_sym) do evaluate_args = [xpath, AwesomeXML::Type.for(type, self.class.name), options] instance_variable_set( "@#{name}", evaluate_nodes(*evaluate_args, &block) ) end register(name, options[:private]) end
ruby
{ "resource": "" }
q23548
WebInspector.Inspector.validate_url_domain
train
def validate_url_domain(u) # Enforce a few bare standards before proceeding u = "#{u}" u = "/" if u.empty? begin # Look for evidence of a host. If this is a relative link # like '/contact', add the page host. domained_url = @host + u unless (u.split("/").first || "").match(/(\:|\.)/) domained_url ||= u # http the URL if it is missing httpped_url = "http://" + domained_url unless domained_url[0..3] == 'http' httpped_url ||= domained_url # Make sure the URL parses uri = URI.parse(httpped_url) # Make sure the URL passes ICANN rules. # The PublicSuffix object splits the domain and subdomain # (unlike URI), which allows more liberal URL matching. return PublicSuffix.parse(uri.host) rescue URI::InvalidURIError, PublicSuffix::DomainInvalid return false end end
ruby
{ "resource": "" }
q23549
Danger.DangerMissedLocalizableStrings.check_localizable_omissions
train
def check_localizable_omissions localizable_files = not_deleted_localizable_files keys_by_file = extract_keys_from_files(localizable_files) entries = localizable_strings_missed_entries(keys_by_file) print_missed_entries entries unless entries.empty? end
ruby
{ "resource": "" }
q23550
Danger.DangerMissedLocalizableStrings.extract_keys_from_files
train
def extract_keys_from_files(localizable_files) keys_from_file = {} localizable_files.each do |file| lines = File.readlines(file) # Grab just the keys, we don't need the translation keys = lines.map { |e| e.split("=").first } # Filter newlines and comments keys = keys.select do |e| e != "\n" && !e.start_with?("/*") && !e.start_with?("//") end keys_from_file[file] = keys end keys_from_file end
ruby
{ "resource": "" }
q23551
OMDB.Client.title
train
def title(title, options = {}) options.merge!(title: title) params = build_params(options) get '/', params end
ruby
{ "resource": "" }
q23552
OMDB.Client.id
train
def id(imdb_id, options = {}) options.merge!(id: imdb_id) params = build_params(options) get '/', params end
ruby
{ "resource": "" }
q23553
OMDB.Client.search
train
def search(title) results = get '/', { s: title } if results[:search] # Return the title if there is only one result, otherwise return the seach results search = results.search search.size == 1 ? title(search[0].title) : search else results end end
ruby
{ "resource": "" }
q23554
OMDB.Client.convert_hash_keys
train
def convert_hash_keys(value) case value when Array value.map { |v| convert_hash_keys(v) } when Hash Hash[value.map { |k, v| [k.to_snake_case.to_sym, convert_hash_keys(v)] }] else value end end
ruby
{ "resource": "" }
q23555
OMDB.Client.build_params
train
def build_params(options) params = {} params[:t] = options[:title] if options[:title] params[:i] = options[:id] if options[:id] params[:y] = options[:year] if options[:year] params[:plot] = options[:plot] if options[:plot] params[:season] = options[:season] if options[:season] params[:episode] = options[:episode] if options[:episode] params[:type] = options[:type] if options[:type] params[:tomatoes] = options[:tomatoes] if options[:tomatoes] params end
ruby
{ "resource": "" }
q23556
Orientdb4r.RestClientNode.transform_error2_response
train
def transform_error2_response(error) response = ["#{error.message}: #{error.http_body}", error.http_code] def response.body self[0] end def response.code self[1] end response end
ruby
{ "resource": "" }
q23557
Orientdb4r.ExconNode.connection
train
def connection return @connection unless @connection.nil? options = {} options[:proxy] = proxy unless proxy.nil? options[:scheme], options[:host], options[:port]=url.scan(/(.*):\/\/(.*):([0-9]*)/).first @connection ||= Excon::Connection.new(options) #:read_timeout => self.class.read_timeout, #:write_timeout => self.class.write_timeout, #:connect_timeout => self.class.connect_timeout end
ruby
{ "resource": "" }
q23558
Orientdb4r.ExconNode.headers
train
def headers(options) rslt = {'Authorization' => basic_auth_header(options[:user], options[:password])} rslt['Cookie'] = "#{SESSION_COOKIE_NAME}=#{session_id}" if !session_id.nil? and !options[:no_session] rslt['Content-Type'] = options[:content_type] if options.include? :content_type rslt['User-Agent'] = user_agent unless user_agent.nil? rslt end
ruby
{ "resource": "" }
q23559
OodAppkit.Configuration.set_default_configuration
train
def set_default_configuration ActiveSupport::Deprecation.warn("The environment variable RAILS_DATAROOT will be deprecated in an upcoming release, please use OOD_DATAROOT instead.") if ENV['RAILS_DATAROOT'] self.dataroot = ENV['OOD_DATAROOT'] || ENV['RAILS_DATAROOT'] self.dataroot ||= "~/#{ENV['OOD_PORTAL'] || "ondemand"}/data/#{ENV['APP_TOKEN']}" if ENV['APP_TOKEN'] # Add markdown template support self.markdown = Redcarpet::Markdown.new( Redcarpet::Render::HTML, autolink: true, tables: true, strikethrough: true, fenced_code_blocks: true, no_intra_emphasis: true ) # Initialize URL handlers for system apps self.public = Urls::Public.new( title: ENV['OOD_PUBLIC_TITLE'] || 'Public Assets', base_url: ENV['OOD_PUBLIC_URL'] || '/public' ) self.dashboard = Urls::Dashboard.new( title: ENV['OOD_DASHBOARD_TITLE'] || 'Open OnDemand', base_url: ENV['OOD_DASHBOARD_URL'] || '/pun/sys/dashboard' ) self.shell = Urls::Shell.new( title: ENV['OOD_SHELL_TITLE'] || 'Shell', base_url: ENV['OOD_SHELL_URL'] || '/pun/sys/shell' ) self.files = Urls::Files.new( title: ENV['OOD_FILES_TITLE'] || 'Files', base_url: ENV['OOD_FILES_URL'] || '/pun/sys/files' ) self.editor = Urls::Editor.new( title: ENV['OOD_EDITOR_TITLE'] || 'Editor', base_url: ENV['OOD_EDITOR_URL'] || '/pun/sys/file-editor' ) # Add routes for useful features self.routes = OpenStruct.new( files_rack_app: true, wiki: true ) # Override Bootstrap SASS variables self.bootstrap = OpenStruct.new( navbar_inverse_bg: '#53565a', navbar_inverse_link_color: '#fff', navbar_inverse_color: '$navbar-inverse-link-color', navbar_inverse_link_hover_color: 'darken($navbar-inverse-link-color, 20%)', navbar_inverse_brand_color: '$navbar-inverse-link-color', navbar_inverse_brand_hover_color: '$navbar-inverse-link-hover-color' ) ENV.each {|k, v| /^BOOTSTRAP_(?<name>.+)$/ =~ k ? self.bootstrap[name.downcase] = v : nil} self.enable_log_formatter = ::Rails.env.production? end
ruby
{ "resource": "" }
q23560
OodAppkit.Configuration.parse_clusters
train
def parse_clusters(config) OodCore::Clusters.load_file(config || '/etc/ood/config/clusters.d') rescue OodCore::ConfigurationNotFound OodCore::Clusters.new([]) end
ruby
{ "resource": "" }
q23561
PandocAbnt.QuadroFilter.convert_to_latex
train
def convert_to_latex(node) latex_code = nil Open3.popen3("pandoc -f json -t latex --wrap=none") {|stdin, stdout, stderr, wait_thr| stdin.write(node.to_json) stdin.close # stdin, stdout and stderr should be closed explicitly in this form. latex_code = stdout.read pid = wait_thr.pid # pid of the started process. exit_status = wait_thr.value # Process::Status object returned. } latex_code end
ruby
{ "resource": "" }
q23562
Naether.Maven.dependencies
train
def dependencies( scopes = nil) if scopes unless scopes.is_a? Array scopes = [scopes] end end if Naether.platform == 'java' if scopes.nil? deps = @project.getDependenciesNotation() else deps = @project.getDependenciesNotation( scopes ) end elsif scopes list = Naether::Java.convert_to_java_list( scopes ) deps = @project._invoke('getDependenciesNotation', 'Ljava.util.List;', list) else deps = @project.getDependenciesNotation() end Naether::Java.convert_to_ruby_array( deps, true ) end
ruby
{ "resource": "" }
q23563
Naether.Maven.invoke
train
def invoke( *opts ) #defaults config = { # Checks ENV for maven home, otherwise defaults /usr/share/maven # XXX: Reuse Eng.getMavenHome? :maven_home => ENV['maven.home'] || ENV['MAVEN_HOME'] || '/usr/share/maven', :local_repo => File.expand_path('~/.m2/repository') } if opts.last.is_a? Hash config = config.merge( opts.pop ) end goals = opts pom = @project.getPomFile().getAbsolutePath() invoker = Naether::Java.create("com.tobedevoured.naether.maven.Invoker", config[:local_repo], config[:maven_home] ) java_list = Naether::Java.convert_to_java_list(goals) if Naether.platform == 'java' invoker.execute( pom, java_list ) else invoker._invoke('execute', 'Ljava.lang.String;Ljava.util.List;', pom, java_list) end end
ruby
{ "resource": "" }
q23564
OVIRT.Client.api_version
train
def api_version return @api_version unless @api_version.nil? xml = http_get("/")/'/api/product_info/version' major = (xml/'version').first[:major] minor = (xml/'version').first[:minor] build = (xml/'version').first[:build] revision = (xml/'version').first[:revision] @api_version = "#{major}.#{minor}.#{build}.#{revision}" end
ruby
{ "resource": "" }
q23565
Rucc.Gen.emit_builtin_reg_class
train
def emit_builtin_reg_class(node) arg = node.args[0] Util.assert!{ arg.ty.kind == Kind::PTR } ty = arg.ty.ptr if ty.kind == Kind::STRUCT emit("mov $2, #eax") elsif Type.is_flotype(ty) emit("mov $1, #eax") else emit("mov $0, #eax") end end
ruby
{ "resource": "" }
q23566
Synced.Model.synced
train
def synced(strategy: :updated_since, **options) options.assert_valid_keys(:associations, :data_key, :fields, :globalized_attributes, :id_key, :include, :initial_sync_since, :local_attributes, :mapper, :only_updated, :remove, :auto_paginate, :transaction_per_page, :delegate_attributes, :query_params, :timestamp_strategy, :handle_processed_objects_proc, :tolerance, :endpoint) class_attribute :synced_id_key, :synced_data_key, :synced_local_attributes, :synced_associations, :synced_only_updated, :synced_mapper, :synced_remove, :synced_include, :synced_fields, :synced_auto_paginate, :synced_transaction_per_page, :synced_globalized_attributes, :synced_initial_sync_since, :synced_delegate_attributes, :synced_query_params, :synced_timestamp_strategy, :synced_strategy, :synced_handle_processed_objects_proc, :synced_tolerance, :synced_endpoint self.synced_strategy = strategy self.synced_id_key = options.fetch(:id_key, :synced_id) self.synced_data_key = options.fetch(:data_key) { synced_column_presence(:synced_data) } self.synced_local_attributes = options.fetch(:local_attributes, []) self.synced_associations = options.fetch(:associations, []) self.synced_only_updated = options.fetch(:only_updated, synced_strategy == :updated_since) self.synced_mapper = options.fetch(:mapper, nil) self.synced_remove = options.fetch(:remove, false) self.synced_include = options.fetch(:include, []) self.synced_fields = options.fetch(:fields, []) self.synced_globalized_attributes = options.fetch(:globalized_attributes, []) self.synced_initial_sync_since = options.fetch(:initial_sync_since, nil) self.synced_delegate_attributes = options.fetch(:delegate_attributes, []) self.synced_query_params = options.fetch(:query_params, {}) self.synced_timestamp_strategy = options.fetch(:timestamp_strategy, nil) self.synced_auto_paginate = options.fetch(:auto_paginate, true) self.synced_transaction_per_page = options.fetch(:transaction_per_page, false) self.synced_handle_processed_objects_proc = options.fetch(:handle_processed_objects_proc, nil) self.synced_tolerance = options.fetch(:tolerance, 0).to_i.abs self.synced_endpoint = options.fetch(:endpoint) { self.to_s.tableize } include Synced::DelegateAttributes include Synced::HasSyncedData end
ruby
{ "resource": "" }
q23567
Synced.Model.synchronize
train
def synchronize(scope: scope_from_relation, strategy: synced_strategy, **options) options.assert_valid_keys(:api, :fields, :include, :remote, :remove, :query_params, :association_sync, :auto_paginate, :transaction_per_page) options[:remove] = synced_remove unless options.has_key?(:remove) options[:include] = Array.wrap(synced_include) unless options.has_key?(:include) options[:fields] = Array.wrap(synced_fields) unless options.has_key?(:fields) options[:query_params] = synced_query_params unless options.has_key?(:query_params) options[:auto_paginate] = synced_auto_paginate unless options.has_key?(:auto_paginate) options[:transaction_per_page] = synced_transaction_per_page unless options.has_key?(:transaction_per_page) options.merge!({ scope: scope, strategy: strategy, id_key: synced_id_key, synced_data_key: synced_data_key, data_key: synced_data_key, local_attributes: synced_local_attributes, associations: synced_associations, only_updated: synced_only_updated, mapper: synced_mapper, globalized_attributes: synced_globalized_attributes, initial_sync_since: synced_initial_sync_since, timestamp_strategy: synced_timestamp_strategy, handle_processed_objects_proc: synced_handle_processed_objects_proc, tolerance: synced_tolerance, synced_endpoint: synced_endpoint }) Synced::Synchronizer.new(self, options).perform end
ruby
{ "resource": "" }
q23568
Synced.Model.reset_synced
train
def reset_synced(scope: scope_from_relation) options = { scope: scope, strategy: synced_strategy, only_updated: synced_only_updated, initial_sync_since: synced_initial_sync_since, timestamp_strategy: synced_timestamp_strategy, synced_endpoint: synced_endpoint } Synced::Synchronizer.new(self, options).reset_synced end
ruby
{ "resource": "" }
q23569
Naether.Runtime.add_remote_repository
train
def add_remote_repository( url, username = nil, password = nil ) if username @resolver.addRemoteRepositoryByUrl( url, username, password ) else @resolver.addRemoteRepositoryByUrl( url ) end end
ruby
{ "resource": "" }
q23570
Naether.Runtime.build_artifacts=
train
def build_artifacts=( artifacts ) @resolver.clearBuildArtifacts() unless artifacts.is_a? Array artifacts = [artifacts] end artifacts.each do |artifact| # Hash of notation => path or notation => { :path =>, :pom => } if artifact.is_a? Hash notation, opts = artifact.shift if opts.is_a? Hash @resolver.add_build_artifact( notation, opts[:path], opts[:pom] ) else @resolver.add_build_artifact( notation, opts ) end else raise "invalid build_artifacts format" end end end
ruby
{ "resource": "" }
q23571
Naether.Runtime.add_pom_dependencies
train
def add_pom_dependencies( pom_path, scopes=['compile'] ) if Naether.platform == 'java' @resolver.addDependencies( pom_path, scopes ) else list = Naether::Java.convert_to_java_list( scopes ) @resolver._invoke( 'addDependencies', 'Ljava.lang.String;Ljava.util.List;', pom_path, list ) end end
ruby
{ "resource": "" }
q23572
Naether.Runtime.dependencies=
train
def dependencies=(dependencies) @resolver.clearDependencies() unless dependencies.is_a? Array dependencies = [dependencies] end dependencies.each do |dependent| # Hash of notation => scope if dependent.is_a? Hash key = dependent.keys.first # Add pom dependencies with scopes if key =~ /\.xml$/i scopes = nil if dependent[key].is_a? Array scopes = dependent[key] else scopes = [dependent[key]] end add_pom_dependencies( key, scopes ) # Add a dependency notation with scopes else add_notation_dependency( key, dependent[key] ) end elsif dependent.is_a? String # Add pom dependencies with default scopes if dependent =~ /\.xml$/i add_pom_dependencies( dependent ) # Add a dependency notation with compile scope else add_notation_dependency( dependent, 'compile' ) end # Add an Aether dependency else add_dependency( dependent ) end end end
ruby
{ "resource": "" }
q23573
Naether.Runtime.dependencies_graph
train
def dependencies_graph(nodes=nil) nodes = @resolver.getDependenciesGraph() unless nodes graph = {} if Naether.platform == 'java' nodes.each do |k,v| deps = dependencies_graph(v) graph[k] = Naether::Java.convert_to_ruby_hash( deps ) end else iterator = nodes.entrySet().iterator(); while iterator.hasNext() entry = iterator.next() deps = dependencies_graph(entry.getValue()) graph[entry.getKey().toString()] = Naether::Java.convert_to_ruby_hash( deps ) end end graph end
ruby
{ "resource": "" }
q23574
Naether.Runtime.load_dependencies_to_classpath
train
def load_dependencies_to_classpath jars = dependencies_classpath.split(File::PATH_SEPARATOR) Naether::Java.load_jars(jars) jars end
ruby
{ "resource": "" }
q23575
Naether.Runtime.to_local_paths
train
def to_local_paths( notations ) if Naether.platform == 'java' Naether::Java.convert_to_ruby_array( Naether::Java.exec_static_method( 'com.tobedevoured.naether.util.Notation', 'getLocalPaths', [local_repo_path, notations ], ['java.lang.String', 'java.util.List'] ) ) else paths = Naether::Java.exec_static_method( 'com.tobedevoured.naether.util.Notation', 'getLocalPaths', [local_repo_path, Naether::Java.convert_to_java_list(notations) ], ['java.lang.String', 'java.util.List'] ) Naether::Java.convert_to_ruby_array( paths, true ) end end
ruby
{ "resource": "" }
q23576
Naether.Runtime.deploy_artifact
train
def deploy_artifact( notation, file_path, url, opts = {} ) artifact = Naether::Java.create( "com.tobedevoured.naether.deploy.DeployArtifact" ) artifact.setRemoteRepo( url ) artifact.setNotation( notation ) artifact.setFilePath( file_path ) if opts[:pom_path] artifact.setPomPath( opts[:pom_path] ) end if opts[:username] || opts[:pub_key] artifact.setAuth(opts[:username], opts[:password], opts[:pub_key], opts[:pub_key_passphrase] ) end if Naether.platform == 'java' @resolver.deployArtifact(artifact) else @resolver._invoke( 'deployArtifact', 'Lcom.tobedevoured.naether.deploy.DeployArtifact;', artifact ) end end
ruby
{ "resource": "" }
q23577
Rucc.Parser.read_int_sval
train
def read_int_sval(s) s = s.downcase if s.match(/^[+-]?0x/) return s.to_i(16) end if s.match(/^[+-]?0b/) return s.to_i(2) end if s.match(/^[+-]?0/) return s.to_i(8) end s.to_i(10) end
ruby
{ "resource": "" }
q23578
Synced.AttributesAsHash.synced_attributes_as_hash
train
def synced_attributes_as_hash(attributes) return attributes if attributes.is_a?(Hash) Hash[Array.wrap(attributes).map { |name| [name, name] }] end
ruby
{ "resource": "" }
q23579
Rucc.Engine.read_from_string
train
def read_from_string(buf) @lexer.stream_stash([FileIO.new(StringIO.new(buf), "-")]) parse.each do |toplevel_ast| @gen.emit_toplevel(toplevel_ast) end @lexer.stream_unstash end
ruby
{ "resource": "" }
q23580
Barcodes.Exec.run
train
def run begin unless self.symbology.nil? unless self.options[:ascii] Barcodes::Renderer::Pdf.new(Barcodes.create(self.symbology, self.options)).render(self.target) else Barcodes::Renderer::Ascii.new(Barcodes.create(self.symbology, self.options)).render(self.target) end end rescue Exception => e puts e.message end end
ruby
{ "resource": "" }
q23581
Barcodes.Exec._init_parser
train
def _init_parser @parser ||= OptionParser.new do |opts| opts.banner = "Usage: barcodes [OPTIONS] symbology target" opts.separator "" opts.on('-D', '--data [DATA]', 'The barcode data to encode (0123456789)') { |v| @options[:data] = v ||= '0123456789' } opts.on('-s', '--start_character [START_CHARACTER]', 'The barcode start character if applicable') { |v| @options[:start_character] = v ||= '' } opts.on('-e', '--stop_character [STOP_CHARACTER]', 'The barcode stop character if applicable') { |v| @options[:stop_character] = v ||= '' } opts.on('-W', '--bar_width [BAR_WIDTH]', 'The barcode bar width in mils (20)') { |v| @options[:bar_width] = v.to_i ||= 20 } opts.on('-H', '--bar_height [BAR_HEIGHT]', 'The barcode bar height in mils (1000)') { |v| @options[:bar_height] = v.to_i ||= 1000 } opts.on('-c', '--caption_height [CAPTION_HEIGHT]', 'The barcode caption height in mils (180)') { |v| @options[:caption_height] = v.to_i ||= 180 } opts.on('-p', '--caption_size [CAPTION_SIZE]', 'The caption font size in mils (167)') { |v| @options[:font_size] = v.to_f ||= 167 } opts.on('-A', '--alpha [ALPHA]', 'The barcode transparency (1.0)') { |v| @options[:alpha] = v.to_f ||= 1.0 } opts.on('-O', '--color [COLOR]', 'The barcode color in hex (000000)') { |v| @options[:color] = v ||= '000000' } opts.on('-a', '--captioned', 'Render barcode caption (true)') { |v| @options[:captioned] = v ||= true } opts.on('-i', '--ascii', 'Render barcode as ASCII string (false)') { |v| @options[:ascii] = v ||= false } opts.on('-v', '--version') { puts self._version; exit } opts.on('-h', '--help') { puts opts; exit } opts.separator "" end end
ruby
{ "resource": "" }
q23582
Barcodes.Exec._parse!
train
def _parse! begin self.parser.parse!(self.argv) rescue puts self.parser.help exit 1 end @symbology = self.argv.shift @target = self.argv.shift end
ruby
{ "resource": "" }
q23583
Ore.CLI.list
train
def list print_template = lambda { |path| puts " #{File.basename(path)}" } say "Builtin templates:", :green Config.builtin_templates(&print_template) say "Installed templates:", :green Config.installed_templates(&print_template) end
ruby
{ "resource": "" }
q23584
Ore.CLI.remove
train
def remove(name) name = File.basename(name) path = File.join(Config::TEMPLATES_DIR,name) unless File.exists?(path) say "Unknown template: #{name}", :red exit -1 end FileUtils.rm_rf(path) end
ruby
{ "resource": "" }
q23585
Ore.Generator.generate
train
def generate self.destination_root = path enable_templates! initialize_variables! extend Template::Helpers::MARKUP.fetch(@markup) unless options.quiet? say "Generating #{self.destination_root}", :green end generate_directories! generate_files! initialize_scm! end
ruby
{ "resource": "" }
q23586
Ore.Generator.enable_template
train
def enable_template(name) name = name.to_sym return false if @enabled_templates.include?(name) unless (template_dir = Template.templates[name]) say "Unknown template #{name}", :red exit -1 end new_template = Template::Directory.new(template_dir) # mark the template as enabled @enabled_templates << name # enable any other templates new_template.enable.each do |sub_template| enable_template(sub_template) end # append the new template to the end of the list, # to override previously loaded templates @templates << new_template # add the template directory to the source-paths self.source_paths << new_template.path return true end
ruby
{ "resource": "" }
q23587
Ore.Generator.disable_template
train
def disable_template(name) name = name.to_sym return false if @disabled_templates.include?(name) if (template_dir = Template.templates[name]) source_paths.delete(template_dir) @templates.delete_if { |template| template.path == template_dir } @enabled_templates.delete(name) end @disabled_templates << name return true end
ruby
{ "resource": "" }
q23588
Ore.Generator.enable_templates!
train
def enable_templates! @templates = [] @enabled_templates = Set[] @disabled_templates = Set[] enable_template :gem # enable the default templates first Options::DEFAULT_TEMPLATES.each do |name| if (Template.template?(name) && options[name]) enable_template(name) end end # enable the templates specified by option options.each do |name,value| if (Template.template?(name) && value) enable_template(name) end end # enable any additionally specified templates options.templates.each { |name| enable_template(name) } # disable any previously enabled templates @templates.reverse_each do |template| template.disable.each { |name| disable_template(name) } end end
ruby
{ "resource": "" }
q23589
Ore.Generator.initialize_variables!
train
def initialize_variables! @root = destination_root @project_dir = File.basename(@root) @name = (options.name || @project_dir) @scm = if File.directory?(File.join(@root,'.git')) then :git elsif File.directory?(File.join(@root,'.hg')) then :hg elsif File.directory?(File.join(@root,'.svn')) then :svn elsif options.hg? then :hg elsif options.git? then :git end case @scm when :git @scm_user = `git config user.name`.chomp @scm_email = `git config user.email`.chomp @github_user = `git config github.user`.chomp when :hg user_email = `hg showconfig ui.username`.chomp user_email.scan(/([^<]+)\s+<([^>]+)>/) do |(user,email)| @scm_user, @scm_email = user, email end end @modules = modules_of(@name) @module_depth = @modules.length @module = @modules.last @namespace = options.namespace || namespace_of(@name) @namespace_dirs = namespace_dirs_of(@name) @namespace_path = namespace_path_of(@name) @namespace_dir = @namespace_dirs.last @version = options.version @summary = options.summary @description = options.description @authors = if options.author || options.author [*options.author, *options.authors] else [@scm_user || ENV['USERNAME'] || ENV['USER'].capitalize] end @author = @authors.first @email = (options.email || @scm_email) @safe_email = @email.sub('@',' at ') if @email @homepage = if options.homepage options.homepage elsif !(@github_user.nil? || @github_user.empty?) "https://github.com/#{@github_user}/#{@name}#readme" else "https://rubygems.org/gems/#{@name}" end @uri = URI(@homepage) @bug_tracker = case @uri.host when 'github.com' "https://#{@uri.host}#{@uri.path}/issues" end @markup = if options.markdown? then :markdown elsif options.textile? then :textile elsif options.markup? then options.markup.to_sym end @markup_ext = Template::Markup::EXT.fetch(@markup) do say "Unknown markup: #{@markup}", :red exit -1 end @date = Date.today @year = @date.year @month = @date.month @day = @date.day @ignore = SortedSet[] @dependencies = {} @development_dependencies = {} @templates.each do |template| @ignore.merge(template.ignore) @dependencies.merge!(template.dependencies) @development_dependencies.merge!(template.development_dependencies) template.variables.each do |name,value| instance_variable_set("@#{name}",value) end end @generated_dirs = {} @generated_files = {} end
ruby
{ "resource": "" }
q23590
Ore.Generator.generate_files!
train
def generate_files! # iterate through the templates in reverse, so files in the templates # loaded last override the previously templates. @templates.reverse_each do |template| # copy in the static files first template.each_file(@markup) do |dest,file| generate_file dest, file end # then render the templates template.each_template(@markup) do |dest,file| generate_file dest, file, template: true end end @generated_files.each_value do |path| dir = path.split(File::SEPARATOR,2).first if dir == 'bin' chmod path, 0755 end end end
ruby
{ "resource": "" }
q23591
Ore.Generator.initialize_scm!
train
def initialize_scm! in_root do case @scm when :git unless File.directory?('.git') run 'git init' run 'git add .' run 'git commit -m "Initial commit."' end when :hg unless File.directory?('.hg') run 'hg init' run 'hg add .' run 'hg commit -m "Initial commit."' end when :svn @ignore.each do |pattern| run "svn propset svn:ignore #{pattern.dump}" end run 'svn add .' run 'svn commit -m "Initial commit."' end end end
ruby
{ "resource": "" }
q23592
Octopress.Deploy.init_config
train
def init_config(options={}) options = options.to_symbol_keys if !options[:method] abort "Please provide a deployment method. e.g. #{METHODS.keys}" end @options = DEFAULT_OPTIONS.deep_merge(options) write_config check_gitignore end
ruby
{ "resource": "" }
q23593
Calyx.Grammar.generate_result
train
def generate_result(*args) start_symbol, rules_map = map_default_args(*args) Result.new(@registry.evaluate(start_symbol, rules_map)) end
ruby
{ "resource": "" }
q23594
VCAP::Services::Base::AsyncJob.Snapshot.service_snapshots
train
def service_snapshots(service_id) return unless service_id res = client.hgetall(redis_key(service_id)) res.values.map{|v| Yajl::Parser.parse(v)} end
ruby
{ "resource": "" }
q23595
VCAP::Services::Base::AsyncJob.Snapshot.snapshot_details
train
def snapshot_details(service_id, snapshot_id) return unless service_id && snapshot_id res = client.hget(redis_key(service_id), snapshot_id) raise ServiceError.new(ServiceError::NOT_FOUND, "snapshot #{snapshot_id}") unless res Yajl::Parser.parse(res) end
ruby
{ "resource": "" }
q23596
VCAP::Services::Base::AsyncJob.Snapshot.filter_keys
train
def filter_keys(snapshot) return unless snapshot.is_a? Hash snapshot.select {|k,v| FILTER_KEYS.include? k.to_s} end
ruby
{ "resource": "" }
q23597
Ore.Actions.generate_dir
train
def generate_dir(dest) return if @generated_dirs.has_key?(dest) path = interpolate(dest) empty_directory path @generated_dirs[dest] = path return path end
ruby
{ "resource": "" }
q23598
Ore.Actions.generate_file
train
def generate_file(dest,file,options={}) return if @generated_files.has_key?(dest) path = interpolate(dest) if options[:template] @current_template_dir = File.dirname(dest) template file, path @current_template_dir = nil else copy_file file, path end @generated_files[dest] = path return path end
ruby
{ "resource": "" }
q23599
Moodle2CC::Moodle2Converter.Migrator.convert_assessments
train
def convert_assessments(quizzes, choices, feedbacks, questionnaires) assessment_converter = Moodle2CC::Moodle2Converter::AssessmentConverter.new assessments = [] assessments += quizzes.map { |quiz| assessment_converter.convert_quiz(quiz) } assessments += choices.map { |choice| assessment_converter.convert_choice(choice) } assessments += feedbacks.map { |feedback| assessment_converter.convert_feedback(feedback) } assessments += questionnaires.map { |questionnaire| assessment_converter.convert_questionnaire(questionnaire) } assessments end
ruby
{ "resource": "" }