repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
williambarry007/caboose-cms | app/controllers/caboose/application_controller.rb | Caboose.ApplicationController.validate_token | def validate_token
token = params[:token]
return false if token.nil?
user = User.validate_token(token)
return false if user.nil?
login_user(user)
return true
end | ruby | def validate_token
token = params[:token]
return false if token.nil?
user = User.validate_token(token)
return false if user.nil?
login_user(user)
return true
end | [
"def",
"validate_token",
"token",
"=",
"params",
"[",
":token",
"]",
"return",
"false",
"if",
"token",
".",
"nil?",
"user",
"=",
"User",
".",
"validate_token",
"(",
"token",
")",
"return",
"false",
"if",
"user",
".",
"nil?",
"login_user",
"(",
"user",
")",
"return",
"true",
"end"
]
| Checks to see if a token is given. If so, it tries to validate the token
and log the user in. | [
"Checks",
"to",
"see",
"if",
"a",
"token",
"is",
"given",
".",
"If",
"so",
"it",
"tries",
"to",
"validate",
"the",
"token",
"and",
"log",
"the",
"user",
"in",
"."
]
| 7c112911318f94cc89dba86091903a3acaf0a833 | https://github.com/williambarry007/caboose-cms/blob/7c112911318f94cc89dba86091903a3acaf0a833/app/controllers/caboose/application_controller.rb#L164-L173 | train |
williambarry007/caboose-cms | app/controllers/caboose/application_controller.rb | Caboose.ApplicationController.validate_cookie | def validate_cookie
if cookies[:caboose_user_id]
user = User.where(:id => cookies[:caboose_user_id]).first
if user
login_user(user)
return true
end
end
return false
end | ruby | def validate_cookie
if cookies[:caboose_user_id]
user = User.where(:id => cookies[:caboose_user_id]).first
if user
login_user(user)
return true
end
end
return false
end | [
"def",
"validate_cookie",
"if",
"cookies",
"[",
":caboose_user_id",
"]",
"user",
"=",
"User",
".",
"where",
"(",
":id",
"=>",
"cookies",
"[",
":caboose_user_id",
"]",
")",
".",
"first",
"if",
"user",
"login_user",
"(",
"user",
")",
"return",
"true",
"end",
"end",
"return",
"false",
"end"
]
| Checks to see if a remember me cookie value is present. | [
"Checks",
"to",
"see",
"if",
"a",
"remember",
"me",
"cookie",
"value",
"is",
"present",
"."
]
| 7c112911318f94cc89dba86091903a3acaf0a833 | https://github.com/williambarry007/caboose-cms/blob/7c112911318f94cc89dba86091903a3acaf0a833/app/controllers/caboose/application_controller.rb#L176-L185 | train |
williambarry007/caboose-cms | app/controllers/caboose/application_controller.rb | Caboose.ApplicationController.reject_param | def reject_param(url, param)
arr = url.split('?')
return url if (arr.count == 1)
qs = arr[1].split('&').reject { |pair| pair.split(/[=;]/).first == param }
url2 = arr[0]
url2 += "?" + qs.join('&') if qs.count > 0
return url2
end | ruby | def reject_param(url, param)
arr = url.split('?')
return url if (arr.count == 1)
qs = arr[1].split('&').reject { |pair| pair.split(/[=;]/).first == param }
url2 = arr[0]
url2 += "?" + qs.join('&') if qs.count > 0
return url2
end | [
"def",
"reject_param",
"(",
"url",
",",
"param",
")",
"arr",
"=",
"url",
".",
"split",
"(",
"'?'",
")",
"return",
"url",
"if",
"(",
"arr",
".",
"count",
"==",
"1",
")",
"qs",
"=",
"arr",
"[",
"1",
"]",
".",
"split",
"(",
"'&'",
")",
".",
"reject",
"{",
"|",
"pair",
"|",
"pair",
".",
"split",
"(",
"/",
"/",
")",
".",
"first",
"==",
"param",
"}",
"url2",
"=",
"arr",
"[",
"0",
"]",
"url2",
"+=",
"\"?\"",
"+",
"qs",
".",
"join",
"(",
"'&'",
")",
"if",
"qs",
".",
"count",
">",
"0",
"return",
"url2",
"end"
]
| Removes a given parameter from a URL querystring | [
"Removes",
"a",
"given",
"parameter",
"from",
"a",
"URL",
"querystring"
]
| 7c112911318f94cc89dba86091903a3acaf0a833 | https://github.com/williambarry007/caboose-cms/blob/7c112911318f94cc89dba86091903a3acaf0a833/app/controllers/caboose/application_controller.rb#L270-L277 | train |
williambarry007/caboose-cms | app/controllers/caboose/application_controller.rb | Caboose.ApplicationController.under_construction_or_forwarding_domain? | def under_construction_or_forwarding_domain?
d = Caboose::Domain.where(:domain => request.host_with_port).first
if d.nil?
Caboose.log("Could not find domain for #{request.host_with_port}\nAdd this domain to the caboose site.")
elsif d.under_construction == true
if d.site.under_construction_html && d.site.under_construction_html.strip.length > 0
render :text => d.site.under_construction_html
else
render :file => 'caboose/application/under_construction', :layout => false
end
return true
# See if we're on a forwarding domain
elsif d.primary == false && d.forward_to_primary == true
pd = d.site.primary_domain
if pd && pd.domain != request.host
url = "#{request.protocol}#{pd.domain}"
if d.forward_to_uri && d.forward_to_uri.strip.length > 0
url << d.forward_to_uri
elsif request.fullpath && request.fullpath.strip.length > 0 && request.fullpath.strip != '/'
url << request.fullpath
end
redirect_to url
return true
end
# Check for a 301 redirect
else
new_url = PermanentRedirect.match(@site.id, request.fullpath)
if new_url
redirect_to new_url, :status => 301
return true
end
end
return false
end | ruby | def under_construction_or_forwarding_domain?
d = Caboose::Domain.where(:domain => request.host_with_port).first
if d.nil?
Caboose.log("Could not find domain for #{request.host_with_port}\nAdd this domain to the caboose site.")
elsif d.under_construction == true
if d.site.under_construction_html && d.site.under_construction_html.strip.length > 0
render :text => d.site.under_construction_html
else
render :file => 'caboose/application/under_construction', :layout => false
end
return true
# See if we're on a forwarding domain
elsif d.primary == false && d.forward_to_primary == true
pd = d.site.primary_domain
if pd && pd.domain != request.host
url = "#{request.protocol}#{pd.domain}"
if d.forward_to_uri && d.forward_to_uri.strip.length > 0
url << d.forward_to_uri
elsif request.fullpath && request.fullpath.strip.length > 0 && request.fullpath.strip != '/'
url << request.fullpath
end
redirect_to url
return true
end
# Check for a 301 redirect
else
new_url = PermanentRedirect.match(@site.id, request.fullpath)
if new_url
redirect_to new_url, :status => 301
return true
end
end
return false
end | [
"def",
"under_construction_or_forwarding_domain?",
"d",
"=",
"Caboose",
"::",
"Domain",
".",
"where",
"(",
":domain",
"=>",
"request",
".",
"host_with_port",
")",
".",
"first",
"if",
"d",
".",
"nil?",
"Caboose",
".",
"log",
"(",
"\"Could not find domain for #{request.host_with_port}\\nAdd this domain to the caboose site.\"",
")",
"elsif",
"d",
".",
"under_construction",
"==",
"true",
"if",
"d",
".",
"site",
".",
"under_construction_html",
"&&",
"d",
".",
"site",
".",
"under_construction_html",
".",
"strip",
".",
"length",
">",
"0",
"render",
":text",
"=>",
"d",
".",
"site",
".",
"under_construction_html",
"else",
"render",
":file",
"=>",
"'caboose/application/under_construction'",
",",
":layout",
"=>",
"false",
"end",
"return",
"true",
"elsif",
"d",
".",
"primary",
"==",
"false",
"&&",
"d",
".",
"forward_to_primary",
"==",
"true",
"pd",
"=",
"d",
".",
"site",
".",
"primary_domain",
"if",
"pd",
"&&",
"pd",
".",
"domain",
"!=",
"request",
".",
"host",
"url",
"=",
"\"#{request.protocol}#{pd.domain}\"",
"if",
"d",
".",
"forward_to_uri",
"&&",
"d",
".",
"forward_to_uri",
".",
"strip",
".",
"length",
">",
"0",
"url",
"<<",
"d",
".",
"forward_to_uri",
"elsif",
"request",
".",
"fullpath",
"&&",
"request",
".",
"fullpath",
".",
"strip",
".",
"length",
">",
"0",
"&&",
"request",
".",
"fullpath",
".",
"strip",
"!=",
"'/'",
"url",
"<<",
"request",
".",
"fullpath",
"end",
"redirect_to",
"url",
"return",
"true",
"end",
"else",
"new_url",
"=",
"PermanentRedirect",
".",
"match",
"(",
"@site",
".",
"id",
",",
"request",
".",
"fullpath",
")",
"if",
"new_url",
"redirect_to",
"new_url",
",",
":status",
"=>",
"301",
"return",
"true",
"end",
"end",
"return",
"false",
"end"
]
| Make sure we're not under construction or on a forwarded domain | [
"Make",
"sure",
"we",
"re",
"not",
"under",
"construction",
"or",
"on",
"a",
"forwarded",
"domain"
]
| 7c112911318f94cc89dba86091903a3acaf0a833 | https://github.com/williambarry007/caboose-cms/blob/7c112911318f94cc89dba86091903a3acaf0a833/app/controllers/caboose/application_controller.rb#L314-L348 | train |
williambarry007/caboose-cms | app/controllers/caboose/checkout_controller.rb | Caboose.CheckoutController.shipping_json | def shipping_json
render :json => { :error => 'Not logged in.' } and return if !logged_in?
render :json => { :error => 'No shippable items.' } and return if [email protected]_shippable_items?
render :json => { :error => 'Empty shipping address.' } and return if @invoice.shipping_address.nil?
@invoice.calculate
#ops = @invoice.invoice_packages
#if params[:recalculate_invoice_packages] || ops.count == 0
# # Remove any invoice packages
# LineItem.where(:invoice_id => @invoice.id).update_all(:invoice_package_id => nil)
# InvoicePackage.where(:invoice_id => @invoice.id).destroy_all
#
# # Calculate what shipping packages we'll need
# InvoicePackage.create_for_invoice(@invoice)
#end
# Now get the rates for those packages
rates = ShippingCalculator.rates(@invoice)
render :json => rates
end | ruby | def shipping_json
render :json => { :error => 'Not logged in.' } and return if !logged_in?
render :json => { :error => 'No shippable items.' } and return if [email protected]_shippable_items?
render :json => { :error => 'Empty shipping address.' } and return if @invoice.shipping_address.nil?
@invoice.calculate
#ops = @invoice.invoice_packages
#if params[:recalculate_invoice_packages] || ops.count == 0
# # Remove any invoice packages
# LineItem.where(:invoice_id => @invoice.id).update_all(:invoice_package_id => nil)
# InvoicePackage.where(:invoice_id => @invoice.id).destroy_all
#
# # Calculate what shipping packages we'll need
# InvoicePackage.create_for_invoice(@invoice)
#end
# Now get the rates for those packages
rates = ShippingCalculator.rates(@invoice)
render :json => rates
end | [
"def",
"shipping_json",
"render",
":json",
"=>",
"{",
":error",
"=>",
"'Not logged in.'",
"}",
"and",
"return",
"if",
"!",
"logged_in?",
"render",
":json",
"=>",
"{",
":error",
"=>",
"'No shippable items.'",
"}",
"and",
"return",
"if",
"!",
"@invoice",
".",
"has_shippable_items?",
"render",
":json",
"=>",
"{",
":error",
"=>",
"'Empty shipping address.'",
"}",
"and",
"return",
"if",
"@invoice",
".",
"shipping_address",
".",
"nil?",
"@invoice",
".",
"calculate",
"rates",
"=",
"ShippingCalculator",
".",
"rates",
"(",
"@invoice",
")",
"render",
":json",
"=>",
"rates",
"end"
]
| Step 3 - Shipping method
@route GET /checkout/shipping/json | [
"Step",
"3",
"-",
"Shipping",
"method"
]
| 7c112911318f94cc89dba86091903a3acaf0a833 | https://github.com/williambarry007/caboose-cms/blob/7c112911318f94cc89dba86091903a3acaf0a833/app/controllers/caboose/checkout_controller.rb#L99-L119 | train |
williambarry007/caboose-cms | app/controllers/caboose/checkout_controller.rb | Caboose.CheckoutController.update_stripe_details | def update_stripe_details
render :json => false and return if !logged_in?
sc = @site.store_config
Stripe.api_key = sc.stripe_secret_key.strip
u = logged_in_user
c = nil
if u.stripe_customer_id
c = Stripe::Customer.retrieve(u.stripe_customer_id)
begin
c.source = params[:token]
c.save
rescue
c = nil
end
end
if c.nil?
c = Stripe::Customer.create(
:source => params[:token],
:email => u.email,
:metadata => { :user_id => u.id }
)
end
u.stripe_customer_id = c.id
u.card_last4 = params[:card][:last4]
u.card_brand = params[:card][:brand]
u.card_exp_month = params[:card][:exp_month]
u.card_exp_year = params[:card][:exp_year]
u.save
render :json => {
:success => true,
:customer_id => u.stripe_customer_id,
:card_last4 => u.card_last4,
:card_brand => u.card_brand,
:card_exp_month => u.card_exp_month,
:card_exp_year => u.card_exp_year
}
end | ruby | def update_stripe_details
render :json => false and return if !logged_in?
sc = @site.store_config
Stripe.api_key = sc.stripe_secret_key.strip
u = logged_in_user
c = nil
if u.stripe_customer_id
c = Stripe::Customer.retrieve(u.stripe_customer_id)
begin
c.source = params[:token]
c.save
rescue
c = nil
end
end
if c.nil?
c = Stripe::Customer.create(
:source => params[:token],
:email => u.email,
:metadata => { :user_id => u.id }
)
end
u.stripe_customer_id = c.id
u.card_last4 = params[:card][:last4]
u.card_brand = params[:card][:brand]
u.card_exp_month = params[:card][:exp_month]
u.card_exp_year = params[:card][:exp_year]
u.save
render :json => {
:success => true,
:customer_id => u.stripe_customer_id,
:card_last4 => u.card_last4,
:card_brand => u.card_brand,
:card_exp_month => u.card_exp_month,
:card_exp_year => u.card_exp_year
}
end | [
"def",
"update_stripe_details",
"render",
":json",
"=>",
"false",
"and",
"return",
"if",
"!",
"logged_in?",
"sc",
"=",
"@site",
".",
"store_config",
"Stripe",
".",
"api_key",
"=",
"sc",
".",
"stripe_secret_key",
".",
"strip",
"u",
"=",
"logged_in_user",
"c",
"=",
"nil",
"if",
"u",
".",
"stripe_customer_id",
"c",
"=",
"Stripe",
"::",
"Customer",
".",
"retrieve",
"(",
"u",
".",
"stripe_customer_id",
")",
"begin",
"c",
".",
"source",
"=",
"params",
"[",
":token",
"]",
"c",
".",
"save",
"rescue",
"c",
"=",
"nil",
"end",
"end",
"if",
"c",
".",
"nil?",
"c",
"=",
"Stripe",
"::",
"Customer",
".",
"create",
"(",
":source",
"=>",
"params",
"[",
":token",
"]",
",",
":email",
"=>",
"u",
".",
"email",
",",
":metadata",
"=>",
"{",
":user_id",
"=>",
"u",
".",
"id",
"}",
")",
"end",
"u",
".",
"stripe_customer_id",
"=",
"c",
".",
"id",
"u",
".",
"card_last4",
"=",
"params",
"[",
":card",
"]",
"[",
":last4",
"]",
"u",
".",
"card_brand",
"=",
"params",
"[",
":card",
"]",
"[",
":brand",
"]",
"u",
".",
"card_exp_month",
"=",
"params",
"[",
":card",
"]",
"[",
":exp_month",
"]",
"u",
".",
"card_exp_year",
"=",
"params",
"[",
":card",
"]",
"[",
":exp_year",
"]",
"u",
".",
"save",
"render",
":json",
"=>",
"{",
":success",
"=>",
"true",
",",
":customer_id",
"=>",
"u",
".",
"stripe_customer_id",
",",
":card_last4",
"=>",
"u",
".",
"card_last4",
",",
":card_brand",
"=>",
"u",
".",
"card_brand",
",",
":card_exp_month",
"=>",
"u",
".",
"card_exp_month",
",",
":card_exp_year",
"=>",
"u",
".",
"card_exp_year",
"}",
"end"
]
| Step 5 - Update Stripe Details
@route PUT /checkout/stripe-details | [
"Step",
"5",
"-",
"Update",
"Stripe",
"Details"
]
| 7c112911318f94cc89dba86091903a3acaf0a833 | https://github.com/williambarry007/caboose-cms/blob/7c112911318f94cc89dba86091903a3acaf0a833/app/controllers/caboose/checkout_controller.rb#L123-L165 | train |
williambarry007/caboose-cms | app/mailers/caboose/invoices_mailer.rb | Caboose.InvoicesMailer.fulfillment_new_invoice | def fulfillment_new_invoice(invoice)
@invoice = invoice
sc = invoice.site.store_config
mail(:to => sc.fulfillment_email, :subject => 'New Order')
end | ruby | def fulfillment_new_invoice(invoice)
@invoice = invoice
sc = invoice.site.store_config
mail(:to => sc.fulfillment_email, :subject => 'New Order')
end | [
"def",
"fulfillment_new_invoice",
"(",
"invoice",
")",
"@invoice",
"=",
"invoice",
"sc",
"=",
"invoice",
".",
"site",
".",
"store_config",
"mail",
"(",
":to",
"=>",
"sc",
".",
"fulfillment_email",
",",
":subject",
"=>",
"'New Order'",
")",
"end"
]
| Sends a notification email to the fulfillment dept about a new invoice | [
"Sends",
"a",
"notification",
"email",
"to",
"the",
"fulfillment",
"dept",
"about",
"a",
"new",
"invoice"
]
| 7c112911318f94cc89dba86091903a3acaf0a833 | https://github.com/williambarry007/caboose-cms/blob/7c112911318f94cc89dba86091903a3acaf0a833/app/mailers/caboose/invoices_mailer.rb#L29-L33 | train |
williambarry007/caboose-cms | app/mailers/caboose/invoices_mailer.rb | Caboose.InvoicesMailer.shipping_invoice_ready | def shipping_invoice_ready(invoice)
@invoice = invoice
sc = invoice.site.store_config
mail(:to => sc.shipping_email, :subject => 'Order ready for shipping')
end | ruby | def shipping_invoice_ready(invoice)
@invoice = invoice
sc = invoice.site.store_config
mail(:to => sc.shipping_email, :subject => 'Order ready for shipping')
end | [
"def",
"shipping_invoice_ready",
"(",
"invoice",
")",
"@invoice",
"=",
"invoice",
"sc",
"=",
"invoice",
".",
"site",
".",
"store_config",
"mail",
"(",
":to",
"=>",
"sc",
".",
"shipping_email",
",",
":subject",
"=>",
"'Order ready for shipping'",
")",
"end"
]
| Sends a notification email to the shipping dept that an invoice is ready to be shipped | [
"Sends",
"a",
"notification",
"email",
"to",
"the",
"shipping",
"dept",
"that",
"an",
"invoice",
"is",
"ready",
"to",
"be",
"shipped"
]
| 7c112911318f94cc89dba86091903a3acaf0a833 | https://github.com/williambarry007/caboose-cms/blob/7c112911318f94cc89dba86091903a3acaf0a833/app/mailers/caboose/invoices_mailer.rb#L36-L40 | train |
gernotkogler/xapian_db | lib/xapian_db/document_blueprint.rb | XapianDb.DocumentBlueprint.accessors_module | def accessors_module
return @accessors_module unless @accessors_module.nil?
@accessors_module = Module.new
# Add the accessors for the indexed class and the score
@accessors_module.instance_eval do
define_method :indexed_class do
self.values[0].value
end
define_method :score do
@score
end
define_method :attributes do
blueprint = XapianDb::DocumentBlueprint.blueprint_for indexed_class
blueprint.attribute_names.inject({}) { |hash, attr| hash.tap { |hash| hash[attr.to_s] = self.send attr } }
end
end
# Add an accessor for each attribute
attribute_names.each do |attribute|
index = DocumentBlueprint.value_number_for(attribute)
codec = XapianDb::TypeCodec.codec_for @type_map[attribute]
@accessors_module.instance_eval do
define_method attribute do
codec.decode self.value(index)
end
end
end
# Let the adapter add its document helper methods (if any)
_adapter.add_doc_helper_methods_to(@accessors_module)
@accessors_module
end | ruby | def accessors_module
return @accessors_module unless @accessors_module.nil?
@accessors_module = Module.new
# Add the accessors for the indexed class and the score
@accessors_module.instance_eval do
define_method :indexed_class do
self.values[0].value
end
define_method :score do
@score
end
define_method :attributes do
blueprint = XapianDb::DocumentBlueprint.blueprint_for indexed_class
blueprint.attribute_names.inject({}) { |hash, attr| hash.tap { |hash| hash[attr.to_s] = self.send attr } }
end
end
# Add an accessor for each attribute
attribute_names.each do |attribute|
index = DocumentBlueprint.value_number_for(attribute)
codec = XapianDb::TypeCodec.codec_for @type_map[attribute]
@accessors_module.instance_eval do
define_method attribute do
codec.decode self.value(index)
end
end
end
# Let the adapter add its document helper methods (if any)
_adapter.add_doc_helper_methods_to(@accessors_module)
@accessors_module
end | [
"def",
"accessors_module",
"return",
"@accessors_module",
"unless",
"@accessors_module",
".",
"nil?",
"@accessors_module",
"=",
"Module",
".",
"new",
"@accessors_module",
".",
"instance_eval",
"do",
"define_method",
":indexed_class",
"do",
"self",
".",
"values",
"[",
"0",
"]",
".",
"value",
"end",
"define_method",
":score",
"do",
"@score",
"end",
"define_method",
":attributes",
"do",
"blueprint",
"=",
"XapianDb",
"::",
"DocumentBlueprint",
".",
"blueprint_for",
"indexed_class",
"blueprint",
".",
"attribute_names",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"hash",
",",
"attr",
"|",
"hash",
".",
"tap",
"{",
"|",
"hash",
"|",
"hash",
"[",
"attr",
".",
"to_s",
"]",
"=",
"self",
".",
"send",
"attr",
"}",
"}",
"end",
"end",
"attribute_names",
".",
"each",
"do",
"|",
"attribute",
"|",
"index",
"=",
"DocumentBlueprint",
".",
"value_number_for",
"(",
"attribute",
")",
"codec",
"=",
"XapianDb",
"::",
"TypeCodec",
".",
"codec_for",
"@type_map",
"[",
"attribute",
"]",
"@accessors_module",
".",
"instance_eval",
"do",
"define_method",
"attribute",
"do",
"codec",
".",
"decode",
"self",
".",
"value",
"(",
"index",
")",
"end",
"end",
"end",
"_adapter",
".",
"add_doc_helper_methods_to",
"(",
"@accessors_module",
")",
"@accessors_module",
"end"
]
| Lazily build and return a module that implements accessors for each field
@return [Module] A module containing all accessor methods | [
"Lazily",
"build",
"and",
"return",
"a",
"module",
"that",
"implements",
"accessors",
"for",
"each",
"field"
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/document_blueprint.rb#L228-L263 | train |
gernotkogler/xapian_db | lib/xapian_db/document_blueprint.rb | XapianDb.DocumentBlueprint.attribute | def attribute(name, options={}, &block)
raise ArgumentError.new("You cannot use #{name} as an attribute name since it is a reserved method name of Xapian::Document") if reserved_method_name?(name)
do_not_index = options.delete(:index) == false
@type_map[name] = (options.delete(:as) || :string)
if block_given?
@attributes_hash[name] = {:block => block}.merge(options)
else
@attributes_hash[name] = options
end
self.index(name, options, &block) unless do_not_index
end | ruby | def attribute(name, options={}, &block)
raise ArgumentError.new("You cannot use #{name} as an attribute name since it is a reserved method name of Xapian::Document") if reserved_method_name?(name)
do_not_index = options.delete(:index) == false
@type_map[name] = (options.delete(:as) || :string)
if block_given?
@attributes_hash[name] = {:block => block}.merge(options)
else
@attributes_hash[name] = options
end
self.index(name, options, &block) unless do_not_index
end | [
"def",
"attribute",
"(",
"name",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"You cannot use #{name} as an attribute name since it is a reserved method name of Xapian::Document\"",
")",
"if",
"reserved_method_name?",
"(",
"name",
")",
"do_not_index",
"=",
"options",
".",
"delete",
"(",
":index",
")",
"==",
"false",
"@type_map",
"[",
"name",
"]",
"=",
"(",
"options",
".",
"delete",
"(",
":as",
")",
"||",
":string",
")",
"if",
"block_given?",
"@attributes_hash",
"[",
"name",
"]",
"=",
"{",
":block",
"=>",
"block",
"}",
".",
"merge",
"(",
"options",
")",
"else",
"@attributes_hash",
"[",
"name",
"]",
"=",
"options",
"end",
"self",
".",
"index",
"(",
"name",
",",
"options",
",",
"&",
"block",
")",
"unless",
"do_not_index",
"end"
]
| Add an attribute to the blueprint. Attributes will be stored in the xapian documents an can be
accessed from a search result.
@param [String] name The name of the method that delivers the value for the attribute
@param [Hash] options
@option options [Integer] :weight (1) The weight for this attribute.
@option options [Boolean] :index (true) Should the attribute be indexed?
@option options [Symbol] :as should add type info for range queries (:date, :numeric)
@example For complex attribute configurations you may pass a block:
XapianDb::DocumentBlueprint.setup(:IndexedObject) do |blueprint|
blueprint.attribute :complex do
if @id == 1
"One"
else
"Not one"
end
end
end | [
"Add",
"an",
"attribute",
"to",
"the",
"blueprint",
".",
"Attributes",
"will",
"be",
"stored",
"in",
"the",
"xapian",
"documents",
"an",
"can",
"be",
"accessed",
"from",
"a",
"search",
"result",
"."
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/document_blueprint.rb#L326-L337 | train |
gernotkogler/xapian_db | lib/xapian_db/document_blueprint.rb | XapianDb.DocumentBlueprint.attributes | def attributes(*attributes)
attributes.each do |attr|
raise ArgumentError.new("You cannot use #{attr} as an attribute name since it is a reserved method name of Xapian::Document") if reserved_method_name?(attr)
@attributes_hash[attr] = {}
@type_map[attr] = :string
self.index attr
end
end | ruby | def attributes(*attributes)
attributes.each do |attr|
raise ArgumentError.new("You cannot use #{attr} as an attribute name since it is a reserved method name of Xapian::Document") if reserved_method_name?(attr)
@attributes_hash[attr] = {}
@type_map[attr] = :string
self.index attr
end
end | [
"def",
"attributes",
"(",
"*",
"attributes",
")",
"attributes",
".",
"each",
"do",
"|",
"attr",
"|",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"You cannot use #{attr} as an attribute name since it is a reserved method name of Xapian::Document\"",
")",
"if",
"reserved_method_name?",
"(",
"attr",
")",
"@attributes_hash",
"[",
"attr",
"]",
"=",
"{",
"}",
"@type_map",
"[",
"attr",
"]",
"=",
":string",
"self",
".",
"index",
"attr",
"end",
"end"
]
| Add a list of attributes to the blueprint. Attributes will be stored in the xapian documents ans
can be accessed from a search result.
@param [Array] attributes An array of method names that deliver the values for the attributes | [
"Add",
"a",
"list",
"of",
"attributes",
"to",
"the",
"blueprint",
".",
"Attributes",
"will",
"be",
"stored",
"in",
"the",
"xapian",
"documents",
"ans",
"can",
"be",
"accessed",
"from",
"a",
"search",
"result",
"."
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/document_blueprint.rb#L342-L349 | train |
gernotkogler/xapian_db | lib/xapian_db/document_blueprint.rb | XapianDb.DocumentBlueprint.index | def index(*args, &block)
case args.size
when 1
@indexed_methods_hash[args.first] = IndexOptions.new(:weight => 1, :block => block)
when 2
# Is it a method name with options?
if args.last.is_a? Hash
options = args.last
assert_valid_keys options, :weight, :prefixed, :no_split
@indexed_methods_hash[args.first] = IndexOptions.new(options.merge(:block => block))
else
add_indexes_from args
end
else # multiple arguments
add_indexes_from args
end
end | ruby | def index(*args, &block)
case args.size
when 1
@indexed_methods_hash[args.first] = IndexOptions.new(:weight => 1, :block => block)
when 2
# Is it a method name with options?
if args.last.is_a? Hash
options = args.last
assert_valid_keys options, :weight, :prefixed, :no_split
@indexed_methods_hash[args.first] = IndexOptions.new(options.merge(:block => block))
else
add_indexes_from args
end
else # multiple arguments
add_indexes_from args
end
end | [
"def",
"index",
"(",
"*",
"args",
",",
"&",
"block",
")",
"case",
"args",
".",
"size",
"when",
"1",
"@indexed_methods_hash",
"[",
"args",
".",
"first",
"]",
"=",
"IndexOptions",
".",
"new",
"(",
":weight",
"=>",
"1",
",",
":block",
"=>",
"block",
")",
"when",
"2",
"if",
"args",
".",
"last",
".",
"is_a?",
"Hash",
"options",
"=",
"args",
".",
"last",
"assert_valid_keys",
"options",
",",
":weight",
",",
":prefixed",
",",
":no_split",
"@indexed_methods_hash",
"[",
"args",
".",
"first",
"]",
"=",
"IndexOptions",
".",
"new",
"(",
"options",
".",
"merge",
"(",
":block",
"=>",
"block",
")",
")",
"else",
"add_indexes_from",
"args",
"end",
"else",
"add_indexes_from",
"args",
"end",
"end"
]
| Add an indexed value to the blueprint. Indexed values are not accessible from a search result.
@param [Array] args An array of arguments; you can pass a method name, an array of method names
or a method name and an options hash.
@param [Block] &block An optional block for complex configurations
Avaliable options:
- :weight (default: 1) The weight for this indexed value
@example Simple index declaration
blueprint.index :name
@example Index declaration with options
blueprint.index :name, :weight => 10
@example Mass index declaration
blueprint.index :name, :first_name, :profession
@example Index declaration with a block
blueprint.index :complex, :weight => 10 do
# add some logic here to calculate the value for 'complex'
end | [
"Add",
"an",
"indexed",
"value",
"to",
"the",
"blueprint",
".",
"Indexed",
"values",
"are",
"not",
"accessible",
"from",
"a",
"search",
"result",
"."
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/document_blueprint.rb#L367-L383 | train |
gernotkogler/xapian_db | lib/xapian_db/document_blueprint.rb | XapianDb.DocumentBlueprint.natural_sort_order | def natural_sort_order(name=nil, &block)
raise ArgumentError.new("natural_sort_order accepts a method name or a block, but not both") if name && block
@_natural_sort_order = name || block
end | ruby | def natural_sort_order(name=nil, &block)
raise ArgumentError.new("natural_sort_order accepts a method name or a block, but not both") if name && block
@_natural_sort_order = name || block
end | [
"def",
"natural_sort_order",
"(",
"name",
"=",
"nil",
",",
"&",
"block",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"natural_sort_order accepts a method name or a block, but not both\"",
")",
"if",
"name",
"&&",
"block",
"@_natural_sort_order",
"=",
"name",
"||",
"block",
"end"
]
| Define the natural sort order.
@param [String] name The name of the method that delivers the sort expression
@param [Block] &block An optional block for complex configurations
Pass a method name or a block, but not both | [
"Define",
"the",
"natural",
"sort",
"order",
"."
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/document_blueprint.rb#L408-L411 | train |
gernotkogler/xapian_db | lib/xapian_db/config.rb | XapianDb.Config.database | def database(path)
# If the current database is a persistent database, we must release the
# database and run the garbage collector to remove the write lock
if @_database.is_a?(XapianDb::PersistentDatabase)
@_database = nil
GC.start
end
if path.to_sym == :memory
@_database = XapianDb.create_db
else
begin
@_database = XapianDb.open_db :path => path
rescue IOError
@_database = XapianDb.create_db :path => path
end
end
end | ruby | def database(path)
# If the current database is a persistent database, we must release the
# database and run the garbage collector to remove the write lock
if @_database.is_a?(XapianDb::PersistentDatabase)
@_database = nil
GC.start
end
if path.to_sym == :memory
@_database = XapianDb.create_db
else
begin
@_database = XapianDb.open_db :path => path
rescue IOError
@_database = XapianDb.create_db :path => path
end
end
end | [
"def",
"database",
"(",
"path",
")",
"if",
"@_database",
".",
"is_a?",
"(",
"XapianDb",
"::",
"PersistentDatabase",
")",
"@_database",
"=",
"nil",
"GC",
".",
"start",
"end",
"if",
"path",
".",
"to_sym",
"==",
":memory",
"@_database",
"=",
"XapianDb",
".",
"create_db",
"else",
"begin",
"@_database",
"=",
"XapianDb",
".",
"open_db",
":path",
"=>",
"path",
"rescue",
"IOError",
"@_database",
"=",
"XapianDb",
".",
"create_db",
":path",
"=>",
"path",
"end",
"end",
"end"
]
| Set the global database to use
@param [String] path The path to the database. Either apply a file sytem path or :memory
for an in memory database | [
"Set",
"the",
"global",
"database",
"to",
"use"
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/config.rb#L83-L101 | train |
gernotkogler/xapian_db | lib/xapian_db/config.rb | XapianDb.Config.adapter | def adapter(type)
begin
@_adapter = XapianDb::Adapters.const_get("#{camelize(type.to_s)}Adapter")
rescue NameError
require File.dirname(__FILE__) + "/adapters/#{type}_adapter"
@_adapter = XapianDb::Adapters.const_get("#{camelize(type.to_s)}Adapter")
end
end | ruby | def adapter(type)
begin
@_adapter = XapianDb::Adapters.const_get("#{camelize(type.to_s)}Adapter")
rescue NameError
require File.dirname(__FILE__) + "/adapters/#{type}_adapter"
@_adapter = XapianDb::Adapters.const_get("#{camelize(type.to_s)}Adapter")
end
end | [
"def",
"adapter",
"(",
"type",
")",
"begin",
"@_adapter",
"=",
"XapianDb",
"::",
"Adapters",
".",
"const_get",
"(",
"\"#{camelize(type.to_s)}Adapter\"",
")",
"rescue",
"NameError",
"require",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"\"/adapters/#{type}_adapter\"",
"@_adapter",
"=",
"XapianDb",
"::",
"Adapters",
".",
"const_get",
"(",
"\"#{camelize(type.to_s)}Adapter\"",
")",
"end",
"end"
]
| Set the adapter
@param [Symbol] type The adapter type; the following adapters are available:
- :generic ({XapianDb::Adapters::GenericAdapter})
- :active_record ({XapianDb::Adapters::ActiveRecordAdapter})
- :datamapper ({XapianDb::Adapters::DatamapperAdapter}) | [
"Set",
"the",
"adapter"
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/config.rb#L108-L115 | train |
gernotkogler/xapian_db | lib/xapian_db/config.rb | XapianDb.Config.writer | def writer(type)
# We try to guess the writer name
begin
require File.dirname(__FILE__) + "/index_writers/#{type}_writer"
@_writer = XapianDb::IndexWriters.const_get("#{camelize(type.to_s)}Writer")
rescue LoadError
puts "XapianDb: cannot load #{type} writer; see README for supported writers and how to install neccessary queue infrastructure"
raise
end
end | ruby | def writer(type)
# We try to guess the writer name
begin
require File.dirname(__FILE__) + "/index_writers/#{type}_writer"
@_writer = XapianDb::IndexWriters.const_get("#{camelize(type.to_s)}Writer")
rescue LoadError
puts "XapianDb: cannot load #{type} writer; see README for supported writers and how to install neccessary queue infrastructure"
raise
end
end | [
"def",
"writer",
"(",
"type",
")",
"begin",
"require",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"\"/index_writers/#{type}_writer\"",
"@_writer",
"=",
"XapianDb",
"::",
"IndexWriters",
".",
"const_get",
"(",
"\"#{camelize(type.to_s)}Writer\"",
")",
"rescue",
"LoadError",
"puts",
"\"XapianDb: cannot load #{type} writer; see README for supported writers and how to install neccessary queue infrastructure\"",
"raise",
"end",
"end"
]
| Set the index writer
@param [Symbol] type The writer type; the following adapters are available:
- :direct ({XapianDb::IndexWriters::DirectWriter})
- :beanstalk ({XapianDb::IndexWriters::BeanstalkWriter})
- :resque ({XapianDb::IndexWriters::ResqueWriter})
- :sidekiq ({XapianDb::IndexWriters::SidekiqWriter}) | [
"Set",
"the",
"index",
"writer"
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/config.rb#L123-L132 | train |
gernotkogler/xapian_db | lib/xapian_db/config.rb | XapianDb.Config.language | def language(lang)
lang ||= :none
@_stemmer = XapianDb::Repositories::Stemmer.stemmer_for lang
@_stopper = lang == :none ? nil : XapianDb::Repositories::Stopper.stopper_for(lang)
end | ruby | def language(lang)
lang ||= :none
@_stemmer = XapianDb::Repositories::Stemmer.stemmer_for lang
@_stopper = lang == :none ? nil : XapianDb::Repositories::Stopper.stopper_for(lang)
end | [
"def",
"language",
"(",
"lang",
")",
"lang",
"||=",
":none",
"@_stemmer",
"=",
"XapianDb",
"::",
"Repositories",
"::",
"Stemmer",
".",
"stemmer_for",
"lang",
"@_stopper",
"=",
"lang",
"==",
":none",
"?",
"nil",
":",
"XapianDb",
"::",
"Repositories",
"::",
"Stopper",
".",
"stopper_for",
"(",
"lang",
")",
"end"
]
| Set the language.
@param [Symbol] lang The language; apply the two letter ISO639 code for the language
@example
XapianDb::Config.setup do |config|
config.language :de
end
see {LANGUAGE_MAP} for supported languages | [
"Set",
"the",
"language",
"."
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/config.rb#L159-L163 | train |
gernotkogler/xapian_db | lib/xapian_db/utilities.rb | XapianDb.Utilities.assert_valid_keys | def assert_valid_keys(hash, *valid_keys)
unknown_keys = hash.keys - [valid_keys].flatten
raise(ArgumentError, "Unsupported option(s) detected: #{unknown_keys.join(", ")}") unless unknown_keys.empty?
end | ruby | def assert_valid_keys(hash, *valid_keys)
unknown_keys = hash.keys - [valid_keys].flatten
raise(ArgumentError, "Unsupported option(s) detected: #{unknown_keys.join(", ")}") unless unknown_keys.empty?
end | [
"def",
"assert_valid_keys",
"(",
"hash",
",",
"*",
"valid_keys",
")",
"unknown_keys",
"=",
"hash",
".",
"keys",
"-",
"[",
"valid_keys",
"]",
".",
"flatten",
"raise",
"(",
"ArgumentError",
",",
"\"Unsupported option(s) detected: #{unknown_keys.join(\", \")}\"",
")",
"unless",
"unknown_keys",
".",
"empty?",
"end"
]
| Taken from Rails | [
"Taken",
"from",
"Rails"
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/utilities.rb#L45-L48 | train |
thoughtbot/bourne | lib/bourne/api.rb | Mocha.API.assert_received | def assert_received(mock, expected_method_name)
matcher = have_received(expected_method_name)
yield(matcher) if block_given?
assert matcher.matches?(mock), matcher.failure_message
end | ruby | def assert_received(mock, expected_method_name)
matcher = have_received(expected_method_name)
yield(matcher) if block_given?
assert matcher.matches?(mock), matcher.failure_message
end | [
"def",
"assert_received",
"(",
"mock",
",",
"expected_method_name",
")",
"matcher",
"=",
"have_received",
"(",
"expected_method_name",
")",
"yield",
"(",
"matcher",
")",
"if",
"block_given?",
"assert",
"matcher",
".",
"matches?",
"(",
"mock",
")",
",",
"matcher",
".",
"failure_message",
"end"
]
| Asserts that the given mock received the given method.
Examples:
assert_received(mock, :to_s)
assert_received(Radio, :new) {|expect| expect.with(1041) }
assert_received(radio, :volume) {|expect| expect.with(11).twice } | [
"Asserts",
"that",
"the",
"given",
"mock",
"received",
"the",
"given",
"method",
"."
]
| 4b1f3d6908011923ffcd423af41eb2f30494e8e6 | https://github.com/thoughtbot/bourne/blob/4b1f3d6908011923ffcd423af41eb2f30494e8e6/lib/bourne/api.rb#L13-L17 | train |
gernotkogler/xapian_db | lib/xapian_db/resultset.rb | XapianDb.Resultset.decorate | def decorate(match)
klass_name = match.document.values[0].value
blueprint = XapianDb::DocumentBlueprint.blueprint_for klass_name
match.document.extend blueprint.accessors_module
match.document.instance_variable_set :@score, match.percent
match
end | ruby | def decorate(match)
klass_name = match.document.values[0].value
blueprint = XapianDb::DocumentBlueprint.blueprint_for klass_name
match.document.extend blueprint.accessors_module
match.document.instance_variable_set :@score, match.percent
match
end | [
"def",
"decorate",
"(",
"match",
")",
"klass_name",
"=",
"match",
".",
"document",
".",
"values",
"[",
"0",
"]",
".",
"value",
"blueprint",
"=",
"XapianDb",
"::",
"DocumentBlueprint",
".",
"blueprint_for",
"klass_name",
"match",
".",
"document",
".",
"extend",
"blueprint",
".",
"accessors_module",
"match",
".",
"document",
".",
"instance_variable_set",
":@score",
",",
"match",
".",
"percent",
"match",
"end"
]
| Decorate a Xapian match with field accessors for each configured attribute
@param [Xapian::Match] a match
@return [Xapian::Match] the decorated match | [
"Decorate",
"a",
"Xapian",
"match",
"with",
"field",
"accessors",
"for",
"each",
"configured",
"attribute"
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/resultset.rb#L113-L119 | train |
gernotkogler/xapian_db | lib/xapian_db/database.rb | XapianDb.Database.delete_docs_of_class | def delete_docs_of_class(klass)
writer.delete_document("C#{klass}")
if klass.respond_to? :descendants
klass.descendants.each do |subclass|
writer.delete_document("C#{subclass}")
end
end
true
end | ruby | def delete_docs_of_class(klass)
writer.delete_document("C#{klass}")
if klass.respond_to? :descendants
klass.descendants.each do |subclass|
writer.delete_document("C#{subclass}")
end
end
true
end | [
"def",
"delete_docs_of_class",
"(",
"klass",
")",
"writer",
".",
"delete_document",
"(",
"\"C#{klass}\"",
")",
"if",
"klass",
".",
"respond_to?",
":descendants",
"klass",
".",
"descendants",
".",
"each",
"do",
"|",
"subclass",
"|",
"writer",
".",
"delete_document",
"(",
"\"C#{subclass}\"",
")",
"end",
"end",
"true",
"end"
]
| Delete all docs of a specific class.
If `klass` tracks its descendants, then docs of any subclasses will be deleted, too.
(ActiveRecord does this by default; the gem 'descendants_tracker' offers an alternative.)
@param [Class] klass A class that has a {XapianDb::DocumentBlueprint} configuration | [
"Delete",
"all",
"docs",
"of",
"a",
"specific",
"class",
"."
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/database.rb#L44-L52 | train |
gernotkogler/xapian_db | lib/xapian_db/database.rb | XapianDb.Database.search | def search(expression, options={})
opts = {:sort_decending => false}.merge(options)
@query_parser ||= QueryParser.new(self)
query = @query_parser.parse(expression)
# If we do not have a valid query we return an empty result set
return Resultset.new(nil, opts) unless query
start = Time.now
enquiry = Xapian::Enquire.new(reader)
enquiry.query = query
sort_indices = opts.delete :sort_indices
sort_decending = opts.delete :sort_decending
order = opts.delete :order
raise ArgumentError.new "you can't use sort_indices and order, only one of them" if sort_indices && order
if order
sort_indices = order.map{ |attr_name| XapianDb::DocumentBlueprint.value_number_for attr_name.to_sym }
end
sorter = Xapian::MultiValueKeyMaker.new
if sort_indices
sort_indices.each { |index| sorter.add_value index }
enquiry.set_sort_by_key_then_relevance(sorter, sort_decending)
else
sorter.add_value DocumentBlueprint.value_number_for(:natural_sort_order)
enquiry.set_sort_by_relevance_then_key sorter, false
end
opts[:spelling_suggestion] = @query_parser.spelling_suggestion
opts[:db_size] = self.size
retries = 0
begin
result = Resultset.new(enquiry, opts)
rescue IOError => ex
raise unless ex.message =~ /DatabaseModifiedError: /
raise if retries >= 5
sleep 0.1
retries += 1
Rails.logger.warn "XapianDb: DatabaseModifiedError, retry #{retries}" if defined?(Rails)
@reader.reopen
retry
end
Rails.logger.debug "XapianDb search (#{(Time.now - start) * 1000}ms) #{expression}" if defined?(Rails)
result
end | ruby | def search(expression, options={})
opts = {:sort_decending => false}.merge(options)
@query_parser ||= QueryParser.new(self)
query = @query_parser.parse(expression)
# If we do not have a valid query we return an empty result set
return Resultset.new(nil, opts) unless query
start = Time.now
enquiry = Xapian::Enquire.new(reader)
enquiry.query = query
sort_indices = opts.delete :sort_indices
sort_decending = opts.delete :sort_decending
order = opts.delete :order
raise ArgumentError.new "you can't use sort_indices and order, only one of them" if sort_indices && order
if order
sort_indices = order.map{ |attr_name| XapianDb::DocumentBlueprint.value_number_for attr_name.to_sym }
end
sorter = Xapian::MultiValueKeyMaker.new
if sort_indices
sort_indices.each { |index| sorter.add_value index }
enquiry.set_sort_by_key_then_relevance(sorter, sort_decending)
else
sorter.add_value DocumentBlueprint.value_number_for(:natural_sort_order)
enquiry.set_sort_by_relevance_then_key sorter, false
end
opts[:spelling_suggestion] = @query_parser.spelling_suggestion
opts[:db_size] = self.size
retries = 0
begin
result = Resultset.new(enquiry, opts)
rescue IOError => ex
raise unless ex.message =~ /DatabaseModifiedError: /
raise if retries >= 5
sleep 0.1
retries += 1
Rails.logger.warn "XapianDb: DatabaseModifiedError, retry #{retries}" if defined?(Rails)
@reader.reopen
retry
end
Rails.logger.debug "XapianDb search (#{(Time.now - start) * 1000}ms) #{expression}" if defined?(Rails)
result
end | [
"def",
"search",
"(",
"expression",
",",
"options",
"=",
"{",
"}",
")",
"opts",
"=",
"{",
":sort_decending",
"=>",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"@query_parser",
"||=",
"QueryParser",
".",
"new",
"(",
"self",
")",
"query",
"=",
"@query_parser",
".",
"parse",
"(",
"expression",
")",
"return",
"Resultset",
".",
"new",
"(",
"nil",
",",
"opts",
")",
"unless",
"query",
"start",
"=",
"Time",
".",
"now",
"enquiry",
"=",
"Xapian",
"::",
"Enquire",
".",
"new",
"(",
"reader",
")",
"enquiry",
".",
"query",
"=",
"query",
"sort_indices",
"=",
"opts",
".",
"delete",
":sort_indices",
"sort_decending",
"=",
"opts",
".",
"delete",
":sort_decending",
"order",
"=",
"opts",
".",
"delete",
":order",
"raise",
"ArgumentError",
".",
"new",
"\"you can't use sort_indices and order, only one of them\"",
"if",
"sort_indices",
"&&",
"order",
"if",
"order",
"sort_indices",
"=",
"order",
".",
"map",
"{",
"|",
"attr_name",
"|",
"XapianDb",
"::",
"DocumentBlueprint",
".",
"value_number_for",
"attr_name",
".",
"to_sym",
"}",
"end",
"sorter",
"=",
"Xapian",
"::",
"MultiValueKeyMaker",
".",
"new",
"if",
"sort_indices",
"sort_indices",
".",
"each",
"{",
"|",
"index",
"|",
"sorter",
".",
"add_value",
"index",
"}",
"enquiry",
".",
"set_sort_by_key_then_relevance",
"(",
"sorter",
",",
"sort_decending",
")",
"else",
"sorter",
".",
"add_value",
"DocumentBlueprint",
".",
"value_number_for",
"(",
":natural_sort_order",
")",
"enquiry",
".",
"set_sort_by_relevance_then_key",
"sorter",
",",
"false",
"end",
"opts",
"[",
":spelling_suggestion",
"]",
"=",
"@query_parser",
".",
"spelling_suggestion",
"opts",
"[",
":db_size",
"]",
"=",
"self",
".",
"size",
"retries",
"=",
"0",
"begin",
"result",
"=",
"Resultset",
".",
"new",
"(",
"enquiry",
",",
"opts",
")",
"rescue",
"IOError",
"=>",
"ex",
"raise",
"unless",
"ex",
".",
"message",
"=~",
"/",
"/",
"raise",
"if",
"retries",
">=",
"5",
"sleep",
"0.1",
"retries",
"+=",
"1",
"Rails",
".",
"logger",
".",
"warn",
"\"XapianDb: DatabaseModifiedError, retry #{retries}\"",
"if",
"defined?",
"(",
"Rails",
")",
"@reader",
".",
"reopen",
"retry",
"end",
"Rails",
".",
"logger",
".",
"debug",
"\"XapianDb search (#{(Time.now - start) * 1000}ms) #{expression}\"",
"if",
"defined?",
"(",
"Rails",
")",
"result",
"end"
]
| Perform a search
@param [String] expression A valid search expression.
@param [Hash] options
@option options [Integer] :per_page How many docs per page?
@option options [Array<Integer>] :sort_indices (nil) An array of attribute indices to sort by. This
option is used internally by the search method implemented on configured classes. Do not use it
directly unless you know what you do
@option options [Boolean] :sort_decending (false) Reverse the sort order?
@example Simple Query
resultset = db.search("foo")
@example Wildcard Query
resultset = db.search("fo*")
@example Boolean Query
resultset = db.search("foo or baz")
@example Field Query
resultset = db.search("name:foo")
@return [XapianDb::Resultset] The resultset | [
"Perform",
"a",
"search"
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/database.rb#L71-L119 | train |
gernotkogler/xapian_db | lib/xapian_db/database.rb | XapianDb.Database.facets | def facets(attribute, expression)
# return an empty hash if no search expression is given
return {} if expression.nil? || expression.strip.empty?
value_number = XapianDb::DocumentBlueprint.value_number_for(attribute)
@query_parser ||= QueryParser.new(self)
query = @query_parser.parse(expression)
enquiry = Xapian::Enquire.new(reader)
enquiry.query = query
enquiry.collapse_key = value_number
facets = {}
enquiry.mset(0, size).matches.each do |match|
facet_value = match.document.value(value_number)
# We must add 1 to the collapse_count since collapse_count means
# "how many other matches are there?"
facets[facet_value] = match.collapse_count + 1
end
facets
end | ruby | def facets(attribute, expression)
# return an empty hash if no search expression is given
return {} if expression.nil? || expression.strip.empty?
value_number = XapianDb::DocumentBlueprint.value_number_for(attribute)
@query_parser ||= QueryParser.new(self)
query = @query_parser.parse(expression)
enquiry = Xapian::Enquire.new(reader)
enquiry.query = query
enquiry.collapse_key = value_number
facets = {}
enquiry.mset(0, size).matches.each do |match|
facet_value = match.document.value(value_number)
# We must add 1 to the collapse_count since collapse_count means
# "how many other matches are there?"
facets[facet_value] = match.collapse_count + 1
end
facets
end | [
"def",
"facets",
"(",
"attribute",
",",
"expression",
")",
"return",
"{",
"}",
"if",
"expression",
".",
"nil?",
"||",
"expression",
".",
"strip",
".",
"empty?",
"value_number",
"=",
"XapianDb",
"::",
"DocumentBlueprint",
".",
"value_number_for",
"(",
"attribute",
")",
"@query_parser",
"||=",
"QueryParser",
".",
"new",
"(",
"self",
")",
"query",
"=",
"@query_parser",
".",
"parse",
"(",
"expression",
")",
"enquiry",
"=",
"Xapian",
"::",
"Enquire",
".",
"new",
"(",
"reader",
")",
"enquiry",
".",
"query",
"=",
"query",
"enquiry",
".",
"collapse_key",
"=",
"value_number",
"facets",
"=",
"{",
"}",
"enquiry",
".",
"mset",
"(",
"0",
",",
"size",
")",
".",
"matches",
".",
"each",
"do",
"|",
"match",
"|",
"facet_value",
"=",
"match",
".",
"document",
".",
"value",
"(",
"value_number",
")",
"facets",
"[",
"facet_value",
"]",
"=",
"match",
".",
"collapse_count",
"+",
"1",
"end",
"facets",
"end"
]
| A very simple implementation of facets using Xapian collapse key.
@param [Symbol, String] attribute the name of an attribute declared in one ore more blueprints
@param [String] expression A valid search expression (see {#search} for examples).
@return [Hash<Class, Integer>] A hash containing the classes and the hits per class | [
"A",
"very",
"simple",
"implementation",
"of",
"facets",
"using",
"Xapian",
"collapse",
"key",
"."
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/database.rb#L156-L173 | train |
gernotkogler/xapian_db | lib/xapian_db/indexer.rb | XapianDb.Indexer.store_fields | def store_fields
# class name of the object goes to position 0
@xapian_doc.add_value 0, @obj.class.name
# natural sort order goes to position 1
if @blueprint._natural_sort_order.is_a? Proc
sort_value = @obj.instance_eval &@blueprint._natural_sort_order
else
sort_value = @obj.send @blueprint._natural_sort_order
end
@xapian_doc.add_value 1, sort_value.to_s
@blueprint.attribute_names.each do |attribute|
block = @blueprint.block_for_attribute attribute
if block
value = @obj.instance_eval &block
else
value = @obj.send attribute
end
codec = XapianDb::TypeCodec.codec_for @blueprint.type_map[attribute]
encoded_string = codec.encode value
@xapian_doc.add_value DocumentBlueprint.value_number_for(attribute), encoded_string unless encoded_string.nil?
end
end | ruby | def store_fields
# class name of the object goes to position 0
@xapian_doc.add_value 0, @obj.class.name
# natural sort order goes to position 1
if @blueprint._natural_sort_order.is_a? Proc
sort_value = @obj.instance_eval &@blueprint._natural_sort_order
else
sort_value = @obj.send @blueprint._natural_sort_order
end
@xapian_doc.add_value 1, sort_value.to_s
@blueprint.attribute_names.each do |attribute|
block = @blueprint.block_for_attribute attribute
if block
value = @obj.instance_eval &block
else
value = @obj.send attribute
end
codec = XapianDb::TypeCodec.codec_for @blueprint.type_map[attribute]
encoded_string = codec.encode value
@xapian_doc.add_value DocumentBlueprint.value_number_for(attribute), encoded_string unless encoded_string.nil?
end
end | [
"def",
"store_fields",
"@xapian_doc",
".",
"add_value",
"0",
",",
"@obj",
".",
"class",
".",
"name",
"if",
"@blueprint",
".",
"_natural_sort_order",
".",
"is_a?",
"Proc",
"sort_value",
"=",
"@obj",
".",
"instance_eval",
"&",
"@blueprint",
".",
"_natural_sort_order",
"else",
"sort_value",
"=",
"@obj",
".",
"send",
"@blueprint",
".",
"_natural_sort_order",
"end",
"@xapian_doc",
".",
"add_value",
"1",
",",
"sort_value",
".",
"to_s",
"@blueprint",
".",
"attribute_names",
".",
"each",
"do",
"|",
"attribute",
"|",
"block",
"=",
"@blueprint",
".",
"block_for_attribute",
"attribute",
"if",
"block",
"value",
"=",
"@obj",
".",
"instance_eval",
"&",
"block",
"else",
"value",
"=",
"@obj",
".",
"send",
"attribute",
"end",
"codec",
"=",
"XapianDb",
"::",
"TypeCodec",
".",
"codec_for",
"@blueprint",
".",
"type_map",
"[",
"attribute",
"]",
"encoded_string",
"=",
"codec",
".",
"encode",
"value",
"@xapian_doc",
".",
"add_value",
"DocumentBlueprint",
".",
"value_number_for",
"(",
"attribute",
")",
",",
"encoded_string",
"unless",
"encoded_string",
".",
"nil?",
"end",
"end"
]
| Store all configured fields | [
"Store",
"all",
"configured",
"fields"
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/indexer.rb#L33-L57 | train |
gernotkogler/xapian_db | lib/xapian_db/indexer.rb | XapianDb.Indexer.index_text | def index_text
term_generator = Xapian::TermGenerator.new
term_generator.database = @database.writer
term_generator.document = @xapian_doc
if XapianDb::Config.stemmer
term_generator.stemmer = XapianDb::Config.stemmer
term_generator.stopper = XapianDb::Config.stopper if XapianDb::Config.stopper
# Enable the creation of a spelling dictionary if the database is not in memory
term_generator.set_flags Xapian::TermGenerator::FLAG_SPELLING if @database.is_a? XapianDb::PersistentDatabase
end
# Index the primary key as a unique term
@xapian_doc.add_term("Q#{@obj.xapian_id}")
# Index the class with the field name
term_generator.index_text("#{@obj.class}".downcase, 1, "XINDEXED_CLASS")
@xapian_doc.add_term("C#{@obj.class}")
@blueprint.indexed_method_names.each do |method|
options = @blueprint.options_for_indexed_method method
if options.block
obj = @obj.instance_eval(&options.block)
else
obj = @obj.send(method)
end
unless obj.nil?
values = get_values_to_index_from obj
values.each do |value|
terms = value.to_s.downcase
terms = @blueprint.preprocess_terms.call(terms) if @blueprint.preprocess_terms
terms = split(terms) if XapianDb::Config.term_splitter_count > 0 && !options.no_split
# Add value with field name
term_generator.index_text(terms, options.weight, "X#{method.upcase}") if options.prefixed
# Add value without field name
term_generator.index_text(terms, options.weight)
end
end
end
terms_to_ignore = @xapian_doc.terms.select{ |term| term.term.length < XapianDb::Config.term_min_length }
terms_to_ignore.each { |term| @xapian_doc.remove_term term.term }
end | ruby | def index_text
term_generator = Xapian::TermGenerator.new
term_generator.database = @database.writer
term_generator.document = @xapian_doc
if XapianDb::Config.stemmer
term_generator.stemmer = XapianDb::Config.stemmer
term_generator.stopper = XapianDb::Config.stopper if XapianDb::Config.stopper
# Enable the creation of a spelling dictionary if the database is not in memory
term_generator.set_flags Xapian::TermGenerator::FLAG_SPELLING if @database.is_a? XapianDb::PersistentDatabase
end
# Index the primary key as a unique term
@xapian_doc.add_term("Q#{@obj.xapian_id}")
# Index the class with the field name
term_generator.index_text("#{@obj.class}".downcase, 1, "XINDEXED_CLASS")
@xapian_doc.add_term("C#{@obj.class}")
@blueprint.indexed_method_names.each do |method|
options = @blueprint.options_for_indexed_method method
if options.block
obj = @obj.instance_eval(&options.block)
else
obj = @obj.send(method)
end
unless obj.nil?
values = get_values_to_index_from obj
values.each do |value|
terms = value.to_s.downcase
terms = @blueprint.preprocess_terms.call(terms) if @blueprint.preprocess_terms
terms = split(terms) if XapianDb::Config.term_splitter_count > 0 && !options.no_split
# Add value with field name
term_generator.index_text(terms, options.weight, "X#{method.upcase}") if options.prefixed
# Add value without field name
term_generator.index_text(terms, options.weight)
end
end
end
terms_to_ignore = @xapian_doc.terms.select{ |term| term.term.length < XapianDb::Config.term_min_length }
terms_to_ignore.each { |term| @xapian_doc.remove_term term.term }
end | [
"def",
"index_text",
"term_generator",
"=",
"Xapian",
"::",
"TermGenerator",
".",
"new",
"term_generator",
".",
"database",
"=",
"@database",
".",
"writer",
"term_generator",
".",
"document",
"=",
"@xapian_doc",
"if",
"XapianDb",
"::",
"Config",
".",
"stemmer",
"term_generator",
".",
"stemmer",
"=",
"XapianDb",
"::",
"Config",
".",
"stemmer",
"term_generator",
".",
"stopper",
"=",
"XapianDb",
"::",
"Config",
".",
"stopper",
"if",
"XapianDb",
"::",
"Config",
".",
"stopper",
"term_generator",
".",
"set_flags",
"Xapian",
"::",
"TermGenerator",
"::",
"FLAG_SPELLING",
"if",
"@database",
".",
"is_a?",
"XapianDb",
"::",
"PersistentDatabase",
"end",
"@xapian_doc",
".",
"add_term",
"(",
"\"Q#{@obj.xapian_id}\"",
")",
"term_generator",
".",
"index_text",
"(",
"\"#{@obj.class}\"",
".",
"downcase",
",",
"1",
",",
"\"XINDEXED_CLASS\"",
")",
"@xapian_doc",
".",
"add_term",
"(",
"\"C#{@obj.class}\"",
")",
"@blueprint",
".",
"indexed_method_names",
".",
"each",
"do",
"|",
"method",
"|",
"options",
"=",
"@blueprint",
".",
"options_for_indexed_method",
"method",
"if",
"options",
".",
"block",
"obj",
"=",
"@obj",
".",
"instance_eval",
"(",
"&",
"options",
".",
"block",
")",
"else",
"obj",
"=",
"@obj",
".",
"send",
"(",
"method",
")",
"end",
"unless",
"obj",
".",
"nil?",
"values",
"=",
"get_values_to_index_from",
"obj",
"values",
".",
"each",
"do",
"|",
"value",
"|",
"terms",
"=",
"value",
".",
"to_s",
".",
"downcase",
"terms",
"=",
"@blueprint",
".",
"preprocess_terms",
".",
"call",
"(",
"terms",
")",
"if",
"@blueprint",
".",
"preprocess_terms",
"terms",
"=",
"split",
"(",
"terms",
")",
"if",
"XapianDb",
"::",
"Config",
".",
"term_splitter_count",
">",
"0",
"&&",
"!",
"options",
".",
"no_split",
"term_generator",
".",
"index_text",
"(",
"terms",
",",
"options",
".",
"weight",
",",
"\"X#{method.upcase}\"",
")",
"if",
"options",
".",
"prefixed",
"term_generator",
".",
"index_text",
"(",
"terms",
",",
"options",
".",
"weight",
")",
"end",
"end",
"end",
"terms_to_ignore",
"=",
"@xapian_doc",
".",
"terms",
".",
"select",
"{",
"|",
"term",
"|",
"term",
".",
"term",
".",
"length",
"<",
"XapianDb",
"::",
"Config",
".",
"term_min_length",
"}",
"terms_to_ignore",
".",
"each",
"{",
"|",
"term",
"|",
"@xapian_doc",
".",
"remove_term",
"term",
".",
"term",
"}",
"end"
]
| Index all configured text methods | [
"Index",
"all",
"configured",
"text",
"methods"
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/indexer.rb#L60-L101 | train |
gernotkogler/xapian_db | lib/xapian_db/indexer.rb | XapianDb.Indexer.get_values_to_index_from | def get_values_to_index_from(obj)
# if it's an array, we collect the values for its elements recursive
if obj.is_a? Array
return obj.map { |element| get_values_to_index_from element }.flatten.compact
end
# if the object responds to attributes and attributes is a hash,
# we use the attributes values (works well for active_record and datamapper objects)
return obj.attributes.values.compact if obj.respond_to?(:attributes) && obj.attributes.is_a?(Hash)
# The object is unkown and will be indexed by its to_s method; if to_s retruns nil, we
# will not index it
obj.to_s.nil? ? [] : [obj]
end | ruby | def get_values_to_index_from(obj)
# if it's an array, we collect the values for its elements recursive
if obj.is_a? Array
return obj.map { |element| get_values_to_index_from element }.flatten.compact
end
# if the object responds to attributes and attributes is a hash,
# we use the attributes values (works well for active_record and datamapper objects)
return obj.attributes.values.compact if obj.respond_to?(:attributes) && obj.attributes.is_a?(Hash)
# The object is unkown and will be indexed by its to_s method; if to_s retruns nil, we
# will not index it
obj.to_s.nil? ? [] : [obj]
end | [
"def",
"get_values_to_index_from",
"(",
"obj",
")",
"if",
"obj",
".",
"is_a?",
"Array",
"return",
"obj",
".",
"map",
"{",
"|",
"element",
"|",
"get_values_to_index_from",
"element",
"}",
".",
"flatten",
".",
"compact",
"end",
"return",
"obj",
".",
"attributes",
".",
"values",
".",
"compact",
"if",
"obj",
".",
"respond_to?",
"(",
":attributes",
")",
"&&",
"obj",
".",
"attributes",
".",
"is_a?",
"(",
"Hash",
")",
"obj",
".",
"to_s",
".",
"nil?",
"?",
"[",
"]",
":",
"[",
"obj",
"]",
"end"
]
| Get the values to index from an object | [
"Get",
"the",
"values",
"to",
"index",
"from",
"an",
"object"
]
| 5d84aa461e33d038cb505907b4a43db280ab3e36 | https://github.com/gernotkogler/xapian_db/blob/5d84aa461e33d038cb505907b4a43db280ab3e36/lib/xapian_db/indexer.rb#L104-L118 | train |
salsify/arc-furnace | lib/arc-furnace/csv_source.rb | ArcFurnace.CSVSource.preprocess | def preprocess
if group_by?
parse_file { |row| @preprocessed_csv << csv_to_hash_with_duplicates(row) }
@preprocessed_csv = @preprocessed_csv.group_by { |row| row[key_column] }
end
end | ruby | def preprocess
if group_by?
parse_file { |row| @preprocessed_csv << csv_to_hash_with_duplicates(row) }
@preprocessed_csv = @preprocessed_csv.group_by { |row| row[key_column] }
end
end | [
"def",
"preprocess",
"if",
"group_by?",
"parse_file",
"{",
"|",
"row",
"|",
"@preprocessed_csv",
"<<",
"csv_to_hash_with_duplicates",
"(",
"row",
")",
"}",
"@preprocessed_csv",
"=",
"@preprocessed_csv",
".",
"group_by",
"{",
"|",
"row",
"|",
"row",
"[",
"key_column",
"]",
"}",
"end",
"end"
]
| note that group_by requires the entire file to be
read into memory | [
"note",
"that",
"group_by",
"requires",
"the",
"entire",
"file",
"to",
"be",
"read",
"into",
"memory"
]
| 006ab6d70cc1a2a991b7a7037f40cd5e15864ea5 | https://github.com/salsify/arc-furnace/blob/006ab6d70cc1a2a991b7a7037f40cd5e15864ea5/lib/arc-furnace/csv_source.rb#L37-L42 | train |
murb/workbook | lib/workbook/table.rb | Workbook.Table.contains_row? | def contains_row? row
raise ArgumentError, "table should be a Workbook::Row (you passed a #{t.class})" unless row.is_a?(Workbook::Row)
self.collect{|r| r.object_id}.include? row.object_id
end | ruby | def contains_row? row
raise ArgumentError, "table should be a Workbook::Row (you passed a #{t.class})" unless row.is_a?(Workbook::Row)
self.collect{|r| r.object_id}.include? row.object_id
end | [
"def",
"contains_row?",
"row",
"raise",
"ArgumentError",
",",
"\"table should be a Workbook::Row (you passed a #{t.class})\"",
"unless",
"row",
".",
"is_a?",
"(",
"Workbook",
"::",
"Row",
")",
"self",
".",
"collect",
"{",
"|",
"r",
"|",
"r",
".",
"object_id",
"}",
".",
"include?",
"row",
".",
"object_id",
"end"
]
| Returns true if the row exists in this table
@param [Workbook::Row] row to test for
@return [Boolean] whether the row exist in this table | [
"Returns",
"true",
"if",
"the",
"row",
"exists",
"in",
"this",
"table"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/table.rb#L132-L135 | train |
murb/workbook | lib/workbook/table.rb | Workbook.Table.dimensions | def dimensions
height = self.count
width = self.collect{|a| a.length}.max
[width,height]
end | ruby | def dimensions
height = self.count
width = self.collect{|a| a.length}.max
[width,height]
end | [
"def",
"dimensions",
"height",
"=",
"self",
".",
"count",
"width",
"=",
"self",
".",
"collect",
"{",
"|",
"a",
"|",
"a",
".",
"length",
"}",
".",
"max",
"[",
"width",
",",
"height",
"]",
"end"
]
| Returns The dimensions of this sheet based on longest row
@return [Array] x-width, y-height | [
"Returns",
"The",
"dimensions",
"of",
"this",
"sheet",
"based",
"on",
"longest",
"row"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/table.rb#L247-L251 | train |
murb/workbook | lib/workbook/template.rb | Workbook.Template.create_or_find_format_by | def create_or_find_format_by name, variant=:default
fs = @formats[name]
fs = @formats[name] = {} if fs.nil?
f = fs[variant]
if f.nil?
f = Workbook::Format.new
if variant != :default and fs[:default]
f = fs[:default].clone
end
@formats[name][variant] = f
end
return @formats[name][variant]
end | ruby | def create_or_find_format_by name, variant=:default
fs = @formats[name]
fs = @formats[name] = {} if fs.nil?
f = fs[variant]
if f.nil?
f = Workbook::Format.new
if variant != :default and fs[:default]
f = fs[:default].clone
end
@formats[name][variant] = f
end
return @formats[name][variant]
end | [
"def",
"create_or_find_format_by",
"name",
",",
"variant",
"=",
":default",
"fs",
"=",
"@formats",
"[",
"name",
"]",
"fs",
"=",
"@formats",
"[",
"name",
"]",
"=",
"{",
"}",
"if",
"fs",
".",
"nil?",
"f",
"=",
"fs",
"[",
"variant",
"]",
"if",
"f",
".",
"nil?",
"f",
"=",
"Workbook",
"::",
"Format",
".",
"new",
"if",
"variant",
"!=",
":default",
"and",
"fs",
"[",
":default",
"]",
"f",
"=",
"fs",
"[",
":default",
"]",
".",
"clone",
"end",
"@formats",
"[",
"name",
"]",
"[",
"variant",
"]",
"=",
"f",
"end",
"return",
"@formats",
"[",
"name",
"]",
"[",
"variant",
"]",
"end"
]
| Create or find a format by name
@return [Workbook::Format] The new or found format
@param [String] name of the format (e.g. whatever you want, in diff names such as 'destroyed', 'updated' and 'created' are being used)
@param [Symbol] variant can also be a strftime formatting string (e.g. "%Y-%m-%d") | [
"Create",
"or",
"find",
"a",
"format",
"by",
"name"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/template.rb#L47-L59 | train |
murb/workbook | lib/workbook/book.rb | Workbook.Book.import | def import filename, extension=nil, options={}
extension = file_extension(filename) unless extension
if ['txt','csv','xml'].include?(extension)
open_text filename, extension, options
else
open_binary filename, extension, options
end
end | ruby | def import filename, extension=nil, options={}
extension = file_extension(filename) unless extension
if ['txt','csv','xml'].include?(extension)
open_text filename, extension, options
else
open_binary filename, extension, options
end
end | [
"def",
"import",
"filename",
",",
"extension",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
"extension",
"=",
"file_extension",
"(",
"filename",
")",
"unless",
"extension",
"if",
"[",
"'txt'",
",",
"'csv'",
",",
"'xml'",
"]",
".",
"include?",
"(",
"extension",
")",
"open_text",
"filename",
",",
"extension",
",",
"options",
"else",
"open_binary",
"filename",
",",
"extension",
",",
"options",
"end",
"end"
]
| Loads an external file into an existing worbook
@param [String] filename a string with a reference to the file to be opened
@param [String] extension an optional string enforcing a certain parser (based on the file extension, e.g. 'txt', 'csv' or 'xls')
@return [Workbook::Book] A new instance, based on the filename | [
"Loads",
"an",
"external",
"file",
"into",
"an",
"existing",
"worbook"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/book.rb#L122-L129 | train |
murb/workbook | lib/workbook/book.rb | Workbook.Book.open_binary | def open_binary filename, extension=nil, options={}
extension = file_extension(filename) unless extension
f = open(filename)
send("load_#{extension}".to_sym, f, options)
end | ruby | def open_binary filename, extension=nil, options={}
extension = file_extension(filename) unless extension
f = open(filename)
send("load_#{extension}".to_sym, f, options)
end | [
"def",
"open_binary",
"filename",
",",
"extension",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
"extension",
"=",
"file_extension",
"(",
"filename",
")",
"unless",
"extension",
"f",
"=",
"open",
"(",
"filename",
")",
"send",
"(",
"\"load_#{extension}\"",
".",
"to_sym",
",",
"f",
",",
"options",
")",
"end"
]
| Open the file in binary, read-only mode, do not read it, but pas it throug to the extension determined loaded
@param [String] filename a string with a reference to the file to be opened
@param [String] extension an optional string enforcing a certain parser (based on the file extension, e.g. 'txt', 'csv' or 'xls')
@return [Workbook::Book] A new instance, based on the filename | [
"Open",
"the",
"file",
"in",
"binary",
"read",
"-",
"only",
"mode",
"do",
"not",
"read",
"it",
"but",
"pas",
"it",
"throug",
"to",
"the",
"extension",
"determined",
"loaded"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/book.rb#L136-L140 | train |
murb/workbook | lib/workbook/book.rb | Workbook.Book.open_text | def open_text filename, extension=nil, options={}
extension = file_extension(filename) unless extension
t = text_to_utf8(open(filename).read)
send("load_#{extension}".to_sym, t, options)
end | ruby | def open_text filename, extension=nil, options={}
extension = file_extension(filename) unless extension
t = text_to_utf8(open(filename).read)
send("load_#{extension}".to_sym, t, options)
end | [
"def",
"open_text",
"filename",
",",
"extension",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
"extension",
"=",
"file_extension",
"(",
"filename",
")",
"unless",
"extension",
"t",
"=",
"text_to_utf8",
"(",
"open",
"(",
"filename",
")",
".",
"read",
")",
"send",
"(",
"\"load_#{extension}\"",
".",
"to_sym",
",",
"t",
",",
"options",
")",
"end"
]
| Open the file in non-binary, read-only mode, read it and parse it to UTF-8
@param [String] filename a string with a reference to the file to be opened
@param [String] extension an optional string enforcing a certain parser (based on the file extension, e.g. 'txt', 'csv' or 'xls') | [
"Open",
"the",
"file",
"in",
"non",
"-",
"binary",
"read",
"-",
"only",
"mode",
"read",
"it",
"and",
"parse",
"it",
"to",
"UTF",
"-",
"8"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/book.rb#L146-L150 | train |
murb/workbook | lib/workbook/book.rb | Workbook.Book.write | def write filename, options={}
extension = file_extension(filename)
send("write_to_#{extension}".to_sym, filename, options)
end | ruby | def write filename, options={}
extension = file_extension(filename)
send("write_to_#{extension}".to_sym, filename, options)
end | [
"def",
"write",
"filename",
",",
"options",
"=",
"{",
"}",
"extension",
"=",
"file_extension",
"(",
"filename",
")",
"send",
"(",
"\"write_to_#{extension}\"",
".",
"to_sym",
",",
"filename",
",",
"options",
")",
"end"
]
| Writes the book to a file. Filetype is based on the extension, but can be overridden
@param [String] filename a string with a reference to the file to be written to
@param [Hash] options depends on the writer chosen by the file's filetype | [
"Writes",
"the",
"book",
"to",
"a",
"file",
".",
"Filetype",
"is",
"based",
"on",
"the",
"extension",
"but",
"can",
"be",
"overridden"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/book.rb#L156-L159 | train |
murb/workbook | lib/workbook/book.rb | Workbook.Book.text_to_utf8 | def text_to_utf8 text
unless text.valid_encoding? and text.encoding == "UTF-8"
# TODO: had some ruby 1.9 problems with rchardet ... but ideally it or a similar functionality will be reintroduced
source_encoding = text.valid_encoding? ? text.encoding : "US-ASCII"
text = text.encode('UTF-8', source_encoding, {:invalid=>:replace, :undef=>:replace, :replace=>""})
text = text.gsub("\u0000","") # TODO: this cleanup of nil values isn't supposed to be needed...
end
text
end | ruby | def text_to_utf8 text
unless text.valid_encoding? and text.encoding == "UTF-8"
# TODO: had some ruby 1.9 problems with rchardet ... but ideally it or a similar functionality will be reintroduced
source_encoding = text.valid_encoding? ? text.encoding : "US-ASCII"
text = text.encode('UTF-8', source_encoding, {:invalid=>:replace, :undef=>:replace, :replace=>""})
text = text.gsub("\u0000","") # TODO: this cleanup of nil values isn't supposed to be needed...
end
text
end | [
"def",
"text_to_utf8",
"text",
"unless",
"text",
".",
"valid_encoding?",
"and",
"text",
".",
"encoding",
"==",
"\"UTF-8\"",
"source_encoding",
"=",
"text",
".",
"valid_encoding?",
"?",
"text",
".",
"encoding",
":",
"\"US-ASCII\"",
"text",
"=",
"text",
".",
"encode",
"(",
"'UTF-8'",
",",
"source_encoding",
",",
"{",
":invalid",
"=>",
":replace",
",",
":undef",
"=>",
":replace",
",",
":replace",
"=>",
"\"\"",
"}",
")",
"text",
"=",
"text",
".",
"gsub",
"(",
"\"\\u0000\"",
",",
"\"\"",
")",
"end",
"text",
"end"
]
| Helper method to convert text in a file to UTF-8
@param [String] text a string to convert | [
"Helper",
"method",
"to",
"convert",
"text",
"in",
"a",
"file",
"to",
"UTF",
"-",
"8"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/book.rb#L165-L173 | train |
murb/workbook | lib/workbook/book.rb | Workbook.Book.create_or_open_sheet_at | def create_or_open_sheet_at index
s = self[index]
s = self[index] = Workbook::Sheet.new if s == nil
s.book = self
s
end | ruby | def create_or_open_sheet_at index
s = self[index]
s = self[index] = Workbook::Sheet.new if s == nil
s.book = self
s
end | [
"def",
"create_or_open_sheet_at",
"index",
"s",
"=",
"self",
"[",
"index",
"]",
"s",
"=",
"self",
"[",
"index",
"]",
"=",
"Workbook",
"::",
"Sheet",
".",
"new",
"if",
"s",
"==",
"nil",
"s",
".",
"book",
"=",
"self",
"s",
"end"
]
| Create or open the existing sheet at an index value
@param [Integer] index the index of the sheet | [
"Create",
"or",
"open",
"the",
"existing",
"sheet",
"at",
"an",
"index",
"value"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/book.rb#L198-L203 | train |
monocle/range_operators | lib/range_operators/array_operator_definitions.rb | RangeOperators.ArrayOperatorDefinitions.missing | def missing
missing, array = [], self.rangify
i, length = 0, array.size - 1
while i < length
current = comparison_value(array[i], :last)
nextt = comparison_value(array[i+1], :first)
missing << (current + 2 == nextt ? current + 1 : (current + 1)..(nextt - 1))
i += 1
end
missing
end | ruby | def missing
missing, array = [], self.rangify
i, length = 0, array.size - 1
while i < length
current = comparison_value(array[i], :last)
nextt = comparison_value(array[i+1], :first)
missing << (current + 2 == nextt ? current + 1 : (current + 1)..(nextt - 1))
i += 1
end
missing
end | [
"def",
"missing",
"missing",
",",
"array",
"=",
"[",
"]",
",",
"self",
".",
"rangify",
"i",
",",
"length",
"=",
"0",
",",
"array",
".",
"size",
"-",
"1",
"while",
"i",
"<",
"length",
"current",
"=",
"comparison_value",
"(",
"array",
"[",
"i",
"]",
",",
":last",
")",
"nextt",
"=",
"comparison_value",
"(",
"array",
"[",
"i",
"+",
"1",
"]",
",",
":first",
")",
"missing",
"<<",
"(",
"current",
"+",
"2",
"==",
"nextt",
"?",
"current",
"+",
"1",
":",
"(",
"current",
"+",
"1",
")",
"..",
"(",
"nextt",
"-",
"1",
")",
")",
"i",
"+=",
"1",
"end",
"missing",
"end"
]
| Returns the missing elements in an array set | [
"Returns",
"the",
"missing",
"elements",
"in",
"an",
"array",
"set"
]
| 66352099589cd942a57d24f9840b861a8096e17c | https://github.com/monocle/range_operators/blob/66352099589cd942a57d24f9840b861a8096e17c/lib/range_operators/array_operator_definitions.rb#L61-L72 | train |
monocle/range_operators | lib/range_operators/array_operator_definitions.rb | RangeOperators.ArrayOperatorDefinitions.comparison_value | def comparison_value(value, position)
return value if value.class != Range
position == :first ? value.first : value.last
end | ruby | def comparison_value(value, position)
return value if value.class != Range
position == :first ? value.first : value.last
end | [
"def",
"comparison_value",
"(",
"value",
",",
"position",
")",
"return",
"value",
"if",
"value",
".",
"class",
"!=",
"Range",
"position",
"==",
":first",
"?",
"value",
".",
"first",
":",
"value",
".",
"last",
"end"
]
| For a Range, will return value.first or value.last. A non-Range will return itself. | [
"For",
"a",
"Range",
"will",
"return",
"value",
".",
"first",
"or",
"value",
".",
"last",
".",
"A",
"non",
"-",
"Range",
"will",
"return",
"itself",
"."
]
| 66352099589cd942a57d24f9840b861a8096e17c | https://github.com/monocle/range_operators/blob/66352099589cd942a57d24f9840b861a8096e17c/lib/range_operators/array_operator_definitions.rb#L83-L86 | train |
murb/workbook | lib/workbook/column.rb | Workbook.Column.table= | def table= table
raise(ArgumentError, "value should be nil or Workbook::Table") unless [NilClass,Workbook::Table].include? table.class
@table = table
end | ruby | def table= table
raise(ArgumentError, "value should be nil or Workbook::Table") unless [NilClass,Workbook::Table].include? table.class
@table = table
end | [
"def",
"table",
"=",
"table",
"raise",
"(",
"ArgumentError",
",",
"\"value should be nil or Workbook::Table\"",
")",
"unless",
"[",
"NilClass",
",",
"Workbook",
"::",
"Table",
"]",
".",
"include?",
"table",
".",
"class",
"@table",
"=",
"table",
"end"
]
| Set the table this column belongs to
@param [Workbook::Table] table this column belongs to | [
"Set",
"the",
"table",
"this",
"column",
"belongs",
"to"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/column.rb#L43-L46 | train |
movitto/rjr | lib/rjr/util/args.rb | RJR.Arguments.validate! | def validate!(*acceptable)
i = 0
if acceptable.first.is_a?(Hash)
# clone acceptable hash, swap keys for string
acceptable = Hash[acceptable.first]
acceptable.keys.each { |k|
acceptable[k.to_s] = acceptable[k]
acceptable.delete(k) unless k.is_a?(String)
}
# compare acceptable against arguments, raising error if issue found
while(i < length) do
val = self[i]
passed = acceptable.has_key?(val)
raise ArgumentError, "#{val} not an acceptable arg" unless passed
skip = acceptable[val]
i += (skip + 1)
end
else
# clone acceptable array, swap values for string
acceptable = Array.new(acceptable).map { |a| a.to_s }
# compare acceptable against arguments, raising error if issue found
while(i < length) do
val = self[i].to_s
passed = acceptable.include?(val)
raise ArgumentError, "#{val} not an acceptable arg" unless passed
i += 1
end
end
nil
end | ruby | def validate!(*acceptable)
i = 0
if acceptable.first.is_a?(Hash)
# clone acceptable hash, swap keys for string
acceptable = Hash[acceptable.first]
acceptable.keys.each { |k|
acceptable[k.to_s] = acceptable[k]
acceptable.delete(k) unless k.is_a?(String)
}
# compare acceptable against arguments, raising error if issue found
while(i < length) do
val = self[i]
passed = acceptable.has_key?(val)
raise ArgumentError, "#{val} not an acceptable arg" unless passed
skip = acceptable[val]
i += (skip + 1)
end
else
# clone acceptable array, swap values for string
acceptable = Array.new(acceptable).map { |a| a.to_s }
# compare acceptable against arguments, raising error if issue found
while(i < length) do
val = self[i].to_s
passed = acceptable.include?(val)
raise ArgumentError, "#{val} not an acceptable arg" unless passed
i += 1
end
end
nil
end | [
"def",
"validate!",
"(",
"*",
"acceptable",
")",
"i",
"=",
"0",
"if",
"acceptable",
".",
"first",
".",
"is_a?",
"(",
"Hash",
")",
"acceptable",
"=",
"Hash",
"[",
"acceptable",
".",
"first",
"]",
"acceptable",
".",
"keys",
".",
"each",
"{",
"|",
"k",
"|",
"acceptable",
"[",
"k",
".",
"to_s",
"]",
"=",
"acceptable",
"[",
"k",
"]",
"acceptable",
".",
"delete",
"(",
"k",
")",
"unless",
"k",
".",
"is_a?",
"(",
"String",
")",
"}",
"while",
"(",
"i",
"<",
"length",
")",
"do",
"val",
"=",
"self",
"[",
"i",
"]",
"passed",
"=",
"acceptable",
".",
"has_key?",
"(",
"val",
")",
"raise",
"ArgumentError",
",",
"\"#{val} not an acceptable arg\"",
"unless",
"passed",
"skip",
"=",
"acceptable",
"[",
"val",
"]",
"i",
"+=",
"(",
"skip",
"+",
"1",
")",
"end",
"else",
"acceptable",
"=",
"Array",
".",
"new",
"(",
"acceptable",
")",
".",
"map",
"{",
"|",
"a",
"|",
"a",
".",
"to_s",
"}",
"while",
"(",
"i",
"<",
"length",
")",
"do",
"val",
"=",
"self",
"[",
"i",
"]",
".",
"to_s",
"passed",
"=",
"acceptable",
".",
"include?",
"(",
"val",
")",
"raise",
"ArgumentError",
",",
"\"#{val} not an acceptable arg\"",
"unless",
"passed",
"i",
"+=",
"1",
"end",
"end",
"nil",
"end"
]
| Validate arguments against acceptable values.
Raises error if value is found which is not on
list of acceptable values.
If acceptable values are hash's, keys are compared
and on matches the values are used as the # of following
arguments to skip in the validator
*Note* args / acceptable params are converted to strings
before comparison
@example
args = Arguments.new :args => ['custom', 'another']
args.validate! 'custom', 'another' #=> nil
args.validate! 'something' #=> ArgumentError
args = Arguments.new :args => ['with_id', 123, 'another']
args.validate! :with_id => 1, :another => 0 #=> nil
args.validate! :with_id => 1 #=> ArgumentError | [
"Validate",
"arguments",
"against",
"acceptable",
"values",
"."
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/util/args.rb#L45-L78 | train |
movitto/rjr | lib/rjr/util/args.rb | RJR.Arguments.extract | def extract(map)
# clone map hash, swap keys for string
map = Hash[map]
map.keys.each { |k|
map[k.to_s] = map[k]
map.delete(k) unless k.is_a?(String)
}
groups = []
i = 0
while(i < length) do
val = self[i]
i += 1
next unless !!map.has_key?(val)
num = map[val]
group = [val]
0.upto(num-1) do |j|
group << self[i]
i += 1
end
groups << group
end
groups
end | ruby | def extract(map)
# clone map hash, swap keys for string
map = Hash[map]
map.keys.each { |k|
map[k.to_s] = map[k]
map.delete(k) unless k.is_a?(String)
}
groups = []
i = 0
while(i < length) do
val = self[i]
i += 1
next unless !!map.has_key?(val)
num = map[val]
group = [val]
0.upto(num-1) do |j|
group << self[i]
i += 1
end
groups << group
end
groups
end | [
"def",
"extract",
"(",
"map",
")",
"map",
"=",
"Hash",
"[",
"map",
"]",
"map",
".",
"keys",
".",
"each",
"{",
"|",
"k",
"|",
"map",
"[",
"k",
".",
"to_s",
"]",
"=",
"map",
"[",
"k",
"]",
"map",
".",
"delete",
"(",
"k",
")",
"unless",
"k",
".",
"is_a?",
"(",
"String",
")",
"}",
"groups",
"=",
"[",
"]",
"i",
"=",
"0",
"while",
"(",
"i",
"<",
"length",
")",
"do",
"val",
"=",
"self",
"[",
"i",
"]",
"i",
"+=",
"1",
"next",
"unless",
"!",
"!",
"map",
".",
"has_key?",
"(",
"val",
")",
"num",
"=",
"map",
"[",
"val",
"]",
"group",
"=",
"[",
"val",
"]",
"0",
".",
"upto",
"(",
"num",
"-",
"1",
")",
"do",
"|",
"j",
"|",
"group",
"<<",
"self",
"[",
"i",
"]",
"i",
"+=",
"1",
"end",
"groups",
"<<",
"group",
"end",
"groups",
"end"
]
| Extract groups of values from argument list
Groups are generated by comparing arguments to keys in the
specified map and on matches extracting the # of following
arguments specified by the map values
Note arguments / keys are converted to strings before comparison
@example
args = Arguments.new :args => ['with_id', 123, 'custom', 'another']
args.extract :with_id => 1, :custom => 0
# => [['with_id', 123], ['custom']] | [
"Extract",
"groups",
"of",
"values",
"from",
"argument",
"list"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/util/args.rb#L93-L118 | train |
movitto/rjr | lib/rjr/util/thread_pool.rb | RJR.ThreadPoolJob.exec | def exec(lock)
lock.synchronize {
@thread = Thread.current
@time_started = Time.now
}
@handler.call *@params
# ensure we do not switch to another job
# before atomic check expiration / terminate
# expired threads happens below
lock.synchronize {
@time_completed = Time.now
@thread = nil
}
end | ruby | def exec(lock)
lock.synchronize {
@thread = Thread.current
@time_started = Time.now
}
@handler.call *@params
# ensure we do not switch to another job
# before atomic check expiration / terminate
# expired threads happens below
lock.synchronize {
@time_completed = Time.now
@thread = nil
}
end | [
"def",
"exec",
"(",
"lock",
")",
"lock",
".",
"synchronize",
"{",
"@thread",
"=",
"Thread",
".",
"current",
"@time_started",
"=",
"Time",
".",
"now",
"}",
"@handler",
".",
"call",
"*",
"@params",
"lock",
".",
"synchronize",
"{",
"@time_completed",
"=",
"Time",
".",
"now",
"@thread",
"=",
"nil",
"}",
"end"
]
| Set job metadata and execute job with specified params.
Used internally by thread pool | [
"Set",
"job",
"metadata",
"and",
"execute",
"job",
"with",
"specified",
"params",
"."
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/util/thread_pool.rb#L60-L75 | train |
movitto/rjr | lib/rjr/util/thread_pool.rb | RJR.ThreadPool.launch_worker | def launch_worker
@worker_threads << Thread.new {
while work = @work_queue.pop
begin
#RJR::Logger.debug "launch thread pool job #{work}"
@running_queue << work
work.exec(@thread_lock)
# TODO cleaner / more immediate way to pop item off running_queue
#RJR::Logger.debug "finished thread pool job #{work}"
rescue Exception => e
# FIXME also send to rjr logger at a critical level
puts "Thread raised Fatal Exception #{e}"
puts "\n#{e.backtrace.join("\n")}"
end
end
}
end | ruby | def launch_worker
@worker_threads << Thread.new {
while work = @work_queue.pop
begin
#RJR::Logger.debug "launch thread pool job #{work}"
@running_queue << work
work.exec(@thread_lock)
# TODO cleaner / more immediate way to pop item off running_queue
#RJR::Logger.debug "finished thread pool job #{work}"
rescue Exception => e
# FIXME also send to rjr logger at a critical level
puts "Thread raised Fatal Exception #{e}"
puts "\n#{e.backtrace.join("\n")}"
end
end
}
end | [
"def",
"launch_worker",
"@worker_threads",
"<<",
"Thread",
".",
"new",
"{",
"while",
"work",
"=",
"@work_queue",
".",
"pop",
"begin",
"@running_queue",
"<<",
"work",
"work",
".",
"exec",
"(",
"@thread_lock",
")",
"rescue",
"Exception",
"=>",
"e",
"puts",
"\"Thread raised Fatal Exception #{e}\"",
"puts",
"\"\\n#{e.backtrace.join(\"\\n\")}\"",
"end",
"end",
"}",
"end"
]
| Internal helper, launch worker thread | [
"Internal",
"helper",
"launch",
"worker",
"thread"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/util/thread_pool.rb#L99-L115 | train |
movitto/rjr | lib/rjr/util/thread_pool.rb | RJR.ThreadPool.check_workers | def check_workers
if @terminate
@worker_threads.each { |t|
t.kill
}
@worker_threads = []
elsif @timeout
readd = []
while @running_queue.size > 0 && work = @running_queue.pop
# check expiration / killing expired threads must be atomic
# and mutually exclusive with the process of marking a job completed above
@thread_lock.synchronize{
if work.expired?(@timeout)
work.thread.kill
@worker_threads.delete(work.thread)
launch_worker
elsif !work.completed?
readd << work
end
}
end
readd.each { |work| @running_queue << work }
end
end | ruby | def check_workers
if @terminate
@worker_threads.each { |t|
t.kill
}
@worker_threads = []
elsif @timeout
readd = []
while @running_queue.size > 0 && work = @running_queue.pop
# check expiration / killing expired threads must be atomic
# and mutually exclusive with the process of marking a job completed above
@thread_lock.synchronize{
if work.expired?(@timeout)
work.thread.kill
@worker_threads.delete(work.thread)
launch_worker
elsif !work.completed?
readd << work
end
}
end
readd.each { |work| @running_queue << work }
end
end | [
"def",
"check_workers",
"if",
"@terminate",
"@worker_threads",
".",
"each",
"{",
"|",
"t",
"|",
"t",
".",
"kill",
"}",
"@worker_threads",
"=",
"[",
"]",
"elsif",
"@timeout",
"readd",
"=",
"[",
"]",
"while",
"@running_queue",
".",
"size",
">",
"0",
"&&",
"work",
"=",
"@running_queue",
".",
"pop",
"@thread_lock",
".",
"synchronize",
"{",
"if",
"work",
".",
"expired?",
"(",
"@timeout",
")",
"work",
".",
"thread",
".",
"kill",
"@worker_threads",
".",
"delete",
"(",
"work",
".",
"thread",
")",
"launch_worker",
"elsif",
"!",
"work",
".",
"completed?",
"readd",
"<<",
"work",
"end",
"}",
"end",
"readd",
".",
"each",
"{",
"|",
"work",
"|",
"@running_queue",
"<<",
"work",
"}",
"end",
"end"
]
| Internal helper, performs checks on workers | [
"Internal",
"helper",
"performs",
"checks",
"on",
"workers"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/util/thread_pool.rb#L118-L143 | train |
murb/workbook | lib/workbook/row.rb | Workbook.Row.table= | def table= t
raise ArgumentError, "table should be a Workbook::Table (you passed a #{t.class})" unless t.is_a?(Workbook::Table) or t == nil
if t
@table = t
table.push(self) #unless table.index(self) and self.placeholder?
end
end | ruby | def table= t
raise ArgumentError, "table should be a Workbook::Table (you passed a #{t.class})" unless t.is_a?(Workbook::Table) or t == nil
if t
@table = t
table.push(self) #unless table.index(self) and self.placeholder?
end
end | [
"def",
"table",
"=",
"t",
"raise",
"ArgumentError",
",",
"\"table should be a Workbook::Table (you passed a #{t.class})\"",
"unless",
"t",
".",
"is_a?",
"(",
"Workbook",
"::",
"Table",
")",
"or",
"t",
"==",
"nil",
"if",
"t",
"@table",
"=",
"t",
"table",
".",
"push",
"(",
"self",
")",
"end",
"end"
]
| Set reference to the table this row belongs to and add the row to this table
@param [Workbook::Table] t the table this row belongs to | [
"Set",
"reference",
"to",
"the",
"table",
"this",
"row",
"belongs",
"to",
"and",
"add",
"the",
"row",
"to",
"this",
"table"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/row.rb#L57-L63 | train |
murb/workbook | lib/workbook/row.rb | Workbook.Row.find_cells_by_background_color | def find_cells_by_background_color color=:any, options={}
options = {:hash_keys=>true}.merge(options)
cells = self.collect {|c| c if c.format.has_background_color?(color) }.compact
r = Row.new cells
options[:hash_keys] ? r.to_symbols : r
end | ruby | def find_cells_by_background_color color=:any, options={}
options = {:hash_keys=>true}.merge(options)
cells = self.collect {|c| c if c.format.has_background_color?(color) }.compact
r = Row.new cells
options[:hash_keys] ? r.to_symbols : r
end | [
"def",
"find_cells_by_background_color",
"color",
"=",
":any",
",",
"options",
"=",
"{",
"}",
"options",
"=",
"{",
":hash_keys",
"=>",
"true",
"}",
".",
"merge",
"(",
"options",
")",
"cells",
"=",
"self",
".",
"collect",
"{",
"|",
"c",
"|",
"c",
"if",
"c",
".",
"format",
".",
"has_background_color?",
"(",
"color",
")",
"}",
".",
"compact",
"r",
"=",
"Row",
".",
"new",
"cells",
"options",
"[",
":hash_keys",
"]",
"?",
"r",
".",
"to_symbols",
":",
"r",
"end"
]
| Returns an array of cells allows you to find cells by a given color, normally a string containing a hex
@param [String] color a CSS-style hex-string
@param [Hash] options Option :hash_keys (default true) returns row as an array of symbols
@return [Array<Symbol>, Workbook::Row<Workbook::Cell>] | [
"Returns",
"an",
"array",
"of",
"cells",
"allows",
"you",
"to",
"find",
"cells",
"by",
"a",
"given",
"color",
"normally",
"a",
"string",
"containing",
"a",
"hex"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/row.rb#L167-L172 | train |
murb/workbook | lib/workbook/row.rb | Workbook.Row.compact | def compact
r = self.clone
r = r.collect{|c| c unless c.nil?}.compact
end | ruby | def compact
r = self.clone
r = r.collect{|c| c unless c.nil?}.compact
end | [
"def",
"compact",
"r",
"=",
"self",
".",
"clone",
"r",
"=",
"r",
".",
"collect",
"{",
"|",
"c",
"|",
"c",
"unless",
"c",
".",
"nil?",
"}",
".",
"compact",
"end"
]
| Compact detaches the row from the table | [
"Compact",
"detaches",
"the",
"row",
"from",
"the",
"table"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/row.rb#L269-L272 | train |
murb/workbook | lib/workbook/format.rb | Workbook.Format.flattened | def flattened
ff=Workbook::Format.new()
formats.each{|a| ff.merge!(a) }
return ff
end | ruby | def flattened
ff=Workbook::Format.new()
formats.each{|a| ff.merge!(a) }
return ff
end | [
"def",
"flattened",
"ff",
"=",
"Workbook",
"::",
"Format",
".",
"new",
"(",
")",
"formats",
".",
"each",
"{",
"|",
"a",
"|",
"ff",
".",
"merge!",
"(",
"a",
")",
"}",
"return",
"ff",
"end"
]
| Applies the formatting options of self with its parents until no parent can be found
@return [Workbook::Format] new Workbook::Format that is the result of merging current style with all its parent's styles. | [
"Applies",
"the",
"formatting",
"options",
"of",
"self",
"with",
"its",
"parents",
"until",
"no",
"parent",
"can",
"be",
"found"
]
| 2e12f43c882b7c235455192a2fc48183fe6ec965 | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/format.rb#L98-L102 | train |
akerl/githubchart | lib/githubchart.rb | GithubChart.Chart.load_stats | def load_stats(data, user)
return data if data
raise('No data or user provided') unless user
stats = GithubStats.new(user).data
raise("Failed to find data for #{user} on GitHub") unless stats
stats
end | ruby | def load_stats(data, user)
return data if data
raise('No data or user provided') unless user
stats = GithubStats.new(user).data
raise("Failed to find data for #{user} on GitHub") unless stats
stats
end | [
"def",
"load_stats",
"(",
"data",
",",
"user",
")",
"return",
"data",
"if",
"data",
"raise",
"(",
"'No data or user provided'",
")",
"unless",
"user",
"stats",
"=",
"GithubStats",
".",
"new",
"(",
"user",
")",
".",
"data",
"raise",
"(",
"\"Failed to find data for #{user} on GitHub\"",
")",
"unless",
"stats",
"stats",
"end"
]
| Load stats from provided arg or github | [
"Load",
"stats",
"from",
"provided",
"arg",
"or",
"github"
]
| d758049b7360f8b22f23092d5b175ff8f4b9e180 | https://github.com/akerl/githubchart/blob/d758049b7360f8b22f23092d5b175ff8f4b9e180/lib/githubchart.rb#L78-L84 | train |
movitto/rjr | lib/rjr/node.rb | RJR.Node.connection_event | def connection_event(event, *args)
return unless @connection_event_handlers.keys.include?(event)
@connection_event_handlers[event].each { |h| h.call(self, *args) }
end | ruby | def connection_event(event, *args)
return unless @connection_event_handlers.keys.include?(event)
@connection_event_handlers[event].each { |h| h.call(self, *args) }
end | [
"def",
"connection_event",
"(",
"event",
",",
"*",
"args",
")",
"return",
"unless",
"@connection_event_handlers",
".",
"keys",
".",
"include?",
"(",
"event",
")",
"@connection_event_handlers",
"[",
"event",
"]",
".",
"each",
"{",
"|",
"h",
"|",
"h",
".",
"call",
"(",
"self",
",",
"*",
"args",
")",
"}",
"end"
]
| Internal helper, run connection event handlers for specified event, passing
self and args to handler | [
"Internal",
"helper",
"run",
"connection",
"event",
"handlers",
"for",
"specified",
"event",
"passing",
"self",
"and",
"args",
"to",
"handler"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/node.rb#L172-L175 | train |
movitto/rjr | lib/rjr/node.rb | RJR.Node.client_for | def client_for(connection)
# skip if an indirect node type or local
return nil, nil if self.indirect? || self.node_type == :local
begin
return Socket.unpack_sockaddr_in(connection.get_peername)
rescue Exception=>e
end
return nil, nil
end | ruby | def client_for(connection)
# skip if an indirect node type or local
return nil, nil if self.indirect? || self.node_type == :local
begin
return Socket.unpack_sockaddr_in(connection.get_peername)
rescue Exception=>e
end
return nil, nil
end | [
"def",
"client_for",
"(",
"connection",
")",
"return",
"nil",
",",
"nil",
"if",
"self",
".",
"indirect?",
"||",
"self",
".",
"node_type",
"==",
":local",
"begin",
"return",
"Socket",
".",
"unpack_sockaddr_in",
"(",
"connection",
".",
"get_peername",
")",
"rescue",
"Exception",
"=>",
"e",
"end",
"return",
"nil",
",",
"nil",
"end"
]
| Internal helper, extract client info from connection | [
"Internal",
"helper",
"extract",
"client",
"info",
"from",
"connection"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/node.rb#L180-L190 | train |
movitto/rjr | lib/rjr/node.rb | RJR.Node.handle_message | def handle_message(msg, connection = {})
intermediate = Messages::Intermediate.parse(msg)
if Messages::Request.is_request_message?(intermediate)
tp << ThreadPoolJob.new(intermediate) { |i|
handle_request(i, false, connection)
}
elsif Messages::Notification.is_notification_message?(intermediate)
tp << ThreadPoolJob.new(intermediate) { |i|
handle_request(i, true, connection)
}
elsif Messages::Response.is_response_message?(intermediate)
handle_response(intermediate)
end
intermediate
end | ruby | def handle_message(msg, connection = {})
intermediate = Messages::Intermediate.parse(msg)
if Messages::Request.is_request_message?(intermediate)
tp << ThreadPoolJob.new(intermediate) { |i|
handle_request(i, false, connection)
}
elsif Messages::Notification.is_notification_message?(intermediate)
tp << ThreadPoolJob.new(intermediate) { |i|
handle_request(i, true, connection)
}
elsif Messages::Response.is_response_message?(intermediate)
handle_response(intermediate)
end
intermediate
end | [
"def",
"handle_message",
"(",
"msg",
",",
"connection",
"=",
"{",
"}",
")",
"intermediate",
"=",
"Messages",
"::",
"Intermediate",
".",
"parse",
"(",
"msg",
")",
"if",
"Messages",
"::",
"Request",
".",
"is_request_message?",
"(",
"intermediate",
")",
"tp",
"<<",
"ThreadPoolJob",
".",
"new",
"(",
"intermediate",
")",
"{",
"|",
"i",
"|",
"handle_request",
"(",
"i",
",",
"false",
",",
"connection",
")",
"}",
"elsif",
"Messages",
"::",
"Notification",
".",
"is_notification_message?",
"(",
"intermediate",
")",
"tp",
"<<",
"ThreadPoolJob",
".",
"new",
"(",
"intermediate",
")",
"{",
"|",
"i",
"|",
"handle_request",
"(",
"i",
",",
"true",
",",
"connection",
")",
"}",
"elsif",
"Messages",
"::",
"Response",
".",
"is_response_message?",
"(",
"intermediate",
")",
"handle_response",
"(",
"intermediate",
")",
"end",
"intermediate",
"end"
]
| Internal helper, handle message received | [
"Internal",
"helper",
"handle",
"message",
"received"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/node.rb#L193-L212 | train |
movitto/rjr | lib/rjr/node.rb | RJR.Node.handle_request | def handle_request(message, notification=false, connection={})
# get client for the specified connection
# TODO should grap port/ip immediately on connection and use that
client_port,client_ip = client_for(connection)
msg = notification ?
Messages::Notification.new(:message => message,
:headers => @message_headers) :
Messages::Request.new(:message => message,
:headers => @message_headers)
callback = NodeCallback.new(:node => self,
:connection => connection)
result = @dispatcher.dispatch(:rjr_method => msg.jr_method,
:rjr_method_args => msg.jr_args,
:rjr_headers => msg.headers,
:rjr_client_ip => client_ip,
:rjr_client_port => client_port,
:rjr_node => self,
:rjr_node_id => node_id,
:rjr_node_type => self.node_type,
:rjr_callback => callback)
unless notification
response = Messages::Response.new(:id => msg.msg_id,
:result => result,
:headers => msg.headers,
:request => msg)
self.send_msg(response.to_s, connection)
return response
end
nil
end | ruby | def handle_request(message, notification=false, connection={})
# get client for the specified connection
# TODO should grap port/ip immediately on connection and use that
client_port,client_ip = client_for(connection)
msg = notification ?
Messages::Notification.new(:message => message,
:headers => @message_headers) :
Messages::Request.new(:message => message,
:headers => @message_headers)
callback = NodeCallback.new(:node => self,
:connection => connection)
result = @dispatcher.dispatch(:rjr_method => msg.jr_method,
:rjr_method_args => msg.jr_args,
:rjr_headers => msg.headers,
:rjr_client_ip => client_ip,
:rjr_client_port => client_port,
:rjr_node => self,
:rjr_node_id => node_id,
:rjr_node_type => self.node_type,
:rjr_callback => callback)
unless notification
response = Messages::Response.new(:id => msg.msg_id,
:result => result,
:headers => msg.headers,
:request => msg)
self.send_msg(response.to_s, connection)
return response
end
nil
end | [
"def",
"handle_request",
"(",
"message",
",",
"notification",
"=",
"false",
",",
"connection",
"=",
"{",
"}",
")",
"client_port",
",",
"client_ip",
"=",
"client_for",
"(",
"connection",
")",
"msg",
"=",
"notification",
"?",
"Messages",
"::",
"Notification",
".",
"new",
"(",
":message",
"=>",
"message",
",",
":headers",
"=>",
"@message_headers",
")",
":",
"Messages",
"::",
"Request",
".",
"new",
"(",
":message",
"=>",
"message",
",",
":headers",
"=>",
"@message_headers",
")",
"callback",
"=",
"NodeCallback",
".",
"new",
"(",
":node",
"=>",
"self",
",",
":connection",
"=>",
"connection",
")",
"result",
"=",
"@dispatcher",
".",
"dispatch",
"(",
":rjr_method",
"=>",
"msg",
".",
"jr_method",
",",
":rjr_method_args",
"=>",
"msg",
".",
"jr_args",
",",
":rjr_headers",
"=>",
"msg",
".",
"headers",
",",
":rjr_client_ip",
"=>",
"client_ip",
",",
":rjr_client_port",
"=>",
"client_port",
",",
":rjr_node",
"=>",
"self",
",",
":rjr_node_id",
"=>",
"node_id",
",",
":rjr_node_type",
"=>",
"self",
".",
"node_type",
",",
":rjr_callback",
"=>",
"callback",
")",
"unless",
"notification",
"response",
"=",
"Messages",
"::",
"Response",
".",
"new",
"(",
":id",
"=>",
"msg",
".",
"msg_id",
",",
":result",
"=>",
"result",
",",
":headers",
"=>",
"msg",
".",
"headers",
",",
":request",
"=>",
"msg",
")",
"self",
".",
"send_msg",
"(",
"response",
".",
"to_s",
",",
"connection",
")",
"return",
"response",
"end",
"nil",
"end"
]
| Internal helper, handle request message received | [
"Internal",
"helper",
"handle",
"request",
"message",
"received"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/node.rb#L215-L249 | train |
movitto/rjr | lib/rjr/node.rb | RJR.Node.handle_response | def handle_response(message)
msg = Messages::Response.new(:message => message,
:headers => self.message_headers)
res = err = nil
begin
res = @dispatcher.handle_response(msg.result)
rescue Exception => e
err = e
end
@response_lock.synchronize {
result = [msg.msg_id, res]
result << err if !err.nil?
@responses << result
@response_cv.broadcast
}
end | ruby | def handle_response(message)
msg = Messages::Response.new(:message => message,
:headers => self.message_headers)
res = err = nil
begin
res = @dispatcher.handle_response(msg.result)
rescue Exception => e
err = e
end
@response_lock.synchronize {
result = [msg.msg_id, res]
result << err if !err.nil?
@responses << result
@response_cv.broadcast
}
end | [
"def",
"handle_response",
"(",
"message",
")",
"msg",
"=",
"Messages",
"::",
"Response",
".",
"new",
"(",
":message",
"=>",
"message",
",",
":headers",
"=>",
"self",
".",
"message_headers",
")",
"res",
"=",
"err",
"=",
"nil",
"begin",
"res",
"=",
"@dispatcher",
".",
"handle_response",
"(",
"msg",
".",
"result",
")",
"rescue",
"Exception",
"=>",
"e",
"err",
"=",
"e",
"end",
"@response_lock",
".",
"synchronize",
"{",
"result",
"=",
"[",
"msg",
".",
"msg_id",
",",
"res",
"]",
"result",
"<<",
"err",
"if",
"!",
"err",
".",
"nil?",
"@responses",
"<<",
"result",
"@response_cv",
".",
"broadcast",
"}",
"end"
]
| Internal helper, handle response message received | [
"Internal",
"helper",
"handle",
"response",
"message",
"received"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/node.rb#L252-L268 | train |
movitto/rjr | lib/rjr/node.rb | RJR.Node.wait_for_result | def wait_for_result(message)
res = nil
message_id = message.msg_id
@pending[message_id] = Time.now
while res.nil?
@response_lock.synchronize{
# Prune messages that timed out
if @timeout
now = Time.now
@pending.delete_if { |_, start_time| (now - start_time) > @timeout }
end
pending_ids = @pending.keys
fail 'Timed out' unless pending_ids.include? message_id
# Prune invalid responses
@responses.keep_if { |response| @pending.has_key? response.first }
res = @responses.find { |response| message.msg_id == response.first }
if !res.nil?
@responses.delete(res)
else
@response_cv.wait @response_lock, @wait_interval
end
}
end
return res
end | ruby | def wait_for_result(message)
res = nil
message_id = message.msg_id
@pending[message_id] = Time.now
while res.nil?
@response_lock.synchronize{
# Prune messages that timed out
if @timeout
now = Time.now
@pending.delete_if { |_, start_time| (now - start_time) > @timeout }
end
pending_ids = @pending.keys
fail 'Timed out' unless pending_ids.include? message_id
# Prune invalid responses
@responses.keep_if { |response| @pending.has_key? response.first }
res = @responses.find { |response| message.msg_id == response.first }
if !res.nil?
@responses.delete(res)
else
@response_cv.wait @response_lock, @wait_interval
end
}
end
return res
end | [
"def",
"wait_for_result",
"(",
"message",
")",
"res",
"=",
"nil",
"message_id",
"=",
"message",
".",
"msg_id",
"@pending",
"[",
"message_id",
"]",
"=",
"Time",
".",
"now",
"while",
"res",
".",
"nil?",
"@response_lock",
".",
"synchronize",
"{",
"if",
"@timeout",
"now",
"=",
"Time",
".",
"now",
"@pending",
".",
"delete_if",
"{",
"|",
"_",
",",
"start_time",
"|",
"(",
"now",
"-",
"start_time",
")",
">",
"@timeout",
"}",
"end",
"pending_ids",
"=",
"@pending",
".",
"keys",
"fail",
"'Timed out'",
"unless",
"pending_ids",
".",
"include?",
"message_id",
"@responses",
".",
"keep_if",
"{",
"|",
"response",
"|",
"@pending",
".",
"has_key?",
"response",
".",
"first",
"}",
"res",
"=",
"@responses",
".",
"find",
"{",
"|",
"response",
"|",
"message",
".",
"msg_id",
"==",
"response",
".",
"first",
"}",
"if",
"!",
"res",
".",
"nil?",
"@responses",
".",
"delete",
"(",
"res",
")",
"else",
"@response_cv",
".",
"wait",
"@response_lock",
",",
"@wait_interval",
"end",
"}",
"end",
"return",
"res",
"end"
]
| Internal helper, block until response matching message id is received | [
"Internal",
"helper",
"block",
"until",
"response",
"matching",
"message",
"id",
"is",
"received"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/node.rb#L271-L296 | train |
movitto/rjr | lib/rjr/dispatcher.rb | RJR.Dispatcher.add_module | def add_module(name)
require name
m = name.downcase.gsub(File::SEPARATOR, '_')
method("dispatch_#{m}".intern).call(self)
self
end | ruby | def add_module(name)
require name
m = name.downcase.gsub(File::SEPARATOR, '_')
method("dispatch_#{m}".intern).call(self)
self
end | [
"def",
"add_module",
"(",
"name",
")",
"require",
"name",
"m",
"=",
"name",
".",
"downcase",
".",
"gsub",
"(",
"File",
"::",
"SEPARATOR",
",",
"'_'",
")",
"method",
"(",
"\"dispatch_#{m}\"",
".",
"intern",
")",
".",
"call",
"(",
"self",
")",
"self",
"end"
]
| Loads module from fs and adds handlers defined there
Assumes module includes a 'dispatch_<module_name>' method
which accepts a dispatcher and defines handlers on it.
@param [String] name location which to load module(s) from, may be
a file, directory, or path specification (dirs seperated with ':')
@return self | [
"Loads",
"module",
"from",
"fs",
"and",
"adds",
"handlers",
"defined",
"there"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/dispatcher.rb#L59-L66 | train |
movitto/rjr | lib/rjr/dispatcher.rb | RJR.Dispatcher.handle | def handle(signature, callback = nil, &bl)
if signature.is_a?(Array)
signature.each { |s| handle(s, callback, &bl) }
return self
end
@handlers[signature] = callback unless callback.nil?
@handlers[signature] = bl unless bl.nil?
self
end | ruby | def handle(signature, callback = nil, &bl)
if signature.is_a?(Array)
signature.each { |s| handle(s, callback, &bl) }
return self
end
@handlers[signature] = callback unless callback.nil?
@handlers[signature] = bl unless bl.nil?
self
end | [
"def",
"handle",
"(",
"signature",
",",
"callback",
"=",
"nil",
",",
"&",
"bl",
")",
"if",
"signature",
".",
"is_a?",
"(",
"Array",
")",
"signature",
".",
"each",
"{",
"|",
"s",
"|",
"handle",
"(",
"s",
",",
"callback",
",",
"&",
"bl",
")",
"}",
"return",
"self",
"end",
"@handlers",
"[",
"signature",
"]",
"=",
"callback",
"unless",
"callback",
".",
"nil?",
"@handlers",
"[",
"signature",
"]",
"=",
"bl",
"unless",
"bl",
".",
"nil?",
"self",
"end"
]
| Register json-rpc handler with dispatcher
@param [String,Regex] signature request signature to match
@param [Callable] callback callable object which to bind to signature
@param [Callable] bl block parameter will be set to callback if specified
@return self | [
"Register",
"json",
"-",
"rpc",
"handler",
"with",
"dispatcher"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/dispatcher.rb#L75-L83 | train |
movitto/rjr | lib/rjr/dispatcher.rb | RJR.Dispatcher.handler_for | def handler_for(rjr_method)
# look for exact match first
handler = @handlers.find { |k,v| k == rjr_method }
# if not found try to match regex's
handler ||= @handlers.find { |k,v| k.is_a?(Regexp) && (k =~ rjr_method) }
handler.nil? ? nil : handler.last
end | ruby | def handler_for(rjr_method)
# look for exact match first
handler = @handlers.find { |k,v| k == rjr_method }
# if not found try to match regex's
handler ||= @handlers.find { |k,v| k.is_a?(Regexp) && (k =~ rjr_method) }
handler.nil? ? nil : handler.last
end | [
"def",
"handler_for",
"(",
"rjr_method",
")",
"handler",
"=",
"@handlers",
".",
"find",
"{",
"|",
"k",
",",
"v",
"|",
"k",
"==",
"rjr_method",
"}",
"handler",
"||=",
"@handlers",
".",
"find",
"{",
"|",
"k",
",",
"v",
"|",
"k",
".",
"is_a?",
"(",
"Regexp",
")",
"&&",
"(",
"k",
"=~",
"rjr_method",
")",
"}",
"handler",
".",
"nil?",
"?",
"nil",
":",
"handler",
".",
"last",
"end"
]
| Return handler for specified method.
Currently we match method name string or regex against signature
@param [String] rjr_method string rjr method to match
@return [Callable, nil] callback proc registered to handle rjr_method
or nil if not found | [
"Return",
"handler",
"for",
"specified",
"method",
"."
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/dispatcher.rb#L91-L99 | train |
movitto/rjr | lib/rjr/dispatcher.rb | RJR.Dispatcher.env_for | def env_for(rjr_method)
# look for exact match first
env = @environments.find { |k,v| k == rjr_method }
# if not found try to match regex's
env ||= @environments.find { |k,v| k.is_a?(Regexp) && (k =~ rjr_method) }
env.nil? ? nil : env.last
end | ruby | def env_for(rjr_method)
# look for exact match first
env = @environments.find { |k,v| k == rjr_method }
# if not found try to match regex's
env ||= @environments.find { |k,v| k.is_a?(Regexp) && (k =~ rjr_method) }
env.nil? ? nil : env.last
end | [
"def",
"env_for",
"(",
"rjr_method",
")",
"env",
"=",
"@environments",
".",
"find",
"{",
"|",
"k",
",",
"v",
"|",
"k",
"==",
"rjr_method",
"}",
"env",
"||=",
"@environments",
".",
"find",
"{",
"|",
"k",
",",
"v",
"|",
"k",
".",
"is_a?",
"(",
"Regexp",
")",
"&&",
"(",
"k",
"=~",
"rjr_method",
")",
"}",
"env",
".",
"nil?",
"?",
"nil",
":",
"env",
".",
"last",
"end"
]
| Return the environment registered for the specified method | [
"Return",
"the",
"environment",
"registered",
"for",
"the",
"specified",
"method"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/dispatcher.rb#L127-L135 | train |
movitto/rjr | lib/rjr/util/em_adapter.rb | RJR.EMAdapter.start | def start
@em_lock.synchronize{
# TODO on event of the process ending this thread will be
# shutdown before a local finalizer can be run,
# would be good to gracefully shut this down / wait for completion
@reactor_thread = Thread.new {
begin
EventMachine.run
rescue Exception => e
# TODO option to autorestart the reactor on errors ?
puts "Critical exception #{e}\n#{e.backtrace.join("\n")}"
ensure
@em_lock.synchronize { @reactor_thread = nil }
end
} unless @reactor_thread
}
sleep 0.01 until EventMachine.reactor_running? # XXX hack but needed
self
end | ruby | def start
@em_lock.synchronize{
# TODO on event of the process ending this thread will be
# shutdown before a local finalizer can be run,
# would be good to gracefully shut this down / wait for completion
@reactor_thread = Thread.new {
begin
EventMachine.run
rescue Exception => e
# TODO option to autorestart the reactor on errors ?
puts "Critical exception #{e}\n#{e.backtrace.join("\n")}"
ensure
@em_lock.synchronize { @reactor_thread = nil }
end
} unless @reactor_thread
}
sleep 0.01 until EventMachine.reactor_running? # XXX hack but needed
self
end | [
"def",
"start",
"@em_lock",
".",
"synchronize",
"{",
"@reactor_thread",
"=",
"Thread",
".",
"new",
"{",
"begin",
"EventMachine",
".",
"run",
"rescue",
"Exception",
"=>",
"e",
"puts",
"\"Critical exception #{e}\\n#{e.backtrace.join(\"\\n\")}\"",
"ensure",
"@em_lock",
".",
"synchronize",
"{",
"@reactor_thread",
"=",
"nil",
"}",
"end",
"}",
"unless",
"@reactor_thread",
"}",
"sleep",
"0.01",
"until",
"EventMachine",
".",
"reactor_running?",
"self",
"end"
]
| EMAdapter initializer
Start the eventmachine reactor thread if not running | [
"EMAdapter",
"initializer",
"Start",
"the",
"eventmachine",
"reactor",
"thread",
"if",
"not",
"running"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/util/em_adapter.rb#L27-L45 | train |
movitto/rjr | lib/rjr/request.rb | RJR.Request.handle | def handle
node_sig = "#{@rjr_node_id}(#{@rjr_node_type})"
method_sig = "#{@rjr_method}(#{@rjr_method_args.join(',')})"
RJR::Logger.info "#{node_sig}->#{method_sig}"
# TODO option to compare arity of handler to number
# of method_args passed in ?
retval = instance_exec(*@rjr_method_args, &@rjr_handler)
RJR::Logger.info \
"#{node_sig}<-#{method_sig}<-#{retval.nil? ? "nil" : retval}"
return retval
end | ruby | def handle
node_sig = "#{@rjr_node_id}(#{@rjr_node_type})"
method_sig = "#{@rjr_method}(#{@rjr_method_args.join(',')})"
RJR::Logger.info "#{node_sig}->#{method_sig}"
# TODO option to compare arity of handler to number
# of method_args passed in ?
retval = instance_exec(*@rjr_method_args, &@rjr_handler)
RJR::Logger.info \
"#{node_sig}<-#{method_sig}<-#{retval.nil? ? "nil" : retval}"
return retval
end | [
"def",
"handle",
"node_sig",
"=",
"\"#{@rjr_node_id}(#{@rjr_node_type})\"",
"method_sig",
"=",
"\"#{@rjr_method}(#{@rjr_method_args.join(',')})\"",
"RJR",
"::",
"Logger",
".",
"info",
"\"#{node_sig}->#{method_sig}\"",
"retval",
"=",
"instance_exec",
"(",
"*",
"@rjr_method_args",
",",
"&",
"@rjr_handler",
")",
"RJR",
"::",
"Logger",
".",
"info",
"\"#{node_sig}<-#{method_sig}<-#{retval.nil? ? \"nil\" : retval}\"",
"return",
"retval",
"end"
]
| Invoke the request by calling the registered handler with the registered
method parameters in the local scope | [
"Invoke",
"the",
"request",
"by",
"calling",
"the",
"registered",
"handler",
"with",
"the",
"registered",
"method",
"parameters",
"in",
"the",
"local",
"scope"
]
| 219f970fbe3a1298d59fc820fdcf968d527fd567 | https://github.com/movitto/rjr/blob/219f970fbe3a1298d59fc820fdcf968d527fd567/lib/rjr/request.rb#L91-L105 | train |
mobi/telephone_number | lib/telephone_number/parser.rb | TelephoneNumber.Parser.validate | def validate
return [] unless country
country.validations.select do |validation|
normalized_number.match?(Regexp.new("^(#{validation.pattern})$"))
end.map(&:name)
end | ruby | def validate
return [] unless country
country.validations.select do |validation|
normalized_number.match?(Regexp.new("^(#{validation.pattern})$"))
end.map(&:name)
end | [
"def",
"validate",
"return",
"[",
"]",
"unless",
"country",
"country",
".",
"validations",
".",
"select",
"do",
"|",
"validation",
"|",
"normalized_number",
".",
"match?",
"(",
"Regexp",
".",
"new",
"(",
"\"^(#{validation.pattern})$\"",
")",
")",
"end",
".",
"map",
"(",
"&",
":name",
")",
"end"
]
| returns an array of valid types for the normalized number
if array is empty, we can assume that the number is invalid | [
"returns",
"an",
"array",
"of",
"valid",
"types",
"for",
"the",
"normalized",
"number",
"if",
"array",
"is",
"empty",
"we",
"can",
"assume",
"that",
"the",
"number",
"is",
"invalid"
]
| 23dbca268be00a6437f0c0d94126e05d4c70b99c | https://github.com/mobi/telephone_number/blob/23dbca268be00a6437f0c0d94126e05d4c70b99c/lib/telephone_number/parser.rb#L31-L36 | train |
loadsmart/danger-pep8 | lib/pep8/plugin.rb | Danger.DangerPep8.lint | def lint(use_inline_comments=false)
ensure_flake8_is_installed
errors = run_flake
return if errors.empty? || errors.count <= threshold
if use_inline_comments
comment_inline(errors)
else
print_markdown_table(errors)
end
end | ruby | def lint(use_inline_comments=false)
ensure_flake8_is_installed
errors = run_flake
return if errors.empty? || errors.count <= threshold
if use_inline_comments
comment_inline(errors)
else
print_markdown_table(errors)
end
end | [
"def",
"lint",
"(",
"use_inline_comments",
"=",
"false",
")",
"ensure_flake8_is_installed",
"errors",
"=",
"run_flake",
"return",
"if",
"errors",
".",
"empty?",
"||",
"errors",
".",
"count",
"<=",
"threshold",
"if",
"use_inline_comments",
"comment_inline",
"(",
"errors",
")",
"else",
"print_markdown_table",
"(",
"errors",
")",
"end",
"end"
]
| Lint all python files inside a given directory. Defaults to "."
@return [void] | [
"Lint",
"all",
"python",
"files",
"inside",
"a",
"given",
"directory",
".",
"Defaults",
"to",
"."
]
| cc6b236fabed72f42a521b31d5ed9be012504a4f | https://github.com/loadsmart/danger-pep8/blob/cc6b236fabed72f42a521b31d5ed9be012504a4f/lib/pep8/plugin.rb#L57-L68 | train |
NestAway/salesforce-orm | lib/salesforce-orm/base.rb | SalesforceOrm.Base.create! | def create!(attributes)
new_attributes = map_to_keys(attributes)
new_attributes = new_attributes.merge(
RecordTypeManager::FIELD_NAME => klass.record_type_id
) if klass.record_type_id
client.create!(klass.object_name, new_attributes)
end | ruby | def create!(attributes)
new_attributes = map_to_keys(attributes)
new_attributes = new_attributes.merge(
RecordTypeManager::FIELD_NAME => klass.record_type_id
) if klass.record_type_id
client.create!(klass.object_name, new_attributes)
end | [
"def",
"create!",
"(",
"attributes",
")",
"new_attributes",
"=",
"map_to_keys",
"(",
"attributes",
")",
"new_attributes",
"=",
"new_attributes",
".",
"merge",
"(",
"RecordTypeManager",
"::",
"FIELD_NAME",
"=>",
"klass",
".",
"record_type_id",
")",
"if",
"klass",
".",
"record_type_id",
"client",
".",
"create!",
"(",
"klass",
".",
"object_name",
",",
"new_attributes",
")",
"end"
]
| create! doesn't return the SalesForce object back
It will return only the object id | [
"create!",
"doesn",
"t",
"return",
"the",
"SalesForce",
"object",
"back",
"It",
"will",
"return",
"only",
"the",
"object",
"id"
]
| aa92a110cfd9a937b561f5d287d354d5efbc0335 | https://github.com/NestAway/salesforce-orm/blob/aa92a110cfd9a937b561f5d287d354d5efbc0335/lib/salesforce-orm/base.rb#L34-L42 | train |
skroutz/rafka-rb | lib/rafka/producer.rb | Rafka.Producer.produce | def produce(topic, msg, key: nil)
Rafka.wrap_errors do
redis_key = "topics:#{topic}"
redis_key << ":#{key}" if key
@redis.rpushx(redis_key, msg.to_s)
end
end | ruby | def produce(topic, msg, key: nil)
Rafka.wrap_errors do
redis_key = "topics:#{topic}"
redis_key << ":#{key}" if key
@redis.rpushx(redis_key, msg.to_s)
end
end | [
"def",
"produce",
"(",
"topic",
",",
"msg",
",",
"key",
":",
"nil",
")",
"Rafka",
".",
"wrap_errors",
"do",
"redis_key",
"=",
"\"topics:#{topic}\"",
"redis_key",
"<<",
"\":#{key}\"",
"if",
"key",
"@redis",
".",
"rpushx",
"(",
"redis_key",
",",
"msg",
".",
"to_s",
")",
"end",
"end"
]
| Create a new producer.
@param [Hash] opts
@option opts [String] :host ("localhost") server hostname
@option opts [Fixnum] :port (6380) server port
@option opts [Hash] :redis Configuration options for the underlying
Redis client
@return [Producer]
Produce a message to a topic. This is an asynchronous operation.
@param topic [String]
@param msg [#to_s] the message
@param key [#to_s] an optional partition hashing key. Two or more messages
with the same key will always be written to the same partition.
@example Simple produce
producer = Rafka::Producer.new
producer.produce("greetings", "Hello there!")
@example Produce two messages with a hashing key. Those messages are guaranteed to be written to the same partition
producer = Rafka::Producer.new
produce("greetings", "Aloha", key: "abc")
produce("greetings", "Hola", key: "abc") | [
"Create",
"a",
"new",
"producer",
"."
]
| 217507aafd8234755194b9f463f2c4c5dc66cd40 | https://github.com/skroutz/rafka-rb/blob/217507aafd8234755194b9f463f2c4c5dc66cd40/lib/rafka/producer.rb#L41-L47 | train |
plated/maitredee | lib/maitredee/publisher.rb | Maitredee.Publisher.publish | def publish(topic_name: nil, event_name: nil, schema_name: nil, primary_key: nil, body:)
defaults = self.class.get_publish_defaults
published_messages << Maitredee.publish(
topic_name: topic_name || defaults[:topic_name],
event_name: event_name || defaults[:event_name],
schema_name: schema_name || defaults[:schema_name],
primary_key: primary_key,
body: body
)
end | ruby | def publish(topic_name: nil, event_name: nil, schema_name: nil, primary_key: nil, body:)
defaults = self.class.get_publish_defaults
published_messages << Maitredee.publish(
topic_name: topic_name || defaults[:topic_name],
event_name: event_name || defaults[:event_name],
schema_name: schema_name || defaults[:schema_name],
primary_key: primary_key,
body: body
)
end | [
"def",
"publish",
"(",
"topic_name",
":",
"nil",
",",
"event_name",
":",
"nil",
",",
"schema_name",
":",
"nil",
",",
"primary_key",
":",
"nil",
",",
"body",
":",
")",
"defaults",
"=",
"self",
".",
"class",
".",
"get_publish_defaults",
"published_messages",
"<<",
"Maitredee",
".",
"publish",
"(",
"topic_name",
":",
"topic_name",
"||",
"defaults",
"[",
":topic_name",
"]",
",",
"event_name",
":",
"event_name",
"||",
"defaults",
"[",
":event_name",
"]",
",",
"schema_name",
":",
"schema_name",
"||",
"defaults",
"[",
":schema_name",
"]",
",",
"primary_key",
":",
"primary_key",
",",
"body",
":",
"body",
")",
"end"
]
| publish a message with defaults
@param topic_name [#to_s, nil]
@param event_name [#to_s, nil]
@param schema_name [#to_s, nil]
@param primary_key [#to_s, nil]
@param body [#to_json] | [
"publish",
"a",
"message",
"with",
"defaults"
]
| 77d879314c12dceb3d88e645ff29c4daebaac3a9 | https://github.com/plated/maitredee/blob/77d879314c12dceb3d88e645ff29c4daebaac3a9/lib/maitredee/publisher.rb#L74-L83 | train |
skroutz/rafka-rb | lib/rafka/consumer.rb | Rafka.Consumer.consume | def consume(timeout=5)
raised = false
msg = consume_one(timeout)
return nil if !msg
begin
yield(msg) if block_given?
rescue => e
raised = true
raise e
end
msg
ensure
commit(msg) if @rafka_opts[:auto_commit] && msg && !raised
end | ruby | def consume(timeout=5)
raised = false
msg = consume_one(timeout)
return nil if !msg
begin
yield(msg) if block_given?
rescue => e
raised = true
raise e
end
msg
ensure
commit(msg) if @rafka_opts[:auto_commit] && msg && !raised
end | [
"def",
"consume",
"(",
"timeout",
"=",
"5",
")",
"raised",
"=",
"false",
"msg",
"=",
"consume_one",
"(",
"timeout",
")",
"return",
"nil",
"if",
"!",
"msg",
"begin",
"yield",
"(",
"msg",
")",
"if",
"block_given?",
"rescue",
"=>",
"e",
"raised",
"=",
"true",
"raise",
"e",
"end",
"msg",
"ensure",
"commit",
"(",
"msg",
")",
"if",
"@rafka_opts",
"[",
":auto_commit",
"]",
"&&",
"msg",
"&&",
"!",
"raised",
"end"
]
| Initialize a new consumer.
@param [Hash] opts
@option opts [String] :host ("localhost") server hostname
@option opts [Fixnum] :port (6380) server port
@option opts [String] :topic Kafka topic to consume (required)
@option opts [String] :group Kafka consumer group name (required)
@option opts [String] :id (random) Kafka consumer id
@option opts [Boolean] :auto_commit (true) automatically commit
offsets
@option opts [Hash] :librdkafka ({}) librdkafka configuration. It will
be merged over the existing configuration set in the server.
See https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md
for more information
@option opts [Hash] :redis ({}) Configuration for the underlying Redis
client. See {REDIS_DEFAULTS}
@raise [RuntimeError] if a required option was not provided
(see {REQUIRED_OPTS})
@return [Consumer]
Consumes the next message.
If :auto_commit is true, offsets are committed automatically.
In the block form, offsets are committed only if the block executes
without raising any exceptions.
If :auto_commit is false, offsets have to be committed manually using
{#commit}.
@param timeout [Fixnum] the time in seconds to wait for a message. If
reached, {#consume} returns nil.
@yieldparam [Message] msg the consumed message
@raise [MalformedMessageError] if the message cannot be parsed
@raise [ConsumeError] if there was a server error
@return [nil, Message] the consumed message, or nil of there wasn't any
@example Consume a message
msg = consumer.consume
msg.value # => "hi"
@example Consume a message and commit offset if the block does not raise an exception
consumer.consume { |msg| puts "I received #{msg.value}" } | [
"Initialize",
"a",
"new",
"consumer",
"."
]
| 217507aafd8234755194b9f463f2c4c5dc66cd40 | https://github.com/skroutz/rafka-rb/blob/217507aafd8234755194b9f463f2c4c5dc66cd40/lib/rafka/consumer.rb#L79-L95 | train |
skroutz/rafka-rb | lib/rafka/consumer.rb | Rafka.Consumer.consume_batch | def consume_batch(timeout: 1.0, batch_size: 0, batching_max_sec: 0)
if batch_size == 0 && batching_max_sec == 0
raise ArgumentError, "one of batch_size or batching_max_sec must be greater than 0"
end
raised = false
start_time = Time.now
msgs = []
loop do
break if batch_size > 0 && msgs.size >= batch_size
break if batching_max_sec > 0 && (Time.now - start_time >= batching_max_sec)
msg = consume_one(timeout)
msgs << msg if msg
end
begin
yield(msgs) if block_given?
rescue => e
raised = true
raise e
end
msgs
ensure
commit(*msgs) if @rafka_opts[:auto_commit] && !raised
end | ruby | def consume_batch(timeout: 1.0, batch_size: 0, batching_max_sec: 0)
if batch_size == 0 && batching_max_sec == 0
raise ArgumentError, "one of batch_size or batching_max_sec must be greater than 0"
end
raised = false
start_time = Time.now
msgs = []
loop do
break if batch_size > 0 && msgs.size >= batch_size
break if batching_max_sec > 0 && (Time.now - start_time >= batching_max_sec)
msg = consume_one(timeout)
msgs << msg if msg
end
begin
yield(msgs) if block_given?
rescue => e
raised = true
raise e
end
msgs
ensure
commit(*msgs) if @rafka_opts[:auto_commit] && !raised
end | [
"def",
"consume_batch",
"(",
"timeout",
":",
"1.0",
",",
"batch_size",
":",
"0",
",",
"batching_max_sec",
":",
"0",
")",
"if",
"batch_size",
"==",
"0",
"&&",
"batching_max_sec",
"==",
"0",
"raise",
"ArgumentError",
",",
"\"one of batch_size or batching_max_sec must be greater than 0\"",
"end",
"raised",
"=",
"false",
"start_time",
"=",
"Time",
".",
"now",
"msgs",
"=",
"[",
"]",
"loop",
"do",
"break",
"if",
"batch_size",
">",
"0",
"&&",
"msgs",
".",
"size",
">=",
"batch_size",
"break",
"if",
"batching_max_sec",
">",
"0",
"&&",
"(",
"Time",
".",
"now",
"-",
"start_time",
">=",
"batching_max_sec",
")",
"msg",
"=",
"consume_one",
"(",
"timeout",
")",
"msgs",
"<<",
"msg",
"if",
"msg",
"end",
"begin",
"yield",
"(",
"msgs",
")",
"if",
"block_given?",
"rescue",
"=>",
"e",
"raised",
"=",
"true",
"raise",
"e",
"end",
"msgs",
"ensure",
"commit",
"(",
"*",
"msgs",
")",
"if",
"@rafka_opts",
"[",
":auto_commit",
"]",
"&&",
"!",
"raised",
"end"
]
| Consume a batch of messages.
Messages are accumulated in a batch until (a) batch_size number of
messages are accumulated or (b) batching_max_sec seconds have passed.
When either of the conditions is met the batch is returned.
If :auto_commit is true, offsets are committed automatically.
In the block form, offsets are committed only if the block executes
without raising any exceptions.
If :auto_commit is false, offsets have to be committed manually using
{#commit}.
@note Either one of, or both batch_size and batching_max_sec may be
provided, but not neither.
@param timeout [Fixnum] the time in seconds to wait for each message
@param batch_size [Fixnum] maximum number of messages to accumulate
in the batch
@param batching_max_sec [Fixnum] maximum time in seconds to wait for
messages to accumulate in the batch
@yieldparam [Array<Message>] msgs the batch
@raise [MalformedMessageError] if a message cannot be parsed
@raise [ConsumeError] if there was a server error
@raise [ArgumentError] if neither batch_size nor batching_max_sec were
provided
@return [Array<Message>] the batch
@example Consume a batch of 10 messages
msgs = consumer.consume_batch(batch_size: 10)
msgs.size # => 10
@example Accumulate messages for 5 seconds and consume the batch
msgs = consumer.consume_batch(batching_max_sec: 5)
msgs.size # => 3813 | [
"Consume",
"a",
"batch",
"of",
"messages",
"."
]
| 217507aafd8234755194b9f463f2c4c5dc66cd40 | https://github.com/skroutz/rafka-rb/blob/217507aafd8234755194b9f463f2c4c5dc66cd40/lib/rafka/consumer.rb#L135-L161 | train |
skroutz/rafka-rb | lib/rafka/consumer.rb | Rafka.Consumer.commit | def commit(*msgs)
tp = prepare_for_commit(*msgs)
tp.each do |topic, po|
po.each do |partition, offset|
Rafka.wrap_errors do
@redis.rpush("acks", "#{topic}:#{partition}:#{offset}")
end
end
end
tp
end | ruby | def commit(*msgs)
tp = prepare_for_commit(*msgs)
tp.each do |topic, po|
po.each do |partition, offset|
Rafka.wrap_errors do
@redis.rpush("acks", "#{topic}:#{partition}:#{offset}")
end
end
end
tp
end | [
"def",
"commit",
"(",
"*",
"msgs",
")",
"tp",
"=",
"prepare_for_commit",
"(",
"*",
"msgs",
")",
"tp",
".",
"each",
"do",
"|",
"topic",
",",
"po",
"|",
"po",
".",
"each",
"do",
"|",
"partition",
",",
"offset",
"|",
"Rafka",
".",
"wrap_errors",
"do",
"@redis",
".",
"rpush",
"(",
"\"acks\"",
",",
"\"#{topic}:#{partition}:#{offset}\"",
")",
"end",
"end",
"end",
"tp",
"end"
]
| Commit offsets for the given messages.
If more than one messages refer to the same topic/partition pair,
only the largest offset amongst them is committed.
@note This is non-blocking operation; a successful server reply means
offsets are received by the server and will _eventually_ be submitted
to Kafka. It is not guaranteed that offsets will be actually committed
in case of failures.
@param msgs [Array<Message>] any number of messages for which to commit
offsets
@raise [ConsumeError] if there was a server error
@return [Hash{String=>Hash{Fixnum=>Fixnum}}] the actual offsets sent
to the server for commit. Keys contain topics while values contain
the respective partition/offset pairs. | [
"Commit",
"offsets",
"for",
"the",
"given",
"messages",
"."
]
| 217507aafd8234755194b9f463f2c4c5dc66cd40 | https://github.com/skroutz/rafka-rb/blob/217507aafd8234755194b9f463f2c4c5dc66cd40/lib/rafka/consumer.rb#L181-L193 | train |
skroutz/rafka-rb | lib/rafka/consumer.rb | Rafka.Consumer.prepare_for_commit | def prepare_for_commit(*msgs)
tp = Hash.new { |h, k| h[k] = Hash.new(0) }
msgs.each do |msg|
if msg.offset >= tp[msg.topic][msg.partition]
tp[msg.topic][msg.partition] = msg.offset
end
end
tp
end | ruby | def prepare_for_commit(*msgs)
tp = Hash.new { |h, k| h[k] = Hash.new(0) }
msgs.each do |msg|
if msg.offset >= tp[msg.topic][msg.partition]
tp[msg.topic][msg.partition] = msg.offset
end
end
tp
end | [
"def",
"prepare_for_commit",
"(",
"*",
"msgs",
")",
"tp",
"=",
"Hash",
".",
"new",
"{",
"|",
"h",
",",
"k",
"|",
"h",
"[",
"k",
"]",
"=",
"Hash",
".",
"new",
"(",
"0",
")",
"}",
"msgs",
".",
"each",
"do",
"|",
"msg",
"|",
"if",
"msg",
".",
"offset",
">=",
"tp",
"[",
"msg",
".",
"topic",
"]",
"[",
"msg",
".",
"partition",
"]",
"tp",
"[",
"msg",
".",
"topic",
"]",
"[",
"msg",
".",
"partition",
"]",
"=",
"msg",
".",
"offset",
"end",
"end",
"tp",
"end"
]
| Accepts one or more messages and prepare them for commit.
@param msgs [Array<Message>]
@return [Hash{String=>Hash{Fixnum=>Fixnum}}] the offsets to be committed.
Keys denote the topics while values contain the partition=>offset pairs. | [
"Accepts",
"one",
"or",
"more",
"messages",
"and",
"prepare",
"them",
"for",
"commit",
"."
]
| 217507aafd8234755194b9f463f2c4c5dc66cd40 | https://github.com/skroutz/rafka-rb/blob/217507aafd8234755194b9f463f2c4c5dc66cd40/lib/rafka/consumer.rb#L221-L231 | train |
ruby-x/rubyx | lib/parfait/space.rb | Parfait.Space.add_type | def add_type( type )
hash = type.hash
raise "upps #{hash} #{hash.class}" unless hash.is_a?(::Integer)
was = types[hash]
return was if was
types[hash] = type
end | ruby | def add_type( type )
hash = type.hash
raise "upps #{hash} #{hash.class}" unless hash.is_a?(::Integer)
was = types[hash]
return was if was
types[hash] = type
end | [
"def",
"add_type",
"(",
"type",
")",
"hash",
"=",
"type",
".",
"hash",
"raise",
"\"upps #{hash} #{hash.class}\"",
"unless",
"hash",
".",
"is_a?",
"(",
"::",
"Integer",
")",
"was",
"=",
"types",
"[",
"hash",
"]",
"return",
"was",
"if",
"was",
"types",
"[",
"hash",
"]",
"=",
"type",
"end"
]
| add a type, meaning the instance given must be a valid type | [
"add",
"a",
"type",
"meaning",
"the",
"instance",
"given",
"must",
"be",
"a",
"valid",
"type"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/parfait/space.rb#L86-L92 | train |
ruby-x/rubyx | lib/parfait/space.rb | Parfait.Space.get_all_methods | def get_all_methods
methods = []
each_type do | type |
type.each_method do |meth|
methods << meth
end
end
methods
end | ruby | def get_all_methods
methods = []
each_type do | type |
type.each_method do |meth|
methods << meth
end
end
methods
end | [
"def",
"get_all_methods",
"methods",
"=",
"[",
"]",
"each_type",
"do",
"|",
"type",
"|",
"type",
".",
"each_method",
"do",
"|",
"meth",
"|",
"methods",
"<<",
"meth",
"end",
"end",
"methods",
"end"
]
| all methods form all types | [
"all",
"methods",
"form",
"all",
"types"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/parfait/space.rb#L100-L108 | train |
tootsuite/ostatus2 | lib/ostatus2/salmon.rb | OStatus2.Salmon.pack | def pack(body, key)
signed = plaintext_signature(body, 'application/atom+xml', 'base64url', 'RSA-SHA256')
signature = Base64.urlsafe_encode64(key.sign(digest, signed))
Nokogiri::XML::Builder.new do |xml|
xml['me'].env({ 'xmlns:me' => XMLNS }) do
xml['me'].data({ type: 'application/atom+xml' }, Base64.urlsafe_encode64(body))
xml['me'].encoding('base64url')
xml['me'].alg('RSA-SHA256')
xml['me'].sig({ key_id: Base64.urlsafe_encode64(key.public_key.to_s) }, signature)
end
end.to_xml
end | ruby | def pack(body, key)
signed = plaintext_signature(body, 'application/atom+xml', 'base64url', 'RSA-SHA256')
signature = Base64.urlsafe_encode64(key.sign(digest, signed))
Nokogiri::XML::Builder.new do |xml|
xml['me'].env({ 'xmlns:me' => XMLNS }) do
xml['me'].data({ type: 'application/atom+xml' }, Base64.urlsafe_encode64(body))
xml['me'].encoding('base64url')
xml['me'].alg('RSA-SHA256')
xml['me'].sig({ key_id: Base64.urlsafe_encode64(key.public_key.to_s) }, signature)
end
end.to_xml
end | [
"def",
"pack",
"(",
"body",
",",
"key",
")",
"signed",
"=",
"plaintext_signature",
"(",
"body",
",",
"'application/atom+xml'",
",",
"'base64url'",
",",
"'RSA-SHA256'",
")",
"signature",
"=",
"Base64",
".",
"urlsafe_encode64",
"(",
"key",
".",
"sign",
"(",
"digest",
",",
"signed",
")",
")",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"do",
"|",
"xml",
"|",
"xml",
"[",
"'me'",
"]",
".",
"env",
"(",
"{",
"'xmlns:me'",
"=>",
"XMLNS",
"}",
")",
"do",
"xml",
"[",
"'me'",
"]",
".",
"data",
"(",
"{",
"type",
":",
"'application/atom+xml'",
"}",
",",
"Base64",
".",
"urlsafe_encode64",
"(",
"body",
")",
")",
"xml",
"[",
"'me'",
"]",
".",
"encoding",
"(",
"'base64url'",
")",
"xml",
"[",
"'me'",
"]",
".",
"alg",
"(",
"'RSA-SHA256'",
")",
"xml",
"[",
"'me'",
"]",
".",
"sig",
"(",
"{",
"key_id",
":",
"Base64",
".",
"urlsafe_encode64",
"(",
"key",
".",
"public_key",
".",
"to_s",
")",
"}",
",",
"signature",
")",
"end",
"end",
".",
"to_xml",
"end"
]
| Create a magical envelope XML document around the original body
and sign it with a private key
@param [String] body
@param [OpenSSL::PKey::RSA] key The private part of the key will be used
@return [String] Magical envelope XML | [
"Create",
"a",
"magical",
"envelope",
"XML",
"document",
"around",
"the",
"original",
"body",
"and",
"sign",
"it",
"with",
"a",
"private",
"key"
]
| d967e6bffd490ae27a5ad41775e8503c3b6e25e2 | https://github.com/tootsuite/ostatus2/blob/d967e6bffd490ae27a5ad41775e8503c3b6e25e2/lib/ostatus2/salmon.rb#L12-L24 | train |
tootsuite/ostatus2 | lib/ostatus2/salmon.rb | OStatus2.Salmon.post | def post(salmon_url, envelope)
http_client.headers(HTTP::Headers::CONTENT_TYPE => 'application/magic-envelope+xml').post(Addressable::URI.parse(salmon_url), body: envelope)
end | ruby | def post(salmon_url, envelope)
http_client.headers(HTTP::Headers::CONTENT_TYPE => 'application/magic-envelope+xml').post(Addressable::URI.parse(salmon_url), body: envelope)
end | [
"def",
"post",
"(",
"salmon_url",
",",
"envelope",
")",
"http_client",
".",
"headers",
"(",
"HTTP",
"::",
"Headers",
"::",
"CONTENT_TYPE",
"=>",
"'application/magic-envelope+xml'",
")",
".",
"post",
"(",
"Addressable",
"::",
"URI",
".",
"parse",
"(",
"salmon_url",
")",
",",
"body",
":",
"envelope",
")",
"end"
]
| Deliver the magical envelope to a Salmon endpoint
@param [String] salmon_url Salmon endpoint URL
@param [String] envelope Magical envelope
@raise [HTTP::Error] Error raised upon delivery failure
@raise [OpenSSL::SSL::SSLError] Error raised upon SSL-related failure during delivery
@return [HTTP::Response] | [
"Deliver",
"the",
"magical",
"envelope",
"to",
"a",
"Salmon",
"endpoint"
]
| d967e6bffd490ae27a5ad41775e8503c3b6e25e2 | https://github.com/tootsuite/ostatus2/blob/d967e6bffd490ae27a5ad41775e8503c3b6e25e2/lib/ostatus2/salmon.rb#L32-L34 | train |
tootsuite/ostatus2 | lib/ostatus2/salmon.rb | OStatus2.Salmon.verify | def verify(raw_body, key)
_, plaintext, signature = parse(raw_body)
key.public_key.verify(digest, signature, plaintext)
rescue OStatus2::BadSalmonError
false
end | ruby | def verify(raw_body, key)
_, plaintext, signature = parse(raw_body)
key.public_key.verify(digest, signature, plaintext)
rescue OStatus2::BadSalmonError
false
end | [
"def",
"verify",
"(",
"raw_body",
",",
"key",
")",
"_",
",",
"plaintext",
",",
"signature",
"=",
"parse",
"(",
"raw_body",
")",
"key",
".",
"public_key",
".",
"verify",
"(",
"digest",
",",
"signature",
",",
"plaintext",
")",
"rescue",
"OStatus2",
"::",
"BadSalmonError",
"false",
"end"
]
| Verify the magical envelope's integrity
@param [String] raw_body Magical envelope
@param [OpenSSL::PKey::RSA] key The public part of the key will be used
@return [Boolean] | [
"Verify",
"the",
"magical",
"envelope",
"s",
"integrity"
]
| d967e6bffd490ae27a5ad41775e8503c3b6e25e2 | https://github.com/tootsuite/ostatus2/blob/d967e6bffd490ae27a5ad41775e8503c3b6e25e2/lib/ostatus2/salmon.rb#L49-L54 | train |
ruby-x/rubyx | lib/risc/builder.rb | Risc.Builder.swap_names | def swap_names(left , right)
left , right = left.to_s , right.to_s
l = @names[left]
r = @names[right]
raise "No such name #{left}" unless l
raise "No such name #{right}" unless r
@names[left] = r
@names[right] = l
end | ruby | def swap_names(left , right)
left , right = left.to_s , right.to_s
l = @names[left]
r = @names[right]
raise "No such name #{left}" unless l
raise "No such name #{right}" unless r
@names[left] = r
@names[right] = l
end | [
"def",
"swap_names",
"(",
"left",
",",
"right",
")",
"left",
",",
"right",
"=",
"left",
".",
"to_s",
",",
"right",
".",
"to_s",
"l",
"=",
"@names",
"[",
"left",
"]",
"r",
"=",
"@names",
"[",
"right",
"]",
"raise",
"\"No such name #{left}\"",
"unless",
"l",
"raise",
"\"No such name #{right}\"",
"unless",
"r",
"@names",
"[",
"left",
"]",
"=",
"r",
"@names",
"[",
"right",
"]",
"=",
"l",
"end"
]
| To avoid many an if, it can be handy to swap variable names.
But since the names in the builder are not variables, we need this method.
As it says, swap the two names around. Names must exist | [
"To",
"avoid",
"many",
"an",
"if",
"it",
"can",
"be",
"handy",
"to",
"swap",
"variable",
"names",
".",
"But",
"since",
"the",
"names",
"in",
"the",
"builder",
"are",
"not",
"variables",
"we",
"need",
"this",
"method",
".",
"As",
"it",
"says",
"swap",
"the",
"two",
"names",
"around",
".",
"Names",
"must",
"exist"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/risc/builder.rb#L95-L103 | train |
ruby-x/rubyx | lib/mom/mom_compiler.rb | Mom.MomCompiler.translate_method | def translate_method( method_compiler , translator)
all = []
all << translate_cpu( method_compiler , translator )
method_compiler.block_compilers.each do |block_compiler|
all << translate_cpu(block_compiler , translator)
end
all
end | ruby | def translate_method( method_compiler , translator)
all = []
all << translate_cpu( method_compiler , translator )
method_compiler.block_compilers.each do |block_compiler|
all << translate_cpu(block_compiler , translator)
end
all
end | [
"def",
"translate_method",
"(",
"method_compiler",
",",
"translator",
")",
"all",
"=",
"[",
"]",
"all",
"<<",
"translate_cpu",
"(",
"method_compiler",
",",
"translator",
")",
"method_compiler",
".",
"block_compilers",
".",
"each",
"do",
"|",
"block_compiler",
"|",
"all",
"<<",
"translate_cpu",
"(",
"block_compiler",
",",
"translator",
")",
"end",
"all",
"end"
]
| translate one method, which means the method itself and all blocks inside it
returns an array of assemblers | [
"translate",
"one",
"method",
"which",
"means",
"the",
"method",
"itself",
"and",
"all",
"blocks",
"inside",
"it",
"returns",
"an",
"array",
"of",
"assemblers"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/mom/mom_compiler.rb#L66-L73 | train |
tootsuite/ostatus2 | lib/ostatus2/subscription.rb | OStatus2.Subscription.verify | def verify(content, signature)
hmac = OpenSSL::HMAC.hexdigest('sha1', @secret, content)
signature.downcase == "sha1=#{hmac}"
end | ruby | def verify(content, signature)
hmac = OpenSSL::HMAC.hexdigest('sha1', @secret, content)
signature.downcase == "sha1=#{hmac}"
end | [
"def",
"verify",
"(",
"content",
",",
"signature",
")",
"hmac",
"=",
"OpenSSL",
"::",
"HMAC",
".",
"hexdigest",
"(",
"'sha1'",
",",
"@secret",
",",
"content",
")",
"signature",
".",
"downcase",
"==",
"\"sha1=#{hmac}\"",
"end"
]
| Verify that the feed contents were meant for this subscription
@param [String] content
@param [String] signature
@return [Boolean] | [
"Verify",
"that",
"the",
"feed",
"contents",
"were",
"meant",
"for",
"this",
"subscription"
]
| d967e6bffd490ae27a5ad41775e8503c3b6e25e2 | https://github.com/tootsuite/ostatus2/blob/d967e6bffd490ae27a5ad41775e8503c3b6e25e2/lib/ostatus2/subscription.rb#L45-L48 | train |
RISCfuture/dropbox | lib/dropbox/memoization.rb | Dropbox.Memoization.disable_memoization | def disable_memoization
@_memoize = false
@_memo_identifiers.each { |identifier| (@_memo_cache_clear_proc || Proc.new { |ident| eval "@_memo_#{ident} = nil" }).call(identifier) }
@_memo_identifiers.clear
end | ruby | def disable_memoization
@_memoize = false
@_memo_identifiers.each { |identifier| (@_memo_cache_clear_proc || Proc.new { |ident| eval "@_memo_#{ident} = nil" }).call(identifier) }
@_memo_identifiers.clear
end | [
"def",
"disable_memoization",
"@_memoize",
"=",
"false",
"@_memo_identifiers",
".",
"each",
"{",
"|",
"identifier",
"|",
"(",
"@_memo_cache_clear_proc",
"||",
"Proc",
".",
"new",
"{",
"|",
"ident",
"|",
"eval",
"\"@_memo_#{ident} = nil\"",
"}",
")",
".",
"call",
"(",
"identifier",
")",
"}",
"@_memo_identifiers",
".",
"clear",
"end"
]
| Halts memoization of API calls and clears the memoization cache. | [
"Halts",
"memoization",
"of",
"API",
"calls",
"and",
"clears",
"the",
"memoization",
"cache",
"."
]
| 702c0f99a25bb319b4a191f3dac2dbbd60427f9d | https://github.com/RISCfuture/dropbox/blob/702c0f99a25bb319b4a191f3dac2dbbd60427f9d/lib/dropbox/memoization.rb#L75-L79 | train |
ruby-x/rubyx | lib/arm/translator.rb | Arm.Translator.translate_Branch | def translate_Branch( code )
target = code.label.is_a?(Risc::Label) ? code.label.to_cpu(self) : code.label
ArmMachine.b( target )
end | ruby | def translate_Branch( code )
target = code.label.is_a?(Risc::Label) ? code.label.to_cpu(self) : code.label
ArmMachine.b( target )
end | [
"def",
"translate_Branch",
"(",
"code",
")",
"target",
"=",
"code",
".",
"label",
".",
"is_a?",
"(",
"Risc",
"::",
"Label",
")",
"?",
"code",
".",
"label",
".",
"to_cpu",
"(",
"self",
")",
":",
"code",
".",
"label",
"ArmMachine",
".",
"b",
"(",
"target",
")",
"end"
]
| This implements branch logic, which is simply assembler branch
The only target for a call is a Block, so we just need to get the address for the code
and branch to it. | [
"This",
"implements",
"branch",
"logic",
"which",
"is",
"simply",
"assembler",
"branch"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/arm/translator.rb#L116-L119 | train |
ruby-x/rubyx | lib/parfait/word.rb | Parfait.Word.set_length | def set_length(len , fill_char)
return if len <= 0
old = char_length
return if old >= len
self.char_length = len
check_length
fill_from_with( old + 1 , fill_char )
end | ruby | def set_length(len , fill_char)
return if len <= 0
old = char_length
return if old >= len
self.char_length = len
check_length
fill_from_with( old + 1 , fill_char )
end | [
"def",
"set_length",
"(",
"len",
",",
"fill_char",
")",
"return",
"if",
"len",
"<=",
"0",
"old",
"=",
"char_length",
"return",
"if",
"old",
">=",
"len",
"self",
".",
"char_length",
"=",
"len",
"check_length",
"fill_from_with",
"(",
"old",
"+",
"1",
",",
"fill_char",
")",
"end"
]
| pad the string with the given character to the given length | [
"pad",
"the",
"string",
"with",
"the",
"given",
"character",
"to",
"the",
"given",
"length"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/parfait/word.rb#L76-L83 | train |
ruby-x/rubyx | lib/parfait/word.rb | Parfait.Word.set_char | def set_char( at , char )
raise "char not fixnum #{char.class}" unless char.kind_of? ::Integer
index = range_correct_index(at)
set_internal_byte( index , char)
end | ruby | def set_char( at , char )
raise "char not fixnum #{char.class}" unless char.kind_of? ::Integer
index = range_correct_index(at)
set_internal_byte( index , char)
end | [
"def",
"set_char",
"(",
"at",
",",
"char",
")",
"raise",
"\"char not fixnum #{char.class}\"",
"unless",
"char",
".",
"kind_of?",
"::",
"Integer",
"index",
"=",
"range_correct_index",
"(",
"at",
")",
"set_internal_byte",
"(",
"index",
",",
"char",
")",
"end"
]
| set the character at the given index to the given character
character must be an integer, as is the index
the index starts at one, but may be negative to count from the end
indexes out of range will raise an error | [
"set",
"the",
"character",
"at",
"the",
"given",
"index",
"to",
"the",
"given",
"character",
"character",
"must",
"be",
"an",
"integer",
"as",
"is",
"the",
"index",
"the",
"index",
"starts",
"at",
"one",
"but",
"may",
"be",
"negative",
"to",
"count",
"from",
"the",
"end",
"indexes",
"out",
"of",
"range",
"will",
"raise",
"an",
"error"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/parfait/word.rb#L89-L93 | train |
ruby-x/rubyx | lib/parfait/word.rb | Parfait.Word.range_correct_index | def range_correct_index( at )
index = at
# index = self.length + at if at < 0
raise "index not integer #{at.class}" unless at.is_a?(::Integer)
raise "index must be positive , not #{at}" if (index < 0)
raise "index too large #{at} > #{self.length}" if (index >= self.length )
return index + 11
end | ruby | def range_correct_index( at )
index = at
# index = self.length + at if at < 0
raise "index not integer #{at.class}" unless at.is_a?(::Integer)
raise "index must be positive , not #{at}" if (index < 0)
raise "index too large #{at} > #{self.length}" if (index >= self.length )
return index + 11
end | [
"def",
"range_correct_index",
"(",
"at",
")",
"index",
"=",
"at",
"raise",
"\"index not integer #{at.class}\"",
"unless",
"at",
".",
"is_a?",
"(",
"::",
"Integer",
")",
"raise",
"\"index must be positive , not #{at}\"",
"if",
"(",
"index",
"<",
"0",
")",
"raise",
"\"index too large #{at} > #{self.length}\"",
"if",
"(",
"index",
">=",
"self",
".",
"length",
")",
"return",
"index",
"+",
"11",
"end"
]
| private method to account for | [
"private",
"method",
"to",
"account",
"for"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/parfait/word.rb#L137-L144 | train |
ruby-x/rubyx | lib/parfait/word.rb | Parfait.Word.compare | def compare( other )
return false if other.class != self.class
return false if other.length != self.length
len = self.length - 1
while(len >= 0)
return false if self.get_char(len) != other.get_char(len)
len = len - 1
end
return true
end | ruby | def compare( other )
return false if other.class != self.class
return false if other.length != self.length
len = self.length - 1
while(len >= 0)
return false if self.get_char(len) != other.get_char(len)
len = len - 1
end
return true
end | [
"def",
"compare",
"(",
"other",
")",
"return",
"false",
"if",
"other",
".",
"class",
"!=",
"self",
".",
"class",
"return",
"false",
"if",
"other",
".",
"length",
"!=",
"self",
".",
"length",
"len",
"=",
"self",
".",
"length",
"-",
"1",
"while",
"(",
"len",
">=",
"0",
")",
"return",
"false",
"if",
"self",
".",
"get_char",
"(",
"len",
")",
"!=",
"other",
".",
"get_char",
"(",
"len",
")",
"len",
"=",
"len",
"-",
"1",
"end",
"return",
"true",
"end"
]
| compare the word to another
currently checks for same class, though really identity of the characters
in right order would suffice | [
"compare",
"the",
"word",
"to",
"another",
"currently",
"checks",
"for",
"same",
"class",
"though",
"really",
"identity",
"of",
"the",
"characters",
"in",
"right",
"order",
"would",
"suffice"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/parfait/word.rb#L149-L158 | train |
ruby-x/rubyx | lib/ruby/normalizer.rb | Ruby.Normalizer.normalize_name | def normalize_name( condition )
if( condition.is_a?(ScopeStatement) and condition.single?)
condition = condition.first
end
return [condition] if condition.is_a?(Variable) or condition.is_a?(Constant)
local = "tmp_#{object_id}".to_sym
assign = LocalAssignment.new( local , condition)
[LocalVariable.new(local) , assign]
end | ruby | def normalize_name( condition )
if( condition.is_a?(ScopeStatement) and condition.single?)
condition = condition.first
end
return [condition] if condition.is_a?(Variable) or condition.is_a?(Constant)
local = "tmp_#{object_id}".to_sym
assign = LocalAssignment.new( local , condition)
[LocalVariable.new(local) , assign]
end | [
"def",
"normalize_name",
"(",
"condition",
")",
"if",
"(",
"condition",
".",
"is_a?",
"(",
"ScopeStatement",
")",
"and",
"condition",
".",
"single?",
")",
"condition",
"=",
"condition",
".",
"first",
"end",
"return",
"[",
"condition",
"]",
"if",
"condition",
".",
"is_a?",
"(",
"Variable",
")",
"or",
"condition",
".",
"is_a?",
"(",
"Constant",
")",
"local",
"=",
"\"tmp_#{object_id}\"",
".",
"to_sym",
"assign",
"=",
"LocalAssignment",
".",
"new",
"(",
"local",
",",
"condition",
")",
"[",
"LocalVariable",
".",
"new",
"(",
"local",
")",
",",
"assign",
"]",
"end"
]
| given a something, determine if it is a Name
Return a Name, and a possible rest that has a hoisted part of the statement
eg if( @var % 5) is not normalized
but if(tmp_123) is with tmp_123 = @var % 5 hoisted above the if
also constants count, though they may not be so useful in ifs, but returns | [
"given",
"a",
"something",
"determine",
"if",
"it",
"is",
"a",
"Name"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/ruby/normalizer.rb#L11-L19 | train |
ruby-x/rubyx | lib/risc/position/position.rb | Risc.Position.position_listener | def position_listener(listener)
unless listener.class.name.include?("Listener")
listener = PositionListener.new(listener)
end
register_event(:position_changed , listener)
end | ruby | def position_listener(listener)
unless listener.class.name.include?("Listener")
listener = PositionListener.new(listener)
end
register_event(:position_changed , listener)
end | [
"def",
"position_listener",
"(",
"listener",
")",
"unless",
"listener",
".",
"class",
".",
"name",
".",
"include?",
"(",
"\"Listener\"",
")",
"listener",
"=",
"PositionListener",
".",
"new",
"(",
"listener",
")",
"end",
"register_event",
"(",
":position_changed",
",",
"listener",
")",
"end"
]
| initialize with a given object, first parameter
The object will be the key in global position map
The actual position starts as -1 (invalid)
utility to register events of type :position_changed
can give an object and a PositionListener will be created for it | [
"initialize",
"with",
"a",
"given",
"object",
"first",
"parameter",
"The",
"object",
"will",
"be",
"the",
"key",
"in",
"global",
"position",
"map"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/risc/position/position.rb#L41-L46 | train |
ruby-x/rubyx | lib/risc/position/position.rb | Risc.Position.get_code | def get_code
listener = event_table.find{|one| one.class == InstructionListener}
return nil unless listener
listener.code
end | ruby | def get_code
listener = event_table.find{|one| one.class == InstructionListener}
return nil unless listener
listener.code
end | [
"def",
"get_code",
"listener",
"=",
"event_table",
".",
"find",
"{",
"|",
"one",
"|",
"one",
".",
"class",
"==",
"InstructionListener",
"}",
"return",
"nil",
"unless",
"listener",
"listener",
".",
"code",
"end"
]
| look for InstructionListener and return its code if found | [
"look",
"for",
"InstructionListener",
"and",
"return",
"its",
"code",
"if",
"found"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/risc/position/position.rb#L60-L64 | train |
ruby-x/rubyx | lib/mom/instruction/not_same_check.rb | Mom.NotSameCheck.to_risc | def to_risc(compiler)
l_reg = left.to_register(compiler, self)
r_reg = right.to_register(compiler, self)
compiler.add_code Risc.op( self , :- , l_reg , r_reg)
compiler.add_code Risc::IsZero.new( self, false_jump.risc_label(compiler))
end | ruby | def to_risc(compiler)
l_reg = left.to_register(compiler, self)
r_reg = right.to_register(compiler, self)
compiler.add_code Risc.op( self , :- , l_reg , r_reg)
compiler.add_code Risc::IsZero.new( self, false_jump.risc_label(compiler))
end | [
"def",
"to_risc",
"(",
"compiler",
")",
"l_reg",
"=",
"left",
".",
"to_register",
"(",
"compiler",
",",
"self",
")",
"r_reg",
"=",
"right",
".",
"to_register",
"(",
"compiler",
",",
"self",
")",
"compiler",
".",
"add_code",
"Risc",
".",
"op",
"(",
"self",
",",
":-",
",",
"l_reg",
",",
"r_reg",
")",
"compiler",
".",
"add_code",
"Risc",
"::",
"IsZero",
".",
"new",
"(",
"self",
",",
"false_jump",
".",
"risc_label",
"(",
"compiler",
")",
")",
"end"
]
| basically move both left and right values into register
subtract them and see if IsZero comparison | [
"basically",
"move",
"both",
"left",
"and",
"right",
"values",
"into",
"register",
"subtract",
"them",
"and",
"see",
"if",
"IsZero",
"comparison"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/mom/instruction/not_same_check.rb#L25-L30 | train |
ruby-x/rubyx | lib/mom/instruction/slot_definition.rb | Mom.SlotDefinition.to_register | def to_register(compiler, source)
if known_object.respond_to?(:ct_type)
type = known_object.ct_type
elsif(known_object.respond_to?(:get_type))
type = known_object.get_type
else
type = :Object
end
right = compiler.use_reg( type )
case known_object
when Constant
parfait = known_object.to_parfait(compiler)
const = Risc.load_constant(source, parfait , right)
compiler.add_code const
raise "Can't have slots into Constants" if slots.length > 0
when Parfait::Object , Risc::Label
const = const = Risc.load_constant(source, known_object , right)
compiler.add_code const
if slots.length > 0
# desctructively replace the existing value to be loaded if more slots
compiler.add_code Risc.slot_to_reg( source , right ,slots[0], right)
end
when Symbol
return sym_to_risc(compiler , source)
else
raise "We have a #{self} #{known_object}"
end
if slots.length > 1
# desctructively replace the existing value to be loaded if more slots
index = Risc.resolve_to_index(slots[0] , slots[1] ,compiler)
compiler.add_code Risc::SlotToReg.new( source , right ,index, right)
if slots.length > 2
raise "3 slots only for type #{slots}" unless slots[2] == :type
compiler.add_code Risc::SlotToReg.new( source , right , Parfait::TYPE_INDEX, right)
end
end
return const.register
end | ruby | def to_register(compiler, source)
if known_object.respond_to?(:ct_type)
type = known_object.ct_type
elsif(known_object.respond_to?(:get_type))
type = known_object.get_type
else
type = :Object
end
right = compiler.use_reg( type )
case known_object
when Constant
parfait = known_object.to_parfait(compiler)
const = Risc.load_constant(source, parfait , right)
compiler.add_code const
raise "Can't have slots into Constants" if slots.length > 0
when Parfait::Object , Risc::Label
const = const = Risc.load_constant(source, known_object , right)
compiler.add_code const
if slots.length > 0
# desctructively replace the existing value to be loaded if more slots
compiler.add_code Risc.slot_to_reg( source , right ,slots[0], right)
end
when Symbol
return sym_to_risc(compiler , source)
else
raise "We have a #{self} #{known_object}"
end
if slots.length > 1
# desctructively replace the existing value to be loaded if more slots
index = Risc.resolve_to_index(slots[0] , slots[1] ,compiler)
compiler.add_code Risc::SlotToReg.new( source , right ,index, right)
if slots.length > 2
raise "3 slots only for type #{slots}" unless slots[2] == :type
compiler.add_code Risc::SlotToReg.new( source , right , Parfait::TYPE_INDEX, right)
end
end
return const.register
end | [
"def",
"to_register",
"(",
"compiler",
",",
"source",
")",
"if",
"known_object",
".",
"respond_to?",
"(",
":ct_type",
")",
"type",
"=",
"known_object",
".",
"ct_type",
"elsif",
"(",
"known_object",
".",
"respond_to?",
"(",
":get_type",
")",
")",
"type",
"=",
"known_object",
".",
"get_type",
"else",
"type",
"=",
":Object",
"end",
"right",
"=",
"compiler",
".",
"use_reg",
"(",
"type",
")",
"case",
"known_object",
"when",
"Constant",
"parfait",
"=",
"known_object",
".",
"to_parfait",
"(",
"compiler",
")",
"const",
"=",
"Risc",
".",
"load_constant",
"(",
"source",
",",
"parfait",
",",
"right",
")",
"compiler",
".",
"add_code",
"const",
"raise",
"\"Can't have slots into Constants\"",
"if",
"slots",
".",
"length",
">",
"0",
"when",
"Parfait",
"::",
"Object",
",",
"Risc",
"::",
"Label",
"const",
"=",
"const",
"=",
"Risc",
".",
"load_constant",
"(",
"source",
",",
"known_object",
",",
"right",
")",
"compiler",
".",
"add_code",
"const",
"if",
"slots",
".",
"length",
">",
"0",
"compiler",
".",
"add_code",
"Risc",
".",
"slot_to_reg",
"(",
"source",
",",
"right",
",",
"slots",
"[",
"0",
"]",
",",
"right",
")",
"end",
"when",
"Symbol",
"return",
"sym_to_risc",
"(",
"compiler",
",",
"source",
")",
"else",
"raise",
"\"We have a #{self} #{known_object}\"",
"end",
"if",
"slots",
".",
"length",
">",
"1",
"index",
"=",
"Risc",
".",
"resolve_to_index",
"(",
"slots",
"[",
"0",
"]",
",",
"slots",
"[",
"1",
"]",
",",
"compiler",
")",
"compiler",
".",
"add_code",
"Risc",
"::",
"SlotToReg",
".",
"new",
"(",
"source",
",",
"right",
",",
"index",
",",
"right",
")",
"if",
"slots",
".",
"length",
">",
"2",
"raise",
"\"3 slots only for type #{slots}\"",
"unless",
"slots",
"[",
"2",
"]",
"==",
":type",
"compiler",
".",
"add_code",
"Risc",
"::",
"SlotToReg",
".",
"new",
"(",
"source",
",",
"right",
",",
"Parfait",
"::",
"TYPE_INDEX",
",",
"right",
")",
"end",
"end",
"return",
"const",
".",
"register",
"end"
]
| load the slots into a register
the code is added to compiler
the register returned | [
"load",
"the",
"slots",
"into",
"a",
"register",
"the",
"code",
"is",
"added",
"to",
"compiler",
"the",
"register",
"returned"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/mom/instruction/slot_definition.rb#L52-L89 | train |
ruby-x/rubyx | lib/rubyx/rubyx_compiler.rb | RubyX.RubyXCompiler.to_binary | def to_binary(platform)
linker = to_risc(platform)
linker.position_all
linker.create_binary
linker
end | ruby | def to_binary(platform)
linker = to_risc(platform)
linker.position_all
linker.create_binary
linker
end | [
"def",
"to_binary",
"(",
"platform",
")",
"linker",
"=",
"to_risc",
"(",
"platform",
")",
"linker",
".",
"position_all",
"linker",
".",
"create_binary",
"linker",
"end"
]
| Process previously stored vool source to binary.
Binary code is generated byu calling to_risc, then positioning and calling
create_binary on the linker. The linker may then be used to creat a binary file.
The biary the method name refers to is binary code in memory, or in BinaryCode
objects to be precise. | [
"Process",
"previously",
"stored",
"vool",
"source",
"to",
"binary",
".",
"Binary",
"code",
"is",
"generated",
"byu",
"calling",
"to_risc",
"then",
"positioning",
"and",
"calling",
"create_binary",
"on",
"the",
"linker",
".",
"The",
"linker",
"may",
"then",
"be",
"used",
"to",
"creat",
"a",
"binary",
"file",
".",
"The",
"biary",
"the",
"method",
"name",
"refers",
"to",
"is",
"binary",
"code",
"in",
"memory",
"or",
"in",
"BinaryCode",
"objects",
"to",
"be",
"precise",
"."
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/rubyx/rubyx_compiler.rb#L45-L50 | train |
ruby-x/rubyx | lib/rubyx/rubyx_compiler.rb | RubyX.RubyXCompiler.ruby_to_vool | def ruby_to_vool(ruby_source)
ruby_tree = Ruby::RubyCompiler.compile( ruby_source )
unless(@vool)
@vool = ruby_tree.to_vool
return @vool
end
# TODO: should check if this works with reopening classes
# or whether we need to unify the vool for a class
unless(@vool.is_a?(Vool::ScopeStatement))
@vool = Vool::ScopeStatement.new([@vool])
end
@vool << ruby_tree.to_vool
end | ruby | def ruby_to_vool(ruby_source)
ruby_tree = Ruby::RubyCompiler.compile( ruby_source )
unless(@vool)
@vool = ruby_tree.to_vool
return @vool
end
# TODO: should check if this works with reopening classes
# or whether we need to unify the vool for a class
unless(@vool.is_a?(Vool::ScopeStatement))
@vool = Vool::ScopeStatement.new([@vool])
end
@vool << ruby_tree.to_vool
end | [
"def",
"ruby_to_vool",
"(",
"ruby_source",
")",
"ruby_tree",
"=",
"Ruby",
"::",
"RubyCompiler",
".",
"compile",
"(",
"ruby_source",
")",
"unless",
"(",
"@vool",
")",
"@vool",
"=",
"ruby_tree",
".",
"to_vool",
"return",
"@vool",
"end",
"unless",
"(",
"@vool",
".",
"is_a?",
"(",
"Vool",
"::",
"ScopeStatement",
")",
")",
"@vool",
"=",
"Vool",
"::",
"ScopeStatement",
".",
"new",
"(",
"[",
"@vool",
"]",
")",
"end",
"@vool",
"<<",
"ruby_tree",
".",
"to_vool",
"end"
]
| ruby_to_vool compiles the ruby to ast, and then to vool | [
"ruby_to_vool",
"compiles",
"the",
"ruby",
"to",
"ast",
"and",
"then",
"to",
"vool"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/rubyx/rubyx_compiler.rb#L84-L96 | train |
pokitdok/pokitdok-ruby | lib/pokitdok.rb | PokitDok.PokitDok.request | def request(endpoint, method='get', file=nil, params={})
method = method.downcase
if file
self.send("post_file", endpoint, file)
else
if endpoint[0] == '/'
endpoint[0] = ''
end
# Work around to delete the leading slash on the request endpoint
# Currently the module we're using appends a slash to the base url
# so an additional url will break the request.
# Refer to ...faraday/connection.rb L#404
self.send("#{method}_request", endpoint, params)
end
end | ruby | def request(endpoint, method='get', file=nil, params={})
method = method.downcase
if file
self.send("post_file", endpoint, file)
else
if endpoint[0] == '/'
endpoint[0] = ''
end
# Work around to delete the leading slash on the request endpoint
# Currently the module we're using appends a slash to the base url
# so an additional url will break the request.
# Refer to ...faraday/connection.rb L#404
self.send("#{method}_request", endpoint, params)
end
end | [
"def",
"request",
"(",
"endpoint",
",",
"method",
"=",
"'get'",
",",
"file",
"=",
"nil",
",",
"params",
"=",
"{",
"}",
")",
"method",
"=",
"method",
".",
"downcase",
"if",
"file",
"self",
".",
"send",
"(",
"\"post_file\"",
",",
"endpoint",
",",
"file",
")",
"else",
"if",
"endpoint",
"[",
"0",
"]",
"==",
"'/'",
"endpoint",
"[",
"0",
"]",
"=",
"''",
"end",
"self",
".",
"send",
"(",
"\"#{method}_request\"",
",",
"endpoint",
",",
"params",
")",
"end",
"end"
]
| Connect to the PokitDok API with the specified Client ID and Client
Secret.
+client_id+ your client ID, provided by PokitDok
+client_secret+ your client secret, provided by PokitDok
+version+ The API version that should be used for requests. Defaults to the latest version.
+base+ The base URL to use for API requests. Defaults to https://platform.pokitdok.com
TODO: Make it simpler to pass in params out of order (also so you don't have to do init(..., nil, nil, nil, param))
******************************
General Use APIs
******************************
Invokes the the general request method for submitting API request.
+endpoint+ the API request path
+method+ the http request method that should be used
+file+ file when the API accepts file uploads as input
+params+ an optional Hash of parameters
NOTE: There might be a better way of achieving the seperation of get/get_request
but currently using the "send" method will go down the ancestor chain until the correct
method is found. In this case the 'httpMethod'_request | [
"Connect",
"to",
"the",
"PokitDok",
"API",
"with",
"the",
"specified",
"Client",
"ID",
"and",
"Client",
"Secret",
"."
]
| 5be064177a54926a93530e30a2f82c497b1c65cd | https://github.com/pokitdok/pokitdok-ruby/blob/5be064177a54926a93530e30a2f82c497b1c65cd/lib/pokitdok.rb#L59-L73 | train |
pokitdok/pokitdok-ruby | lib/pokitdok.rb | PokitDok.PokitDok.pharmacy_network | def pharmacy_network(params = {})
npi = params.delete :npi
endpoint = npi ? "pharmacy/network/#{npi}" : "pharmacy/network"
get(endpoint, params)
end | ruby | def pharmacy_network(params = {})
npi = params.delete :npi
endpoint = npi ? "pharmacy/network/#{npi}" : "pharmacy/network"
get(endpoint, params)
end | [
"def",
"pharmacy_network",
"(",
"params",
"=",
"{",
"}",
")",
"npi",
"=",
"params",
".",
"delete",
":npi",
"endpoint",
"=",
"npi",
"?",
"\"pharmacy/network/#{npi}\"",
":",
"\"pharmacy/network\"",
"get",
"(",
"endpoint",
",",
"params",
")",
"end"
]
| Invokes the pharmacy network cost endpoint.
+params+ an optional Hash of parameters | [
"Invokes",
"the",
"pharmacy",
"network",
"cost",
"endpoint",
"."
]
| 5be064177a54926a93530e30a2f82c497b1c65cd | https://github.com/pokitdok/pokitdok-ruby/blob/5be064177a54926a93530e30a2f82c497b1c65cd/lib/pokitdok.rb#L341-L345 | train |
ruby-x/rubyx | lib/risc/block_compiler.rb | Risc.BlockCompiler.slot_type_for | def slot_type_for(name)
if @callable.arguments_type.variable_index(name)
slot_def = [:arguments]
elsif @callable.frame_type.variable_index(name)
slot_def = [:frame]
elsif @method.arguments_type.variable_index(name)
slot_def = [:caller , :caller ,:arguments ]
elsif @method.frame_type.variable_index(name)
slot_def = [:caller ,:caller , :frame ]
elsif
raise "no variable #{name} , need to resolve at runtime"
end
slot_def << name
end | ruby | def slot_type_for(name)
if @callable.arguments_type.variable_index(name)
slot_def = [:arguments]
elsif @callable.frame_type.variable_index(name)
slot_def = [:frame]
elsif @method.arguments_type.variable_index(name)
slot_def = [:caller , :caller ,:arguments ]
elsif @method.frame_type.variable_index(name)
slot_def = [:caller ,:caller , :frame ]
elsif
raise "no variable #{name} , need to resolve at runtime"
end
slot_def << name
end | [
"def",
"slot_type_for",
"(",
"name",
")",
"if",
"@callable",
".",
"arguments_type",
".",
"variable_index",
"(",
"name",
")",
"slot_def",
"=",
"[",
":arguments",
"]",
"elsif",
"@callable",
".",
"frame_type",
".",
"variable_index",
"(",
"name",
")",
"slot_def",
"=",
"[",
":frame",
"]",
"elsif",
"@method",
".",
"arguments_type",
".",
"variable_index",
"(",
"name",
")",
"slot_def",
"=",
"[",
":caller",
",",
":caller",
",",
":arguments",
"]",
"elsif",
"@method",
".",
"frame_type",
".",
"variable_index",
"(",
"name",
")",
"slot_def",
"=",
"[",
":caller",
",",
":caller",
",",
":frame",
"]",
"elsif",
"raise",
"\"no variable #{name} , need to resolve at runtime\"",
"end",
"slot_def",
"<<",
"name",
"end"
]
| determine how given name need to be accsessed.
For blocks the options are args or frame
or then the methods arg or frame | [
"determine",
"how",
"given",
"name",
"need",
"to",
"be",
"accsessed",
".",
"For",
"blocks",
"the",
"options",
"are",
"args",
"or",
"frame",
"or",
"then",
"the",
"methods",
"arg",
"or",
"frame"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/risc/block_compiler.rb#L36-L49 | train |
ruby-x/rubyx | lib/mom/instruction/argument_transfer.rb | Mom.ArgumentTransfer.to_risc | def to_risc(compiler)
transfer = SlotLoad.new([:message , :next_message , :receiver] , @receiver, self).to_risc(compiler)
compiler.reset_regs
@arguments.each do |arg|
arg.to_risc(compiler)
compiler.reset_regs
end
transfer
end | ruby | def to_risc(compiler)
transfer = SlotLoad.new([:message , :next_message , :receiver] , @receiver, self).to_risc(compiler)
compiler.reset_regs
@arguments.each do |arg|
arg.to_risc(compiler)
compiler.reset_regs
end
transfer
end | [
"def",
"to_risc",
"(",
"compiler",
")",
"transfer",
"=",
"SlotLoad",
".",
"new",
"(",
"[",
":message",
",",
":next_message",
",",
":receiver",
"]",
",",
"@receiver",
",",
"self",
")",
".",
"to_risc",
"(",
"compiler",
")",
"compiler",
".",
"reset_regs",
"@arguments",
".",
"each",
"do",
"|",
"arg",
"|",
"arg",
".",
"to_risc",
"(",
"compiler",
")",
"compiler",
".",
"reset_regs",
"end",
"transfer",
"end"
]
| load receiver and then each arg into the new message
delegates to SlotLoad for receiver and to the actual args.to_risc | [
"load",
"receiver",
"and",
"then",
"each",
"arg",
"into",
"the",
"new",
"message",
"delegates",
"to",
"SlotLoad",
"for",
"receiver",
"and",
"to",
"the",
"actual",
"args",
".",
"to_risc"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/mom/instruction/argument_transfer.rb#L37-L45 | train |
ruby-x/rubyx | lib/util/eventable.rb | Util.Eventable.trigger | def trigger(name, *args)
event_table[name].each { |handler| handler.send( name.to_sym , *args) }
end | ruby | def trigger(name, *args)
event_table[name].each { |handler| handler.send( name.to_sym , *args) }
end | [
"def",
"trigger",
"(",
"name",
",",
"*",
"args",
")",
"event_table",
"[",
"name",
"]",
".",
"each",
"{",
"|",
"handler",
"|",
"handler",
".",
"send",
"(",
"name",
".",
"to_sym",
",",
"*",
"args",
")",
"}",
"end"
]
| Trigger the given event name and passes all args to each handler
for this event.
obj.trigger(:foo)
obj.trigger(:foo, 1, 2, 3)
@param [String, Symbol] name event name to trigger | [
"Trigger",
"the",
"given",
"event",
"name",
"and",
"passes",
"all",
"args",
"to",
"each",
"handler",
"for",
"this",
"event",
"."
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/util/eventable.rb#L35-L37 | train |
ruby-x/rubyx | lib/risc/interpreter.rb | Risc.Interpreter.execute_DynamicJump | def execute_DynamicJump
method = get_register(@instruction.register)
pos = Position.get(method.binary)
log.debug "Jump to binary at: #{pos} #{method.name}:#{method.binary.class}"
raise "Invalid position for #{method.name}" unless pos.valid?
pos = pos + Parfait::BinaryCode.byte_offset
set_pc( pos )
false
end | ruby | def execute_DynamicJump
method = get_register(@instruction.register)
pos = Position.get(method.binary)
log.debug "Jump to binary at: #{pos} #{method.name}:#{method.binary.class}"
raise "Invalid position for #{method.name}" unless pos.valid?
pos = pos + Parfait::BinaryCode.byte_offset
set_pc( pos )
false
end | [
"def",
"execute_DynamicJump",
"method",
"=",
"get_register",
"(",
"@instruction",
".",
"register",
")",
"pos",
"=",
"Position",
".",
"get",
"(",
"method",
".",
"binary",
")",
"log",
".",
"debug",
"\"Jump to binary at: #{pos} #{method.name}:#{method.binary.class}\"",
"raise",
"\"Invalid position for #{method.name}\"",
"unless",
"pos",
".",
"valid?",
"pos",
"=",
"pos",
"+",
"Parfait",
"::",
"BinaryCode",
".",
"byte_offset",
"set_pc",
"(",
"pos",
")",
"false",
"end"
]
| Instruction interpretation starts here | [
"Instruction",
"interpretation",
"starts",
"here"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/risc/interpreter.rb#L111-L119 | train |
ruby-x/rubyx | lib/risc/linker.rb | Risc.Linker.position_code | def position_code(code_start)
assemblers.each do |asm|
Position.log.debug "Method start #{code_start.to_s(16)} #{asm.callable.name}"
code_pos = CodeListener.init(asm.callable.binary, platform)
instructions = asm.instructions
InstructionListener.init( instructions, asm.callable.binary)
code_pos.position_listener( LabelListener.new(instructions))
code_pos.set(code_start)
code_start = Position.get(asm.callable.binary.last_code).next_slot
end
end | ruby | def position_code(code_start)
assemblers.each do |asm|
Position.log.debug "Method start #{code_start.to_s(16)} #{asm.callable.name}"
code_pos = CodeListener.init(asm.callable.binary, platform)
instructions = asm.instructions
InstructionListener.init( instructions, asm.callable.binary)
code_pos.position_listener( LabelListener.new(instructions))
code_pos.set(code_start)
code_start = Position.get(asm.callable.binary.last_code).next_slot
end
end | [
"def",
"position_code",
"(",
"code_start",
")",
"assemblers",
".",
"each",
"do",
"|",
"asm",
"|",
"Position",
".",
"log",
".",
"debug",
"\"Method start #{code_start.to_s(16)} #{asm.callable.name}\"",
"code_pos",
"=",
"CodeListener",
".",
"init",
"(",
"asm",
".",
"callable",
".",
"binary",
",",
"platform",
")",
"instructions",
"=",
"asm",
".",
"instructions",
"InstructionListener",
".",
"init",
"(",
"instructions",
",",
"asm",
".",
"callable",
".",
"binary",
")",
"code_pos",
".",
"position_listener",
"(",
"LabelListener",
".",
"new",
"(",
"instructions",
")",
")",
"code_pos",
".",
"set",
"(",
"code_start",
")",
"code_start",
"=",
"Position",
".",
"get",
"(",
"asm",
".",
"callable",
".",
"binary",
".",
"last_code",
")",
".",
"next_slot",
"end",
"end"
]
| Position all BinaryCode.
So that all code from one method is layed out linearly (for debugging)
we go through methods, and then through all codes from the method
start at code_start. | [
"Position",
"all",
"BinaryCode",
"."
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/risc/linker.rb#L83-L93 | train |
ruby-x/rubyx | lib/risc/position/code_listener.rb | Risc.CodeListener.position_inserted | def position_inserted(position)
Position.log.debug "extending one at #{position}"
pos = CodeListener.init( position.object.next_code , @platform)
raise "HI #{position}" unless position.valid?
return unless position.valid?
Position.log.debug "insert #{position.object.next_code.object_id.to_s(16)}"
pos.set( position + position.object.padded_length)
set_jump_for(position)
end | ruby | def position_inserted(position)
Position.log.debug "extending one at #{position}"
pos = CodeListener.init( position.object.next_code , @platform)
raise "HI #{position}" unless position.valid?
return unless position.valid?
Position.log.debug "insert #{position.object.next_code.object_id.to_s(16)}"
pos.set( position + position.object.padded_length)
set_jump_for(position)
end | [
"def",
"position_inserted",
"(",
"position",
")",
"Position",
".",
"log",
".",
"debug",
"\"extending one at #{position}\"",
"pos",
"=",
"CodeListener",
".",
"init",
"(",
"position",
".",
"object",
".",
"next_code",
",",
"@platform",
")",
"raise",
"\"HI #{position}\"",
"unless",
"position",
".",
"valid?",
"return",
"unless",
"position",
".",
"valid?",
"Position",
".",
"log",
".",
"debug",
"\"insert #{position.object.next_code.object_id.to_s(16)}\"",
"pos",
".",
"set",
"(",
"position",
"+",
"position",
".",
"object",
".",
"padded_length",
")",
"set_jump_for",
"(",
"position",
")",
"end"
]
| need to pass the platform to translate new jumps | [
"need",
"to",
"pass",
"the",
"platform",
"to",
"translate",
"new",
"jumps"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/risc/position/code_listener.rb#L17-L25 | train |
ruby-x/rubyx | lib/risc/position/code_listener.rb | Risc.CodeListener.set_jump_for | def set_jump_for(position)
at = position.at
code = position.object
return unless code.next_code #dont jump beyond and
jump = Branch.new("BinaryCode #{at.to_s(16)}" , code.next_code)
translator = @platform.translator
cpu_jump = translator.translate(jump)
pos = at + code.padded_length - cpu_jump.byte_length
Position.create(cpu_jump).set(pos)
cpu_jump.assemble(JumpWriter.new(code))
end | ruby | def set_jump_for(position)
at = position.at
code = position.object
return unless code.next_code #dont jump beyond and
jump = Branch.new("BinaryCode #{at.to_s(16)}" , code.next_code)
translator = @platform.translator
cpu_jump = translator.translate(jump)
pos = at + code.padded_length - cpu_jump.byte_length
Position.create(cpu_jump).set(pos)
cpu_jump.assemble(JumpWriter.new(code))
end | [
"def",
"set_jump_for",
"(",
"position",
")",
"at",
"=",
"position",
".",
"at",
"code",
"=",
"position",
".",
"object",
"return",
"unless",
"code",
".",
"next_code",
"jump",
"=",
"Branch",
".",
"new",
"(",
"\"BinaryCode #{at.to_s(16)}\"",
",",
"code",
".",
"next_code",
")",
"translator",
"=",
"@platform",
".",
"translator",
"cpu_jump",
"=",
"translator",
".",
"translate",
"(",
"jump",
")",
"pos",
"=",
"at",
"+",
"code",
".",
"padded_length",
"-",
"cpu_jump",
".",
"byte_length",
"Position",
".",
"create",
"(",
"cpu_jump",
")",
".",
"set",
"(",
"pos",
")",
"cpu_jump",
".",
"assemble",
"(",
"JumpWriter",
".",
"new",
"(",
"code",
")",
")",
"end"
]
| insert a jump to the next instruction, at the last instruction
thus hopping over the object header | [
"insert",
"a",
"jump",
"to",
"the",
"next",
"instruction",
"at",
"the",
"last",
"instruction",
"thus",
"hopping",
"over",
"the",
"object",
"header"
]
| 1391667f6cf16c8e132cbf85cc6a5171fb8c444e | https://github.com/ruby-x/rubyx/blob/1391667f6cf16c8e132cbf85cc6a5171fb8c444e/lib/risc/position/code_listener.rb#L47-L57 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.