_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q5100
|
ErbLatex.Template.compile_latex
|
train
|
def compile_latex
begin
context = @context.new( @partials_path || @view.dirname, @data )
content = ErbLatex::File.evaluate(@view, context.getBinding)
if layout
ErbLatex::File.evaluate(layout_file, context.getBinding{ content })
else
content
end
rescue LocalJumpError=>e
raise LatexError.new( "ERB compile raised #{e.class} on #{@view}", e.backtrace )
end
end
|
ruby
|
{
"resource": ""
}
|
q5101
|
ErbLatex.Template.execute_xelatex
|
train
|
def execute_xelatex( latex, dir )
success = false
@log = ''
if @packages_path
ENV['TEXINPUTS'] = "#{@packages_path}:"
end
Open3.popen2e( ErbLatex.config.xelatex_path,
"--no-shell-escape", "-shell-restricted",
"-jobname=output", "-output-directory=#{dir}",
) do |stdin, output, wait_thr|
stdin.write latex
stdin.close
@log = output.read.strip
success = ( 0 == wait_thr.value )
end
success
end
|
ruby
|
{
"resource": ""
}
|
q5102
|
SQLTree::Node.UpdateQuery.to_sql
|
train
|
def to_sql(options = {})
sql = "UPDATE #{table.to_sql(options)} SET "
sql << updates.map { |u| u.to_sql(options) }.join(', ')
sql << " WHERE " << where.to_sql(options) if self.where
sql
end
|
ruby
|
{
"resource": ""
}
|
q5103
|
Ldaptic.Entry.attributes
|
train
|
def attributes
(@original_attributes||{}).merge(@attributes).keys.inject({}) do |hash, key|
hash[key] = read_attribute(key)
hash
end
end
|
ruby
|
{
"resource": ""
}
|
q5104
|
Ldaptic.Entry.modify_attribute
|
train
|
def modify_attribute(action, key, *values)
key = Ldaptic.encode(key)
values.flatten!.map! {|v| Ldaptic.encode(v)}
@original_attributes[key] ||= []
virgin = @original_attributes[key].dup
original = Ldaptic::AttributeSet.new(self, key, @original_attributes[key])
original.__send__(action, values)
begin
namespace.modify(dn, [[action, key, values]])
rescue
@original_attributes[key] = virgin
raise $!
end
if @attributes[key]
read_attribute(key).__send__(action, values)
end
self
end
|
ruby
|
{
"resource": ""
}
|
q5105
|
Ldaptic.Entry.method_missing
|
train
|
def method_missing(method, *args, &block)
attribute = Ldaptic.encode(method)
if attribute[-1] == ?=
attribute.chop!
if may_must(attribute)
return write_attribute(attribute, *args, &block)
end
elsif attribute[-1] == ??
attribute.chop!
if may_must(attribute)
if args.empty?
return !read_attribute(attribute).empty?
else
return args.flatten.any? {|arg| compare(attribute, arg)}
end
end
elsif attribute =~ /\A(.*)-before-type-cast\z/ && may_must($1)
return read_attribute($1, *args, &block)
elsif may_must(attribute)
return read_attribute(attribute, *args, &block).one
end
super(method, *args, &block)
end
|
ruby
|
{
"resource": ""
}
|
q5106
|
Ldaptic.Entry.reload
|
train
|
def reload
new = search(:scope => :base, :limit => true)
@original_attributes = new.instance_variable_get(:@original_attributes)
@attributes = new.instance_variable_get(:@attributes)
@dn = Ldaptic::DN(new.dn, self)
@children = {}
self
end
|
ruby
|
{
"resource": ""
}
|
q5107
|
Tableau.TimetableParser.sort_classes
|
train
|
def sort_classes(timetable, classes)
classes.each do |c|
if !(cmodule = timetable.module_for_code(c.code))
cmodule = Tableau::Module.new(c.code)
timetable.push_module(cmodule)
end
cmodule.add_class(c)
end
end
|
ruby
|
{
"resource": ""
}
|
q5108
|
ITunesIngestion.Fetcher.fetch
|
train
|
def fetch(options={})
params = {
:USERNAME => @username, :PASSWORD => @password, :VNDNUMBER => @vadnumber
}
params[:TYPEOFREPORT] = options[:type_of_report] || REPORT_TYPE_SALES
params[:DATETYPE] = options[:date_type] || DATE_TYPE_DAILY
params[:REPORTTYPE] = options[:report_type] || REPORT_SUMMARY
params[:REPORTDATE] = options[:report_date] || (Time.now-60*60*24).strftime("%Y%m%d")
response = RestClient.post BASE_URL, params
if response.headers[:"errormsg"]
raise ITunesConnectError.new response.headers[:"errormsg"]
elsif response.headers[:"filename"]
Zlib::GzipReader.new(StringIO.new(response.body)).read
else
raise "no data returned from itunes: #{response.body}"
end
end
|
ruby
|
{
"resource": ""
}
|
q5109
|
ErbLatex.Context.partial
|
train
|
def partial( template, data={} )
context = self.class.new( @directory, data )
ErbLatex::File.evaluate(Pathname.new(template), context.getBinding, @directory)
end
|
ruby
|
{
"resource": ""
}
|
q5110
|
Languages.ClassData.add_attribute
|
train
|
def add_attribute(pAttribute)
pAttribute.each do |attributeElement|
next unless attributeElement.is_a?(Languages::AttributeData)
@attributes.push(attributeElement)
end
end
|
ruby
|
{
"resource": ""
}
|
q5111
|
WWW.Delicious.bundles_set
|
train
|
def bundles_set(bundle_or_name, tags = [])
params = prepare_bundles_set_params(bundle_or_name, tags)
response = request(API_PATH_BUNDLES_SET, params)
parse_and_eval_execution_response(response.body)
end
|
ruby
|
{
"resource": ""
}
|
q5112
|
WWW.Delicious.tags_rename
|
train
|
def tags_rename(from_name_or_tag, to_name_or_tag)
params = prepare_tags_rename_params(from_name_or_tag, to_name_or_tag)
response = request(API_PATH_TAGS_RENAME, params)
parse_and_eval_execution_response(response.body)
end
|
ruby
|
{
"resource": ""
}
|
q5113
|
WWW.Delicious.posts_recent
|
train
|
def posts_recent(options = {})
params = prepare_posts_params(options.clone, [:count, :tag])
response = request(API_PATH_POSTS_RECENT, params)
parse_post_collection(response.body)
end
|
ruby
|
{
"resource": ""
}
|
q5114
|
WWW.Delicious.posts_all
|
train
|
def posts_all(options = {})
params = prepare_posts_params(options.clone, [:tag])
response = request(API_PATH_POSTS_ALL, params)
parse_post_collection(response.body)
end
|
ruby
|
{
"resource": ""
}
|
q5115
|
WWW.Delicious.posts_dates
|
train
|
def posts_dates(options = {})
params = prepare_posts_params(options.clone, [:tag])
response = request(API_PATH_POSTS_DATES, params)
parse_posts_dates_response(response.body)
end
|
ruby
|
{
"resource": ""
}
|
q5116
|
WWW.Delicious.posts_delete
|
train
|
def posts_delete(url)
params = prepare_posts_params({ :url => url }, [:url])
response = request(API_PATH_POSTS_DELETE, params)
parse_and_eval_execution_response(response.body)
end
|
ruby
|
{
"resource": ""
}
|
q5117
|
WWW.Delicious.init_http_client
|
train
|
def init_http_client(options)
http = Net::HTTP.new(@base_uri.host, 443)
http.use_ssl = true if @base_uri.scheme == "https"
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # FIXME: not 100% supported
self.http_client = http
end
|
ruby
|
{
"resource": ""
}
|
q5118
|
WWW.Delicious.http_build_query
|
train
|
def http_build_query(params = {})
params.collect do |k,v|
"#{URI.encode(k.to_s)}=#{URI.encode(v.to_s)}" unless v.nil?
end.compact.join('&')
end
|
ruby
|
{
"resource": ""
}
|
q5119
|
WWW.Delicious.request
|
train
|
def request(path, params = {})
raise Error, 'Invalid HTTP Client' unless http_client
wait_before_new_request
uri = @base_uri.merge(path)
uri.query = http_build_query(params) unless params.empty?
begin
@last_request = Time.now # see #wait_before_new_request
@last_request_uri = uri # useful for debug
response = make_request(uri)
rescue => e # catch EOFError, SocketError and more
raise HTTPError, e.message
end
case response
when Net::HTTPSuccess
response
when Net::HTTPUnauthorized # 401
raise HTTPError, 'Invalid username or password'
when Net::HTTPServiceUnavailable # 503
raise HTTPError, 'You have been throttled.' +
'Please ensure you are waiting at least one second before each request.'
else
raise HTTPError, "HTTP #{response.code}: #{response.message}"
end
end
|
ruby
|
{
"resource": ""
}
|
q5120
|
WWW.Delicious.make_request
|
train
|
def make_request(uri)
http_client.start do |http|
req = Net::HTTP::Get.new(uri.request_uri, @headers)
req.basic_auth(@username, @password)
http.request(req)
end
end
|
ruby
|
{
"resource": ""
}
|
q5121
|
WWW.Delicious.parse_update_response
|
train
|
def parse_update_response(body)
dom = parse_and_validate_response(body, :root_name => 'update')
dom.root.if_attribute_value(:time) { |v| Time.parse(v) }
end
|
ruby
|
{
"resource": ""
}
|
q5122
|
WWW.Delicious.prepare_tags_rename_params
|
train
|
def prepare_tags_rename_params(from_name_or_tag, to_name_or_tag)
from, to = [from_name_or_tag, to_name_or_tag].collect do |v|
prepare_param_tag(v)
end
{ :old => from, :new => to }
end
|
ruby
|
{
"resource": ""
}
|
q5123
|
WWW.Delicious.prepare_param_post
|
train
|
def prepare_param_post(post_or_values, &block)
post = case post_or_values
when WWW::Delicious::Post
post_or_values
when Hash
Post.new(post_or_values)
else
raise ArgumentError, 'Expected `args` to be `WWW::Delicious::Post` or `Hash`'
end
yield(post) if block_given?
# TODO: validate post with post.validate!
raise ArgumentError, 'Both `url` and `title` are required' unless post.api_valid?
post
end
|
ruby
|
{
"resource": ""
}
|
q5124
|
WWW.Delicious.prepare_param_bundle
|
train
|
def prepare_param_bundle(name_or_bundle, tags = [], &block) # :yields: bundle
bundle = case name_or_bundle
when WWW::Delicious::Bundle
name_or_bundle
else
Bundle.new(:name => name_or_bundle, :tags => tags)
end
yield(bundle) if block_given?
# TODO: validate bundle with bundle.validate!
bundle
end
|
ruby
|
{
"resource": ""
}
|
q5125
|
WWW.Delicious.prepare_param_tag
|
train
|
def prepare_param_tag(name_or_tag, &block) # :yields: tag
tag = case name_or_tag
when WWW::Delicious::Tag
name_or_tag
else
Tag.new(:name => name_or_tag.to_s)
end
yield(tag) if block_given?
# TODO: validate tag with tag.validate!
raise "Invalid `tag` value supplied" unless tag.api_valid?
tag
end
|
ruby
|
{
"resource": ""
}
|
q5126
|
WWW.Delicious.compare_params
|
train
|
def compare_params(params, valid_params)
raise ArgumentError, "Expected `params` to be a kind of `Hash`" unless params.kind_of?(Hash)
raise ArgumentError, "Expected `valid_params` to be a kind of `Array`" unless valid_params.kind_of?(Array)
# compute options difference
difference = params.keys - valid_params
raise Error, "Invalid params: `#{difference.join('`, `')}`" unless difference.empty?
end
|
ruby
|
{
"resource": ""
}
|
q5127
|
Groupon.Client.deals
|
train
|
def deals(query={})
division = query.delete(:division)
query.merge! :client_id => @api_key
path = division ? "/#{division}" : ""
path += "/deals.json"
self.class.get(path, :query => query).deals
end
|
ruby
|
{
"resource": ""
}
|
q5128
|
Sycl.Array.[]=
|
train
|
def []=(*args) # :nodoc:
raise ArgumentError => 'wrong number of arguments' unless args.size > 1
unless args[-1].is_a?(Sycl::Hash) || args[-1].is_a?(Sycl::Array)
args[-1] = Sycl::from_object(args[-1])
end
super
end
|
ruby
|
{
"resource": ""
}
|
q5129
|
Sycl.Hash.[]=
|
train
|
def []=(k, v) # :nodoc:
unless v.is_a?(Sycl::Hash) || v.is_a?(Sycl::Array)
v = Sycl::from_object(v)
end
super
end
|
ruby
|
{
"resource": ""
}
|
q5130
|
StatBoard.GraphHelper.first_day_of
|
train
|
def first_day_of(klass_name)
klass = klass_name.to_s.constantize
klass.order("created_at ASC").first.try(:created_at) || Time.now
end
|
ruby
|
{
"resource": ""
}
|
q5131
|
Magma.Utils.read_file_or_stdin
|
train
|
def read_file_or_stdin(filename = nil)
filename.nil? ? !STDIN.tty? && STDIN.read : File.read(filename)
end
|
ruby
|
{
"resource": ""
}
|
q5132
|
Magma.Utils.run
|
train
|
def run(*args, &block)
return Open3.popen3(*args, &block) if block_given?
Open3.popen3(*args)
end
|
ruby
|
{
"resource": ""
}
|
q5133
|
Magma.Utils.symbolize_keys
|
train
|
def symbolize_keys(hash)
hash.each_with_object({}) { |(k, v), memo| memo[k.to_sym] = v }
end
|
ruby
|
{
"resource": ""
}
|
q5134
|
TCFG.Helper.tcfg_get
|
train
|
def tcfg_get(key)
t_tcfg = tcfg
unless t_tcfg.key? key
raise NoSuchConfigurationKeyError, "No configuration defined for '#{key}'"
end
t_tcfg[key]
end
|
ruby
|
{
"resource": ""
}
|
q5135
|
Languages.LanguageFactory.get_language
|
train
|
def get_language(pType)
pType.downcase!
return Languages::RubySyntax.new if pType == 'ruby'
# if pType == "python"
# raise Error::LanguageError
# end
# if pType == "vhdl"
# raise Error::LanguageError
# end
# if pType == "c"
# raise Error::LanguageError
# end
# if pType == "cplusplus"
# raise Error::LanguageError
# end
# if pType == "java"
# raise Error::LanguageError
# end
# if pType == "assemblyarm"
# raise Error::LanguageError
# end
# if pType == "php"
# raise Error::LanguageError
raise Error::LanguageError
end
|
ruby
|
{
"resource": ""
}
|
q5136
|
JsonRecord.EmbeddedDocumentArray.concat
|
train
|
def concat (objects)
objects = objects.collect do |obj|
obj = @klass.new(obj) if obj.is_a?(Hash)
raise ArgumentError.new("#{obj.inspect} is not a #{@klass}") unless obj.is_a?(@klass)
obj.parent = @parent
obj
end
super(objects)
end
|
ruby
|
{
"resource": ""
}
|
q5137
|
JsonRecord.EmbeddedDocumentArray.build
|
train
|
def build (obj)
obj = @klass.new(obj) if obj.is_a?(Hash)
raise ArgumentError.new("#{obj.inspect} is not a #{@klass}") unless obj.is_a?(@klass)
obj.parent = @parent
self << obj
obj
end
|
ruby
|
{
"resource": ""
}
|
q5138
|
Skydrive.Client.put
|
train
|
def put url, body=nil, options={}
response = filtered_response(self.class.put(url, { :body => body, :query => options, headers: { 'content-type' => ''} }))
end
|
ruby
|
{
"resource": ""
}
|
q5139
|
Skydrive.Client.filtered_response
|
train
|
def filtered_response response
raise Skydrive::Error.new({"code" => "no_response_received", "message" => "Request didn't make through or response not received"}) unless response
if response.success?
filtered_response = response.parsed_response
if response.response.code =~ /(201|200)/
raise Skydrive::Error.new(filtered_response["error"]) if filtered_response["error"]
if filtered_response["data"]
return Skydrive::Collection.new(self, filtered_response["data"])
elsif filtered_response["id"] && (filtered_response["id"].match /^comment\..+/)
return Skydrive::Comment.new(self, filtered_response)
elsif filtered_response["id"] && (filtered_response["id"].match /^file\..+/)
return Skydrive::File.new(self, filtered_response)
elsif filtered_response["type"]
return "Skydrive::#{filtered_response["type"].capitalize}".constantize.new(self, filtered_response)
else
return filtered_response
end
else
return true
end
else
raise Skydrive::Error.new("code" => "http_error_#{response.response.code}", "message" => response.response.message)
end
end
|
ruby
|
{
"resource": ""
}
|
q5140
|
Parser.OutputFactory.get_output
|
train
|
def get_output(pType)
pType.downcase!
return XMLOutputFormat.new if pType == 'xml'
raise Error::ParserError if pType == 'yml'
end
|
ruby
|
{
"resource": ""
}
|
q5141
|
RedisMasterSlave.Client.method_missing
|
train
|
def method_missing(name, *args, &block) # :nodoc:
if writable_master.respond_to?(name)
Client.send(:send_to_master, name)
send(name, *args, &block)
else
super
end
end
|
ruby
|
{
"resource": ""
}
|
q5142
|
PaynetEasy::PaynetEasyApi::Callback.CallbackPrototype.process_callback
|
train
|
def process_callback(payment_transaction, callback_response)
begin
validate_callback payment_transaction, callback_response
rescue Exception => error
payment_transaction.add_error error
payment_transaction.status = PaymentTransaction::STATUS_ERROR
raise error
end
update_payment_transaction payment_transaction, callback_response
if callback_response.error?
raise callback_response.error
end
callback_response
end
|
ruby
|
{
"resource": ""
}
|
q5143
|
PaynetEasy::PaynetEasyApi::Callback.CallbackPrototype.validate_signature
|
train
|
def validate_signature(payment_transaction, callback_response)
expected_control_code = Digest::SHA1.hexdigest(
callback_response.status +
callback_response.payment_paynet_id.to_s +
callback_response.payment_client_id.to_s +
payment_transaction.query_config.signing_key
)
if expected_control_code != callback_response.control_code
raise ValidationError, "Actual control code '#{callback_response.control_code}' does " +
"not equal expected '#{expected_control_code}'"
end
end
|
ruby
|
{
"resource": ""
}
|
q5144
|
PaynetEasy::PaynetEasyApi::Callback.CallbackPrototype.update_payment_transaction
|
train
|
def update_payment_transaction(payment_transaction, callback_response)
payment_transaction.status = callback_response.status
payment_transaction.payment.paynet_id = callback_response.payment_paynet_id
if callback_response.error? || callback_response.declined?
payment_transaction.add_error callback_response.error
end
end
|
ruby
|
{
"resource": ""
}
|
q5145
|
Massimo.UI.report_errors
|
train
|
def report_errors
begin
yield
true
rescue Exception => error
say 'massimo had a problem', :red
indent do
say error.message, :magenta
say error.backtrace.first, :magenta
end
growl "#{error.message}\n#{error.backtrace.first}", 'massimo problem'
false
end
end
|
ruby
|
{
"resource": ""
}
|
q5146
|
FreshdeskAPI.Client.method_missing
|
train
|
def method_missing(method, *args)
method = method.to_s
method_class = method_as_class(method)
options = args.last.is_a?(Hash) ? args.pop : {}
FreshdeskAPI::Collection.new(self, method_class, options)
end
|
ruby
|
{
"resource": ""
}
|
q5147
|
Kuniri.Kuniri.run_analysis
|
train
|
def run_analysis
@filesPathProject = get_project_file(@configurationInfo[:source])
unless @filesPathProject
message = "Problem on source path: #{@configurationInfo[:source]}"
Util::LoggerKuniri.error(message)
return -1
end
@parser = Parser::Parser.new(@filesPathProject,
@configurationInfo[:language])
Util::LoggerKuniri.info('Start parse...')
begin
@parser.start_parser
rescue Error::ConfigurationFileError => e
puts e.message
end
end
|
ruby
|
{
"resource": ""
}
|
q5148
|
GithubPivotalFlow.Publish.run!
|
train
|
def run!
story = @configuration.story
fail("Could not find story associated with branch") unless story
Git.clean_working_tree?
Git.push(story.branch_name, set_upstream: true)
unless story.release?
print "Creating pull-request on Github... "
pull_request_params = story.params_for_pull_request.merge(project: @configuration.project)
@configuration.github_client.create_pullrequest(pull_request_params)
puts 'OK'
end
return 0
end
|
ruby
|
{
"resource": ""
}
|
q5149
|
PaynetEasy::PaynetEasyApi::Query.CreateCardRefQuery.check_payment_transaction_status
|
train
|
def check_payment_transaction_status(payment_transaction)
unless payment_transaction.finished?
raise ValidationError, 'Only finished payment transaction can be used for create-card-ref-id'
end
unless payment_transaction.payment.paid?
raise ValidationError, "Can not use new payment for create-card-ref-id. Execute 'sale' or 'preauth' query first"
end
end
|
ruby
|
{
"resource": ""
}
|
q5150
|
Roomer.Utils.current_tenant=
|
train
|
def current_tenant=(val)
key = :"roomer_current_tenant"
unless Thread.current[key].try(:url_identifier) == val.try(:url_identifier)
Thread.current[key] = val
ensure_tenant_model_reset
end
Thread.current[key]
end
|
ruby
|
{
"resource": ""
}
|
q5151
|
Roomer.Utils.with_tenant
|
train
|
def with_tenant(tenant,&blk)
orig = self.current_tenant
begin
self.current_tenant = tenant
return blk.call(tenant)
ensure
self.current_tenant = orig
end
end
|
ruby
|
{
"resource": ""
}
|
q5152
|
JsonRecord.FieldDefinition.convert
|
train
|
def convert (val)
return nil if val.blank? and val != false
if @type == String
return val.to_s
elsif @type == Integer
return Kernel.Integer(val) rescue val
elsif @type == Float
return Kernel.Float(val) rescue val
elsif @type == Boolean
v = BOOLEAN_MAPPING[val]
v = val.to_s.downcase == 'true' if v.nil? # Check all mixed case spellings for true
return v
elsif @type == Date
if val.is_a?(Date)
return val
elsif val.is_a?(Time)
return val.to_date
else
return Date.parse(val.to_s) rescue val
end
elsif @type == Time
if val.is_a?(Time)
return Time.at((val.to_i / 60) * 60).utc
else
return Time.parse(val).utc rescue val
end
elsif @type == DateTime
if val.is_a?(DateTime)
return val.utc
else
return DateTime.parse(val).utc rescue val
end
elsif @type == Array
val = [val] unless val.is_a?(Array)
raise ArgumentError.new("#{name} must be an Array") unless val.is_a?(Array)
return val
elsif @type == Hash
raise ArgumentError.new("#{name} must be a Hash") unless val.is_a?(Hash)
return val
elsif @type == BigDecimal
return BigDecimal.new(val.to_s)
else
if val.is_a?(@type)
val
elsif val.is_a?(Hash) and (@type < EmbeddedDocument)
return @type.new(val)
else
raise ArgumentError.new("#{name} must be a #{@type}")
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5153
|
GritterNotices::ActiveRecord.InstanceMethods.method_missing
|
train
|
def method_missing(method_name, *args, &block)
if level = ValidMethods[method_name.to_s] or level = ValidMethods["gritter_#{method_name}"]
options = args.extract_options!
options[:level] = level
args << options
gritter_notice *args
else
super(method_name, *args, &block)
end
end
|
ruby
|
{
"resource": ""
}
|
q5154
|
EISCP.Message.get_human_readable_attrs
|
train
|
def get_human_readable_attrs
@zone = Dictionary.zone_from_command(@command)
@command_name = Dictionary.command_to_name(@command)
@command_description = Dictionary.description_from_command(@command)
@value_name = Dictionary.command_value_to_value_name(@command, @value)
@value_description = Dictionary.description_from_command_value(@command, @value)
end
|
ruby
|
{
"resource": ""
}
|
q5155
|
ConfigCurator.PackageLookup.installed?
|
train
|
def installed?(package)
fail LookupFailed, 'No supported package tool found.' if tool.nil?
cmd = tools[tool]
fail LookupFailed, "Package tool '#{cmd}' not found." if command?(cmd).nil?
send tool, package
end
|
ruby
|
{
"resource": ""
}
|
q5156
|
ConfigCurator.PackageLookup.dpkg
|
train
|
def dpkg(package)
cmd = command? 'dpkg'
Open3.popen3 cmd, '-s', package do |_, _, _, wait_thr|
wait_thr.value.to_i == 0
end
end
|
ruby
|
{
"resource": ""
}
|
q5157
|
Mongo.Fixture.check
|
train
|
def check
return @checked if @checked # If already checked, it's alright
raise MissingFixtureError, "No fixture has been loaded, nothing to check" unless @data
raise MissingConnectionError, "No connection has been provided, impossible to check" unless @connection
@data.each_key do |collection|
raise CollectionsNotEmptyError, "The collection '#{collection}' is not empty, all collections should be empty prior to testing" if @connection[collection].count != 0
end
return @checked = true
end
|
ruby
|
{
"resource": ""
}
|
q5158
|
Mongo.Fixture.rollback
|
train
|
def rollback
begin
check
@data.each_key do |collection|
@connection[collection].drop
end
rescue CollectionsNotEmptyError => e
raise RollbackIllegalError, "The collections weren't empty to begin with, rollback aborted."
end
end
|
ruby
|
{
"resource": ""
}
|
q5159
|
Altria.Scheduler.scheduled?
|
train
|
def scheduled?
[:min, :hour, :day, :month, :wday].all? do |key|
send(key).nil? || send(key) == now.send(key)
end
end
|
ruby
|
{
"resource": ""
}
|
q5160
|
AutoExcerpt.Parser.close_tags
|
train
|
def close_tags(text)
# Don't bother closing tags if html is stripped since there are no tags.
if @settings[:strip_html] && @settings[:allowed_tags].empty?
tagstoclose = nil
else
tagstoclose = ""
tags = []
opentags = text.scan(OPENING_TAG).transpose[0] || []
opentags.reverse!
closedtags = text.scan(CLOSING_TAG).transpose[0] || []
opentags.each do |ot|
if closedtags.include?(ot)
closedtags.delete_at(closedtags.index(ot))
else
tags << ot
end
end
tags.each do |tag|
tagstoclose << "</#{tag.strip.downcase}>" unless NO_CLOSE.include?(tag)
end
end
@excerpt = [text, @settings[:ending], tagstoclose].join
end
|
ruby
|
{
"resource": ""
}
|
q5161
|
AutoExcerpt.Parser.paragraphs
|
train
|
def paragraphs
return non_excerpted_text if @pghcount < @settings[:paragraphs]
text = @body.split("</p>").slice(@settings[:skip_paragraphs], @settings[:paragraphs])
@settings[:ending] = nil
text = text.join("</p>")
close_tags(text)
end
|
ruby
|
{
"resource": ""
}
|
q5162
|
AutoExcerpt.Parser.strip_html
|
train
|
def strip_html(html)
return @stripped_html if @stripped_html
allowed = @settings[:allowed_tags]
reg = if allowed.any?
Regexp.new(
%(<(?!(\\s|\\/)*(#{
allowed.map {|tag| Regexp.escape( tag )}.join( "|" )
})( |>|\\/|'|"|<|\\s*\\z))[^>]*(>+|\\s*\\z)),
Regexp::IGNORECASE | Regexp::MULTILINE, 'u'
)
else
/<[^>]*(>+|\s*\z)/m
end
@stripped_html = html.gsub(reg,'')
end
|
ruby
|
{
"resource": ""
}
|
q5163
|
Algebra.SquareMatrix.determinant_by_elimination_old
|
train
|
def determinant_by_elimination_old
m = dup
inv, k = m.left_eliminate!
s = ground.unity
(0...size).each do |i|
s *= m[i, i]
end
s / k
end
|
ruby
|
{
"resource": ""
}
|
q5164
|
Algebra.SquareMatrix.determinant_by_elimination
|
train
|
def determinant_by_elimination
m = dup
det = ground.unity
each_j do |d|
if i = (d...size).find{|i| !m[i, d].zero?}
if i != d
m.sswap_r!(d, i)
det = -det
end
c = m[d, d]
det *= c
(d+1...size).each do |i0|
r = m.row!(i0)
q = ground.unity * m[i0, d] / c #this lets the entries be in ground
(d+1...size).each do |j0|
r[j0] -= q * m[d, j0]
end
end
else
return ground.zero
end
end
det
end
|
ruby
|
{
"resource": ""
}
|
q5165
|
TextTractor.Project.update_blurb
|
train
|
def update_blurb(state, locale, key, value, overwrite = false)
id = key
key = "projects:#{api_key}:#{state}_blurbs:#{key}"
current_value = redis.sismember("projects:#{api_key}:#{state}_blurb_keys", id) ? JSON.parse(redis.get(key)) : {}
phrase = Phrase.new(self, current_value)
# A new value is only written if no previous translation was present, or overwriting is enabled.
if overwrite || phrase[locale].text.nil?
phrase[locale] = value
redis.sadd "projects:#{api_key}:#{state}_blurb_keys", id
redis.sadd "projects:#{api_key}:locales", locale
redis.set key, phrase.to_hash.to_json
redis.set "projects:#{api_key}:#{state}_blurbs_etag", Projects.random_key
end
end
|
ruby
|
{
"resource": ""
}
|
q5166
|
KonoUtils.BaseSearch.get_query_params
|
train
|
def get_query_params
out = {}
search_attributes.each do |val|
out[val.field]=self.send(val.field) unless self.send(val.field).blank?
end
out
end
|
ruby
|
{
"resource": ""
}
|
q5167
|
KonoUtils.BaseSearch.update_attributes
|
train
|
def update_attributes(datas)
search_attributes.each do |val|
self.send("#{val.field}=", val.cast_value(datas[val.field]))
end
end
|
ruby
|
{
"resource": ""
}
|
q5168
|
Mongoid.Criteria.fuse
|
train
|
def fuse(criteria_conditions = {})
criteria_conditions.inject(self) do |criteria, (key, value)|
criteria.send(key, value)
end
end
|
ruby
|
{
"resource": ""
}
|
q5169
|
Mongoid.Criteria.merge
|
train
|
def merge(other)
@selector.update(other.selector)
@options.update(other.options)
@documents = other.documents
end
|
ruby
|
{
"resource": ""
}
|
q5170
|
Mongoid.Criteria.filter_options
|
train
|
def filter_options
page_num = @options.delete(:page)
per_page_num = @options.delete(:per_page)
if (page_num || per_page_num)
@options[:limit] = limits = (per_page_num || 20).to_i
@options[:skip] = (page_num || 1).to_i * limits - limits
end
end
|
ruby
|
{
"resource": ""
}
|
q5171
|
Mongoid.Criteria.update_selector
|
train
|
def update_selector(attributes, operator)
attributes.each { |key, value| @selector[key] = { operator => value } }; self
end
|
ruby
|
{
"resource": ""
}
|
q5172
|
AridCache.Framework.active_record?
|
train
|
def active_record?(*args)
version, comparator = args.pop, (args.pop || :==)
result =
if version.nil?
defined?(::ActiveRecord)
elsif defined?(::ActiveRecord)
ar_version = ::ActiveRecord::VERSION::STRING.to_f
ar_version = ar_version.floor if version.is_a?(Integer)
ar_version.send(comparator, version.to_f)
else
false
end
!!result
end
|
ruby
|
{
"resource": ""
}
|
q5173
|
VulnDBHQ.Client.private_page
|
train
|
def private_page(id, options={})
response = get("/api/private_pages/#{id}", options)
VulnDBHQ::PrivatePage.from_response(response)
end
|
ruby
|
{
"resource": ""
}
|
q5174
|
Substation.Environment.inherit
|
train
|
def inherit(app_env = self.app_env, actions = Dispatcher.new_registry, &block)
self.class.new(app_env, actions, merged_chain_dsl(&block))
end
|
ruby
|
{
"resource": ""
}
|
q5175
|
Substation.Environment.register
|
train
|
def register(name, other = Chain::EMPTY, exception_chain = Chain::EMPTY, &block)
actions[name] = chain(name, other, exception_chain, &block)
self
end
|
ruby
|
{
"resource": ""
}
|
q5176
|
GroupMe.Messages.create_message
|
train
|
def create_message(group_id, text, attachments = [])
data = {
:message => {
:source_guid => SecureRandom.uuid,
:text => text
}
}
data[:message][:attachments] = attachments if attachments.any?
post("/groups/#{group_id}/messages", data).message
end
|
ruby
|
{
"resource": ""
}
|
q5177
|
GroupMe.Messages.messages
|
train
|
def messages(group_id, options = {}, fetch_all = false)
if fetch_all
get_all_messages(group_id)
else
get_messages(group_id, options)
end
end
|
ruby
|
{
"resource": ""
}
|
q5178
|
ConfigCurator.Symlink.install_symlink
|
train
|
def install_symlink
FileUtils.mkdir_p File.dirname(destination_path)
FileUtils.symlink source_path, destination_path, force: true
end
|
ruby
|
{
"resource": ""
}
|
q5179
|
LatoCore.Interface::Layout.core__get_partials_for_module
|
train
|
def core__get_partials_for_module(module_name)
module_configs = core__get_module_configs(module_name)
return [] unless module_configs
# load module items
module_partials = []
if module_configs[:partials]
module_configs[:partials].each do |key, value|
module_partials.push(core__generate_partial(key, value, module_name))
end
end
# return module items
module_partials
end
|
ruby
|
{
"resource": ""
}
|
q5180
|
LatoCore.Interface::Layout.core__generate_partial
|
train
|
def core__generate_partial(key, values, module_name)
partial = {}
partial[:key] = key
partial[:path] = values[:path] ? values[:path] : ''
partial[:position] = values[:position] ? values[:position] : 999
partial
end
|
ruby
|
{
"resource": ""
}
|
q5181
|
LatoCore.Interface::Layout.core__get_widgets_for_module
|
train
|
def core__get_widgets_for_module module_name
module_configs = core__get_module_configs(module_name)
return [] unless module_configs
# load module items
module_widgets = []
if module_configs[:widgets]
module_configs[:widgets].each do |key, value|
module_widgets.push(core__generate_widget(key, value, module_name))
end
end
# return module items
return module_widgets
end
|
ruby
|
{
"resource": ""
}
|
q5182
|
LatoCore.Interface::Layout.core__generate_widget
|
train
|
def core__generate_widget key, values, module_name
widget = {}
widget[:key] = key
widget[:icon] = values[:icon] ? values[:icon] : 'check-circle'
widget[:path] = values[:path] ? values[:path] : ''
widget[:position] = values[:position] ? values[:position] : 999
widget[:title] = values[:title] ? values[:title] : ''
return widget
end
|
ruby
|
{
"resource": ""
}
|
q5183
|
LatoCore.Interface::Layout.core__get_menu_for_module
|
train
|
def core__get_menu_for_module module_name
module_configs = core__get_module_configs(module_name)
return [] unless module_configs
# load module items
module_menu = []
if module_configs[:menu]
module_configs[:menu].each do |key, value|
module_menu.push(core__generate_menu_item(key, value, module_name))
end
end
# return module items
return module_menu
end
|
ruby
|
{
"resource": ""
}
|
q5184
|
LatoCore.Interface::Layout.core__generate_menu_item
|
train
|
def core__generate_menu_item key, values, module_name
menu_item = {}
menu_item[:key] = key
menu_item[:title] = values[:title] ? core__get_menu_title_translation(values[:title], module_name) : 'Undefined'
menu_item[:icon] = values[:icon] ? values[:icon] : 'check-circle'
menu_item[:url] = values[:url] ? values[:url] : ''
menu_item[:position] = values[:position] ? values[:position] : 999
menu_item[:permission_min] = values[:permission_min] ? values[:permission_min] : 0
menu_item[:permission_max] = values[:permission_max] ? values[:permission_max] : 999
menu_item[:sub_items] = []
if values[:sub_items]
values[:sub_items].each do |key, value|
menu_item[:sub_items].push(core__generate_menu_sub_item(key, value, module_name))
end
end
return menu_item
end
|
ruby
|
{
"resource": ""
}
|
q5185
|
LatoCore.Interface::Layout.core__generate_menu_sub_item
|
train
|
def core__generate_menu_sub_item key, values, module_name
menu_sub_item = {}
menu_sub_item[:key] = key
menu_sub_item[:title] = values[:title] ? core__get_menu_title_translation(values[:title], module_name) : 'Undefined'
menu_sub_item[:url] = values[:url] ? values[:url] : ''
menu_sub_item[:permission_min] = values[:permission_min] ? values[:permission_min] : 0
menu_sub_item[:permission_max] = values[:permission_max] ? values[:permission_max] : 999
return menu_sub_item
end
|
ruby
|
{
"resource": ""
}
|
q5186
|
LatoCore.Interface::Layout.core__get_menu_title_translation
|
train
|
def core__get_menu_title_translation title, module_name
return title if (!title.start_with?('translate'))
title_key = core__get_string_inside_strings(title, '[', ']')
module_languages = core__get_module_languages(module_name)
return title if !module_languages || !module_languages[:menu] || !module_languages[:menu][title_key]
return module_languages[:menu][title_key]
end
|
ruby
|
{
"resource": ""
}
|
q5187
|
LatoCore.Interface::Layout.core__get_assets_for_module
|
train
|
def core__get_assets_for_module module_name
module_configs = core__get_module_configs(module_name)
return [] unless module_configs
# load module assets
module_assets = []
if module_configs[:assets]
module_configs[:assets].each do |key, value|
module_assets.push(value)
end
end
# return module assets
return module_assets
end
|
ruby
|
{
"resource": ""
}
|
q5188
|
AzureMediaService.Service.create_access_policy
|
train
|
def create_access_policy(name:'Policy', duration_minutes:300, permission:2)
warn("DEPRECATION WARNING: Service#create_access_policy is deprecated. Use AzureMediaService::AccessPolicy.create() instead.")
post_body = {
"Name" => name,
"DurationInMinutes" => duration_minutes,
"Permissions" => permission
}
res = @request.post("AccessPolicies", post_body)
AccessPolicy.new(res["d"])
end
|
ruby
|
{
"resource": ""
}
|
q5189
|
Chatrix.Room.process_join
|
train
|
def process_join(data)
@state.update data['state'] if data.key? 'state'
@timeline.update data['timeline'] if data.key? 'timeline'
end
|
ruby
|
{
"resource": ""
}
|
q5190
|
Chatrix.Room.process_leave
|
train
|
def process_leave(data)
@state.update data['state'] if data.key? 'state'
@timeline.update data['timeline'] if data.key? 'timeline'
end
|
ruby
|
{
"resource": ""
}
|
q5191
|
Chatrix.Room.process_invite_event
|
train
|
def process_invite_event(event)
return unless event['type'] == 'm.room.member'
return unless event['content']['membership'] == 'invite'
@users.process_invite self, event
sender = @users[event['sender']]
invitee = @users[event['state_key']]
# Return early if the user is already in the room
return if @state.member? invitee
broadcast(:invited, sender, invitee)
end
|
ruby
|
{
"resource": ""
}
|
q5192
|
HungryForm.Resolver.get_value
|
train
|
def get_value(name, element = nil)
return name.call(element) if name.respond_to? :call
# We don't want to mess up elements names
name = name.to_s.dup
# Apply placeholders to the name.
# A sample name string can look like this: page1_group[GROUP_NUMBER]_field
# where [GROUP_NUMBER] is a placeholder. When an element is present
# we get its placeholders and replace substrings in the name argument
element.placeholders.each { |k, v| name[k] &&= v } if element
elements[name].try(:value) || params[name] || name
end
|
ruby
|
{
"resource": ""
}
|
q5193
|
HungryForm.Resolver.resolve_dependency
|
train
|
def resolve_dependency(dependency)
dependency.each do |operator, arguments|
operator = operator.to_sym
case operator
when :and, :or
return resolve_multi_dependency(operator, arguments)
when :not
return !resolve_dependency(arguments)
end
arguments = [arguments] unless arguments.is_a?(Array)
values = arguments[0..1].map { |name| get_value(name) }
return false if values.any?(&:nil?)
case operator
when :eq
return values[0].to_s == values[1].to_s
when :lt
return values[0].to_f < values[1].to_f
when :gt
return values[0].to_f > values[1].to_f
when :set
return !values[0].empty?
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5194
|
HungryForm.Resolver.resolve_multi_dependency
|
train
|
def resolve_multi_dependency(type, arguments)
if arguments.size == 0
fail HungryFormException, "No arguments for #{type.upcase} comparison: #{arguments}"
end
result = type == :and
arguments.each do |argument|
return !result unless resolve_dependency(argument)
end
result
end
|
ruby
|
{
"resource": ""
}
|
q5195
|
Reflexive.Methods.append_ancestor_entry
|
train
|
def append_ancestor_entry(ancestors, ancestor, class_methods, instance_methods = nil)
if class_methods || instance_methods
ancestor_entry = {}
ancestor_entry[:class] = class_methods if class_methods
ancestor_entry[:instance] = instance_methods if instance_methods
ancestors << {ancestor => ancestor_entry}
end
end
|
ruby
|
{
"resource": ""
}
|
q5196
|
LatoCore.Inputs::Select::Cell.get_option_value_selected
|
train
|
def get_option_value_selected(option_value)
if @args[:multiple]
values = @args[:value].is_a?(Array) ? @args[:value] : @args[:value].split(',')
return values.include?(option_value) ? "selected='selected'" : ''
end
@args[:value] == option_value ? "selected='selected'" : ''
end
|
ruby
|
{
"resource": ""
}
|
q5197
|
Biopsy.Target.load_by_name
|
train
|
def load_by_name name
path = self.locate_definition name
raise TargetLoadError.new("Target definition file does not exist for #{name}") if path.nil?
config = YAML::load_file(path)
raise TargetLoadError.new("Target definition file #{path} is not valid YAML") if config.nil?
config = config.deep_symbolize
self.store_config config
self.check_constructor name
self.load_constructor
end
|
ruby
|
{
"resource": ""
}
|
q5198
|
Biopsy.Target.locate_file
|
train
|
def locate_file name
Settings.instance.target_dir.each do |dir|
Dir.chdir File.expand_path(dir) do
return File.expand_path(name) if File.exists? name
end
end
raise TargetLoadError.new("Couldn't find file #{name}")
nil
end
|
ruby
|
{
"resource": ""
}
|
q5199
|
Biopsy.Target.count_parameter_permutations
|
train
|
def count_parameter_permutations
@parameters.each_pair.map{ |k, v| v }.reduce(1) { |n, arr| n * arr.size }
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.