_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....
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....
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 ran...
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::Payme...
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::T...
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:...
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:...
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:...
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 ...
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::SettlementSearchMsgProce...
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 == '' u...
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_...
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 = ...
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
{ "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? ...
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 += "&u...
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 =~ /ORe...
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 rai...
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 ...
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(ba...
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.s...
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. # ...
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...
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, :r...
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_v...
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 || "").mat...
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...
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[:se...
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 => se...
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 rsl...
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_POR...
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_...
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( s...
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') } ...
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_versio...
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_param...
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[:in...
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, ...
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 = art...
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 ) ...
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...
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 =...
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....
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( o...
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.targ...
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...
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...
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 templat...
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) ...
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_t...
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 Fil...
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, fil...
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' ...
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 ...
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_convert...
ruby
{ "resource": "" }