id
int32 0
24.9k
| 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
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
5,000 | fuminori-ido/edgarj | app/controllers/edgarj/edgarj_controller.rb | Edgarj.EdgarjController.update | def update
upsert do
# NOTE:
# 1. update ++then++ valid to set new values in @record to draw form.
# 1. user_scoped may have joins so that record could be
# ActiveRecord::ReadOnlyRecord so that's why access again from
# model.
@record = model.find(user_scoped.find(params[:id]).id)
#upsert_files
if [email protected]_attributes(permitted_params(:update))
raise ActiveRecord::RecordInvalid.new(@record)
end
end
end | ruby | def update
upsert do
# NOTE:
# 1. update ++then++ valid to set new values in @record to draw form.
# 1. user_scoped may have joins so that record could be
# ActiveRecord::ReadOnlyRecord so that's why access again from
# model.
@record = model.find(user_scoped.find(params[:id]).id)
#upsert_files
if [email protected]_attributes(permitted_params(:update))
raise ActiveRecord::RecordInvalid.new(@record)
end
end
end | [
"def",
"update",
"upsert",
"do",
"# NOTE:",
"# 1. update ++then++ valid to set new values in @record to draw form.",
"# 1. user_scoped may have joins so that record could be",
"# ActiveRecord::ReadOnlyRecord so that's why access again from",
"# model.",
"@record",
"=",
"model",
".",
"find",
"(",
"user_scoped",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
".",
"id",
")",
"#upsert_files",
"if",
"!",
"@record",
".",
"update_attributes",
"(",
"permitted_params",
"(",
":update",
")",
")",
"raise",
"ActiveRecord",
"::",
"RecordInvalid",
".",
"new",
"(",
"@record",
")",
"end",
"end",
"end"
] | save existence modified record
=== Permission
ModelPermission::UPDATE on this controller is required. | [
"save",
"existence",
"modified",
"record"
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/controllers/edgarj/edgarj_controller.rb#L176-L189 |
5,001 | fuminori-ido/edgarj | app/controllers/edgarj/edgarj_controller.rb | Edgarj.EdgarjController.search_save | def search_save
SavedVcontext.save(current_user, nil,
params[:saved_page_info_name], page_info)
render :update do |page|
page << "Edgarj.SearchSavePopup.close();"
page.replace 'edgarj_load_condition_menu',
:partial=>'edgarj/load_condition_menu'
end
rescue ActiveRecord::ActiveRecordError
app_rescue
render :update do |page|
page.replace_html 'search_save_popup_flash_error', :text=>t('save_fail')
end
end | ruby | def search_save
SavedVcontext.save(current_user, nil,
params[:saved_page_info_name], page_info)
render :update do |page|
page << "Edgarj.SearchSavePopup.close();"
page.replace 'edgarj_load_condition_menu',
:partial=>'edgarj/load_condition_menu'
end
rescue ActiveRecord::ActiveRecordError
app_rescue
render :update do |page|
page.replace_html 'search_save_popup_flash_error', :text=>t('save_fail')
end
end | [
"def",
"search_save",
"SavedVcontext",
".",
"save",
"(",
"current_user",
",",
"nil",
",",
"params",
"[",
":saved_page_info_name",
"]",
",",
"page_info",
")",
"render",
":update",
"do",
"|",
"page",
"|",
"page",
"<<",
"\"Edgarj.SearchSavePopup.close();\"",
"page",
".",
"replace",
"'edgarj_load_condition_menu'",
",",
":partial",
"=>",
"'edgarj/load_condition_menu'",
"end",
"rescue",
"ActiveRecord",
"::",
"ActiveRecordError",
"app_rescue",
"render",
":update",
"do",
"|",
"page",
"|",
"page",
".",
"replace_html",
"'search_save_popup_flash_error'",
",",
":text",
"=>",
"t",
"(",
"'save_fail'",
")",
"end",
"end"
] | Ajax method to save search conditions
=== call flow
Edgarj.SearchSavePopup.open() (javascript)
(show $('search_save_popup'))
Edgarj.SearchSavePopup.submit() (javascript)
(copy entered name into $('saved_page_info_name') in form)
call :action=>'search_save'
==== TRICKY PART
There are two requirements:
1. use modal-dialog to enter name to decrese busy in search form.
1. send Search Form with name to server.
To comply these, Edgarj.SearchSavePopup copies the entered name to
'saved_page_info_name' hidden field and then sends the form which includes
the copied name.
=== Permission
ModelPermission::READ on this controller is required. | [
"Ajax",
"method",
"to",
"save",
"search",
"conditions"
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/controllers/edgarj/edgarj_controller.rb#L260-L274 |
5,002 | fuminori-ido/edgarj | app/controllers/edgarj/edgarj_controller.rb | Edgarj.EdgarjController.csv_download | def csv_download
filename = sprintf("%s-%s.csv",
model_name,
Time.now.strftime("%Y%m%d-%H%M%S"))
file = Tempfile.new(filename, Settings.edgarj.csv_dir)
csv_visitor = EdgarjHelper::CsvVisitor.new(view_context)
file.write CSV.generate_line(model.columns.map{|c| c.name})
for rec in user_scoped.where(page_info.record.conditions).
order(
page_info.order_by.blank? ?
nil :
page_info.order_by + ' ' + page_info.dir) do
array = []
for col in model.columns do
array << csv_visitor.visit_column(rec, col)
end
file.write CSV.generate_line(array)
end
file.close
File.chmod(Settings.edgarj.csv_permission, file.path)
send_file(file.path, {
type: 'text/csv',
filename: filename})
#file.close(true)
end | ruby | def csv_download
filename = sprintf("%s-%s.csv",
model_name,
Time.now.strftime("%Y%m%d-%H%M%S"))
file = Tempfile.new(filename, Settings.edgarj.csv_dir)
csv_visitor = EdgarjHelper::CsvVisitor.new(view_context)
file.write CSV.generate_line(model.columns.map{|c| c.name})
for rec in user_scoped.where(page_info.record.conditions).
order(
page_info.order_by.blank? ?
nil :
page_info.order_by + ' ' + page_info.dir) do
array = []
for col in model.columns do
array << csv_visitor.visit_column(rec, col)
end
file.write CSV.generate_line(array)
end
file.close
File.chmod(Settings.edgarj.csv_permission, file.path)
send_file(file.path, {
type: 'text/csv',
filename: filename})
#file.close(true)
end | [
"def",
"csv_download",
"filename",
"=",
"sprintf",
"(",
"\"%s-%s.csv\"",
",",
"model_name",
",",
"Time",
".",
"now",
".",
"strftime",
"(",
"\"%Y%m%d-%H%M%S\"",
")",
")",
"file",
"=",
"Tempfile",
".",
"new",
"(",
"filename",
",",
"Settings",
".",
"edgarj",
".",
"csv_dir",
")",
"csv_visitor",
"=",
"EdgarjHelper",
"::",
"CsvVisitor",
".",
"new",
"(",
"view_context",
")",
"file",
".",
"write",
"CSV",
".",
"generate_line",
"(",
"model",
".",
"columns",
".",
"map",
"{",
"|",
"c",
"|",
"c",
".",
"name",
"}",
")",
"for",
"rec",
"in",
"user_scoped",
".",
"where",
"(",
"page_info",
".",
"record",
".",
"conditions",
")",
".",
"order",
"(",
"page_info",
".",
"order_by",
".",
"blank?",
"?",
"nil",
":",
"page_info",
".",
"order_by",
"+",
"' '",
"+",
"page_info",
".",
"dir",
")",
"do",
"array",
"=",
"[",
"]",
"for",
"col",
"in",
"model",
".",
"columns",
"do",
"array",
"<<",
"csv_visitor",
".",
"visit_column",
"(",
"rec",
",",
"col",
")",
"end",
"file",
".",
"write",
"CSV",
".",
"generate_line",
"(",
"array",
")",
"end",
"file",
".",
"close",
"File",
".",
"chmod",
"(",
"Settings",
".",
"edgarj",
".",
"csv_permission",
",",
"file",
".",
"path",
")",
"send_file",
"(",
"file",
".",
"path",
",",
"{",
"type",
":",
"'text/csv'",
",",
"filename",
":",
"filename",
"}",
")",
"#file.close(true)",
"end"
] | zip -> address completion
=== INPUTS
params[:zip]:: key to find address info. hyphen is supported.
params[:adrs_prefix]:: address fields DOM id prefix. e.g. 'org_adrs_0_'
=== call flow
==== on drawing
EdgarjHelper.draw_adrs() app/helpers/edgarj_helper.rb
app/views/edgarj/_address.html.erb
Example:
:
<input type=text name='org[adrs_0_zip]'>
:
==== on clicking zip->address button
Edgarj.zip_complete() public/javascripts/edgarj.js
Ajax.Request()
EdgarjController.zip_complete app/controllers/edgarj_controller.rb
inline RJS to fill address info
=begin
def zip_complete
zip = params[:zip].gsub(/\D/, '')
@address = ZipAddress.find_by_zip(zip) || ZipAddress.new(
:prefecture => '?',
:city => '',
:other => '')
# sanitize
@adrs_prefix = params[:adrs_prefix].gsub(/[^a-zA-Z_0-9]/, '')
end
=end
download model under current condition
<tt>respond_to...format.csv</tt> approach was not used since
\@list is different as follows:
* csv returns all of records under the conditions
* HTML returns *just* in specified 'page'.
=== Permission
ModelPermission::READ on this controller is required.
FIXME: file.close(true) deletes files *BEFORE* actually send file
so that comment it out. Need to clean these work files. | [
"zip",
"-",
">",
"address",
"completion"
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/controllers/edgarj/edgarj_controller.rb#L329-L353 |
5,003 | fuminori-ido/edgarj | app/controllers/edgarj/edgarj_controller.rb | Edgarj.EdgarjController.drawer_class | def drawer_class
@_drawer_cache ||=
if self.class == Edgarj::EdgarjController
Edgarj::Drawer::Normal
else
(self.class.name.gsub(/Controller$/, '').singularize +
'Drawer').constantize
end
end | ruby | def drawer_class
@_drawer_cache ||=
if self.class == Edgarj::EdgarjController
Edgarj::Drawer::Normal
else
(self.class.name.gsub(/Controller$/, '').singularize +
'Drawer').constantize
end
end | [
"def",
"drawer_class",
"@_drawer_cache",
"||=",
"if",
"self",
".",
"class",
"==",
"Edgarj",
"::",
"EdgarjController",
"Edgarj",
"::",
"Drawer",
"::",
"Normal",
"else",
"(",
"self",
".",
"class",
".",
"name",
".",
"gsub",
"(",
"/",
"/",
",",
"''",
")",
".",
"singularize",
"+",
"'Drawer'",
")",
".",
"constantize",
"end",
"end"
] | derive drawer class from this controller.
If controller cannot guess drawer class, overwrite this.
=== Examples:
* AuthorsController -> AuthorDrawer
* UsersController -> UserDrawer | [
"derive",
"drawer",
"class",
"from",
"this",
"controller",
"."
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/controllers/edgarj/edgarj_controller.rb#L440-L448 |
5,004 | fuminori-ido/edgarj | app/models/edgarj/search.rb | Edgarj.Search.column_type | def column_type(col_name)
cache = Cache.instance
cache.klass_hash[@_klass_str] ||= {}
if v = cache.klass_hash[@_klass_str][col_name.to_s]
cache.hit += 1
v
else
cache.miss += 1
col = @_klass_str.constantize.columns.find{|c|
c.name == col_name.to_s
}
if col
cache.klass_hash[@_klass_str][col_name.to_s] = col.type
end
end
end | ruby | def column_type(col_name)
cache = Cache.instance
cache.klass_hash[@_klass_str] ||= {}
if v = cache.klass_hash[@_klass_str][col_name.to_s]
cache.hit += 1
v
else
cache.miss += 1
col = @_klass_str.constantize.columns.find{|c|
c.name == col_name.to_s
}
if col
cache.klass_hash[@_klass_str][col_name.to_s] = col.type
end
end
end | [
"def",
"column_type",
"(",
"col_name",
")",
"cache",
"=",
"Cache",
".",
"instance",
"cache",
".",
"klass_hash",
"[",
"@_klass_str",
"]",
"||=",
"{",
"}",
"if",
"v",
"=",
"cache",
".",
"klass_hash",
"[",
"@_klass_str",
"]",
"[",
"col_name",
".",
"to_s",
"]",
"cache",
".",
"hit",
"+=",
"1",
"v",
"else",
"cache",
".",
"miss",
"+=",
"1",
"col",
"=",
"@_klass_str",
".",
"constantize",
".",
"columns",
".",
"find",
"{",
"|",
"c",
"|",
"c",
".",
"name",
"==",
"col_name",
".",
"to_s",
"}",
"if",
"col",
"cache",
".",
"klass_hash",
"[",
"@_klass_str",
"]",
"[",
"col_name",
".",
"to_s",
"]",
"=",
"col",
".",
"type",
"end",
"end",
"end"
] | cache column type | [
"cache",
"column",
"type"
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/models/edgarj/search.rb#L64-L79 |
5,005 | efreesen/active_repository | lib/active_repository/writers.rb | ActiveRepository.Writers.create | def create(attributes={})
attributes = attributes.symbolize_keys if attributes.respond_to?(:symbolize_keys)
object = self.new(attributes)
if object.present? && object.valid?
if persistence_class == self
object.id = nil unless exists?(object.id)
object.save
else
object = PersistenceAdapter.create(self, object.attributes)
end
end
new_object = serialize!(object.reload.attributes)
new_object.valid?
new_object
end | ruby | def create(attributes={})
attributes = attributes.symbolize_keys if attributes.respond_to?(:symbolize_keys)
object = self.new(attributes)
if object.present? && object.valid?
if persistence_class == self
object.id = nil unless exists?(object.id)
object.save
else
object = PersistenceAdapter.create(self, object.attributes)
end
end
new_object = serialize!(object.reload.attributes)
new_object.valid?
new_object
end | [
"def",
"create",
"(",
"attributes",
"=",
"{",
"}",
")",
"attributes",
"=",
"attributes",
".",
"symbolize_keys",
"if",
"attributes",
".",
"respond_to?",
"(",
":symbolize_keys",
")",
"object",
"=",
"self",
".",
"new",
"(",
"attributes",
")",
"if",
"object",
".",
"present?",
"&&",
"object",
".",
"valid?",
"if",
"persistence_class",
"==",
"self",
"object",
".",
"id",
"=",
"nil",
"unless",
"exists?",
"(",
"object",
".",
"id",
")",
"object",
".",
"save",
"else",
"object",
"=",
"PersistenceAdapter",
".",
"create",
"(",
"self",
",",
"object",
".",
"attributes",
")",
"end",
"end",
"new_object",
"=",
"serialize!",
"(",
"object",
".",
"reload",
".",
"attributes",
")",
"new_object",
".",
"valid?",
"new_object",
"end"
] | Creates an object and persists it. | [
"Creates",
"an",
"object",
"and",
"persists",
"it",
"."
] | e134b0e02959ac7e745319a2d74398101dfc5900 | https://github.com/efreesen/active_repository/blob/e134b0e02959ac7e745319a2d74398101dfc5900/lib/active_repository/writers.rb#L5-L24 |
5,006 | MattRyder/tableau | lib/tableau/tablebuilder.rb | Tableau.TableBuilder.to_html | def to_html
time_header, rows = '<th></th>', Array.new
end_time = Time.new(2013, 1, 1, 21, 0, 0)
# make the time row
@time = Time.new(2013, 1, 1, 9, 0, 0)
while @time < end_time
time_header += "<th>#{@time.strftime("%-k:%M")}</th>"
@time += 900
end
#make each day row
(0..4).each do |day|
classes = @timetable.classes_for_day(day)
rows << day_row(day, classes)
end
rows_str, id_str = '', "id=\"#{@timetable.name}\""
rows.each{ |r| rows_str += "<tr class=\"day\">\n#{r}\n</tr>\n" }
%Q{
<!DOCTYPE html>
<html>
<head>
<title>#{@timetable.name || 'Timetable' } - Timetablr.co</title>
<style>#{build_css}</style>
</head>
<body>
<h3>#{@timetable.name}</h3>
<table #{id_str if @timetable.name}>
<tr id="time">#{time_header}</tr>
#{rows_str}
</table>
</body>
</html>
}
end | ruby | def to_html
time_header, rows = '<th></th>', Array.new
end_time = Time.new(2013, 1, 1, 21, 0, 0)
# make the time row
@time = Time.new(2013, 1, 1, 9, 0, 0)
while @time < end_time
time_header += "<th>#{@time.strftime("%-k:%M")}</th>"
@time += 900
end
#make each day row
(0..4).each do |day|
classes = @timetable.classes_for_day(day)
rows << day_row(day, classes)
end
rows_str, id_str = '', "id=\"#{@timetable.name}\""
rows.each{ |r| rows_str += "<tr class=\"day\">\n#{r}\n</tr>\n" }
%Q{
<!DOCTYPE html>
<html>
<head>
<title>#{@timetable.name || 'Timetable' } - Timetablr.co</title>
<style>#{build_css}</style>
</head>
<body>
<h3>#{@timetable.name}</h3>
<table #{id_str if @timetable.name}>
<tr id="time">#{time_header}</tr>
#{rows_str}
</table>
</body>
</html>
}
end | [
"def",
"to_html",
"time_header",
",",
"rows",
"=",
"'<th></th>'",
",",
"Array",
".",
"new",
"end_time",
"=",
"Time",
".",
"new",
"(",
"2013",
",",
"1",
",",
"1",
",",
"21",
",",
"0",
",",
"0",
")",
"# make the time row",
"@time",
"=",
"Time",
".",
"new",
"(",
"2013",
",",
"1",
",",
"1",
",",
"9",
",",
"0",
",",
"0",
")",
"while",
"@time",
"<",
"end_time",
"time_header",
"+=",
"\"<th>#{@time.strftime(\"%-k:%M\")}</th>\"",
"@time",
"+=",
"900",
"end",
"#make each day row",
"(",
"0",
"..",
"4",
")",
".",
"each",
"do",
"|",
"day",
"|",
"classes",
"=",
"@timetable",
".",
"classes_for_day",
"(",
"day",
")",
"rows",
"<<",
"day_row",
"(",
"day",
",",
"classes",
")",
"end",
"rows_str",
",",
"id_str",
"=",
"''",
",",
"\"id=\\\"#{@timetable.name}\\\"\"",
"rows",
".",
"each",
"{",
"|",
"r",
"|",
"rows_str",
"+=",
"\"<tr class=\\\"day\\\">\\n#{r}\\n</tr>\\n\"",
"}",
"%Q{\n <!DOCTYPE html>\n <html>\n <head>\n <title>#{@timetable.name || 'Timetable' } - Timetablr.co</title>\n <style>#{build_css}</style>\n </head>\n <body>\n <h3>#{@timetable.name}</h3>\n <table #{id_str if @timetable.name}>\n <tr id=\"time\">#{time_header}</tr>\n #{rows_str}\n </table>\n </body>\n </html>\n }",
"end"
] | HTML5 representation of the timetable | [
"HTML5",
"representation",
"of",
"the",
"timetable"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/tablebuilder.rb#L95-L131 |
5,007 | Kuniri/kuniri | lib/kuniri/core/setting.rb | Kuniri.Setting.read_configuration_file | def read_configuration_file(pPath = '.kuniri.yml')
if !(File.exist?(pPath))
set_default_configuration
else
safeInfo = SafeYAML.load(File.read(pPath))
# SafeYAML add collon (':') in the begin of each key. We handle it here
@configurationInfo = safeInfo.map do |key, value|
[key.tr(':', '').to_sym, value]
end.to_h
verify_syntax
end
return @configurationInfo
end | ruby | def read_configuration_file(pPath = '.kuniri.yml')
if !(File.exist?(pPath))
set_default_configuration
else
safeInfo = SafeYAML.load(File.read(pPath))
# SafeYAML add collon (':') in the begin of each key. We handle it here
@configurationInfo = safeInfo.map do |key, value|
[key.tr(':', '').to_sym, value]
end.to_h
verify_syntax
end
return @configurationInfo
end | [
"def",
"read_configuration_file",
"(",
"pPath",
"=",
"'.kuniri.yml'",
")",
"if",
"!",
"(",
"File",
".",
"exist?",
"(",
"pPath",
")",
")",
"set_default_configuration",
"else",
"safeInfo",
"=",
"SafeYAML",
".",
"load",
"(",
"File",
".",
"read",
"(",
"pPath",
")",
")",
"# SafeYAML add collon (':') in the begin of each key. We handle it here",
"@configurationInfo",
"=",
"safeInfo",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"[",
"key",
".",
"tr",
"(",
"':'",
",",
"''",
")",
".",
"to_sym",
",",
"value",
"]",
"end",
".",
"to_h",
"verify_syntax",
"end",
"return",
"@configurationInfo",
"end"
] | In this method it is checked the configuration file syntax.
@param pPath [String] Path to ".kuniri" file, it means, the
configurations.
@return [Hash] Return a Hash with the configurations read in ".kuniri",
otherwise, raise an exception. | [
"In",
"this",
"method",
"it",
"is",
"checked",
"the",
"configuration",
"file",
"syntax",
"."
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/core/setting.rb#L39-L52 |
5,008 | godfat/pagify | lib/pagify/pager/basic.rb | Pagify.BasicPager.page | def page page
if page_exists?(page)
return BasicPage.new(self, normalize_page(page))
else
if null_page
return null_page_instance
else
return nil
end
end
end | ruby | def page page
if page_exists?(page)
return BasicPage.new(self, normalize_page(page))
else
if null_page
return null_page_instance
else
return nil
end
end
end | [
"def",
"page",
"page",
"if",
"page_exists?",
"(",
"page",
")",
"return",
"BasicPage",
".",
"new",
"(",
"self",
",",
"normalize_page",
"(",
"page",
")",
")",
"else",
"if",
"null_page",
"return",
"null_page_instance",
"else",
"return",
"nil",
"end",
"end",
"end"
] | create page instance by page number.
if page number you specified was not existed,
nil would be returned. note, page start at 1, not zero. | [
"create",
"page",
"instance",
"by",
"page",
"number",
".",
"if",
"page",
"number",
"you",
"specified",
"was",
"not",
"existed",
"nil",
"would",
"be",
"returned",
".",
"note",
"page",
"start",
"at",
"1",
"not",
"zero",
"."
] | 178fafc959335050e89e9d5a1d1a347145ee61db | https://github.com/godfat/pagify/blob/178fafc959335050e89e9d5a1d1a347145ee61db/lib/pagify/pager/basic.rb#L70-L83 |
5,009 | news-scraper/news_scraper | lib/news_scraper/scraper.rb | NewsScraper.Scraper.scrape | def scrape
article_urls = Extractors::GoogleNewsRss.new(query: @query).extract
transformed_articles = []
article_urls.each do |article_url|
payload = Extractors::Article.new(url: article_url).extract
article_transformer = Transformers::Article.new(url: article_url, payload: payload)
begin
transformed_article = article_transformer.transform
transformed_articles << transformed_article
yield transformed_article if block_given?
rescue Transformers::ScrapePatternNotDefined => e
raise e unless block_given?
yield e
end
end
transformed_articles
end | ruby | def scrape
article_urls = Extractors::GoogleNewsRss.new(query: @query).extract
transformed_articles = []
article_urls.each do |article_url|
payload = Extractors::Article.new(url: article_url).extract
article_transformer = Transformers::Article.new(url: article_url, payload: payload)
begin
transformed_article = article_transformer.transform
transformed_articles << transformed_article
yield transformed_article if block_given?
rescue Transformers::ScrapePatternNotDefined => e
raise e unless block_given?
yield e
end
end
transformed_articles
end | [
"def",
"scrape",
"article_urls",
"=",
"Extractors",
"::",
"GoogleNewsRss",
".",
"new",
"(",
"query",
":",
"@query",
")",
".",
"extract",
"transformed_articles",
"=",
"[",
"]",
"article_urls",
".",
"each",
"do",
"|",
"article_url",
"|",
"payload",
"=",
"Extractors",
"::",
"Article",
".",
"new",
"(",
"url",
":",
"article_url",
")",
".",
"extract",
"article_transformer",
"=",
"Transformers",
"::",
"Article",
".",
"new",
"(",
"url",
":",
"article_url",
",",
"payload",
":",
"payload",
")",
"begin",
"transformed_article",
"=",
"article_transformer",
".",
"transform",
"transformed_articles",
"<<",
"transformed_article",
"yield",
"transformed_article",
"if",
"block_given?",
"rescue",
"Transformers",
"::",
"ScrapePatternNotDefined",
"=>",
"e",
"raise",
"e",
"unless",
"block_given?",
"yield",
"e",
"end",
"end",
"transformed_articles",
"end"
] | Initialize a Scraper object
*Params*
- <code>query</code>: a keyword arugment specifying the query to scrape
Fetches articles from Extraction sources and scrapes the results
*Yields*
- Will yield individually extracted articles
*Raises*
- Will raise a <code>Transformers::ScrapePatternNotDefined</code> if an article is not in the root domains
- Will <code>yield</code> the error if a block is given
- Root domains are specified by the <code>article_scrape_patterns.yml</code> file
- This root domain will need to be trained, it would be helpful to have a PR created to train the domain
- You can train the domain by running <code>NewsScraper::Trainer::UrlTrainer.new(URL_TO_TRAIN).train</code>
*Returns*
- <code>transformed_articles</code>: The transformed articles fetched from the extracted sources | [
"Initialize",
"a",
"Scraper",
"object"
] | 3ee2ea9590d081ffb8e98120b2e1344dec88a15e | https://github.com/news-scraper/news_scraper/blob/3ee2ea9590d081ffb8e98120b2e1344dec88a15e/lib/news_scraper/scraper.rb#L27-L47 |
5,010 | news-scraper/news_scraper | lib/news_scraper/trainer.rb | NewsScraper.Trainer.train | def train(query: '')
article_urls = Extractors::GoogleNewsRss.new(query: query).extract
article_urls.each do |url|
Trainer::UrlTrainer.new(url).train
end
end | ruby | def train(query: '')
article_urls = Extractors::GoogleNewsRss.new(query: query).extract
article_urls.each do |url|
Trainer::UrlTrainer.new(url).train
end
end | [
"def",
"train",
"(",
"query",
":",
"''",
")",
"article_urls",
"=",
"Extractors",
"::",
"GoogleNewsRss",
".",
"new",
"(",
"query",
":",
"query",
")",
".",
"extract",
"article_urls",
".",
"each",
"do",
"|",
"url",
"|",
"Trainer",
"::",
"UrlTrainer",
".",
"new",
"(",
"url",
")",
".",
"train",
"end",
"end"
] | Fetches articles from Extraction sources and trains on the results
*Training* is a process where we take an untrained url (root domain
is not in <code>article_scrape_patterns.yml</code>) and determine patterns and methods
to match the data_types listed in <code>article_scrape_patterns.yml</code>, then record
them to the <code>article_scrape_patterns.yml</code> file
*Params*
- <code>query</code>: a keyword arugment specifying the query to train on | [
"Fetches",
"articles",
"from",
"Extraction",
"sources",
"and",
"trains",
"on",
"the",
"results"
] | 3ee2ea9590d081ffb8e98120b2e1344dec88a15e | https://github.com/news-scraper/news_scraper/blob/3ee2ea9590d081ffb8e98120b2e1344dec88a15e/lib/news_scraper/trainer.rb#L18-L23 |
5,011 | bdurand/json_record | lib/json_record/schema.rb | JsonRecord.Schema.key | def key (name, *args)
options = args.extract_options!
name = name.to_s
json_type = args.first || String
raise ArgumentError.new("too many arguments (must be 1 or 2 plus an options hash)") if args.length > 1
field = FieldDefinition.new(name, :type => json_type, :default => options[:default])
fields[name] = field
add_json_validations(field, options)
define_json_accessor(field, json_field_name)
end | ruby | def key (name, *args)
options = args.extract_options!
name = name.to_s
json_type = args.first || String
raise ArgumentError.new("too many arguments (must be 1 or 2 plus an options hash)") if args.length > 1
field = FieldDefinition.new(name, :type => json_type, :default => options[:default])
fields[name] = field
add_json_validations(field, options)
define_json_accessor(field, json_field_name)
end | [
"def",
"key",
"(",
"name",
",",
"*",
"args",
")",
"options",
"=",
"args",
".",
"extract_options!",
"name",
"=",
"name",
".",
"to_s",
"json_type",
"=",
"args",
".",
"first",
"||",
"String",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"too many arguments (must be 1 or 2 plus an options hash)\"",
")",
"if",
"args",
".",
"length",
">",
"1",
"field",
"=",
"FieldDefinition",
".",
"new",
"(",
"name",
",",
":type",
"=>",
"json_type",
",",
":default",
"=>",
"options",
"[",
":default",
"]",
")",
"fields",
"[",
"name",
"]",
"=",
"field",
"add_json_validations",
"(",
"field",
",",
"options",
")",
"define_json_accessor",
"(",
"field",
",",
"json_field_name",
")",
"end"
] | Create a schema on the class for a particular field.
Define a single valued field in the schema.
The first argument is the field name. This must be unique for the class accross all attributes.
The optional second argument can be used to specify the class of the field values. It will default to
String if not specified. Valid types are String, Integer, Float, Date, Time, DateTime, Boolean, Array, Hash,
or any class that inherits from EmbeddedDocument.
The last argument can be a hash with any of these keys:
* :default -
* :required -
* :length -
* :format -
* :in - | [
"Create",
"a",
"schema",
"on",
"the",
"class",
"for",
"a",
"particular",
"field",
".",
"Define",
"a",
"single",
"valued",
"field",
"in",
"the",
"schema",
".",
"The",
"first",
"argument",
"is",
"the",
"field",
"name",
".",
"This",
"must",
"be",
"unique",
"for",
"the",
"class",
"accross",
"all",
"attributes",
"."
] | 463f4719d9618f6d2406c0aab6028e0156f7c775 | https://github.com/bdurand/json_record/blob/463f4719d9618f6d2406c0aab6028e0156f7c775/lib/json_record/schema.rb#L27-L38 |
5,012 | bdurand/json_record | lib/json_record/schema.rb | JsonRecord.Schema.many | def many (name, *args)
name = name.to_s
options = args.extract_options!
type = args.first || name.singularize.classify.constantize
field = FieldDefinition.new(name, :type => type, :multivalued => true)
fields[name] = field
add_json_validations(field, options)
define_many_json_accessor(field, json_field_name)
end | ruby | def many (name, *args)
name = name.to_s
options = args.extract_options!
type = args.first || name.singularize.classify.constantize
field = FieldDefinition.new(name, :type => type, :multivalued => true)
fields[name] = field
add_json_validations(field, options)
define_many_json_accessor(field, json_field_name)
end | [
"def",
"many",
"(",
"name",
",",
"*",
"args",
")",
"name",
"=",
"name",
".",
"to_s",
"options",
"=",
"args",
".",
"extract_options!",
"type",
"=",
"args",
".",
"first",
"||",
"name",
".",
"singularize",
".",
"classify",
".",
"constantize",
"field",
"=",
"FieldDefinition",
".",
"new",
"(",
"name",
",",
":type",
"=>",
"type",
",",
":multivalued",
"=>",
"true",
")",
"fields",
"[",
"name",
"]",
"=",
"field",
"add_json_validations",
"(",
"field",
",",
"options",
")",
"define_many_json_accessor",
"(",
"field",
",",
"json_field_name",
")",
"end"
] | Define a multi valued field in the schema.
The first argument is the field name. This must be unique for the class accross all attributes.
The optional second argument should be the class of field values. This class must include EmbeddedDocument.
If it is not specified, the class name will be guessed from the field name.
The last argument can be :unique => field_name which is used to indicate that the values in the field
must have unique values in the indicated field name.
The value of the field will always be an EmbeddedDocumentArray and adding and removing values is as
simple as appending them to the array. You can also call the build method on the array to keep the syntax the
same as when dealing with ActiveRecord has_many associations. | [
"Define",
"a",
"multi",
"valued",
"field",
"in",
"the",
"schema",
".",
"The",
"first",
"argument",
"is",
"the",
"field",
"name",
".",
"This",
"must",
"be",
"unique",
"for",
"the",
"class",
"accross",
"all",
"attributes",
"."
] | 463f4719d9618f6d2406c0aab6028e0156f7c775 | https://github.com/bdurand/json_record/blob/463f4719d9618f6d2406c0aab6028e0156f7c775/lib/json_record/schema.rb#L52-L60 |
5,013 | MattRyder/tableau | lib/tableau/classarray.rb | Tableau.ClassArray.classes_for_day | def classes_for_day(day)
days_classes = ClassArray.new
self.each { |c| days_classes << c if c.day == day }
days_classes.count > 0 ? days_classes : nil
end | ruby | def classes_for_day(day)
days_classes = ClassArray.new
self.each { |c| days_classes << c if c.day == day }
days_classes.count > 0 ? days_classes : nil
end | [
"def",
"classes_for_day",
"(",
"day",
")",
"days_classes",
"=",
"ClassArray",
".",
"new",
"self",
".",
"each",
"{",
"|",
"c",
"|",
"days_classes",
"<<",
"c",
"if",
"c",
".",
"day",
"==",
"day",
"}",
"days_classes",
".",
"count",
">",
"0",
"?",
"days_classes",
":",
"nil",
"end"
] | Returns an array of all the classes for the day | [
"Returns",
"an",
"array",
"of",
"all",
"the",
"classes",
"for",
"the",
"day"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/classarray.rb#L9-L13 |
5,014 | MattRyder/tableau | lib/tableau/classarray.rb | Tableau.ClassArray.earliest_class | def earliest_class
earliest = self.first
self.each { |c| earliest = c if c.time < earliest.time }
earliest
end | ruby | def earliest_class
earliest = self.first
self.each { |c| earliest = c if c.time < earliest.time }
earliest
end | [
"def",
"earliest_class",
"earliest",
"=",
"self",
".",
"first",
"self",
".",
"each",
"{",
"|",
"c",
"|",
"earliest",
"=",
"c",
"if",
"c",
".",
"time",
"<",
"earliest",
".",
"time",
"}",
"earliest",
"end"
] | Returns the earliest class in the module | [
"Returns",
"the",
"earliest",
"class",
"in",
"the",
"module"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/classarray.rb#L16-L20 |
5,015 | namelessjon/todoist | lib/todoist/task.rb | Todoist.Task.save | def save
opts = {}
opts['priority'] = priority if priority
opts['date_string'] = date if date
# if we don't have an id, then we can assume this is a new task.
unless (task_details.has_key?('id'))
result = self.class.create(self.content, self.project_id, opts)
else
result = self.class.update(self.content, self.id, opts)
end
self.content = result.content
self.project_id = result.project_id
self.task_details = result.task_details
self
end | ruby | def save
opts = {}
opts['priority'] = priority if priority
opts['date_string'] = date if date
# if we don't have an id, then we can assume this is a new task.
unless (task_details.has_key?('id'))
result = self.class.create(self.content, self.project_id, opts)
else
result = self.class.update(self.content, self.id, opts)
end
self.content = result.content
self.project_id = result.project_id
self.task_details = result.task_details
self
end | [
"def",
"save",
"opts",
"=",
"{",
"}",
"opts",
"[",
"'priority'",
"]",
"=",
"priority",
"if",
"priority",
"opts",
"[",
"'date_string'",
"]",
"=",
"date",
"if",
"date",
"# if we don't have an id, then we can assume this is a new task.",
"unless",
"(",
"task_details",
".",
"has_key?",
"(",
"'id'",
")",
")",
"result",
"=",
"self",
".",
"class",
".",
"create",
"(",
"self",
".",
"content",
",",
"self",
".",
"project_id",
",",
"opts",
")",
"else",
"result",
"=",
"self",
".",
"class",
".",
"update",
"(",
"self",
".",
"content",
",",
"self",
".",
"id",
",",
"opts",
")",
"end",
"self",
".",
"content",
"=",
"result",
".",
"content",
"self",
".",
"project_id",
"=",
"result",
".",
"project_id",
"self",
".",
"task_details",
"=",
"result",
".",
"task_details",
"self",
"end"
] | Saves the task
Save the task, either creating a new task on the todoist service, or
updating a previously retrieved task with new content, priority etc. | [
"Saves",
"the",
"task"
] | 65f049436f639fcb7dc3c8f5b5737ba0f81be9d5 | https://github.com/namelessjon/todoist/blob/65f049436f639fcb7dc3c8f5b5737ba0f81be9d5/lib/todoist/task.rb#L188-L203 |
5,016 | tpope/ldaptic | lib/ldaptic/attribute_set.rb | Ldaptic.AttributeSet.replace | def replace(*attributes)
attributes = safe_array(attributes)
user_modification_guard
seen = {}
filtered = []
attributes.each do |value|
matchable = matchable(value)
unless seen[matchable]
filtered << value
seen[matchable] = true
end
end
@target.replace(filtered)
self
end | ruby | def replace(*attributes)
attributes = safe_array(attributes)
user_modification_guard
seen = {}
filtered = []
attributes.each do |value|
matchable = matchable(value)
unless seen[matchable]
filtered << value
seen[matchable] = true
end
end
@target.replace(filtered)
self
end | [
"def",
"replace",
"(",
"*",
"attributes",
")",
"attributes",
"=",
"safe_array",
"(",
"attributes",
")",
"user_modification_guard",
"seen",
"=",
"{",
"}",
"filtered",
"=",
"[",
"]",
"attributes",
".",
"each",
"do",
"|",
"value",
"|",
"matchable",
"=",
"matchable",
"(",
"value",
")",
"unless",
"seen",
"[",
"matchable",
"]",
"filtered",
"<<",
"value",
"seen",
"[",
"matchable",
"]",
"=",
"true",
"end",
"end",
"@target",
".",
"replace",
"(",
"filtered",
")",
"self",
"end"
] | Does a complete replacement of the attributes. Multiple attributes can
be given as either multiple arguments or as an array. | [
"Does",
"a",
"complete",
"replacement",
"of",
"the",
"attributes",
".",
"Multiple",
"attributes",
"can",
"be",
"given",
"as",
"either",
"multiple",
"arguments",
"or",
"as",
"an",
"array",
"."
] | 159a39464e9f5a05c0145db2b21cb256ef859612 | https://github.com/tpope/ldaptic/blob/159a39464e9f5a05c0145db2b21cb256ef859612/lib/ldaptic/attribute_set.rb#L124-L138 |
5,017 | fuminori-ido/edgarj | app/models/edgarj/search_form.rb | Edgarj.SearchForm.method_missing | def method_missing(method_name, *args)
if method_name.to_s =~ /^(.*)=$/
@attrs[$1.to_sym] = args[0]
else
val = @attrs[method_name.to_sym]
case column_type(method_name)
when :integer
if val =~ /^\d+$/
val.to_i
else
val
end
else
val
end
end
end | ruby | def method_missing(method_name, *args)
if method_name.to_s =~ /^(.*)=$/
@attrs[$1.to_sym] = args[0]
else
val = @attrs[method_name.to_sym]
case column_type(method_name)
when :integer
if val =~ /^\d+$/
val.to_i
else
val
end
else
val
end
end
end | [
"def",
"method_missing",
"(",
"method_name",
",",
"*",
"args",
")",
"if",
"method_name",
".",
"to_s",
"=~",
"/",
"/",
"@attrs",
"[",
"$1",
".",
"to_sym",
"]",
"=",
"args",
"[",
"0",
"]",
"else",
"val",
"=",
"@attrs",
"[",
"method_name",
".",
"to_sym",
"]",
"case",
"column_type",
"(",
"method_name",
")",
"when",
":integer",
"if",
"val",
"=~",
"/",
"\\d",
"/",
"val",
".",
"to_i",
"else",
"val",
"end",
"else",
"val",
"end",
"end",
"end"
] | Build SearchForm object from ActiveRecord 'klass' and attrs.
=== INPUTS
klass:: ActiveRecord
attrs:: hash of key=>value pair
map attribute name to hash entry.
This mechanism is required to be used in 'form_for' helper.
When column type is integer and has digits value, return integer.
This is required for selection helper.
Even it is integer but has no value, keeps blank.
When attribute name ends '=', assignment to hash works.
=== EXAMPLE
s = Searchform.new(Product, :name=>'a')
s.name
s.conditions # ["name=?", "a"]
s.name = 'b' # method_missing('name=', 'b') is called
s.conditions # ["name=?", "b"] | [
"Build",
"SearchForm",
"object",
"from",
"ActiveRecord",
"klass",
"and",
"attrs",
"."
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/models/edgarj/search_form.rb#L127-L143 |
5,018 | imanel/libwebsocket | lib/libwebsocket/url.rb | LibWebSocket.URL.parse | def parse(string)
return nil unless string.is_a?(String)
uri = Addressable::URI.parse(string)
scheme = uri.scheme
return nil unless scheme
self.secure = true if scheme.match(/ss\Z/m)
host = uri.host
host = '/' unless host && host != ''
self.host = host
self.port = uri.port.to_s if uri.port
request_uri = uri.path
request_uri = '/' unless request_uri && request_uri != ''
request_uri += "?" + uri.query if uri.query
self.resource_name = request_uri
return self
end | ruby | def parse(string)
return nil unless string.is_a?(String)
uri = Addressable::URI.parse(string)
scheme = uri.scheme
return nil unless scheme
self.secure = true if scheme.match(/ss\Z/m)
host = uri.host
host = '/' unless host && host != ''
self.host = host
self.port = uri.port.to_s if uri.port
request_uri = uri.path
request_uri = '/' unless request_uri && request_uri != ''
request_uri += "?" + uri.query if uri.query
self.resource_name = request_uri
return self
end | [
"def",
"parse",
"(",
"string",
")",
"return",
"nil",
"unless",
"string",
".",
"is_a?",
"(",
"String",
")",
"uri",
"=",
"Addressable",
"::",
"URI",
".",
"parse",
"(",
"string",
")",
"scheme",
"=",
"uri",
".",
"scheme",
"return",
"nil",
"unless",
"scheme",
"self",
".",
"secure",
"=",
"true",
"if",
"scheme",
".",
"match",
"(",
"/",
"\\Z",
"/m",
")",
"host",
"=",
"uri",
".",
"host",
"host",
"=",
"'/'",
"unless",
"host",
"&&",
"host",
"!=",
"''",
"self",
".",
"host",
"=",
"host",
"self",
".",
"port",
"=",
"uri",
".",
"port",
".",
"to_s",
"if",
"uri",
".",
"port",
"request_uri",
"=",
"uri",
".",
"path",
"request_uri",
"=",
"'/'",
"unless",
"request_uri",
"&&",
"request_uri",
"!=",
"''",
"request_uri",
"+=",
"\"?\"",
"+",
"uri",
".",
"query",
"if",
"uri",
".",
"query",
"self",
".",
"resource_name",
"=",
"request_uri",
"return",
"self",
"end"
] | Parse a WebSocket URL.
@example Parse
url = LibWebSocket::URL.new
url.parse('wss://example.com:3000')
url.host # => example.com
url.port # => 3000
url.secure # => true | [
"Parse",
"a",
"WebSocket",
"URL",
"."
] | 3e071439246f5a2c306e16fefc772d2f6f716f6b | https://github.com/imanel/libwebsocket/blob/3e071439246f5a2c306e16fefc772d2f6f716f6b/lib/libwebsocket/url.rb#L24-L45 |
5,019 | imanel/libwebsocket | lib/libwebsocket/url.rb | LibWebSocket.URL.to_s | def to_s
string = ''
string += 'ws'
string += 's' if self.secure
string += '://'
string += self.host
string += ':' + self.port.to_s if self.port
string += self.resource_name || '/'
return string
end | ruby | def to_s
string = ''
string += 'ws'
string += 's' if self.secure
string += '://'
string += self.host
string += ':' + self.port.to_s if self.port
string += self.resource_name || '/'
return string
end | [
"def",
"to_s",
"string",
"=",
"''",
"string",
"+=",
"'ws'",
"string",
"+=",
"'s'",
"if",
"self",
".",
"secure",
"string",
"+=",
"'://'",
"string",
"+=",
"self",
".",
"host",
"string",
"+=",
"':'",
"+",
"self",
".",
"port",
".",
"to_s",
"if",
"self",
".",
"port",
"string",
"+=",
"self",
".",
"resource_name",
"||",
"'/'",
"return",
"string",
"end"
] | Construct a WebSocket URL.
@example Construct
url = LibWebSocket::URL.new
url.host = 'example.com'
url.port = '3000'
url.secure = true
url.to_s # => 'wss://example.com:3000' | [
"Construct",
"a",
"WebSocket",
"URL",
"."
] | 3e071439246f5a2c306e16fefc772d2f6f716f6b | https://github.com/imanel/libwebsocket/blob/3e071439246f5a2c306e16fefc772d2f6f716f6b/lib/libwebsocket/url.rb#L54-L65 |
5,020 | at-point/loggr | lib/loggr/adapter.rb | Loggr.Adapter.logger | def logger(name, options = {}, &block)
use_adapter = options.key?(:adapter) ? get_adapter(options.delete(:adapter)) : self.adapter
use_adapter.logger(name, options).tap do |logger|
yield(logger) if block_given?
end
end | ruby | def logger(name, options = {}, &block)
use_adapter = options.key?(:adapter) ? get_adapter(options.delete(:adapter)) : self.adapter
use_adapter.logger(name, options).tap do |logger|
yield(logger) if block_given?
end
end | [
"def",
"logger",
"(",
"name",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"use_adapter",
"=",
"options",
".",
"key?",
"(",
":adapter",
")",
"?",
"get_adapter",
"(",
"options",
".",
"delete",
"(",
":adapter",
")",
")",
":",
"self",
".",
"adapter",
"use_adapter",
".",
"logger",
"(",
"name",
",",
"options",
")",
".",
"tap",
"do",
"|",
"logger",
"|",
"yield",
"(",
"logger",
")",
"if",
"block_given?",
"end",
"end"
] | Get a new logger instance for supplied named logger or class name.
All adapters must ensure that they provide the same API for creating
new loggers. Each logger has a name, further possible options are:
- `:to`, filename or IO, where to write the output to
- `:level`, Fixnum, starting log level, @see `Loggr::Severity`
- `:marker`, String, name of the category/marker
If an adapter does not support setting a specific option, just
ignore it. | [
"Get",
"a",
"new",
"logger",
"instance",
"for",
"supplied",
"named",
"logger",
"or",
"class",
"name",
"."
] | d87f2d7bf4566fc5a2038fb6c559786d23aade75 | https://github.com/at-point/loggr/blob/d87f2d7bf4566fc5a2038fb6c559786d23aade75/lib/loggr/adapter.rb#L56-L61 |
5,021 | at-point/loggr | lib/loggr/adapter.rb | Loggr.Adapter.get_adapter | def get_adapter(adp)
# okay, this is only because we can't camelize it :)
adp = Loggr::Adapter::NOP if !adp
# Code adapter from ActiveSupport::Inflector#camelize
# https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L30
adp = adp.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } if adp.is_a?(Symbol)
clazz = adp
if adp.respond_to?(:to_str)
const = begin Loggr::Adapter.const_get(adp.to_s) rescue begin Loggr::Adapter.const_get(adp.to_s.upcase) rescue nil end end
unless const
# code adapter from ActiveSupport::Inflector#constantize
# https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L107
names = adp.to_s.split('::')
names.shift if names.empty? || names.first.empty?
const = ::Object
names.each { |n| const = const.const_get(n) }
end
clazz = const
end
raise "#{clazz}: an adapter must implement #logger and #mdc" unless clazz.respond_to?(:logger) && clazz.respond_to?(:mdc)
clazz
end | ruby | def get_adapter(adp)
# okay, this is only because we can't camelize it :)
adp = Loggr::Adapter::NOP if !adp
# Code adapter from ActiveSupport::Inflector#camelize
# https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L30
adp = adp.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } if adp.is_a?(Symbol)
clazz = adp
if adp.respond_to?(:to_str)
const = begin Loggr::Adapter.const_get(adp.to_s) rescue begin Loggr::Adapter.const_get(adp.to_s.upcase) rescue nil end end
unless const
# code adapter from ActiveSupport::Inflector#constantize
# https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L107
names = adp.to_s.split('::')
names.shift if names.empty? || names.first.empty?
const = ::Object
names.each { |n| const = const.const_get(n) }
end
clazz = const
end
raise "#{clazz}: an adapter must implement #logger and #mdc" unless clazz.respond_to?(:logger) && clazz.respond_to?(:mdc)
clazz
end | [
"def",
"get_adapter",
"(",
"adp",
")",
"# okay, this is only because we can't camelize it :)",
"adp",
"=",
"Loggr",
"::",
"Adapter",
"::",
"NOP",
"if",
"!",
"adp",
"# Code adapter from ActiveSupport::Inflector#camelize",
"# https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L30",
"adp",
"=",
"adp",
".",
"to_s",
".",
"gsub",
"(",
"/",
"\\/",
"/",
")",
"{",
"\"::#{$1.upcase}\"",
"}",
".",
"gsub",
"(",
"/",
"/",
")",
"{",
"$1",
".",
"upcase",
"}",
"if",
"adp",
".",
"is_a?",
"(",
"Symbol",
")",
"clazz",
"=",
"adp",
"if",
"adp",
".",
"respond_to?",
"(",
":to_str",
")",
"const",
"=",
"begin",
"Loggr",
"::",
"Adapter",
".",
"const_get",
"(",
"adp",
".",
"to_s",
")",
"rescue",
"begin",
"Loggr",
"::",
"Adapter",
".",
"const_get",
"(",
"adp",
".",
"to_s",
".",
"upcase",
")",
"rescue",
"nil",
"end",
"end",
"unless",
"const",
"# code adapter from ActiveSupport::Inflector#constantize",
"# https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L107",
"names",
"=",
"adp",
".",
"to_s",
".",
"split",
"(",
"'::'",
")",
"names",
".",
"shift",
"if",
"names",
".",
"empty?",
"||",
"names",
".",
"first",
".",
"empty?",
"const",
"=",
"::",
"Object",
"names",
".",
"each",
"{",
"|",
"n",
"|",
"const",
"=",
"const",
".",
"const_get",
"(",
"n",
")",
"}",
"end",
"clazz",
"=",
"const",
"end",
"raise",
"\"#{clazz}: an adapter must implement #logger and #mdc\"",
"unless",
"clazz",
".",
"respond_to?",
"(",
":logger",
")",
"&&",
"clazz",
".",
"respond_to?",
"(",
":mdc",
")",
"clazz",
"end"
] | Try to get adapter class from Symbol, String or use Object as-is. | [
"Try",
"to",
"get",
"adapter",
"class",
"from",
"Symbol",
"String",
"or",
"use",
"Object",
"as",
"-",
"is",
"."
] | d87f2d7bf4566fc5a2038fb6c559786d23aade75 | https://github.com/at-point/loggr/blob/d87f2d7bf4566fc5a2038fb6c559786d23aade75/lib/loggr/adapter.rb#L87-L113 |
5,022 | CITguy/xml-fu | lib/xml-fu/node.rb | XmlFu.Node.name_parse_special_characters | def name_parse_special_characters(val)
use_this = val.dup
# Ensure that we don't have special characters at end of name
while ["!","/","*"].include?(use_this.to_s[-1,1]) do
# Will this node contain escaped XML?
if use_this.to_s[-1,1] == '!'
@escape_xml = false
use_this.chop!
end
# Will this be a self closing node?
if use_this.to_s[-1,1] == '/'
@self_closing = true
use_this.chop!
end
# Will this node contain a collection of sibling nodes?
if use_this.to_s[-1,1] == '*'
@content_type = "collection"
use_this.chop!
end
end
return use_this
end | ruby | def name_parse_special_characters(val)
use_this = val.dup
# Ensure that we don't have special characters at end of name
while ["!","/","*"].include?(use_this.to_s[-1,1]) do
# Will this node contain escaped XML?
if use_this.to_s[-1,1] == '!'
@escape_xml = false
use_this.chop!
end
# Will this be a self closing node?
if use_this.to_s[-1,1] == '/'
@self_closing = true
use_this.chop!
end
# Will this node contain a collection of sibling nodes?
if use_this.to_s[-1,1] == '*'
@content_type = "collection"
use_this.chop!
end
end
return use_this
end | [
"def",
"name_parse_special_characters",
"(",
"val",
")",
"use_this",
"=",
"val",
".",
"dup",
"# Ensure that we don't have special characters at end of name",
"while",
"[",
"\"!\"",
",",
"\"/\"",
",",
"\"*\"",
"]",
".",
"include?",
"(",
"use_this",
".",
"to_s",
"[",
"-",
"1",
",",
"1",
"]",
")",
"do",
"# Will this node contain escaped XML?",
"if",
"use_this",
".",
"to_s",
"[",
"-",
"1",
",",
"1",
"]",
"==",
"'!'",
"@escape_xml",
"=",
"false",
"use_this",
".",
"chop!",
"end",
"# Will this be a self closing node?",
"if",
"use_this",
".",
"to_s",
"[",
"-",
"1",
",",
"1",
"]",
"==",
"'/'",
"@self_closing",
"=",
"true",
"use_this",
".",
"chop!",
"end",
"# Will this node contain a collection of sibling nodes?",
"if",
"use_this",
".",
"to_s",
"[",
"-",
"1",
",",
"1",
"]",
"==",
"'*'",
"@content_type",
"=",
"\"collection\"",
"use_this",
".",
"chop!",
"end",
"end",
"return",
"use_this",
"end"
] | name=
Converts name into proper XML node name
@param [String, Symbol] val Raw name | [
"name",
"=",
"Converts",
"name",
"into",
"proper",
"XML",
"node",
"name"
] | 2499571130ba2cac2e62f6e9d27d953a2f1e6ad7 | https://github.com/CITguy/xml-fu/blob/2499571130ba2cac2e62f6e9d27d953a2f1e6ad7/lib/xml-fu/node.rb#L66-L91 |
5,023 | CITguy/xml-fu | lib/xml-fu/node.rb | XmlFu.Node.value= | def value=(val)
case val
when ::String then @value = val.to_s
when ::Hash then @value = val
when ::Array then @value = val
when ::OpenStruct then @value = val
when ::DateTime then @value = val.strftime XS_DATETIME_FORMAT
when ::Time then @value = val.strftime XS_DATETIME_FORMAT
when ::Date then @value = val.strftime XS_DATETIME_FORMAT
else
if val.respond_to?(:to_datetime)
@value = val.to_datetime
elsif val.respond_to?(:call)
@value = val.call
elsif val.nil?
@value = nil
else
@value = val.to_s
end
end
rescue => e
@value = val.to_s
end | ruby | def value=(val)
case val
when ::String then @value = val.to_s
when ::Hash then @value = val
when ::Array then @value = val
when ::OpenStruct then @value = val
when ::DateTime then @value = val.strftime XS_DATETIME_FORMAT
when ::Time then @value = val.strftime XS_DATETIME_FORMAT
when ::Date then @value = val.strftime XS_DATETIME_FORMAT
else
if val.respond_to?(:to_datetime)
@value = val.to_datetime
elsif val.respond_to?(:call)
@value = val.call
elsif val.nil?
@value = nil
else
@value = val.to_s
end
end
rescue => e
@value = val.to_s
end | [
"def",
"value",
"=",
"(",
"val",
")",
"case",
"val",
"when",
"::",
"String",
"then",
"@value",
"=",
"val",
".",
"to_s",
"when",
"::",
"Hash",
"then",
"@value",
"=",
"val",
"when",
"::",
"Array",
"then",
"@value",
"=",
"val",
"when",
"::",
"OpenStruct",
"then",
"@value",
"=",
"val",
"when",
"::",
"DateTime",
"then",
"@value",
"=",
"val",
".",
"strftime",
"XS_DATETIME_FORMAT",
"when",
"::",
"Time",
"then",
"@value",
"=",
"val",
".",
"strftime",
"XS_DATETIME_FORMAT",
"when",
"::",
"Date",
"then",
"@value",
"=",
"val",
".",
"strftime",
"XS_DATETIME_FORMAT",
"else",
"if",
"val",
".",
"respond_to?",
"(",
":to_datetime",
")",
"@value",
"=",
"val",
".",
"to_datetime",
"elsif",
"val",
".",
"respond_to?",
"(",
":call",
")",
"@value",
"=",
"val",
".",
"call",
"elsif",
"val",
".",
"nil?",
"@value",
"=",
"nil",
"else",
"@value",
"=",
"val",
".",
"to_s",
"end",
"end",
"rescue",
"=>",
"e",
"@value",
"=",
"val",
".",
"to_s",
"end"
] | name_parse_special_characters
Custom Setter for @value instance method | [
"name_parse_special_characters",
"Custom",
"Setter",
"for"
] | 2499571130ba2cac2e62f6e9d27d953a2f1e6ad7 | https://github.com/CITguy/xml-fu/blob/2499571130ba2cac2e62f6e9d27d953a2f1e6ad7/lib/xml-fu/node.rb#L95-L117 |
5,024 | Kuniri/kuniri | lib/kuniri/language/ruby/ruby_syntax.rb | Languages.RubySyntax.handle_semicolon | def handle_semicolon(pLine)
commentLine = []
if pLine =~ /^=begin(.*?)/
@flagMultipleLineComment = true
elsif pLine =~ /^=end/
@flagMultipleLineComment = false
end
unless @flagMultipleLineComment == true || pLine =~ /#(.*)/
return pLine.split(/;/)
end
commentLine << pLine
end | ruby | def handle_semicolon(pLine)
commentLine = []
if pLine =~ /^=begin(.*?)/
@flagMultipleLineComment = true
elsif pLine =~ /^=end/
@flagMultipleLineComment = false
end
unless @flagMultipleLineComment == true || pLine =~ /#(.*)/
return pLine.split(/;/)
end
commentLine << pLine
end | [
"def",
"handle_semicolon",
"(",
"pLine",
")",
"commentLine",
"=",
"[",
"]",
"if",
"pLine",
"=~",
"/",
"/",
"@flagMultipleLineComment",
"=",
"true",
"elsif",
"pLine",
"=~",
"/",
"/",
"@flagMultipleLineComment",
"=",
"false",
"end",
"unless",
"@flagMultipleLineComment",
"==",
"true",
"||",
"pLine",
"=~",
"/",
"/",
"return",
"pLine",
".",
"split",
"(",
"/",
"/",
")",
"end",
"commentLine",
"<<",
"pLine",
"end"
] | Puts every statement in a single line
@param pLine Line of the file to be analysed. | [
"Puts",
"every",
"statement",
"in",
"a",
"single",
"line"
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/ruby/ruby_syntax.rb#L58-L71 |
5,025 | tpope/ldaptic | lib/ldaptic/dn.rb | Ldaptic.DN.find | def find(source = @source)
scope = 0
filter = "(objectClass=*)"
if source.respond_to?(:search2_ext)
source.search2(
to_s,
scope,
filter
)
elsif source.respond_to?(:search)
Array(source.search(
:base => to_s,
:scope => scope,
:filter => filter,
:limit => 1
))
else
raise RuntimeError, "missing or invalid source for LDAP search", caller
end.first
end | ruby | def find(source = @source)
scope = 0
filter = "(objectClass=*)"
if source.respond_to?(:search2_ext)
source.search2(
to_s,
scope,
filter
)
elsif source.respond_to?(:search)
Array(source.search(
:base => to_s,
:scope => scope,
:filter => filter,
:limit => 1
))
else
raise RuntimeError, "missing or invalid source for LDAP search", caller
end.first
end | [
"def",
"find",
"(",
"source",
"=",
"@source",
")",
"scope",
"=",
"0",
"filter",
"=",
"\"(objectClass=*)\"",
"if",
"source",
".",
"respond_to?",
"(",
":search2_ext",
")",
"source",
".",
"search2",
"(",
"to_s",
",",
"scope",
",",
"filter",
")",
"elsif",
"source",
".",
"respond_to?",
"(",
":search",
")",
"Array",
"(",
"source",
".",
"search",
"(",
":base",
"=>",
"to_s",
",",
":scope",
"=>",
"scope",
",",
":filter",
"=>",
"filter",
",",
":limit",
"=>",
"1",
")",
")",
"else",
"raise",
"RuntimeError",
",",
"\"missing or invalid source for LDAP search\"",
",",
"caller",
"end",
".",
"first",
"end"
] | If a source object was given, it is used to search for the DN.
Otherwise, an exception is raised. | [
"If",
"a",
"source",
"object",
"was",
"given",
"it",
"is",
"used",
"to",
"search",
"for",
"the",
"DN",
".",
"Otherwise",
"an",
"exception",
"is",
"raised",
"."
] | 159a39464e9f5a05c0145db2b21cb256ef859612 | https://github.com/tpope/ldaptic/blob/159a39464e9f5a05c0145db2b21cb256ef859612/lib/ldaptic/dn.rb#L73-L92 |
5,026 | tpope/ldaptic | lib/ldaptic/dn.rb | Ldaptic.DN.domain | def domain
components = rdns.map {|rdn| rdn[:dc]}.compact
components.join('.') unless components.empty?
end | ruby | def domain
components = rdns.map {|rdn| rdn[:dc]}.compact
components.join('.') unless components.empty?
end | [
"def",
"domain",
"components",
"=",
"rdns",
".",
"map",
"{",
"|",
"rdn",
"|",
"rdn",
"[",
":dc",
"]",
"}",
".",
"compact",
"components",
".",
"join",
"(",
"'.'",
")",
"unless",
"components",
".",
"empty?",
"end"
] | Join all DC elements with periods. | [
"Join",
"all",
"DC",
"elements",
"with",
"periods",
"."
] | 159a39464e9f5a05c0145db2b21cb256ef859612 | https://github.com/tpope/ldaptic/blob/159a39464e9f5a05c0145db2b21cb256ef859612/lib/ldaptic/dn.rb#L117-L120 |
5,027 | stepheneb/jnlp | lib/jnlp/jnlp.rb | Jnlp.Jnlp.generate_local_jnlp | def generate_local_jnlp(options={})
#
# get a copy of the existing jnlp
# (it should be easier than this)
#
@local_jnlp = Nokogiri::XML(@jnlp.to_s)
#
# we'll be working with the Hpricot root element
#
jnlp_elem = (@local_jnlp/"jnlp").first
#
# set the new codebase
#
jnlp_elem[:codebase] = "file:#{@local_cache_dir}"
#
# set the new href
#
jnlp_elem[:href] = @local_jnlp_href
#
# for each jar and nativelib remove the version
# attribute and point the href to the local cache
#
@jars.each do |jar|
j = @local_jnlp.at("//jar[@href=#{jar.href}]")
j.remove_attribute(:version)
if options[:include_pack_gz]
j[:href] = jar.relative_local_path_pack_gz
else
j[:href] = jar.relative_local_path
end
end
@nativelibs.each do |nativelib|
nl = @local_jnlp.at("//nativelib[@href=#{nativelib.href}]")
nl.remove_attribute(:version)
if options[:include_pack_gz]
nl[:href] = nativelib.relative_local_path_pack_gz
else
nl[:href] = nativelib.relative_local_path
end
end
end | ruby | def generate_local_jnlp(options={})
#
# get a copy of the existing jnlp
# (it should be easier than this)
#
@local_jnlp = Nokogiri::XML(@jnlp.to_s)
#
# we'll be working with the Hpricot root element
#
jnlp_elem = (@local_jnlp/"jnlp").first
#
# set the new codebase
#
jnlp_elem[:codebase] = "file:#{@local_cache_dir}"
#
# set the new href
#
jnlp_elem[:href] = @local_jnlp_href
#
# for each jar and nativelib remove the version
# attribute and point the href to the local cache
#
@jars.each do |jar|
j = @local_jnlp.at("//jar[@href=#{jar.href}]")
j.remove_attribute(:version)
if options[:include_pack_gz]
j[:href] = jar.relative_local_path_pack_gz
else
j[:href] = jar.relative_local_path
end
end
@nativelibs.each do |nativelib|
nl = @local_jnlp.at("//nativelib[@href=#{nativelib.href}]")
nl.remove_attribute(:version)
if options[:include_pack_gz]
nl[:href] = nativelib.relative_local_path_pack_gz
else
nl[:href] = nativelib.relative_local_path
end
end
end | [
"def",
"generate_local_jnlp",
"(",
"options",
"=",
"{",
"}",
")",
"#",
"# get a copy of the existing jnlp",
"# (it should be easier than this)",
"#",
"@local_jnlp",
"=",
"Nokogiri",
"::",
"XML",
"(",
"@jnlp",
".",
"to_s",
")",
"#",
"# we'll be working with the Hpricot root element",
"#",
"jnlp_elem",
"=",
"(",
"@local_jnlp",
"/",
"\"jnlp\"",
")",
".",
"first",
"#",
"# set the new codebase",
"#",
"jnlp_elem",
"[",
":codebase",
"]",
"=",
"\"file:#{@local_cache_dir}\"",
"#",
"# set the new href",
"#",
"jnlp_elem",
"[",
":href",
"]",
"=",
"@local_jnlp_href",
"#",
"# for each jar and nativelib remove the version",
"# attribute and point the href to the local cache",
"#",
"@jars",
".",
"each",
"do",
"|",
"jar",
"|",
"j",
"=",
"@local_jnlp",
".",
"at",
"(",
"\"//jar[@href=#{jar.href}]\"",
")",
"j",
".",
"remove_attribute",
"(",
":version",
")",
"if",
"options",
"[",
":include_pack_gz",
"]",
"j",
"[",
":href",
"]",
"=",
"jar",
".",
"relative_local_path_pack_gz",
"else",
"j",
"[",
":href",
"]",
"=",
"jar",
".",
"relative_local_path",
"end",
"end",
"@nativelibs",
".",
"each",
"do",
"|",
"nativelib",
"|",
"nl",
"=",
"@local_jnlp",
".",
"at",
"(",
"\"//nativelib[@href=#{nativelib.href}]\"",
")",
"nl",
".",
"remove_attribute",
"(",
":version",
")",
"if",
"options",
"[",
":include_pack_gz",
"]",
"nl",
"[",
":href",
"]",
"=",
"nativelib",
".",
"relative_local_path_pack_gz",
"else",
"nl",
"[",
":href",
"]",
"=",
"nativelib",
".",
"relative_local_path",
"end",
"end",
"end"
] | Copies the original Hpricot jnlp into @local_jnlp and
modifies it to reference resources in the local cache. | [
"Copies",
"the",
"original",
"Hpricot",
"jnlp",
"into"
] | 9d78fe8b0ebf5bcc68105513d35ce43199607ac4 | https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/jnlp.rb#L485-L525 |
5,028 | stepheneb/jnlp | lib/jnlp/jnlp.rb | Jnlp.Jnlp.resource_paths | def resource_paths(options={})
if options[:include_pack_gs]
cp_jars = @jars.empty? ? [] : @jars.collect {|j| j.local_path_pack_gz}
cp_nativelibs = @nativelibs.empty? ? [] : @nativelibs.collect {|n| n.local_path_pack_gz}
resources = cp_jars + cp_nativelibs
else
cp_jars = @jars.empty? ? [] : @jars.collect {|j| j.local_path}
cp_nativelibs = @nativelibs.empty? ? [] : @nativelibs.collect {|n| n.local_path}
resources = cp_jars + cp_nativelibs
end
#
# FIXME: this should probably be more discriminatory
#
if options[:remove_jruby]
resources = resources.reject {|r| r =~ /\/jruby\//}
end
resources
end | ruby | def resource_paths(options={})
if options[:include_pack_gs]
cp_jars = @jars.empty? ? [] : @jars.collect {|j| j.local_path_pack_gz}
cp_nativelibs = @nativelibs.empty? ? [] : @nativelibs.collect {|n| n.local_path_pack_gz}
resources = cp_jars + cp_nativelibs
else
cp_jars = @jars.empty? ? [] : @jars.collect {|j| j.local_path}
cp_nativelibs = @nativelibs.empty? ? [] : @nativelibs.collect {|n| n.local_path}
resources = cp_jars + cp_nativelibs
end
#
# FIXME: this should probably be more discriminatory
#
if options[:remove_jruby]
resources = resources.reject {|r| r =~ /\/jruby\//}
end
resources
end | [
"def",
"resource_paths",
"(",
"options",
"=",
"{",
"}",
")",
"if",
"options",
"[",
":include_pack_gs",
"]",
"cp_jars",
"=",
"@jars",
".",
"empty?",
"?",
"[",
"]",
":",
"@jars",
".",
"collect",
"{",
"|",
"j",
"|",
"j",
".",
"local_path_pack_gz",
"}",
"cp_nativelibs",
"=",
"@nativelibs",
".",
"empty?",
"?",
"[",
"]",
":",
"@nativelibs",
".",
"collect",
"{",
"|",
"n",
"|",
"n",
".",
"local_path_pack_gz",
"}",
"resources",
"=",
"cp_jars",
"+",
"cp_nativelibs",
"else",
"cp_jars",
"=",
"@jars",
".",
"empty?",
"?",
"[",
"]",
":",
"@jars",
".",
"collect",
"{",
"|",
"j",
"|",
"j",
".",
"local_path",
"}",
"cp_nativelibs",
"=",
"@nativelibs",
".",
"empty?",
"?",
"[",
"]",
":",
"@nativelibs",
".",
"collect",
"{",
"|",
"n",
"|",
"n",
".",
"local_path",
"}",
"resources",
"=",
"cp_jars",
"+",
"cp_nativelibs",
"end",
"#",
"# FIXME: this should probably be more discriminatory",
"#",
"if",
"options",
"[",
":remove_jruby",
"]",
"resources",
"=",
"resources",
".",
"reject",
"{",
"|",
"r",
"|",
"r",
"=~",
"/",
"\\/",
"\\/",
"/",
"}",
"end",
"resources",
"end"
] | Returns an array containing all the local paths for this jnlp's resources.
Pass in the options hash: (:remove_jruby => true) and
the first resource that contains the string /jruby/ will
be removed from the returned array.
Example:
resource_paths(:remove_jruby => true)
This is useful when the jruby-complete jar has been included
in the jnlp and you don't want to require that jruby into this
specific instance which is already running jruby.
Here's an example of a jruby resource reference:
"org/jruby/jruby/jruby__V1.0RC2.jar"
Pass in the options hash: (:include_pack_gz => true) and the
resources returned with be pack.gz jars instead of regular jars | [
"Returns",
"an",
"array",
"containing",
"all",
"the",
"local",
"paths",
"for",
"this",
"jnlp",
"s",
"resources",
"."
] | 9d78fe8b0ebf5bcc68105513d35ce43199607ac4 | https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/jnlp.rb#L548-L565 |
5,029 | stepheneb/jnlp | lib/jnlp/jnlp.rb | Jnlp.Jnlp.write_local_classpath_shell_script | def write_local_classpath_shell_script(filename="#{@name[/[A-Za-z0-9_-]*/]}_classpath.sh", options={})
script = "export CLASSPATH=$CLASSPATH#{local_classpath(options)}"
File.open(filename, 'w'){|f| f.write script}
end | ruby | def write_local_classpath_shell_script(filename="#{@name[/[A-Za-z0-9_-]*/]}_classpath.sh", options={})
script = "export CLASSPATH=$CLASSPATH#{local_classpath(options)}"
File.open(filename, 'w'){|f| f.write script}
end | [
"def",
"write_local_classpath_shell_script",
"(",
"filename",
"=",
"\"#{@name[/[A-Za-z0-9_-]*/]}_classpath.sh\"",
",",
"options",
"=",
"{",
"}",
")",
"script",
"=",
"\"export CLASSPATH=$CLASSPATH#{local_classpath(options)}\"",
"File",
".",
"open",
"(",
"filename",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"script",
"}",
"end"
] | Writes a shell script to the local filesystem
that will export a modified CLASSPATH environmental
variable with the paths to the resources used by
this jnlp.
Writes a jnlp to current working directory
using name of original jnlp.
Pass in the optional hash: (:remove_jruby => true) and
the first resource that contains the string /jruby/ will
be removed from the classapath shell script.
Example:
write_local_classpath_shell_scrip(:remove_jruby => true) | [
"Writes",
"a",
"shell",
"script",
"to",
"the",
"local",
"filesystem",
"that",
"will",
"export",
"a",
"modified",
"CLASSPATH",
"environmental",
"variable",
"with",
"the",
"paths",
"to",
"the",
"resources",
"used",
"by",
"this",
"jnlp",
"."
] | 9d78fe8b0ebf5bcc68105513d35ce43199607ac4 | https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/jnlp.rb#L599-L602 |
5,030 | stepheneb/jnlp | lib/jnlp/jnlp.rb | Jnlp.Jnlp.write_jnlp | def write_jnlp(options={})
dir = options[:dir] || '.'
path = options[:path] || @path.gsub(/^\//, '')
Dir.chdir(dir) do
FileUtils.mkdir_p(File.dirname(path))
File.open(path, 'w') {|f| f.write to_jnlp(options[:jnlp]) }
if options[:snapshot]
snapshot_path = "#{File.dirname(path)}/#{@family}.jnlp"
File.open(snapshot_path, 'w') {|f| f.write to_jnlp(options[:jnlp]) }
current_version_path = "#{File.dirname(path)}/#{@family}-CURRENT_VERSION.txt"
File.open(current_version_path, 'w') {|f| f.write @version_str }
end
end
end | ruby | def write_jnlp(options={})
dir = options[:dir] || '.'
path = options[:path] || @path.gsub(/^\//, '')
Dir.chdir(dir) do
FileUtils.mkdir_p(File.dirname(path))
File.open(path, 'w') {|f| f.write to_jnlp(options[:jnlp]) }
if options[:snapshot]
snapshot_path = "#{File.dirname(path)}/#{@family}.jnlp"
File.open(snapshot_path, 'w') {|f| f.write to_jnlp(options[:jnlp]) }
current_version_path = "#{File.dirname(path)}/#{@family}-CURRENT_VERSION.txt"
File.open(current_version_path, 'w') {|f| f.write @version_str }
end
end
end | [
"def",
"write_jnlp",
"(",
"options",
"=",
"{",
"}",
")",
"dir",
"=",
"options",
"[",
":dir",
"]",
"||",
"'.'",
"path",
"=",
"options",
"[",
":path",
"]",
"||",
"@path",
".",
"gsub",
"(",
"/",
"\\/",
"/",
",",
"''",
")",
"Dir",
".",
"chdir",
"(",
"dir",
")",
"do",
"FileUtils",
".",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"path",
")",
")",
"File",
".",
"open",
"(",
"path",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"to_jnlp",
"(",
"options",
"[",
":jnlp",
"]",
")",
"}",
"if",
"options",
"[",
":snapshot",
"]",
"snapshot_path",
"=",
"\"#{File.dirname(path)}/#{@family}.jnlp\"",
"File",
".",
"open",
"(",
"snapshot_path",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"to_jnlp",
"(",
"options",
"[",
":jnlp",
"]",
")",
"}",
"current_version_path",
"=",
"\"#{File.dirname(path)}/#{@family}-CURRENT_VERSION.txt\"",
"File",
".",
"open",
"(",
"current_version_path",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"@version_str",
"}",
"end",
"end",
"end"
] | Writes a local copy of the original jnlp .
Writes jnlp to path of original jnlp into current working directory.
A number of options can be passed modify the result.
Example:
server = 'http://localhost:4321'
jnlp_cache = 'jnlp'
new_href = "#{server}#{jnlp.path}"
jnlp.write_jnlp( { :dir => jnlp_cache, :jnlp => { :codebase => server, :href => new_href }, :snapshot => true } )
Writes a duplicate of the remote jnlp to a local path rooted at 'jnlp/'.
With the codebase and href re-written referencing: 'http://localhost:4321'
In addition a duplicate of the versioned jnlp is written without the version string as a snapshot
jnlp and the version string is written to this file:
jnlp-name-CURRENT_VERSION.txt | [
"Writes",
"a",
"local",
"copy",
"of",
"the",
"original",
"jnlp",
"."
] | 9d78fe8b0ebf5bcc68105513d35ce43199607ac4 | https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/jnlp.rb#L642-L655 |
5,031 | stepheneb/jnlp | lib/jnlp/jnlp.rb | Jnlp.Jnlp.write_local_jnlp | def write_local_jnlp(filename=@local_jnlp_name)
destination = File.expand_path(filename)
unless @local_jnlp_href == destination
@local_jnlp_href = destination
@local_jnlp_name = File.basename(destination)
self.generate_local_jnlp
end
File.open(filename, 'w') {|f| f.write to_local_jnlp }
end | ruby | def write_local_jnlp(filename=@local_jnlp_name)
destination = File.expand_path(filename)
unless @local_jnlp_href == destination
@local_jnlp_href = destination
@local_jnlp_name = File.basename(destination)
self.generate_local_jnlp
end
File.open(filename, 'w') {|f| f.write to_local_jnlp }
end | [
"def",
"write_local_jnlp",
"(",
"filename",
"=",
"@local_jnlp_name",
")",
"destination",
"=",
"File",
".",
"expand_path",
"(",
"filename",
")",
"unless",
"@local_jnlp_href",
"==",
"destination",
"@local_jnlp_href",
"=",
"destination",
"@local_jnlp_name",
"=",
"File",
".",
"basename",
"(",
"destination",
")",
"self",
".",
"generate_local_jnlp",
"end",
"File",
".",
"open",
"(",
"filename",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"to_local_jnlp",
"}",
"end"
] | Writes a local file-based jnlp.
Will write jnlp to current working directory
using name of original jnlp with "local-" prefix. | [
"Writes",
"a",
"local",
"file",
"-",
"based",
"jnlp",
"."
] | 9d78fe8b0ebf5bcc68105513d35ce43199607ac4 | https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/jnlp.rb#L662-L670 |
5,032 | stepheneb/jnlp | lib/jnlp/jnlp.rb | Jnlp.Jnlp.require_resources | def require_resources
if RUBY_PLATFORM =~ /java/
resource_paths(:remove_jruby => true).each {|res| require res}
true
else
false
end
end | ruby | def require_resources
if RUBY_PLATFORM =~ /java/
resource_paths(:remove_jruby => true).each {|res| require res}
true
else
false
end
end | [
"def",
"require_resources",
"if",
"RUBY_PLATFORM",
"=~",
"/",
"/",
"resource_paths",
"(",
":remove_jruby",
"=>",
"true",
")",
".",
"each",
"{",
"|",
"res",
"|",
"require",
"res",
"}",
"true",
"else",
"false",
"end",
"end"
] | This will add all the jars for this jnlp to the effective
classpath for this Java process.
*If* you are already running in JRuby *AND* the jnlp references a
JRuby resource the JRuby resource will not be required. | [
"This",
"will",
"add",
"all",
"the",
"jars",
"for",
"this",
"jnlp",
"to",
"the",
"effective",
"classpath",
"for",
"this",
"Java",
"process",
"."
] | 9d78fe8b0ebf5bcc68105513d35ce43199607ac4 | https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/jnlp.rb#L678-L685 |
5,033 | brianjlandau/unobtrusive_date_picker | lib/unobtrusive_date_picker.rb | UnobtrusiveDatePicker.UnobtrusiveDatePickerHelper.unobtrusive_date_text_picker_tag | def unobtrusive_date_text_picker_tag(name, date = Date.current, options = {}, html_options = {})
date ||= Date.current
options = merge_defaults_for_text_picker(options)
DateTimePickerSelector.new(date, options, html_options).text_date_picker(name)
end | ruby | def unobtrusive_date_text_picker_tag(name, date = Date.current, options = {}, html_options = {})
date ||= Date.current
options = merge_defaults_for_text_picker(options)
DateTimePickerSelector.new(date, options, html_options).text_date_picker(name)
end | [
"def",
"unobtrusive_date_text_picker_tag",
"(",
"name",
",",
"date",
"=",
"Date",
".",
"current",
",",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
")",
"date",
"||=",
"Date",
".",
"current",
"options",
"=",
"merge_defaults_for_text_picker",
"(",
"options",
")",
"DateTimePickerSelector",
".",
"new",
"(",
"date",
",",
"options",
",",
"html_options",
")",
".",
"text_date_picker",
"(",
"name",
")",
"end"
] | Creates the text field based date picker with the calendar widget without a model object. | [
"Creates",
"the",
"text",
"field",
"based",
"date",
"picker",
"with",
"the",
"calendar",
"widget",
"without",
"a",
"model",
"object",
"."
] | fd15b829a92951c4a7550c0644502587040fdedc | https://github.com/brianjlandau/unobtrusive_date_picker/blob/fd15b829a92951c4a7550c0644502587040fdedc/lib/unobtrusive_date_picker.rb#L67-L71 |
5,034 | stepheneb/jnlp | lib/jnlp/resource.rb | Jnlp.Resource.update_cache | def update_cache(source=@url, destination=@local_path, options={})
unless destination
raise ArgumentError, "Must specify destination directory when updatng resource", caller
end
file_exists = File.exists?(destination)
if file_exists && @signature_verified == nil
verify_signature
end
unless file_exists && @signature_verified
FileUtils.mkdir_p(File.dirname(destination))
puts "reading: #{source}" if options[:verbose]
tried_to_read = 0
begin
jarfile = open(source)
rescue OpenURI::HTTPError => e
puts e
if tried_to_read < 1
tried_to_read += 1
retry
end
end
if jarfile.class == Tempfile
FileUtils.cp(jarfile.path, destination)
puts "copying to: #{destination}" if options[:verbose]
else
File.open(destination, 'w') {|f| f.write jarfile.read }
puts "writing to: #{destination}" if options[:verbose]
end
puts "#{jarfile.size} bytes written" if options[:verbose]
verify_signature ? jarfile.size : false
else
File.size(destination)
end
end | ruby | def update_cache(source=@url, destination=@local_path, options={})
unless destination
raise ArgumentError, "Must specify destination directory when updatng resource", caller
end
file_exists = File.exists?(destination)
if file_exists && @signature_verified == nil
verify_signature
end
unless file_exists && @signature_verified
FileUtils.mkdir_p(File.dirname(destination))
puts "reading: #{source}" if options[:verbose]
tried_to_read = 0
begin
jarfile = open(source)
rescue OpenURI::HTTPError => e
puts e
if tried_to_read < 1
tried_to_read += 1
retry
end
end
if jarfile.class == Tempfile
FileUtils.cp(jarfile.path, destination)
puts "copying to: #{destination}" if options[:verbose]
else
File.open(destination, 'w') {|f| f.write jarfile.read }
puts "writing to: #{destination}" if options[:verbose]
end
puts "#{jarfile.size} bytes written" if options[:verbose]
verify_signature ? jarfile.size : false
else
File.size(destination)
end
end | [
"def",
"update_cache",
"(",
"source",
"=",
"@url",
",",
"destination",
"=",
"@local_path",
",",
"options",
"=",
"{",
"}",
")",
"unless",
"destination",
"raise",
"ArgumentError",
",",
"\"Must specify destination directory when updatng resource\"",
",",
"caller",
"end",
"file_exists",
"=",
"File",
".",
"exists?",
"(",
"destination",
")",
"if",
"file_exists",
"&&",
"@signature_verified",
"==",
"nil",
"verify_signature",
"end",
"unless",
"file_exists",
"&&",
"@signature_verified",
"FileUtils",
".",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"destination",
")",
")",
"puts",
"\"reading: #{source}\"",
"if",
"options",
"[",
":verbose",
"]",
"tried_to_read",
"=",
"0",
"begin",
"jarfile",
"=",
"open",
"(",
"source",
")",
"rescue",
"OpenURI",
"::",
"HTTPError",
"=>",
"e",
"puts",
"e",
"if",
"tried_to_read",
"<",
"1",
"tried_to_read",
"+=",
"1",
"retry",
"end",
"end",
"if",
"jarfile",
".",
"class",
"==",
"Tempfile",
"FileUtils",
".",
"cp",
"(",
"jarfile",
".",
"path",
",",
"destination",
")",
"puts",
"\"copying to: #{destination}\"",
"if",
"options",
"[",
":verbose",
"]",
"else",
"File",
".",
"open",
"(",
"destination",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"jarfile",
".",
"read",
"}",
"puts",
"\"writing to: #{destination}\"",
"if",
"options",
"[",
":verbose",
"]",
"end",
"puts",
"\"#{jarfile.size} bytes written\"",
"if",
"options",
"[",
":verbose",
"]",
"verify_signature",
"?",
"jarfile",
".",
"size",
":",
"false",
"else",
"File",
".",
"size",
"(",
"destination",
")",
"end",
"end"
] | Copies the file referenced in _source_ to _destination_
_source_ can be a url or local file path
_destination_ must be a local path
Will copy file if the file does not exists
OR if the the file exists but the signature has
not been successfully verified.
Returns file size if cached succesfully, false otherwise. | [
"Copies",
"the",
"file",
"referenced",
"in",
"_source_",
"to",
"_destination_",
"_source_",
"can",
"be",
"a",
"url",
"or",
"local",
"file",
"path",
"_destination_",
"must",
"be",
"a",
"local",
"path"
] | 9d78fe8b0ebf5bcc68105513d35ce43199607ac4 | https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/resource.rb#L334-L367 |
5,035 | stepheneb/jnlp | lib/jnlp/resource.rb | Jnlp.Resource.verify_signature | def verify_signature
if @local_path
if RUBY_PLATFORM =~ /java/
begin
jarfile = java.util.jar.JarInputStream.new(FileInputStream.new(@local_path), true)
@signature_verified = true
rescue NativeException
@signature_verified = false
end
else
# Use IO.popen instead of system() to absorb
# jarsigners messages to $stdout
response = IO.popen("jarsigner -verify #{@local_path}"){|io| io.gets}
@signature_verified = ($?.exitstatus == 0)
end
else
nil
end
end | ruby | def verify_signature
if @local_path
if RUBY_PLATFORM =~ /java/
begin
jarfile = java.util.jar.JarInputStream.new(FileInputStream.new(@local_path), true)
@signature_verified = true
rescue NativeException
@signature_verified = false
end
else
# Use IO.popen instead of system() to absorb
# jarsigners messages to $stdout
response = IO.popen("jarsigner -verify #{@local_path}"){|io| io.gets}
@signature_verified = ($?.exitstatus == 0)
end
else
nil
end
end | [
"def",
"verify_signature",
"if",
"@local_path",
"if",
"RUBY_PLATFORM",
"=~",
"/",
"/",
"begin",
"jarfile",
"=",
"java",
".",
"util",
".",
"jar",
".",
"JarInputStream",
".",
"new",
"(",
"FileInputStream",
".",
"new",
"(",
"@local_path",
")",
",",
"true",
")",
"@signature_verified",
"=",
"true",
"rescue",
"NativeException",
"@signature_verified",
"=",
"false",
"end",
"else",
"# Use IO.popen instead of system() to absorb",
"# jarsigners messages to $stdout",
"response",
"=",
"IO",
".",
"popen",
"(",
"\"jarsigner -verify #{@local_path}\"",
")",
"{",
"|",
"io",
"|",
"io",
".",
"gets",
"}",
"@signature_verified",
"=",
"(",
"$?",
".",
"exitstatus",
"==",
"0",
")",
"end",
"else",
"nil",
"end",
"end"
] | Verifies signature of locallly cached resource
Returns boolean value indicating whether the signature of the
cached local copy of the resource verified successfully
The value return is nil if no local cache has been created.
Example:
true || false || nil | [
"Verifies",
"signature",
"of",
"locallly",
"cached",
"resource"
] | 9d78fe8b0ebf5bcc68105513d35ce43199607ac4 | https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/resource.rb#L380-L398 |
5,036 | fuminori-ido/edgarj | app/helpers/edgarj/assoc_helper.rb | Edgarj.AssocHelper.draw_belongs_to_clear_link | def draw_belongs_to_clear_link(f, col_name, popup_field, parent_name, default_label)
if Settings.edgarj.belongs_to.disable_clear_link
f.hidden_field(col_name)
else
(' ' +
link_to("[#{I18n.t('edgarj.default.clear')}]", '#',
onClick: "Edgarj.Popup.clear('#{j(popup_field.id_target)}','#{j(default_label)}'); return false;",
id: popup_field.clear_link,
style: 'display:' + (parent_name.blank? ? 'none' : '')) +
f.hidden_field(col_name)).html_safe
end
end | ruby | def draw_belongs_to_clear_link(f, col_name, popup_field, parent_name, default_label)
if Settings.edgarj.belongs_to.disable_clear_link
f.hidden_field(col_name)
else
(' ' +
link_to("[#{I18n.t('edgarj.default.clear')}]", '#',
onClick: "Edgarj.Popup.clear('#{j(popup_field.id_target)}','#{j(default_label)}'); return false;",
id: popup_field.clear_link,
style: 'display:' + (parent_name.blank? ? 'none' : '')) +
f.hidden_field(col_name)).html_safe
end
end | [
"def",
"draw_belongs_to_clear_link",
"(",
"f",
",",
"col_name",
",",
"popup_field",
",",
"parent_name",
",",
"default_label",
")",
"if",
"Settings",
".",
"edgarj",
".",
"belongs_to",
".",
"disable_clear_link",
"f",
".",
"hidden_field",
"(",
"col_name",
")",
"else",
"(",
"' '",
"+",
"link_to",
"(",
"\"[#{I18n.t('edgarj.default.clear')}]\"",
",",
"'#'",
",",
"onClick",
":",
"\"Edgarj.Popup.clear('#{j(popup_field.id_target)}','#{j(default_label)}'); return false;\"",
",",
"id",
":",
"popup_field",
".",
"clear_link",
",",
"style",
":",
"'display:'",
"+",
"(",
"parent_name",
".",
"blank?",
"?",
"'none'",
":",
"''",
")",
")",
"+",
"f",
".",
"hidden_field",
"(",
"col_name",
")",
")",
".",
"html_safe",
"end",
"end"
] | draw 'clear' link for 'belongs_to' popup data-entry field
=== INPUTS
f:: FormBuilder object
col_name:: 'belongs_to' column name
popup_field:: Edgarj::PopupHelper::PopupField object
parent_name:: initial parent name | [
"draw",
"clear",
"link",
"for",
"belongs_to",
"popup",
"data",
"-",
"entry",
"field"
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L179-L190 |
5,037 | fuminori-ido/edgarj | app/helpers/edgarj/assoc_helper.rb | Edgarj.AssocHelper.draw_belongs_to_field | def draw_belongs_to_field(f, popup_path, col_name, model = f.object.class)
col = model.columns.detect{|c| c.name == col_name.to_s}
return "no column found" if !col
parent_model = model.belongs_to_AR(col)
return "parent_model is nil" if !parent_model
parent_obj = f.object.belongs_to_AR(col)
popup_field = Edgarj::PopupHelper::PopupField.new_builder(
f.object_name, col_name)
default_label = '[' + draw_belongs_to_label_sub(model, col.name, parent_model) + ']'
label = content_tag(:span,
parent_obj ? parent_obj.name : default_label.html_safe,
id: popup_field.label_target)
link_tag = Settings.edgarj.belongs_to.link_tag.html_safe
if parent_obj
if Settings.edgarj.belongs_to.popup_on == 'field'
link_to(
label + link_tag,
popup_path,
remote: true)
else
link_to(label,
# TODO: Hardcoded 'master' prefix should be fixed
controller: url_prefix + parent_obj.class.name.underscore.pluralize,
action: 'show',
id: parent_obj,
topic_path: 'add')
end
else
if Settings.edgarj.belongs_to.popup_on == 'field'
link_to(
label + link_tag,
popup_path,
remote: true)
else
label
end
end +
draw_belongs_to_clear_link(f, col.name, popup_field,
parent_obj && parent_obj.name,
default_label)
end | ruby | def draw_belongs_to_field(f, popup_path, col_name, model = f.object.class)
col = model.columns.detect{|c| c.name == col_name.to_s}
return "no column found" if !col
parent_model = model.belongs_to_AR(col)
return "parent_model is nil" if !parent_model
parent_obj = f.object.belongs_to_AR(col)
popup_field = Edgarj::PopupHelper::PopupField.new_builder(
f.object_name, col_name)
default_label = '[' + draw_belongs_to_label_sub(model, col.name, parent_model) + ']'
label = content_tag(:span,
parent_obj ? parent_obj.name : default_label.html_safe,
id: popup_field.label_target)
link_tag = Settings.edgarj.belongs_to.link_tag.html_safe
if parent_obj
if Settings.edgarj.belongs_to.popup_on == 'field'
link_to(
label + link_tag,
popup_path,
remote: true)
else
link_to(label,
# TODO: Hardcoded 'master' prefix should be fixed
controller: url_prefix + parent_obj.class.name.underscore.pluralize,
action: 'show',
id: parent_obj,
topic_path: 'add')
end
else
if Settings.edgarj.belongs_to.popup_on == 'field'
link_to(
label + link_tag,
popup_path,
remote: true)
else
label
end
end +
draw_belongs_to_clear_link(f, col.name, popup_field,
parent_obj && parent_obj.name,
default_label)
end | [
"def",
"draw_belongs_to_field",
"(",
"f",
",",
"popup_path",
",",
"col_name",
",",
"model",
"=",
"f",
".",
"object",
".",
"class",
")",
"col",
"=",
"model",
".",
"columns",
".",
"detect",
"{",
"|",
"c",
"|",
"c",
".",
"name",
"==",
"col_name",
".",
"to_s",
"}",
"return",
"\"no column found\"",
"if",
"!",
"col",
"parent_model",
"=",
"model",
".",
"belongs_to_AR",
"(",
"col",
")",
"return",
"\"parent_model is nil\"",
"if",
"!",
"parent_model",
"parent_obj",
"=",
"f",
".",
"object",
".",
"belongs_to_AR",
"(",
"col",
")",
"popup_field",
"=",
"Edgarj",
"::",
"PopupHelper",
"::",
"PopupField",
".",
"new_builder",
"(",
"f",
".",
"object_name",
",",
"col_name",
")",
"default_label",
"=",
"'['",
"+",
"draw_belongs_to_label_sub",
"(",
"model",
",",
"col",
".",
"name",
",",
"parent_model",
")",
"+",
"']'",
"label",
"=",
"content_tag",
"(",
":span",
",",
"parent_obj",
"?",
"parent_obj",
".",
"name",
":",
"default_label",
".",
"html_safe",
",",
"id",
":",
"popup_field",
".",
"label_target",
")",
"link_tag",
"=",
"Settings",
".",
"edgarj",
".",
"belongs_to",
".",
"link_tag",
".",
"html_safe",
"if",
"parent_obj",
"if",
"Settings",
".",
"edgarj",
".",
"belongs_to",
".",
"popup_on",
"==",
"'field'",
"link_to",
"(",
"label",
"+",
"link_tag",
",",
"popup_path",
",",
"remote",
":",
"true",
")",
"else",
"link_to",
"(",
"label",
",",
"# TODO: Hardcoded 'master' prefix should be fixed",
"controller",
":",
"url_prefix",
"+",
"parent_obj",
".",
"class",
".",
"name",
".",
"underscore",
".",
"pluralize",
",",
"action",
":",
"'show'",
",",
"id",
":",
"parent_obj",
",",
"topic_path",
":",
"'add'",
")",
"end",
"else",
"if",
"Settings",
".",
"edgarj",
".",
"belongs_to",
".",
"popup_on",
"==",
"'field'",
"link_to",
"(",
"label",
"+",
"link_tag",
",",
"popup_path",
",",
"remote",
":",
"true",
")",
"else",
"label",
"end",
"end",
"+",
"draw_belongs_to_clear_link",
"(",
"f",
",",
"col",
".",
"name",
",",
"popup_field",
",",
"parent_obj",
"&&",
"parent_obj",
".",
"name",
",",
"default_label",
")",
"end"
] | draw 'belongs_to' popup data-entry field
This is usually used with draw_belongs_to_label().
@param f [FormBuilder] FormBuilder object
@param popup_path [String] popup path(url)
@param col_name [String] 'belongs_to' column name
@param model [AR] data model class | [
"draw",
"belongs_to",
"popup",
"data",
"-",
"entry",
"field"
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L200-L242 |
5,038 | fuminori-ido/edgarj | app/helpers/edgarj/assoc_helper.rb | Edgarj.AssocHelper.flag_on? | def flag_on?(column_value, bitset, flag)
val = column_value || 0
(val & bitset.const_get(flag)) != 0
end | ruby | def flag_on?(column_value, bitset, flag)
val = column_value || 0
(val & bitset.const_get(flag)) != 0
end | [
"def",
"flag_on?",
"(",
"column_value",
",",
"bitset",
",",
"flag",
")",
"val",
"=",
"column_value",
"||",
"0",
"(",
"val",
"&",
"bitset",
".",
"const_get",
"(",
"flag",
")",
")",
"!=",
"0",
"end"
] | Is flag in column_value on? | [
"Is",
"flag",
"in",
"column_value",
"on?"
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L245-L248 |
5,039 | fuminori-ido/edgarj | app/helpers/edgarj/assoc_helper.rb | Edgarj.AssocHelper.get_bitset | def get_bitset(model, col)
bitset_name = col.name.camelize + 'Bitset'
if model.const_defined?(bitset_name, false)
_module = model.const_get(bitset_name)
_module.is_a?(Module) ? _module : nil
else
nil
end
end | ruby | def get_bitset(model, col)
bitset_name = col.name.camelize + 'Bitset'
if model.const_defined?(bitset_name, false)
_module = model.const_get(bitset_name)
_module.is_a?(Module) ? _module : nil
else
nil
end
end | [
"def",
"get_bitset",
"(",
"model",
",",
"col",
")",
"bitset_name",
"=",
"col",
".",
"name",
".",
"camelize",
"+",
"'Bitset'",
"if",
"model",
".",
"const_defined?",
"(",
"bitset_name",
",",
"false",
")",
"_module",
"=",
"model",
".",
"const_get",
"(",
"bitset_name",
")",
"_module",
".",
"is_a?",
"(",
"Module",
")",
"?",
"_module",
":",
"nil",
"else",
"nil",
"end",
"end"
] | get bitset Module.
When ColBitset(camelized argument col name + 'Bitset') module exists,
the ColBitset is assumed enum definition. | [
"get",
"bitset",
"Module",
"."
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L254-L262 |
5,040 | fuminori-ido/edgarj | app/helpers/edgarj/assoc_helper.rb | Edgarj.AssocHelper.draw_column_bitset | def draw_column_bitset(rec, col_or_sym, bitset)
turn_on_flags = []
value = rec.send(get_column_name(col_or_sym))
for flag in bitset.constants do
turn_on_flags << flag if flag_on?(value, bitset, flag)
end
turn_on_flags.map{|f| rec.class.human_const_name(bitset, f) }.join(' ')
end | ruby | def draw_column_bitset(rec, col_or_sym, bitset)
turn_on_flags = []
value = rec.send(get_column_name(col_or_sym))
for flag in bitset.constants do
turn_on_flags << flag if flag_on?(value, bitset, flag)
end
turn_on_flags.map{|f| rec.class.human_const_name(bitset, f) }.join(' ')
end | [
"def",
"draw_column_bitset",
"(",
"rec",
",",
"col_or_sym",
",",
"bitset",
")",
"turn_on_flags",
"=",
"[",
"]",
"value",
"=",
"rec",
".",
"send",
"(",
"get_column_name",
"(",
"col_or_sym",
")",
")",
"for",
"flag",
"in",
"bitset",
".",
"constants",
"do",
"turn_on_flags",
"<<",
"flag",
"if",
"flag_on?",
"(",
"value",
",",
"bitset",
",",
"flag",
")",
"end",
"turn_on_flags",
".",
"map",
"{",
"|",
"f",
"|",
"rec",
".",
"class",
".",
"human_const_name",
"(",
"bitset",
",",
"f",
")",
"}",
".",
"join",
"(",
"' '",
")",
"end"
] | draw bitset column in list.
=== INPUTS
rec:: AR object
col_or_sym:: column object returned by rec.class.columns
bitset:: Module which contains bitset constants
=== SEE ALSO
get_bitset():: get bitset definition
draw_bitset():: draw bitste checkboxes field
draw_column_enum():: draw bitset column in list | [
"draw",
"bitset",
"column",
"in",
"list",
"."
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L275-L282 |
5,041 | fuminori-ido/edgarj | app/helpers/edgarj/assoc_helper.rb | Edgarj.AssocHelper.draw_column_enum | def draw_column_enum(rec, col_or_sym, enum)
Edgarj::EnumCache.instance.label(rec, get_column_name(col_or_sym), enum)
end | ruby | def draw_column_enum(rec, col_or_sym, enum)
Edgarj::EnumCache.instance.label(rec, get_column_name(col_or_sym), enum)
end | [
"def",
"draw_column_enum",
"(",
"rec",
",",
"col_or_sym",
",",
"enum",
")",
"Edgarj",
"::",
"EnumCache",
".",
"instance",
".",
"label",
"(",
"rec",
",",
"get_column_name",
"(",
"col_or_sym",
")",
",",
"enum",
")",
"end"
] | draw enum column in list.
When enum for col is defined, constant string (rather than rec.col value)
is drawn. See get_enum() for more detail of enum for the col.
=== EXAMPLE
Question has status attribute and Question::Status enum.
When question.status == 300,
draw_column_enum(question, status_col, Question::Status) returns
I18n.t('WORKING').
Where:
* question is Question AR object.
* status_col is one of Question.columns object for status column.
=== INPUTS
rec:: AR object
col_or_sym:: column object returned by rec.class.columns
enum:: Module which contains constants
=== SEE ALSO
get_enum():: get enum definition
draw_enum():: draw enum selection field
draw_column_bitset():: draw bitset column in list | [
"draw",
"enum",
"column",
"in",
"list",
"."
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L309-L311 |
5,042 | fuminori-ido/edgarj | app/helpers/edgarj/assoc_helper.rb | Edgarj.AssocHelper.adrs_str_sub | def adrs_str_sub(model, prefix, element)
e = model.send(prefix + element)
e.blank? ? '' : e
end | ruby | def adrs_str_sub(model, prefix, element)
e = model.send(prefix + element)
e.blank? ? '' : e
end | [
"def",
"adrs_str_sub",
"(",
"model",
",",
"prefix",
",",
"element",
")",
"e",
"=",
"model",
".",
"send",
"(",
"prefix",
"+",
"element",
")",
"e",
".",
"blank?",
"?",
"''",
":",
"e",
"end"
] | return address element string or '' | [
"return",
"address",
"element",
"string",
"or"
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L314-L317 |
5,043 | fuminori-ido/edgarj | app/helpers/edgarj/assoc_helper.rb | Edgarj.AssocHelper.adrs_str | def adrs_str(model, adrs_prefix)
result = ''
for adrs_element in ['prefecture', 'city', 'other', 'bldg'] do
result << adrs_str_sub(model, adrs_prefix, adrs_element)
end
result
end | ruby | def adrs_str(model, adrs_prefix)
result = ''
for adrs_element in ['prefecture', 'city', 'other', 'bldg'] do
result << adrs_str_sub(model, adrs_prefix, adrs_element)
end
result
end | [
"def",
"adrs_str",
"(",
"model",
",",
"adrs_prefix",
")",
"result",
"=",
"''",
"for",
"adrs_element",
"in",
"[",
"'prefecture'",
",",
"'city'",
",",
"'other'",
",",
"'bldg'",
"]",
"do",
"result",
"<<",
"adrs_str_sub",
"(",
"model",
",",
"adrs_prefix",
",",
"adrs_element",
")",
"end",
"result",
"end"
] | model & adrs_prefix -> address string | [
"model",
"&",
"adrs_prefix",
"-",
">",
"address",
"string"
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L320-L326 |
5,044 | fuminori-ido/edgarj | app/helpers/edgarj/assoc_helper.rb | Edgarj.AssocHelper.permitted? | def permitted?(requested_flags = 0)
current_user_roles.any?{|ug| ug.admin?} ||
current_model_permissions.any?{|cp| cp.permitted?(requested_flags)}
end | ruby | def permitted?(requested_flags = 0)
current_user_roles.any?{|ug| ug.admin?} ||
current_model_permissions.any?{|cp| cp.permitted?(requested_flags)}
end | [
"def",
"permitted?",
"(",
"requested_flags",
"=",
"0",
")",
"current_user_roles",
".",
"any?",
"{",
"|",
"ug",
"|",
"ug",
".",
"admin?",
"}",
"||",
"current_model_permissions",
".",
"any?",
"{",
"|",
"cp",
"|",
"cp",
".",
"permitted?",
"(",
"requested_flags",
")",
"}",
"end"
] | return true if login user has enough permission on current controller. | [
"return",
"true",
"if",
"login",
"user",
"has",
"enough",
"permission",
"on",
"current",
"controller",
"."
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L329-L332 |
5,045 | ksylvest/serializer | lib/serializer.rb | Serializer.ClassMethods.has_serialized | def has_serialized(name, &block)
serialize name, Hash
initializer = Serializer::Initializer.new
block.call(initializer)
initializer.each do |method, options|
define_method "#{method}" do
hash = send(name)
result = hash[method.to_sym] if hash
if hash.nil? or result.nil?
send("#{name}=", {}) unless send(name)
hash = send(name)
result = options[:default]
result = result.clone if result.duplicable?
hash[method.to_sym] = result
end
return result
end
define_method "#{method}?" do
hash = send(name)
result = hash[method.to_sym] if hash
if hash.nil? or result.nil?
send("#{name}=", {}) unless send(name)
hash = send(name)
result = options[:default]
result = result.clone if result.duplicable?
hash[method.to_sym] = result
end
return result
end
define_method "#{method}=" do |value|
original = send(name) || {}
if options[:type] and value
case options[:type].to_sym
when :float then value = value.to_f if value.respond_to? :to_f
when :integer then value = value.to_i if value.respond_to? :to_i
when :string then value = value.to_str if value.respond_to? :to_str
when :symbol then value = value.to_sym if value.respond_to? :to_sym
when :boolean then
value = true if value.eql? "true"
value = false if value.eql? "false"
value = !value.to_i.zero? if value.respond_to? :to_i
end
end
modified = original.clone
modified[method.to_sym] = value
send("#{name}_will_change!") unless modified.eql?(original)
send("#{name}=", modified)
end
end
end | ruby | def has_serialized(name, &block)
serialize name, Hash
initializer = Serializer::Initializer.new
block.call(initializer)
initializer.each do |method, options|
define_method "#{method}" do
hash = send(name)
result = hash[method.to_sym] if hash
if hash.nil? or result.nil?
send("#{name}=", {}) unless send(name)
hash = send(name)
result = options[:default]
result = result.clone if result.duplicable?
hash[method.to_sym] = result
end
return result
end
define_method "#{method}?" do
hash = send(name)
result = hash[method.to_sym] if hash
if hash.nil? or result.nil?
send("#{name}=", {}) unless send(name)
hash = send(name)
result = options[:default]
result = result.clone if result.duplicable?
hash[method.to_sym] = result
end
return result
end
define_method "#{method}=" do |value|
original = send(name) || {}
if options[:type] and value
case options[:type].to_sym
when :float then value = value.to_f if value.respond_to? :to_f
when :integer then value = value.to_i if value.respond_to? :to_i
when :string then value = value.to_str if value.respond_to? :to_str
when :symbol then value = value.to_sym if value.respond_to? :to_sym
when :boolean then
value = true if value.eql? "true"
value = false if value.eql? "false"
value = !value.to_i.zero? if value.respond_to? :to_i
end
end
modified = original.clone
modified[method.to_sym] = value
send("#{name}_will_change!") unless modified.eql?(original)
send("#{name}=", modified)
end
end
end | [
"def",
"has_serialized",
"(",
"name",
",",
"&",
"block",
")",
"serialize",
"name",
",",
"Hash",
"initializer",
"=",
"Serializer",
"::",
"Initializer",
".",
"new",
"block",
".",
"call",
"(",
"initializer",
")",
"initializer",
".",
"each",
"do",
"|",
"method",
",",
"options",
"|",
"define_method",
"\"#{method}\"",
"do",
"hash",
"=",
"send",
"(",
"name",
")",
"result",
"=",
"hash",
"[",
"method",
".",
"to_sym",
"]",
"if",
"hash",
"if",
"hash",
".",
"nil?",
"or",
"result",
".",
"nil?",
"send",
"(",
"\"#{name}=\"",
",",
"{",
"}",
")",
"unless",
"send",
"(",
"name",
")",
"hash",
"=",
"send",
"(",
"name",
")",
"result",
"=",
"options",
"[",
":default",
"]",
"result",
"=",
"result",
".",
"clone",
"if",
"result",
".",
"duplicable?",
"hash",
"[",
"method",
".",
"to_sym",
"]",
"=",
"result",
"end",
"return",
"result",
"end",
"define_method",
"\"#{method}?\"",
"do",
"hash",
"=",
"send",
"(",
"name",
")",
"result",
"=",
"hash",
"[",
"method",
".",
"to_sym",
"]",
"if",
"hash",
"if",
"hash",
".",
"nil?",
"or",
"result",
".",
"nil?",
"send",
"(",
"\"#{name}=\"",
",",
"{",
"}",
")",
"unless",
"send",
"(",
"name",
")",
"hash",
"=",
"send",
"(",
"name",
")",
"result",
"=",
"options",
"[",
":default",
"]",
"result",
"=",
"result",
".",
"clone",
"if",
"result",
".",
"duplicable?",
"hash",
"[",
"method",
".",
"to_sym",
"]",
"=",
"result",
"end",
"return",
"result",
"end",
"define_method",
"\"#{method}=\"",
"do",
"|",
"value",
"|",
"original",
"=",
"send",
"(",
"name",
")",
"||",
"{",
"}",
"if",
"options",
"[",
":type",
"]",
"and",
"value",
"case",
"options",
"[",
":type",
"]",
".",
"to_sym",
"when",
":float",
"then",
"value",
"=",
"value",
".",
"to_f",
"if",
"value",
".",
"respond_to?",
":to_f",
"when",
":integer",
"then",
"value",
"=",
"value",
".",
"to_i",
"if",
"value",
".",
"respond_to?",
":to_i",
"when",
":string",
"then",
"value",
"=",
"value",
".",
"to_str",
"if",
"value",
".",
"respond_to?",
":to_str",
"when",
":symbol",
"then",
"value",
"=",
"value",
".",
"to_sym",
"if",
"value",
".",
"respond_to?",
":to_sym",
"when",
":boolean",
"then",
"value",
"=",
"true",
"if",
"value",
".",
"eql?",
"\"true\"",
"value",
"=",
"false",
"if",
"value",
".",
"eql?",
"\"false\"",
"value",
"=",
"!",
"value",
".",
"to_i",
".",
"zero?",
"if",
"value",
".",
"respond_to?",
":to_i",
"end",
"end",
"modified",
"=",
"original",
".",
"clone",
"modified",
"[",
"method",
".",
"to_sym",
"]",
"=",
"value",
"send",
"(",
"\"#{name}_will_change!\"",
")",
"unless",
"modified",
".",
"eql?",
"(",
"original",
")",
"send",
"(",
"\"#{name}=\"",
",",
"modified",
")",
"end",
"end",
"end"
] | Add serializer to a class.
Usage:
has_serialized :settings do |settings|
settings.define :tw_share, default: true, type: :boolean
settings.define :fb_share, default: true, type: :boolean
end | [
"Add",
"serializer",
"to",
"a",
"class",
"."
] | cb018a5bf73a88eb7ec59fd996702337ddb81439 | https://github.com/ksylvest/serializer/blob/cb018a5bf73a88eb7ec59fd996702337ddb81439/lib/serializer.rb#L22-L88 |
5,046 | MattRyder/tableau | lib/tableau/baseparser.rb | Tableau.BaseParser.parse_table | def parse_table(table_rows)
classes = Tableau::ClassArray.new
@day = 0
# delete the time header row
table_rows.delete(table_rows.first)
table_rows.each do |row|
@time = Time.new(2013, 1, 1, 9, 0, 0)
# drop the 'Day' cell from the row
row_items = row.xpath('td')
row_items.delete(row_items.first)
row_items.each do |cell|
if cell.attribute('colspan')
intervals = cell.attribute('colspan').value
classes << create_class(cell)
else intervals = 1
end
inc_time(intervals)
end
@day += 1
end
classes
end | ruby | def parse_table(table_rows)
classes = Tableau::ClassArray.new
@day = 0
# delete the time header row
table_rows.delete(table_rows.first)
table_rows.each do |row|
@time = Time.new(2013, 1, 1, 9, 0, 0)
# drop the 'Day' cell from the row
row_items = row.xpath('td')
row_items.delete(row_items.first)
row_items.each do |cell|
if cell.attribute('colspan')
intervals = cell.attribute('colspan').value
classes << create_class(cell)
else intervals = 1
end
inc_time(intervals)
end
@day += 1
end
classes
end | [
"def",
"parse_table",
"(",
"table_rows",
")",
"classes",
"=",
"Tableau",
"::",
"ClassArray",
".",
"new",
"@day",
"=",
"0",
"# delete the time header row",
"table_rows",
".",
"delete",
"(",
"table_rows",
".",
"first",
")",
"table_rows",
".",
"each",
"do",
"|",
"row",
"|",
"@time",
"=",
"Time",
".",
"new",
"(",
"2013",
",",
"1",
",",
"1",
",",
"9",
",",
"0",
",",
"0",
")",
"# drop the 'Day' cell from the row",
"row_items",
"=",
"row",
".",
"xpath",
"(",
"'td'",
")",
"row_items",
".",
"delete",
"(",
"row_items",
".",
"first",
")",
"row_items",
".",
"each",
"do",
"|",
"cell",
"|",
"if",
"cell",
".",
"attribute",
"(",
"'colspan'",
")",
"intervals",
"=",
"cell",
".",
"attribute",
"(",
"'colspan'",
")",
".",
"value",
"classes",
"<<",
"create_class",
"(",
"cell",
")",
"else",
"intervals",
"=",
"1",
"end",
"inc_time",
"(",
"intervals",
")",
"end",
"@day",
"+=",
"1",
"end",
"classes",
"end"
] | Parse the module table for any classes | [
"Parse",
"the",
"module",
"table",
"for",
"any",
"classes"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/baseparser.rb#L20-L48 |
5,047 | MattRyder/tableau | lib/tableau/baseparser.rb | Tableau.BaseParser.create_class | def create_class(class_element)
begin
tt_class = Tableau::Class.new(@day, @time)
data = class_element.xpath('table/tr/td//text()')
raise "Misformed cell for #{module_id}" if data.count < 4
rescue Exception => e
p "EXCEPTION: #{e.message}", "Data Parsed:", data
return nil
end
# If the weeks are in the 2nd index, it's a core timetable
if @@WEEKS_REGEX.match(data[1].text())
tt_class.code = data[0].text().match(/^[A-Za-z0-9\-]+/).to_s
tt_class.type = data[0].text().gsub(tt_class.code, '').gsub('/', '')
tt_class.weeks = create_class_weeks(data[1].text())
tt_class.location = data[2].text()
tt_class.name = data[3].text()
else # this is a module timetable, laid out differently
if data[0].to_s != ""
tt_class.code = data[0].text().match(/^[A-Za-z0-9\-]+/).to_s
tt_class.type = data[0].text().gsub(tt_class.code, '').gsub('/', '')
end
tt_class.location = data[1].text()
tt_class.name = data[2].text()
tt_class.weeks = create_class_weeks(data[3].text())
end
# Same attribute on both timetables, DRY'd here
tt_class.tutor = data[4] ? data[4].text() : nil
if intervals = class_element.attribute('colspan').value
tt_class.intervals = intervals.to_i
end
tt_class
end | ruby | def create_class(class_element)
begin
tt_class = Tableau::Class.new(@day, @time)
data = class_element.xpath('table/tr/td//text()')
raise "Misformed cell for #{module_id}" if data.count < 4
rescue Exception => e
p "EXCEPTION: #{e.message}", "Data Parsed:", data
return nil
end
# If the weeks are in the 2nd index, it's a core timetable
if @@WEEKS_REGEX.match(data[1].text())
tt_class.code = data[0].text().match(/^[A-Za-z0-9\-]+/).to_s
tt_class.type = data[0].text().gsub(tt_class.code, '').gsub('/', '')
tt_class.weeks = create_class_weeks(data[1].text())
tt_class.location = data[2].text()
tt_class.name = data[3].text()
else # this is a module timetable, laid out differently
if data[0].to_s != ""
tt_class.code = data[0].text().match(/^[A-Za-z0-9\-]+/).to_s
tt_class.type = data[0].text().gsub(tt_class.code, '').gsub('/', '')
end
tt_class.location = data[1].text()
tt_class.name = data[2].text()
tt_class.weeks = create_class_weeks(data[3].text())
end
# Same attribute on both timetables, DRY'd here
tt_class.tutor = data[4] ? data[4].text() : nil
if intervals = class_element.attribute('colspan').value
tt_class.intervals = intervals.to_i
end
tt_class
end | [
"def",
"create_class",
"(",
"class_element",
")",
"begin",
"tt_class",
"=",
"Tableau",
"::",
"Class",
".",
"new",
"(",
"@day",
",",
"@time",
")",
"data",
"=",
"class_element",
".",
"xpath",
"(",
"'table/tr/td//text()'",
")",
"raise",
"\"Misformed cell for #{module_id}\"",
"if",
"data",
".",
"count",
"<",
"4",
"rescue",
"Exception",
"=>",
"e",
"p",
"\"EXCEPTION: #{e.message}\"",
",",
"\"Data Parsed:\"",
",",
"data",
"return",
"nil",
"end",
"# If the weeks are in the 2nd index, it's a core timetable",
"if",
"@@WEEKS_REGEX",
".",
"match",
"(",
"data",
"[",
"1",
"]",
".",
"text",
"(",
")",
")",
"tt_class",
".",
"code",
"=",
"data",
"[",
"0",
"]",
".",
"text",
"(",
")",
".",
"match",
"(",
"/",
"\\-",
"/",
")",
".",
"to_s",
"tt_class",
".",
"type",
"=",
"data",
"[",
"0",
"]",
".",
"text",
"(",
")",
".",
"gsub",
"(",
"tt_class",
".",
"code",
",",
"''",
")",
".",
"gsub",
"(",
"'/'",
",",
"''",
")",
"tt_class",
".",
"weeks",
"=",
"create_class_weeks",
"(",
"data",
"[",
"1",
"]",
".",
"text",
"(",
")",
")",
"tt_class",
".",
"location",
"=",
"data",
"[",
"2",
"]",
".",
"text",
"(",
")",
"tt_class",
".",
"name",
"=",
"data",
"[",
"3",
"]",
".",
"text",
"(",
")",
"else",
"# this is a module timetable, laid out differently",
"if",
"data",
"[",
"0",
"]",
".",
"to_s",
"!=",
"\"\"",
"tt_class",
".",
"code",
"=",
"data",
"[",
"0",
"]",
".",
"text",
"(",
")",
".",
"match",
"(",
"/",
"\\-",
"/",
")",
".",
"to_s",
"tt_class",
".",
"type",
"=",
"data",
"[",
"0",
"]",
".",
"text",
"(",
")",
".",
"gsub",
"(",
"tt_class",
".",
"code",
",",
"''",
")",
".",
"gsub",
"(",
"'/'",
",",
"''",
")",
"end",
"tt_class",
".",
"location",
"=",
"data",
"[",
"1",
"]",
".",
"text",
"(",
")",
"tt_class",
".",
"name",
"=",
"data",
"[",
"2",
"]",
".",
"text",
"(",
")",
"tt_class",
".",
"weeks",
"=",
"create_class_weeks",
"(",
"data",
"[",
"3",
"]",
".",
"text",
"(",
")",
")",
"end",
"# Same attribute on both timetables, DRY'd here",
"tt_class",
".",
"tutor",
"=",
"data",
"[",
"4",
"]",
"?",
"data",
"[",
"4",
"]",
".",
"text",
"(",
")",
":",
"nil",
"if",
"intervals",
"=",
"class_element",
".",
"attribute",
"(",
"'colspan'",
")",
".",
"value",
"tt_class",
".",
"intervals",
"=",
"intervals",
".",
"to_i",
"end",
"tt_class",
"end"
] | Create a Class from the given data element | [
"Create",
"a",
"Class",
"from",
"the",
"given",
"data",
"element"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/baseparser.rb#L51-L88 |
5,048 | MattRyder/tableau | lib/tableau/baseparser.rb | Tableau.BaseParser.create_class_weeks | def create_class_weeks(week_data)
week_span_regex = /([\d]{2}-[\d]{2})/
week_start_regex = /^[0-9]{2}/
week_end_regex = /[0-9]{2}$/
week_single_regex = /[\d]{2}/
class_weeks = Array.new
week_data.scan(@@WEEKS_REGEX).each do |weekspan|
# if it's a 28-39 week span
if weekspan =~ week_span_regex
start = week_start_regex.match(weekspan)[0].to_i
finish = week_end_regex.match(weekspan)[0].to_i
while start <= finish
class_weeks << start
start += 1
end
# some single week (30, 31, 32 etc) support
elsif weekspan =~ week_single_regex
class_weeks << week_single_regex.match(weekspan)[0].to_i
end
end
class_weeks
end | ruby | def create_class_weeks(week_data)
week_span_regex = /([\d]{2}-[\d]{2})/
week_start_regex = /^[0-9]{2}/
week_end_regex = /[0-9]{2}$/
week_single_regex = /[\d]{2}/
class_weeks = Array.new
week_data.scan(@@WEEKS_REGEX).each do |weekspan|
# if it's a 28-39 week span
if weekspan =~ week_span_regex
start = week_start_regex.match(weekspan)[0].to_i
finish = week_end_regex.match(weekspan)[0].to_i
while start <= finish
class_weeks << start
start += 1
end
# some single week (30, 31, 32 etc) support
elsif weekspan =~ week_single_regex
class_weeks << week_single_regex.match(weekspan)[0].to_i
end
end
class_weeks
end | [
"def",
"create_class_weeks",
"(",
"week_data",
")",
"week_span_regex",
"=",
"/",
"\\d",
"\\d",
"/",
"week_start_regex",
"=",
"/",
"/",
"week_end_regex",
"=",
"/",
"/",
"week_single_regex",
"=",
"/",
"\\d",
"/",
"class_weeks",
"=",
"Array",
".",
"new",
"week_data",
".",
"scan",
"(",
"@@WEEKS_REGEX",
")",
".",
"each",
"do",
"|",
"weekspan",
"|",
"# if it's a 28-39 week span",
"if",
"weekspan",
"=~",
"week_span_regex",
"start",
"=",
"week_start_regex",
".",
"match",
"(",
"weekspan",
")",
"[",
"0",
"]",
".",
"to_i",
"finish",
"=",
"week_end_regex",
".",
"match",
"(",
"weekspan",
")",
"[",
"0",
"]",
".",
"to_i",
"while",
"start",
"<=",
"finish",
"class_weeks",
"<<",
"start",
"start",
"+=",
"1",
"end",
"# some single week (30, 31, 32 etc) support",
"elsif",
"weekspan",
"=~",
"week_single_regex",
"class_weeks",
"<<",
"week_single_regex",
".",
"match",
"(",
"weekspan",
")",
"[",
"0",
"]",
".",
"to_i",
"end",
"end",
"class_weeks",
"end"
] | Create the week range array for the given week string | [
"Create",
"the",
"week",
"range",
"array",
"for",
"the",
"given",
"week",
"string"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/baseparser.rb#L91-L118 |
5,049 | Kuniri/kuniri | lib/kuniri/parser/output_format.rb | Parser.OutputFormat.create_all_data | def create_all_data(pParser)
return nil unless pParser
wrapper = self
# Go through each file
pParser.fileLanguage.each do |listOfFile|
# Inspect each element
listOfFile.fileElements.each do |singleElement|
@outputEngine.kuniri do
wrapper.handle_element(singleElement)
end
currentFilePathAndName = singleElement.name
write_file(currentFilePathAndName)
@outputEngine.reset_engine
end
end
end | ruby | def create_all_data(pParser)
return nil unless pParser
wrapper = self
# Go through each file
pParser.fileLanguage.each do |listOfFile|
# Inspect each element
listOfFile.fileElements.each do |singleElement|
@outputEngine.kuniri do
wrapper.handle_element(singleElement)
end
currentFilePathAndName = singleElement.name
write_file(currentFilePathAndName)
@outputEngine.reset_engine
end
end
end | [
"def",
"create_all_data",
"(",
"pParser",
")",
"return",
"nil",
"unless",
"pParser",
"wrapper",
"=",
"self",
"# Go through each file",
"pParser",
".",
"fileLanguage",
".",
"each",
"do",
"|",
"listOfFile",
"|",
"# Inspect each element",
"listOfFile",
".",
"fileElements",
".",
"each",
"do",
"|",
"singleElement",
"|",
"@outputEngine",
".",
"kuniri",
"do",
"wrapper",
".",
"handle_element",
"(",
"singleElement",
")",
"end",
"currentFilePathAndName",
"=",
"singleElement",
".",
"name",
"write_file",
"(",
"currentFilePathAndName",
")",
"@outputEngine",
".",
"reset_engine",
"end",
"end",
"end"
] | Go through all the data, and generate the output
@param pParser
@return | [
"Go",
"through",
"all",
"the",
"data",
"and",
"generate",
"the",
"output"
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/parser/output_format.rb#L28-L44 |
5,050 | kul1/jinda | lib/jinda/helpers.rb | Jinda.Helpers.markdown | def markdown(text)
erbified = ERB.new(text.html_safe).result(binding)
red = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true)
red.render(erbified).html_safe
end | ruby | def markdown(text)
erbified = ERB.new(text.html_safe).result(binding)
red = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true)
red.render(erbified).html_safe
end | [
"def",
"markdown",
"(",
"text",
")",
"erbified",
"=",
"ERB",
".",
"new",
"(",
"text",
".",
"html_safe",
")",
".",
"result",
"(",
"binding",
")",
"red",
"=",
"Redcarpet",
"::",
"Markdown",
".",
"new",
"(",
"Redcarpet",
"::",
"Render",
"::",
"HTML",
",",
":autolink",
"=>",
"true",
",",
":space_after_headers",
"=>",
"true",
")",
"red",
".",
"render",
"(",
"erbified",
")",
".",
"html_safe",
"end"
] | methods from application_helper | [
"methods",
"from",
"application_helper"
] | 97cbf13fa5f9c8b6afdc50c61fc76a4d21f1d7f6 | https://github.com/kul1/jinda/blob/97cbf13fa5f9c8b6afdc50c61fc76a4d21f1d7f6/lib/jinda/helpers.rb#L178-L182 |
5,051 | kul1/jinda | lib/jinda/helpers.rb | Jinda.Helpers.gen_views | def gen_views
t = ["*** generate ui ***"]
# create array of files to be tested
$afile = Array.new
Jinda::Module.all.each do |m|
m.services.each do |s|
dir ="app/views/#{s.module.code}"
unless gen_view_file_exist?(dir)
gen_view_mkdir(dir,t)
end
if s.code=='link'
f= "app/views/#{s.module.code}/index.haml"
$afile << f
unless gen_view_file_exist?(f)
sv = "app/jinda/template/linkview.haml"
f= "app/views/#{s.module.code}/index.haml"
gen_view_createfile(sv,f,t)
end
next
end
dir ="app/views/#{s.module.code}/#{s.code}"
unless gen_view_file_exist?(dir)
gen_view_mkdir(dir,t)
end
xml= REXML::Document.new(s.xml)
xml.elements.each('*/node') do |activity|
icon = activity.elements['icon']
next unless icon
action= freemind2action(icon.attributes['BUILTIN'])
next unless ui_action?(action)
code_name = activity.attributes["TEXT"].to_s
next if code_name.comment?
code= name2code(code_name)
if action=="pdf"
f= "app/views/#{s.module.code}/#{s.code}/#{code}.pdf.prawn"
else
f= "app/views/#{s.module.code}/#{s.code}/#{code}.html.erb"
end
$afile << f
unless gen_view_file_exist?(f)
sv = "app/jinda/template/view.html.erb"
gen_view_createfile(sv,f,t)
end
end
end
end
puts $afile.join("\n")
puts t.join("\n")
return $afile
end | ruby | def gen_views
t = ["*** generate ui ***"]
# create array of files to be tested
$afile = Array.new
Jinda::Module.all.each do |m|
m.services.each do |s|
dir ="app/views/#{s.module.code}"
unless gen_view_file_exist?(dir)
gen_view_mkdir(dir,t)
end
if s.code=='link'
f= "app/views/#{s.module.code}/index.haml"
$afile << f
unless gen_view_file_exist?(f)
sv = "app/jinda/template/linkview.haml"
f= "app/views/#{s.module.code}/index.haml"
gen_view_createfile(sv,f,t)
end
next
end
dir ="app/views/#{s.module.code}/#{s.code}"
unless gen_view_file_exist?(dir)
gen_view_mkdir(dir,t)
end
xml= REXML::Document.new(s.xml)
xml.elements.each('*/node') do |activity|
icon = activity.elements['icon']
next unless icon
action= freemind2action(icon.attributes['BUILTIN'])
next unless ui_action?(action)
code_name = activity.attributes["TEXT"].to_s
next if code_name.comment?
code= name2code(code_name)
if action=="pdf"
f= "app/views/#{s.module.code}/#{s.code}/#{code}.pdf.prawn"
else
f= "app/views/#{s.module.code}/#{s.code}/#{code}.html.erb"
end
$afile << f
unless gen_view_file_exist?(f)
sv = "app/jinda/template/view.html.erb"
gen_view_createfile(sv,f,t)
end
end
end
end
puts $afile.join("\n")
puts t.join("\n")
return $afile
end | [
"def",
"gen_views",
"t",
"=",
"[",
"\"*** generate ui ***\"",
"]",
"# create array of files to be tested",
"$afile",
"=",
"Array",
".",
"new",
"Jinda",
"::",
"Module",
".",
"all",
".",
"each",
"do",
"|",
"m",
"|",
"m",
".",
"services",
".",
"each",
"do",
"|",
"s",
"|",
"dir",
"=",
"\"app/views/#{s.module.code}\"",
"unless",
"gen_view_file_exist?",
"(",
"dir",
")",
"gen_view_mkdir",
"(",
"dir",
",",
"t",
")",
"end",
"if",
"s",
".",
"code",
"==",
"'link'",
"f",
"=",
"\"app/views/#{s.module.code}/index.haml\"",
"$afile",
"<<",
"f",
"unless",
"gen_view_file_exist?",
"(",
"f",
")",
"sv",
"=",
"\"app/jinda/template/linkview.haml\"",
"f",
"=",
"\"app/views/#{s.module.code}/index.haml\"",
"gen_view_createfile",
"(",
"sv",
",",
"f",
",",
"t",
")",
"end",
"next",
"end",
"dir",
"=",
"\"app/views/#{s.module.code}/#{s.code}\"",
"unless",
"gen_view_file_exist?",
"(",
"dir",
")",
"gen_view_mkdir",
"(",
"dir",
",",
"t",
")",
"end",
"xml",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"s",
".",
"xml",
")",
"xml",
".",
"elements",
".",
"each",
"(",
"'*/node'",
")",
"do",
"|",
"activity",
"|",
"icon",
"=",
"activity",
".",
"elements",
"[",
"'icon'",
"]",
"next",
"unless",
"icon",
"action",
"=",
"freemind2action",
"(",
"icon",
".",
"attributes",
"[",
"'BUILTIN'",
"]",
")",
"next",
"unless",
"ui_action?",
"(",
"action",
")",
"code_name",
"=",
"activity",
".",
"attributes",
"[",
"\"TEXT\"",
"]",
".",
"to_s",
"next",
"if",
"code_name",
".",
"comment?",
"code",
"=",
"name2code",
"(",
"code_name",
")",
"if",
"action",
"==",
"\"pdf\"",
"f",
"=",
"\"app/views/#{s.module.code}/#{s.code}/#{code}.pdf.prawn\"",
"else",
"f",
"=",
"\"app/views/#{s.module.code}/#{s.code}/#{code}.html.erb\"",
"end",
"$afile",
"<<",
"f",
"unless",
"gen_view_file_exist?",
"(",
"f",
")",
"sv",
"=",
"\"app/jinda/template/view.html.erb\"",
"gen_view_createfile",
"(",
"sv",
",",
"f",
",",
"t",
")",
"end",
"end",
"end",
"end",
"puts",
"$afile",
".",
"join",
"(",
"\"\\n\"",
")",
"puts",
"t",
".",
"join",
"(",
"\"\\n\"",
")",
"return",
"$afile",
"end"
] | Jinda Rake Task | [
"Jinda",
"Rake",
"Task"
] | 97cbf13fa5f9c8b6afdc50c61fc76a4d21f1d7f6 | https://github.com/kul1/jinda/blob/97cbf13fa5f9c8b6afdc50c61fc76a4d21f1d7f6/lib/jinda/helpers.rb#L380-L434 |
5,052 | ndlib/rof | lib/rof/utility.rb | ROF.Utility.decode_work_type | def decode_work_type(obj)
if obj['type'] =~ WORK_TYPE_WITH_PREFIX_PATTERN
return 'GenericWork' if Regexp.last_match(2).nil?
Regexp.last_match(2)
else
# this will return nil if key t does not exist
work_type = obj['type'].downcase
WORK_TYPES[work_type]
end
end | ruby | def decode_work_type(obj)
if obj['type'] =~ WORK_TYPE_WITH_PREFIX_PATTERN
return 'GenericWork' if Regexp.last_match(2).nil?
Regexp.last_match(2)
else
# this will return nil if key t does not exist
work_type = obj['type'].downcase
WORK_TYPES[work_type]
end
end | [
"def",
"decode_work_type",
"(",
"obj",
")",
"if",
"obj",
"[",
"'type'",
"]",
"=~",
"WORK_TYPE_WITH_PREFIX_PATTERN",
"return",
"'GenericWork'",
"if",
"Regexp",
".",
"last_match",
"(",
"2",
")",
".",
"nil?",
"Regexp",
".",
"last_match",
"(",
"2",
")",
"else",
"# this will return nil if key t does not exist",
"work_type",
"=",
"obj",
"[",
"'type'",
"]",
".",
"downcase",
"WORK_TYPES",
"[",
"work_type",
"]",
"end",
"end"
] | Given an object's type, detrmine and return its af-model | [
"Given",
"an",
"object",
"s",
"type",
"detrmine",
"and",
"return",
"its",
"af",
"-",
"model"
] | 18a8cc009540a868447952eed82de035451025e8 | https://github.com/ndlib/rof/blob/18a8cc009540a868447952eed82de035451025e8/lib/rof/utility.rb#L36-L45 |
5,053 | stepheneb/jnlp | lib/jnlp/otrunk.rb | Jnlp.Otrunk.run_local | def run_local(argument=@argument, main_class='net.sf.sail.emf.launch.EMFLauncher2')
if RUBY_PLATFORM =~ /java/
java.lang.Thread.currentThread.setContextClassLoader(JRuby.runtime.jruby_class_loader)
require_resources
configUrl = URL.new(JavaIO::File.new("dummy.txt").toURL, argument)
# configUrl = URL.new("document-edit.config")
unless @bundleManager
@bundleManager = SailCoreBundle::BundleManager.new
@serviceContext = @bundleManager.getServiceContext
@bundleManager.setContextURL(configUrl)
#
# Add the <code>bundles</code> configured in this bundles xml file. The format of the file
# is XMLEncoder
#
@bundleManager.addBundles(configUrl.openStream)
#
# Have all the bundles register their services, and then do any linking
# to other registered services
#
@bundleManager.initializeBundles
#
# Start the session manager
#
@manager = @serviceContext.getService(SailCoreService::SessionManager.java_class)
end
@manager.start(@serviceContext)
else
command = "java -classpath #{local_classpath} #{main_class} '#{argument}'"
$pid = fork { exec command }
end
end | ruby | def run_local(argument=@argument, main_class='net.sf.sail.emf.launch.EMFLauncher2')
if RUBY_PLATFORM =~ /java/
java.lang.Thread.currentThread.setContextClassLoader(JRuby.runtime.jruby_class_loader)
require_resources
configUrl = URL.new(JavaIO::File.new("dummy.txt").toURL, argument)
# configUrl = URL.new("document-edit.config")
unless @bundleManager
@bundleManager = SailCoreBundle::BundleManager.new
@serviceContext = @bundleManager.getServiceContext
@bundleManager.setContextURL(configUrl)
#
# Add the <code>bundles</code> configured in this bundles xml file. The format of the file
# is XMLEncoder
#
@bundleManager.addBundles(configUrl.openStream)
#
# Have all the bundles register their services, and then do any linking
# to other registered services
#
@bundleManager.initializeBundles
#
# Start the session manager
#
@manager = @serviceContext.getService(SailCoreService::SessionManager.java_class)
end
@manager.start(@serviceContext)
else
command = "java -classpath #{local_classpath} #{main_class} '#{argument}'"
$pid = fork { exec command }
end
end | [
"def",
"run_local",
"(",
"argument",
"=",
"@argument",
",",
"main_class",
"=",
"'net.sf.sail.emf.launch.EMFLauncher2'",
")",
"if",
"RUBY_PLATFORM",
"=~",
"/",
"/",
"java",
".",
"lang",
".",
"Thread",
".",
"currentThread",
".",
"setContextClassLoader",
"(",
"JRuby",
".",
"runtime",
".",
"jruby_class_loader",
")",
"require_resources",
"configUrl",
"=",
"URL",
".",
"new",
"(",
"JavaIO",
"::",
"File",
".",
"new",
"(",
"\"dummy.txt\"",
")",
".",
"toURL",
",",
"argument",
")",
"# configUrl = URL.new(\"document-edit.config\") ",
"unless",
"@bundleManager",
"@bundleManager",
"=",
"SailCoreBundle",
"::",
"BundleManager",
".",
"new",
"@serviceContext",
"=",
"@bundleManager",
".",
"getServiceContext",
"@bundleManager",
".",
"setContextURL",
"(",
"configUrl",
")",
"# ",
"# Add the <code>bundles</code> configured in this bundles xml file. The format of the file",
"# is XMLEncoder",
"# ",
"@bundleManager",
".",
"addBundles",
"(",
"configUrl",
".",
"openStream",
")",
"# ",
"# Have all the bundles register their services, and then do any linking",
"# to other registered services",
"# ",
"@bundleManager",
".",
"initializeBundles",
"# ",
"# Start the session manager",
"# ",
"@manager",
"=",
"@serviceContext",
".",
"getService",
"(",
"SailCoreService",
"::",
"SessionManager",
".",
"java_class",
")",
"end",
"@manager",
".",
"start",
"(",
"@serviceContext",
")",
"else",
"command",
"=",
"\"java -classpath #{local_classpath} #{main_class} '#{argument}'\"",
"$pid",
"=",
"fork",
"{",
"exec",
"command",
"}",
"end",
"end"
] | This will start the jnlp locally in Java without
using Java Web Start
This method works in MRI by forking and using exec
to start a separate javavm process.
JRuby Note:
In JRuby the jars are required which makes them available
to JRuby -- but to make this work you will need to also
included them on the CLASSPATH.
The convienence method Jnlp#write_local_classpath_shell_script
can be used to create a shell script to set the classpath.
If you are using the JRuby interactive console you will need to
exclude any reference to a separate jruby included in the jnlp.
Example in JRuby jirb:
j = Jnlp::Otrunk.new('http://rails.dev.concord.org/sds/2/offering/144/jnlp/540/view?sailotrunk.otmlurl=http://continuum.concord.org/otrunk/examples/BasicExamples/document-edit.otml&sailotrunk.hidetree=false', 'cache'); nil
j.write_local_classpath_shell_script('document-edit_classpath.sh', :remove_jruby => true)
Now exit jirb and execute this in the shell:
source document-edit_classpath.sh
Now restart jirb:
j = Jnlp::Otrunk.new('http://rails.dev.concord.org/sds/2/offering/144/jnlp/540/view?sailotrunk.otmlurl=http://continuum.concord.org/otrunk/examples/BasicExamples/document-edit.otml&sailotrunk.hidetree=false', 'cache'); nil
j.run_local
You can optionally pass in jnlp and main-class arguments
If these paramaters are not present Otrunk#run_local will
use:
net.sf.sail.emf.launch.EMFLauncher2
as the default main class and the default argument in
the original jnlp. | [
"This",
"will",
"start",
"the",
"jnlp",
"locally",
"in",
"Java",
"without",
"using",
"Java",
"Web",
"Start"
] | 9d78fe8b0ebf5bcc68105513d35ce43199607ac4 | https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/otrunk.rb#L142-L174 |
5,054 | ljcooke/putqr | lib/putqr.rb | PutQR.QRCode.render_image_iterm2 | def render_image_iterm2
return nil unless valid?
# References:
# https://iterm2.com/documentation-images.html
# https://iterm2.com/utilities/imgcat
# tmux requires some extra work for unrecognised escape code sequences
screen = ENV['TERM'].start_with? 'screen'
prefix = screen ? "\ePtmux;\e\e]" : "\e]"
suffix = screen ? "\a\e\\" : "\a"
png = qrcode.as_png(size: 600)
png_base64 = Base64.encode64(png.to_s).chomp
options = 'inline=1'
"#{prefix}1337;File=#{options}:#{png_base64}#{suffix}"
end | ruby | def render_image_iterm2
return nil unless valid?
# References:
# https://iterm2.com/documentation-images.html
# https://iterm2.com/utilities/imgcat
# tmux requires some extra work for unrecognised escape code sequences
screen = ENV['TERM'].start_with? 'screen'
prefix = screen ? "\ePtmux;\e\e]" : "\e]"
suffix = screen ? "\a\e\\" : "\a"
png = qrcode.as_png(size: 600)
png_base64 = Base64.encode64(png.to_s).chomp
options = 'inline=1'
"#{prefix}1337;File=#{options}:#{png_base64}#{suffix}"
end | [
"def",
"render_image_iterm2",
"return",
"nil",
"unless",
"valid?",
"# References:",
"# https://iterm2.com/documentation-images.html",
"# https://iterm2.com/utilities/imgcat",
"# tmux requires some extra work for unrecognised escape code sequences",
"screen",
"=",
"ENV",
"[",
"'TERM'",
"]",
".",
"start_with?",
"'screen'",
"prefix",
"=",
"screen",
"?",
"\"\\ePtmux;\\e\\e]\"",
":",
"\"\\e]\"",
"suffix",
"=",
"screen",
"?",
"\"\\a\\e\\\\\"",
":",
"\"\\a\"",
"png",
"=",
"qrcode",
".",
"as_png",
"(",
"size",
":",
"600",
")",
"png_base64",
"=",
"Base64",
".",
"encode64",
"(",
"png",
".",
"to_s",
")",
".",
"chomp",
"options",
"=",
"'inline=1'",
"\"#{prefix}1337;File=#{options}:#{png_base64}#{suffix}\"",
"end"
] | Render the QR code as an inline image for iTerm2.
Returns a string. | [
"Render",
"the",
"QR",
"code",
"as",
"an",
"inline",
"image",
"for",
"iTerm2",
".",
"Returns",
"a",
"string",
"."
] | 0305d63b52130ff78ba433ac9f6c327d1abd3d27 | https://github.com/ljcooke/putqr/blob/0305d63b52130ff78ba433ac9f6c327d1abd3d27/lib/putqr.rb#L47-L63 |
5,055 | MattRyder/tableau | lib/tableau/timetable.rb | Tableau.Timetable.remove_class | def remove_class(rem_class)
@modules.each do |m|
if m.name == rem_class.name
m.classes.delete(rem_class)
break
end
end
end | ruby | def remove_class(rem_class)
@modules.each do |m|
if m.name == rem_class.name
m.classes.delete(rem_class)
break
end
end
end | [
"def",
"remove_class",
"(",
"rem_class",
")",
"@modules",
".",
"each",
"do",
"|",
"m",
"|",
"if",
"m",
".",
"name",
"==",
"rem_class",
".",
"name",
"m",
".",
"classes",
".",
"delete",
"(",
"rem_class",
")",
"break",
"end",
"end",
"end"
] | Removes a class from the timetable | [
"Removes",
"a",
"class",
"from",
"the",
"timetable"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/timetable.rb#L29-L36 |
5,056 | MattRyder/tableau | lib/tableau/timetable.rb | Tableau.Timetable.classes_for_day | def classes_for_day(day)
classes = Tableau::ClassArray.new
@modules.each do |mod|
cfd = mod.classes_for_day(day)
cfd.each { |cl| classes << cl } if cfd
end
classes.count > 0 ? classes : nil
end | ruby | def classes_for_day(day)
classes = Tableau::ClassArray.new
@modules.each do |mod|
cfd = mod.classes_for_day(day)
cfd.each { |cl| classes << cl } if cfd
end
classes.count > 0 ? classes : nil
end | [
"def",
"classes_for_day",
"(",
"day",
")",
"classes",
"=",
"Tableau",
"::",
"ClassArray",
".",
"new",
"@modules",
".",
"each",
"do",
"|",
"mod",
"|",
"cfd",
"=",
"mod",
".",
"classes_for_day",
"(",
"day",
")",
"cfd",
".",
"each",
"{",
"|",
"cl",
"|",
"classes",
"<<",
"cl",
"}",
"if",
"cfd",
"end",
"classes",
".",
"count",
">",
"0",
"?",
"classes",
":",
"nil",
"end"
] | Returns an array of the given day's classes | [
"Returns",
"an",
"array",
"of",
"the",
"given",
"day",
"s",
"classes"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/timetable.rb#L39-L48 |
5,057 | MattRyder/tableau | lib/tableau/timetable.rb | Tableau.Timetable.class_for_time | def class_for_time(day, time)
cfd = self.classes_for_day(day)
cfd.each { |c| return c if c.time == time }
nil
end | ruby | def class_for_time(day, time)
cfd = self.classes_for_day(day)
cfd.each { |c| return c if c.time == time }
nil
end | [
"def",
"class_for_time",
"(",
"day",
",",
"time",
")",
"cfd",
"=",
"self",
".",
"classes_for_day",
"(",
"day",
")",
"cfd",
".",
"each",
"{",
"|",
"c",
"|",
"return",
"c",
"if",
"c",
".",
"time",
"==",
"time",
"}",
"nil",
"end"
] | Returns the class at the given day & time | [
"Returns",
"the",
"class",
"at",
"the",
"given",
"day",
"&",
"time"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/timetable.rb#L51-L55 |
5,058 | MattRyder/tableau | lib/tableau/timetable.rb | Tableau.Timetable.earliest_class | def earliest_class
earliest_classes = Tableau::ClassArray.new
@modules.each { |m| earliest_classes << m.earliest_class }
earliest = earliest_classes.first
earliest_classes.each { |c| earliest = c if c.time < earliest.time }
earliest
end | ruby | def earliest_class
earliest_classes = Tableau::ClassArray.new
@modules.each { |m| earliest_classes << m.earliest_class }
earliest = earliest_classes.first
earliest_classes.each { |c| earliest = c if c.time < earliest.time }
earliest
end | [
"def",
"earliest_class",
"earliest_classes",
"=",
"Tableau",
"::",
"ClassArray",
".",
"new",
"@modules",
".",
"each",
"{",
"|",
"m",
"|",
"earliest_classes",
"<<",
"m",
".",
"earliest_class",
"}",
"earliest",
"=",
"earliest_classes",
".",
"first",
"earliest_classes",
".",
"each",
"{",
"|",
"c",
"|",
"earliest",
"=",
"c",
"if",
"c",
".",
"time",
"<",
"earliest",
".",
"time",
"}",
"earliest",
"end"
] | Returns the earliest class on the timetable | [
"Returns",
"the",
"earliest",
"class",
"on",
"the",
"timetable"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/timetable.rb#L70-L77 |
5,059 | MattRyder/tableau | lib/tableau/timetable.rb | Tableau.Timetable.conflicts | def conflicts
conflicts = Tableau::ClassArray.new
(0..4).each do |day|
days_classes = self.classes_for_day(day)
next if !days_classes || days_classes.count == 0
# get the last element index
last = days_classes.count - 1
for i in 0..last
i_c = days_classes[i]
time_range = i_c.time..(i_c.time + 3600 * i_c.duration)
for j in (i+1)..last
if time_range.cover?(days_classes[j].time)
conflicts << [days_classes[i], days_classes[j]]
end
end
end
end
conflicts # return the conflicts
end | ruby | def conflicts
conflicts = Tableau::ClassArray.new
(0..4).each do |day|
days_classes = self.classes_for_day(day)
next if !days_classes || days_classes.count == 0
# get the last element index
last = days_classes.count - 1
for i in 0..last
i_c = days_classes[i]
time_range = i_c.time..(i_c.time + 3600 * i_c.duration)
for j in (i+1)..last
if time_range.cover?(days_classes[j].time)
conflicts << [days_classes[i], days_classes[j]]
end
end
end
end
conflicts # return the conflicts
end | [
"def",
"conflicts",
"conflicts",
"=",
"Tableau",
"::",
"ClassArray",
".",
"new",
"(",
"0",
"..",
"4",
")",
".",
"each",
"do",
"|",
"day",
"|",
"days_classes",
"=",
"self",
".",
"classes_for_day",
"(",
"day",
")",
"next",
"if",
"!",
"days_classes",
"||",
"days_classes",
".",
"count",
"==",
"0",
"# get the last element index",
"last",
"=",
"days_classes",
".",
"count",
"-",
"1",
"for",
"i",
"in",
"0",
"..",
"last",
"i_c",
"=",
"days_classes",
"[",
"i",
"]",
"time_range",
"=",
"i_c",
".",
"time",
"..",
"(",
"i_c",
".",
"time",
"+",
"3600",
"*",
"i_c",
".",
"duration",
")",
"for",
"j",
"in",
"(",
"i",
"+",
"1",
")",
"..",
"last",
"if",
"time_range",
".",
"cover?",
"(",
"days_classes",
"[",
"j",
"]",
".",
"time",
")",
"conflicts",
"<<",
"[",
"days_classes",
"[",
"i",
"]",
",",
"days_classes",
"[",
"j",
"]",
"]",
"end",
"end",
"end",
"end",
"conflicts",
"# return the conflicts",
"end"
] | Returns an array of time conflicts found in the timetable | [
"Returns",
"an",
"array",
"of",
"time",
"conflicts",
"found",
"in",
"the",
"timetable"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/timetable.rb#L90-L112 |
5,060 | rsanheim/chatterbox | lib/chatterbox/exception_notification/presenter.rb | Chatterbox::ExceptionNotification.Presenter.render_hash | def render_hash(hsh)
str = ""
indiff_hsh = hsh.with_indifferent_access
indiff_hsh.keys.sort.each do |key|
str << "#{key}: "
value = indiff_hsh[key]
PP::pp(value, str)
end
str
end | ruby | def render_hash(hsh)
str = ""
indiff_hsh = hsh.with_indifferent_access
indiff_hsh.keys.sort.each do |key|
str << "#{key}: "
value = indiff_hsh[key]
PP::pp(value, str)
end
str
end | [
"def",
"render_hash",
"(",
"hsh",
")",
"str",
"=",
"\"\"",
"indiff_hsh",
"=",
"hsh",
".",
"with_indifferent_access",
"indiff_hsh",
".",
"keys",
".",
"sort",
".",
"each",
"do",
"|",
"key",
"|",
"str",
"<<",
"\"#{key}: \"",
"value",
"=",
"indiff_hsh",
"[",
"key",
"]",
"PP",
"::",
"pp",
"(",
"value",
",",
"str",
")",
"end",
"str",
"end"
] | renders hashes with keys in alpha-sorted order | [
"renders",
"hashes",
"with",
"keys",
"in",
"alpha",
"-",
"sorted",
"order"
] | 89f9596656a2724f399936017cf0a807ec284134 | https://github.com/rsanheim/chatterbox/blob/89f9596656a2724f399936017cf0a807ec284134/lib/chatterbox/exception_notification/presenter.rb#L74-L83 |
5,061 | furunkel/gv | lib/gv.rb | GV.Component.html | def html(string)
ptr = Libcgraph.agstrdup_html(graph.ptr, string)
string = ptr.read_string
Libcgraph.agstrfree graph.ptr, ptr
string
end | ruby | def html(string)
ptr = Libcgraph.agstrdup_html(graph.ptr, string)
string = ptr.read_string
Libcgraph.agstrfree graph.ptr, ptr
string
end | [
"def",
"html",
"(",
"string",
")",
"ptr",
"=",
"Libcgraph",
".",
"agstrdup_html",
"(",
"graph",
".",
"ptr",
",",
"string",
")",
"string",
"=",
"ptr",
".",
"read_string",
"Libcgraph",
".",
"agstrfree",
"graph",
".",
"ptr",
",",
"ptr",
"string",
"end"
] | Creates an HTML label
@param string [String] the HTML to parse
@return [Object] a HTML label | [
"Creates",
"an",
"HTML",
"label"
] | 3a744032ee806d5ef78f94ff2dde290a2541029a | https://github.com/furunkel/gv/blob/3a744032ee806d5ef78f94ff2dde290a2541029a/lib/gv.rb#L75-L81 |
5,062 | furunkel/gv | lib/gv.rb | GV.BaseGraph.edge | def edge(name, tail, head, attrs = {})
component Edge, [name, tail, head], attrs
end | ruby | def edge(name, tail, head, attrs = {})
component Edge, [name, tail, head], attrs
end | [
"def",
"edge",
"(",
"name",
",",
"tail",
",",
"head",
",",
"attrs",
"=",
"{",
"}",
")",
"component",
"Edge",
",",
"[",
"name",
",",
"tail",
",",
"head",
"]",
",",
"attrs",
"end"
] | Creates a new edge
@param name [String] the name (identifier) of the edge
@param tail [Node] the edge's tail node
@param head [Node] the edge's head node
@param attrs [Hash{String, Symbol => Object}] the attributes
to associate with this edge
@see http://www.graphviz.org/doc/info/attrs.html Node, Edge and Graph Attributes
@return [Edge] the newly created edge | [
"Creates",
"a",
"new",
"edge"
] | 3a744032ee806d5ef78f94ff2dde290a2541029a | https://github.com/furunkel/gv/blob/3a744032ee806d5ef78f94ff2dde290a2541029a/lib/gv.rb#L172-L174 |
5,063 | furunkel/gv | lib/gv.rb | GV.BaseGraph.sub_graph | def sub_graph(name, attrs = {})
graph = component SubGraph, [name], attrs
yield graph if block_given?
graph
end | ruby | def sub_graph(name, attrs = {})
graph = component SubGraph, [name], attrs
yield graph if block_given?
graph
end | [
"def",
"sub_graph",
"(",
"name",
",",
"attrs",
"=",
"{",
"}",
")",
"graph",
"=",
"component",
"SubGraph",
",",
"[",
"name",
"]",
",",
"attrs",
"yield",
"graph",
"if",
"block_given?",
"graph",
"end"
] | Creates a new sub-graph
@param name [String] the name (identifier) of the sub-graph
@param attrs [Hash{String, Symbol => Object}] the attributes
to associate with this sub-graph
@see http://www.graphviz.org/doc/info/attrs.html Node, Edge and Graph Attributes
@return [SubGraph] the newly created sub-graph | [
"Creates",
"a",
"new",
"sub",
"-",
"graph"
] | 3a744032ee806d5ef78f94ff2dde290a2541029a | https://github.com/furunkel/gv/blob/3a744032ee806d5ef78f94ff2dde290a2541029a/lib/gv.rb#L182-L187 |
5,064 | furunkel/gv | lib/gv.rb | GV.Graph.save | def save(filename, format = 'png', layout = 'dot')
Libgvc.gvLayout(@@gvc, ptr, layout.to_s)
Libgvc.gvRenderFilename(@@gvc, ptr, format.to_s, filename);
Libgvc.gvFreeLayout(@@gvc, ptr)
nil
end | ruby | def save(filename, format = 'png', layout = 'dot')
Libgvc.gvLayout(@@gvc, ptr, layout.to_s)
Libgvc.gvRenderFilename(@@gvc, ptr, format.to_s, filename);
Libgvc.gvFreeLayout(@@gvc, ptr)
nil
end | [
"def",
"save",
"(",
"filename",
",",
"format",
"=",
"'png'",
",",
"layout",
"=",
"'dot'",
")",
"Libgvc",
".",
"gvLayout",
"(",
"@@gvc",
",",
"ptr",
",",
"layout",
".",
"to_s",
")",
"Libgvc",
".",
"gvRenderFilename",
"(",
"@@gvc",
",",
"ptr",
",",
"format",
".",
"to_s",
",",
"filename",
")",
";",
"Libgvc",
".",
"gvFreeLayout",
"(",
"@@gvc",
",",
"ptr",
")",
"nil",
"end"
] | Renders the graph to an images and saves the result to a file
@param filename [String] the filename
@param format [String] the image format to use, e.g. 'svg', 'pdf' etc.
@param layout [String] the layout to use, e.g. 'dot' or 'neato' etc.
@return [nil] | [
"Renders",
"the",
"graph",
"to",
"an",
"images",
"and",
"saves",
"the",
"result",
"to",
"a",
"file"
] | 3a744032ee806d5ef78f94ff2dde290a2541029a | https://github.com/furunkel/gv/blob/3a744032ee806d5ef78f94ff2dde290a2541029a/lib/gv.rb#L282-L288 |
5,065 | furunkel/gv | lib/gv.rb | GV.Graph.render | def render(format = 'png', layout = 'dot')
Libgvc.gvLayout(@@gvc, ptr, layout.to_s)
data_ptr = FFI::MemoryPointer.new(:pointer, 1)
len_ptr = FFI::MemoryPointer.new(:int, 1)
Libgvc.gvRenderData(@@gvc, ptr, format.to_s, data_ptr, len_ptr)
len = len_ptr.read_uint
data_ptr = data_ptr.read_pointer
data = data_ptr.read_string len
Libgvc.gvFreeRenderData(data_ptr)
Libgvc.gvFreeLayout(@@gvc, ptr)
data
end | ruby | def render(format = 'png', layout = 'dot')
Libgvc.gvLayout(@@gvc, ptr, layout.to_s)
data_ptr = FFI::MemoryPointer.new(:pointer, 1)
len_ptr = FFI::MemoryPointer.new(:int, 1)
Libgvc.gvRenderData(@@gvc, ptr, format.to_s, data_ptr, len_ptr)
len = len_ptr.read_uint
data_ptr = data_ptr.read_pointer
data = data_ptr.read_string len
Libgvc.gvFreeRenderData(data_ptr)
Libgvc.gvFreeLayout(@@gvc, ptr)
data
end | [
"def",
"render",
"(",
"format",
"=",
"'png'",
",",
"layout",
"=",
"'dot'",
")",
"Libgvc",
".",
"gvLayout",
"(",
"@@gvc",
",",
"ptr",
",",
"layout",
".",
"to_s",
")",
"data_ptr",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":pointer",
",",
"1",
")",
"len_ptr",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":int",
",",
"1",
")",
"Libgvc",
".",
"gvRenderData",
"(",
"@@gvc",
",",
"ptr",
",",
"format",
".",
"to_s",
",",
"data_ptr",
",",
"len_ptr",
")",
"len",
"=",
"len_ptr",
".",
"read_uint",
"data_ptr",
"=",
"data_ptr",
".",
"read_pointer",
"data",
"=",
"data_ptr",
".",
"read_string",
"len",
"Libgvc",
".",
"gvFreeRenderData",
"(",
"data_ptr",
")",
"Libgvc",
".",
"gvFreeLayout",
"(",
"@@gvc",
",",
"ptr",
")",
"data",
"end"
] | Renders the graph to an image and returns the result as a string
@param format [String] the image format to use, e.g. 'svg', 'pdf' etc.
@param layout [String] the layout to use, e.g. 'dot' or 'neato' etc.
@return [String] the rendered graph in the given format | [
"Renders",
"the",
"graph",
"to",
"an",
"image",
"and",
"returns",
"the",
"result",
"as",
"a",
"string"
] | 3a744032ee806d5ef78f94ff2dde290a2541029a | https://github.com/furunkel/gv/blob/3a744032ee806d5ef78f94ff2dde290a2541029a/lib/gv.rb#L294-L310 |
5,066 | Kuniri/kuniri | lib/kuniri/language/abstract_container/structured_and_oo/variable_behaviour_helpers.rb | Languages.VariableBehaviourHelpers.setup_variable_behaviour | def setup_variable_behaviour
expression = MODULEBASE + type_of_language + VARIABLECLASS +
type_of_language
begin
clazz = Object.const_get(expression)
@variableBehaviour = clazz.new(who_am_i)
rescue NameError
Util::LoggerKuniri.error('Class name error')
end
end | ruby | def setup_variable_behaviour
expression = MODULEBASE + type_of_language + VARIABLECLASS +
type_of_language
begin
clazz = Object.const_get(expression)
@variableBehaviour = clazz.new(who_am_i)
rescue NameError
Util::LoggerKuniri.error('Class name error')
end
end | [
"def",
"setup_variable_behaviour",
"expression",
"=",
"MODULEBASE",
"+",
"type_of_language",
"+",
"VARIABLECLASS",
"+",
"type_of_language",
"begin",
"clazz",
"=",
"Object",
".",
"const_get",
"(",
"expression",
")",
"@variableBehaviour",
"=",
"clazz",
".",
"new",
"(",
"who_am_i",
")",
"rescue",
"NameError",
"Util",
"::",
"LoggerKuniri",
".",
"error",
"(",
"'Class name error'",
")",
"end",
"end"
] | Setup basic configurations for make attribute work correctly. It is
mandatory to call it with the correct parameters in the child class.
@param pVariableBehaviour Reference to a variable behaviour. | [
"Setup",
"basic",
"configurations",
"for",
"make",
"attribute",
"work",
"correctly",
".",
"It",
"is",
"mandatory",
"to",
"call",
"it",
"with",
"the",
"correct",
"parameters",
"in",
"the",
"child",
"class",
"."
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/abstract_container/structured_and_oo/variable_behaviour_helpers.rb#L20-L29 |
5,067 | Kuniri/kuniri | data/lang_syntax.rb | Languages.{LANG}.analyse_source | def analyse_source(pPath)
@name = File.basename(pPath, ".*")
@path = File.dirname(pPath)
analyse_first_step(pPath)
analyse_second_step
end | ruby | def analyse_source(pPath)
@name = File.basename(pPath, ".*")
@path = File.dirname(pPath)
analyse_first_step(pPath)
analyse_second_step
end | [
"def",
"analyse_source",
"(",
"pPath",
")",
"@name",
"=",
"File",
".",
"basename",
"(",
"pPath",
",",
"\".*\"",
")",
"@path",
"=",
"File",
".",
"dirname",
"(",
"pPath",
")",
"analyse_first_step",
"(",
"pPath",
")",
"analyse_second_step",
"end"
] | Analyse source code.
@param pPath Path of file to be analysed. | [
"Analyse",
"source",
"code",
"."
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/data/lang_syntax.rb#L48-L53 |
5,068 | Kuniri/kuniri | lib/kuniri/parser/parser.rb | Parser.Parser.start_parser | def start_parser
if (@filesPath.empty?)
raise Error::ConfigurationFileError,
"Source path not have #{@language} files."
end
@filesPath.each do |file|
language = @factory.get_language(@language)
fileElement = Languages::FileElementData.new(file)
source = File.open(file, 'rb')
language.analyse_source(fileElement, source)
@fileLanguage.push(language)
end
end | ruby | def start_parser
if (@filesPath.empty?)
raise Error::ConfigurationFileError,
"Source path not have #{@language} files."
end
@filesPath.each do |file|
language = @factory.get_language(@language)
fileElement = Languages::FileElementData.new(file)
source = File.open(file, 'rb')
language.analyse_source(fileElement, source)
@fileLanguage.push(language)
end
end | [
"def",
"start_parser",
"if",
"(",
"@filesPath",
".",
"empty?",
")",
"raise",
"Error",
"::",
"ConfigurationFileError",
",",
"\"Source path not have #{@language} files.\"",
"end",
"@filesPath",
".",
"each",
"do",
"|",
"file",
"|",
"language",
"=",
"@factory",
".",
"get_language",
"(",
"@language",
")",
"fileElement",
"=",
"Languages",
"::",
"FileElementData",
".",
"new",
"(",
"file",
")",
"source",
"=",
"File",
".",
"open",
"(",
"file",
",",
"'rb'",
")",
"language",
".",
"analyse_source",
"(",
"fileElement",
",",
"source",
")",
"@fileLanguage",
".",
"push",
"(",
"language",
")",
"end",
"end"
] | Start parse in the project. | [
"Start",
"parse",
"in",
"the",
"project",
"."
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/parser/parser.rb#L45-L59 |
5,069 | payneteasy/ruby-library-payneteasy-api | lib/paynet_easy/paynet_easy_api/callback/callback_factory.rb | PaynetEasy::PaynetEasyApi::Callback.CallbackFactory.callback | def callback(callback_type)
callback_class = "#{callback_type.camelize}Callback"
callback_file = "callback/#{callback_type}_callback"
begin
instantiate_callback callback_file, callback_class, callback_type
rescue LoadError => error
if @@allowed_payneteasy_callback_types.include? callback_type
instantiate_callback 'callback/paynet_easy_callback', 'PaynetEasyCallback', callback_type
else
raise error
end
end
end | ruby | def callback(callback_type)
callback_class = "#{callback_type.camelize}Callback"
callback_file = "callback/#{callback_type}_callback"
begin
instantiate_callback callback_file, callback_class, callback_type
rescue LoadError => error
if @@allowed_payneteasy_callback_types.include? callback_type
instantiate_callback 'callback/paynet_easy_callback', 'PaynetEasyCallback', callback_type
else
raise error
end
end
end | [
"def",
"callback",
"(",
"callback_type",
")",
"callback_class",
"=",
"\"#{callback_type.camelize}Callback\"",
"callback_file",
"=",
"\"callback/#{callback_type}_callback\"",
"begin",
"instantiate_callback",
"callback_file",
",",
"callback_class",
",",
"callback_type",
"rescue",
"LoadError",
"=>",
"error",
"if",
"@@allowed_payneteasy_callback_types",
".",
"include?",
"callback_type",
"instantiate_callback",
"'callback/paynet_easy_callback'",
",",
"'PaynetEasyCallback'",
",",
"callback_type",
"else",
"raise",
"error",
"end",
"end",
"end"
] | Get callback processor by callback type
@param callback_type [String] Callback type
@return [CallbackPrototype] Callback processor | [
"Get",
"callback",
"processor",
"by",
"callback",
"type"
] | 3200a447829b62e241fdc329f80fddb5f8d68cc0 | https://github.com/payneteasy/ruby-library-payneteasy-api/blob/3200a447829b62e241fdc329f80fddb5f8d68cc0/lib/paynet_easy/paynet_easy_api/callback/callback_factory.rb#L18-L31 |
5,070 | payneteasy/ruby-library-payneteasy-api | lib/paynet_easy/paynet_easy_api/callback/callback_factory.rb | PaynetEasy::PaynetEasyApi::Callback.CallbackFactory.instantiate_callback | def instantiate_callback(callback_file, callback_class, callback_type)
require callback_file
PaynetEasy::PaynetEasyApi::Callback.const_get(callback_class).new(callback_type)
end | ruby | def instantiate_callback(callback_file, callback_class, callback_type)
require callback_file
PaynetEasy::PaynetEasyApi::Callback.const_get(callback_class).new(callback_type)
end | [
"def",
"instantiate_callback",
"(",
"callback_file",
",",
"callback_class",
",",
"callback_type",
")",
"require",
"callback_file",
"PaynetEasy",
"::",
"PaynetEasyApi",
"::",
"Callback",
".",
"const_get",
"(",
"callback_class",
")",
".",
"new",
"(",
"callback_type",
")",
"end"
] | Load callback class file and return new callback object
@param callback_file [String] Callback class file
@param callback_class [String] Callback class
@param callback_type [String] Callback type
@return [CallbackPrototype] Callback object | [
"Load",
"callback",
"class",
"file",
"and",
"return",
"new",
"callback",
"object"
] | 3200a447829b62e241fdc329f80fddb5f8d68cc0 | https://github.com/payneteasy/ruby-library-payneteasy-api/blob/3200a447829b62e241fdc329f80fddb5f8d68cc0/lib/paynet_easy/paynet_easy_api/callback/callback_factory.rb#L42-L45 |
5,071 | wvanbergen/sql_tree | lib/sql_tree/node.rb | SQLTree::Node.Base.equal_children? | def equal_children?(other)
self.class.children.all? { |child| send(child) == other.send(child) }
end | ruby | def equal_children?(other)
self.class.children.all? { |child| send(child) == other.send(child) }
end | [
"def",
"equal_children?",
"(",
"other",
")",
"self",
".",
"class",
".",
"children",
".",
"all?",
"{",
"|",
"child",
"|",
"send",
"(",
"child",
")",
"==",
"other",
".",
"send",
"(",
"child",
")",
"}",
"end"
] | Compares this node with another node, returns true if the nodes are equal.
Returns true if all children of the current object and the other object are equal. | [
"Compares",
"this",
"node",
"with",
"another",
"node",
"returns",
"true",
"if",
"the",
"nodes",
"are",
"equal",
".",
"Returns",
"true",
"if",
"all",
"children",
"of",
"the",
"current",
"object",
"and",
"the",
"other",
"object",
"are",
"equal",
"."
] | b45566c4c52962def5bfd376622a19697dd49969 | https://github.com/wvanbergen/sql_tree/blob/b45566c4c52962def5bfd376622a19697dd49969/lib/sql_tree/node.rb#L58-L60 |
5,072 | wvanbergen/sql_tree | lib/sql_tree/node.rb | SQLTree::Node.Base.equal_leafs? | def equal_leafs?(other)
self.class.leafs.all? { |leaf| send(leaf) == other.send(leaf) }
end | ruby | def equal_leafs?(other)
self.class.leafs.all? { |leaf| send(leaf) == other.send(leaf) }
end | [
"def",
"equal_leafs?",
"(",
"other",
")",
"self",
".",
"class",
".",
"leafs",
".",
"all?",
"{",
"|",
"leaf",
"|",
"send",
"(",
"leaf",
")",
"==",
"other",
".",
"send",
"(",
"leaf",
")",
"}",
"end"
] | Returns true if all leaf values of the current object and the other object are equal. | [
"Returns",
"true",
"if",
"all",
"leaf",
"values",
"of",
"the",
"current",
"object",
"and",
"the",
"other",
"object",
"are",
"equal",
"."
] | b45566c4c52962def5bfd376622a19697dd49969 | https://github.com/wvanbergen/sql_tree/blob/b45566c4c52962def5bfd376622a19697dd49969/lib/sql_tree/node.rb#L63-L65 |
5,073 | hulihanapplications/fletcher | spec/support/benchmark.rb | RSpec.Benchmark.benchmark | def benchmark(times = 1, &block)
elapsed = (1..times).collect do
GC.start
::Benchmark.realtime(&block) * times
end
Result.new(elapsed)
end | ruby | def benchmark(times = 1, &block)
elapsed = (1..times).collect do
GC.start
::Benchmark.realtime(&block) * times
end
Result.new(elapsed)
end | [
"def",
"benchmark",
"(",
"times",
"=",
"1",
",",
"&",
"block",
")",
"elapsed",
"=",
"(",
"1",
"..",
"times",
")",
".",
"collect",
"do",
"GC",
".",
"start",
"::",
"Benchmark",
".",
"realtime",
"(",
"block",
")",
"*",
"times",
"end",
"Result",
".",
"new",
"(",
"elapsed",
")",
"end"
] | Run a given block and calculate the average execution time.
The block will be executed 1 times by default.
benchmark { do something }
benchmark(100) { do something } | [
"Run",
"a",
"given",
"block",
"and",
"calculate",
"the",
"average",
"execution",
"time",
".",
"The",
"block",
"will",
"be",
"executed",
"1",
"times",
"by",
"default",
"."
] | 8843bfb908007da654268e13b7973219570cde54 | https://github.com/hulihanapplications/fletcher/blob/8843bfb908007da654268e13b7973219570cde54/spec/support/benchmark.rb#L27-L34 |
5,074 | darbylabs/magma | lib/magma/renderer.rb | Magma.Renderer.format | def format(options)
options.map do |key, value|
[{
format: :f,
size: :s,
length: :hls_time,
}[key] || key, value].map(&:to_s).join('=')
end
end | ruby | def format(options)
options.map do |key, value|
[{
format: :f,
size: :s,
length: :hls_time,
}[key] || key, value].map(&:to_s).join('=')
end
end | [
"def",
"format",
"(",
"options",
")",
"options",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"[",
"{",
"format",
":",
":f",
",",
"size",
":",
":s",
",",
"length",
":",
":hls_time",
",",
"}",
"[",
"key",
"]",
"||",
"key",
",",
"value",
"]",
".",
"map",
"(",
":to_s",
")",
".",
"join",
"(",
"'='",
")",
"end",
"end"
] | Formats keys to melt arguments | [
"Formats",
"keys",
"to",
"melt",
"arguments"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/renderer.rb#L37-L45 |
5,075 | darbylabs/magma | lib/magma/renderer.rb | Magma.Renderer.melt_args | def melt_args(options)
[
options[:infile],
"-consumer avformat:#{outfile}",
].concat(pipe(options, %i[
symbolize_keys
add_defaults
select
transform
table
format
]))
end | ruby | def melt_args(options)
[
options[:infile],
"-consumer avformat:#{outfile}",
].concat(pipe(options, %i[
symbolize_keys
add_defaults
select
transform
table
format
]))
end | [
"def",
"melt_args",
"(",
"options",
")",
"[",
"options",
"[",
":infile",
"]",
",",
"\"-consumer avformat:#{outfile}\"",
",",
"]",
".",
"concat",
"(",
"pipe",
"(",
"options",
",",
"%i[",
"symbolize_keys",
"add_defaults",
"select",
"transform",
"table",
"format",
"]",
")",
")",
"end"
] | Constructs melt arguments from options hash | [
"Constructs",
"melt",
"arguments",
"from",
"options",
"hash"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/renderer.rb#L54-L66 |
5,076 | darbylabs/magma | lib/magma/renderer.rb | Magma.Renderer.render! | def render!
cmd = melt melt_args(options.merge(outfile: outfile)).join(' ')
puts "Run: #{cmd}"
puts
run(cmd) do |_stdin, _stdout, stderr|
stderr.each("\r") do |line|
STDOUT.write "\r#{line}"
end
end
end | ruby | def render!
cmd = melt melt_args(options.merge(outfile: outfile)).join(' ')
puts "Run: #{cmd}"
puts
run(cmd) do |_stdin, _stdout, stderr|
stderr.each("\r") do |line|
STDOUT.write "\r#{line}"
end
end
end | [
"def",
"render!",
"cmd",
"=",
"melt",
"melt_args",
"(",
"options",
".",
"merge",
"(",
"outfile",
":",
"outfile",
")",
")",
".",
"join",
"(",
"' '",
")",
"puts",
"\"Run: #{cmd}\"",
"puts",
"run",
"(",
"cmd",
")",
"do",
"|",
"_stdin",
",",
"_stdout",
",",
"stderr",
"|",
"stderr",
".",
"each",
"(",
"\"\\r\"",
")",
"do",
"|",
"line",
"|",
"STDOUT",
".",
"write",
"\"\\r#{line}\"",
"end",
"end",
"end"
] | Renders the project | [
"Renders",
"the",
"project"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/renderer.rb#L69-L79 |
5,077 | darbylabs/magma | lib/magma/renderer.rb | Magma.Renderer.select | def select(options)
# Clone original
options = options.clone
# Handle related options
options.delete(:real_time) unless options.delete(:enable_real_time)
# Reject
options.select do |key, value|
!value.nil? && %i[
format
hls_list_size
real_time
length
preset
size
start_number
vcodec
].include?(key)
end
end | ruby | def select(options)
# Clone original
options = options.clone
# Handle related options
options.delete(:real_time) unless options.delete(:enable_real_time)
# Reject
options.select do |key, value|
!value.nil? && %i[
format
hls_list_size
real_time
length
preset
size
start_number
vcodec
].include?(key)
end
end | [
"def",
"select",
"(",
"options",
")",
"# Clone original",
"options",
"=",
"options",
".",
"clone",
"# Handle related options",
"options",
".",
"delete",
"(",
":real_time",
")",
"unless",
"options",
".",
"delete",
"(",
":enable_real_time",
")",
"# Reject",
"options",
".",
"select",
"do",
"|",
"key",
",",
"value",
"|",
"!",
"value",
".",
"nil?",
"&&",
"%i[",
"format",
"hls_list_size",
"real_time",
"length",
"preset",
"size",
"start_number",
"vcodec",
"]",
".",
"include?",
"(",
"key",
")",
"end",
"end"
] | Selects certain options | [
"Selects",
"certain",
"options"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/renderer.rb#L82-L102 |
5,078 | darbylabs/magma | lib/magma/renderer.rb | Magma.Renderer.table | def table(options)
lpadding = options.keys.max_by(&:length).length + 2
rpadding = options.values.max_by { |v| v.to_s.length }.to_s.length
puts 'PROPERTY'.ljust(lpadding) + 'VALUE'
puts '=' * (lpadding + rpadding)
options.keys.sort.each do |key|
puts key.to_s.ljust(lpadding) + options[key].to_s
end
puts
options
end | ruby | def table(options)
lpadding = options.keys.max_by(&:length).length + 2
rpadding = options.values.max_by { |v| v.to_s.length }.to_s.length
puts 'PROPERTY'.ljust(lpadding) + 'VALUE'
puts '=' * (lpadding + rpadding)
options.keys.sort.each do |key|
puts key.to_s.ljust(lpadding) + options[key].to_s
end
puts
options
end | [
"def",
"table",
"(",
"options",
")",
"lpadding",
"=",
"options",
".",
"keys",
".",
"max_by",
"(",
":length",
")",
".",
"length",
"+",
"2",
"rpadding",
"=",
"options",
".",
"values",
".",
"max_by",
"{",
"|",
"v",
"|",
"v",
".",
"to_s",
".",
"length",
"}",
".",
"to_s",
".",
"length",
"puts",
"'PROPERTY'",
".",
"ljust",
"(",
"lpadding",
")",
"+",
"'VALUE'",
"puts",
"'='",
"*",
"(",
"lpadding",
"+",
"rpadding",
")",
"options",
".",
"keys",
".",
"sort",
".",
"each",
"do",
"|",
"key",
"|",
"puts",
"key",
".",
"to_s",
".",
"ljust",
"(",
"lpadding",
")",
"+",
"options",
"[",
"key",
"]",
".",
"to_s",
"end",
"puts",
"options",
"end"
] | Prints a table and passes through the options hash | [
"Prints",
"a",
"table",
"and",
"passes",
"through",
"the",
"options",
"hash"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/renderer.rb#L105-L115 |
5,079 | darbylabs/magma | lib/magma/renderer.rb | Magma.Renderer.transform | def transform(options)
options.map do |key, value|
[key, ({
real_time: ->(x) { "-#{x}" },
}[key] || proc { |x| x }).call(value)]
end.to_h
end | ruby | def transform(options)
options.map do |key, value|
[key, ({
real_time: ->(x) { "-#{x}" },
}[key] || proc { |x| x }).call(value)]
end.to_h
end | [
"def",
"transform",
"(",
"options",
")",
"options",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"[",
"key",
",",
"(",
"{",
"real_time",
":",
"->",
"(",
"x",
")",
"{",
"\"-#{x}\"",
"}",
",",
"}",
"[",
"key",
"]",
"||",
"proc",
"{",
"|",
"x",
"|",
"x",
"}",
")",
".",
"call",
"(",
"value",
")",
"]",
"end",
".",
"to_h",
"end"
] | Transforms certain options values | [
"Transforms",
"certain",
"options",
"values"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/renderer.rb#L118-L124 |
5,080 | ronyv89/skydrive | lib/skydrive/collection.rb | Skydrive.Collection.items | def items
@items = []
@data.each do |object_data|
if object_data["type"]
@items << "Skydrive::#{object_data["type"].capitalize}".constantize.new(client, object_data)
elsif object_data["id"].match /^comment\..+/
@items << Skydrive::Comment.new(client, object_data)
end
end
@items
end | ruby | def items
@items = []
@data.each do |object_data|
if object_data["type"]
@items << "Skydrive::#{object_data["type"].capitalize}".constantize.new(client, object_data)
elsif object_data["id"].match /^comment\..+/
@items << Skydrive::Comment.new(client, object_data)
end
end
@items
end | [
"def",
"items",
"@items",
"=",
"[",
"]",
"@data",
".",
"each",
"do",
"|",
"object_data",
"|",
"if",
"object_data",
"[",
"\"type\"",
"]",
"@items",
"<<",
"\"Skydrive::#{object_data[\"type\"].capitalize}\"",
".",
"constantize",
".",
"new",
"(",
"client",
",",
"object_data",
")",
"elsif",
"object_data",
"[",
"\"id\"",
"]",
".",
"match",
"/",
"\\.",
"/",
"@items",
"<<",
"Skydrive",
"::",
"Comment",
".",
"new",
"(",
"client",
",",
"object_data",
")",
"end",
"end",
"@items",
"end"
] | Array of items in the collection
@return [Array] | [
"Array",
"of",
"items",
"in",
"the",
"collection"
] | 6cf7b692f64c6f00a81bc7ca6fffca3020244072 | https://github.com/ronyv89/skydrive/blob/6cf7b692f64c6f00a81bc7ca6fffca3020244072/lib/skydrive/collection.rb#L19-L29 |
5,081 | bdurand/json_record | lib/json_record/attribute_methods.rb | JsonRecord.AttributeMethods.read_attribute | def read_attribute (field, context)
if field.multivalued?
arr = json_attributes[field.name]
unless arr
arr = EmbeddedDocumentArray.new(field.type, context)
json_attributes[field.name] = arr
end
return arr
else
val = json_attributes[field.name]
if val.nil? and !field.default.nil?
val = field.default.dup rescue field.default
json_attributes[field.name] = val
end
return val
end
end | ruby | def read_attribute (field, context)
if field.multivalued?
arr = json_attributes[field.name]
unless arr
arr = EmbeddedDocumentArray.new(field.type, context)
json_attributes[field.name] = arr
end
return arr
else
val = json_attributes[field.name]
if val.nil? and !field.default.nil?
val = field.default.dup rescue field.default
json_attributes[field.name] = val
end
return val
end
end | [
"def",
"read_attribute",
"(",
"field",
",",
"context",
")",
"if",
"field",
".",
"multivalued?",
"arr",
"=",
"json_attributes",
"[",
"field",
".",
"name",
"]",
"unless",
"arr",
"arr",
"=",
"EmbeddedDocumentArray",
".",
"new",
"(",
"field",
".",
"type",
",",
"context",
")",
"json_attributes",
"[",
"field",
".",
"name",
"]",
"=",
"arr",
"end",
"return",
"arr",
"else",
"val",
"=",
"json_attributes",
"[",
"field",
".",
"name",
"]",
"if",
"val",
".",
"nil?",
"and",
"!",
"field",
".",
"default",
".",
"nil?",
"val",
"=",
"field",
".",
"default",
".",
"dup",
"rescue",
"field",
".",
"default",
"json_attributes",
"[",
"field",
".",
"name",
"]",
"=",
"val",
"end",
"return",
"val",
"end",
"end"
] | Read a field. The field param must be a FieldDefinition and the context should be the record
which is being read from. | [
"Read",
"a",
"field",
".",
"The",
"field",
"param",
"must",
"be",
"a",
"FieldDefinition",
"and",
"the",
"context",
"should",
"be",
"the",
"record",
"which",
"is",
"being",
"read",
"from",
"."
] | 463f4719d9618f6d2406c0aab6028e0156f7c775 | https://github.com/bdurand/json_record/blob/463f4719d9618f6d2406c0aab6028e0156f7c775/lib/json_record/attribute_methods.rb#L6-L22 |
5,082 | bdurand/json_record | lib/json_record/attribute_methods.rb | JsonRecord.AttributeMethods.write_attribute | def write_attribute (field, val, context)
if field.multivalued?
val = val.values if val.is_a?(Hash)
json_attributes[field.name] = EmbeddedDocumentArray.new(field.type, context, val)
else
old_value = read_attribute(field, context)
converted_value = field.convert(val)
converted_value.parent = context if converted_value.is_a?(EmbeddedDocument)
unless old_value == converted_value
unless field.type.include?(EmbeddedDocument) or Thread.current[:do_not_track_json_field_changes]
changes = changed_attributes
if changes.include?(field.name)
changes.delete(field.name) if converted_value == changes[field.name]
else
old_value = (old_value.clone rescue old_value) unless old_value.nil? || old_value.is_a?(Numeric) || old_value.is_a?(Symbol) || old_value.is_a?(TrueClass) || old_value.is_a?(FalseClass)
changes[field.name] = old_value
end
end
unless converted_value.nil?
json_attributes[field.name] = converted_value
else
json_attributes.delete(field.name)
end
end
context.json_attributes_before_type_cast[field.name] = val
end
return val
end | ruby | def write_attribute (field, val, context)
if field.multivalued?
val = val.values if val.is_a?(Hash)
json_attributes[field.name] = EmbeddedDocumentArray.new(field.type, context, val)
else
old_value = read_attribute(field, context)
converted_value = field.convert(val)
converted_value.parent = context if converted_value.is_a?(EmbeddedDocument)
unless old_value == converted_value
unless field.type.include?(EmbeddedDocument) or Thread.current[:do_not_track_json_field_changes]
changes = changed_attributes
if changes.include?(field.name)
changes.delete(field.name) if converted_value == changes[field.name]
else
old_value = (old_value.clone rescue old_value) unless old_value.nil? || old_value.is_a?(Numeric) || old_value.is_a?(Symbol) || old_value.is_a?(TrueClass) || old_value.is_a?(FalseClass)
changes[field.name] = old_value
end
end
unless converted_value.nil?
json_attributes[field.name] = converted_value
else
json_attributes.delete(field.name)
end
end
context.json_attributes_before_type_cast[field.name] = val
end
return val
end | [
"def",
"write_attribute",
"(",
"field",
",",
"val",
",",
"context",
")",
"if",
"field",
".",
"multivalued?",
"val",
"=",
"val",
".",
"values",
"if",
"val",
".",
"is_a?",
"(",
"Hash",
")",
"json_attributes",
"[",
"field",
".",
"name",
"]",
"=",
"EmbeddedDocumentArray",
".",
"new",
"(",
"field",
".",
"type",
",",
"context",
",",
"val",
")",
"else",
"old_value",
"=",
"read_attribute",
"(",
"field",
",",
"context",
")",
"converted_value",
"=",
"field",
".",
"convert",
"(",
"val",
")",
"converted_value",
".",
"parent",
"=",
"context",
"if",
"converted_value",
".",
"is_a?",
"(",
"EmbeddedDocument",
")",
"unless",
"old_value",
"==",
"converted_value",
"unless",
"field",
".",
"type",
".",
"include?",
"(",
"EmbeddedDocument",
")",
"or",
"Thread",
".",
"current",
"[",
":do_not_track_json_field_changes",
"]",
"changes",
"=",
"changed_attributes",
"if",
"changes",
".",
"include?",
"(",
"field",
".",
"name",
")",
"changes",
".",
"delete",
"(",
"field",
".",
"name",
")",
"if",
"converted_value",
"==",
"changes",
"[",
"field",
".",
"name",
"]",
"else",
"old_value",
"=",
"(",
"old_value",
".",
"clone",
"rescue",
"old_value",
")",
"unless",
"old_value",
".",
"nil?",
"||",
"old_value",
".",
"is_a?",
"(",
"Numeric",
")",
"||",
"old_value",
".",
"is_a?",
"(",
"Symbol",
")",
"||",
"old_value",
".",
"is_a?",
"(",
"TrueClass",
")",
"||",
"old_value",
".",
"is_a?",
"(",
"FalseClass",
")",
"changes",
"[",
"field",
".",
"name",
"]",
"=",
"old_value",
"end",
"end",
"unless",
"converted_value",
".",
"nil?",
"json_attributes",
"[",
"field",
".",
"name",
"]",
"=",
"converted_value",
"else",
"json_attributes",
".",
"delete",
"(",
"field",
".",
"name",
")",
"end",
"end",
"context",
".",
"json_attributes_before_type_cast",
"[",
"field",
".",
"name",
"]",
"=",
"val",
"end",
"return",
"val",
"end"
] | Write a field. The field param must be a FieldDefinition and the context should be the record
which is being read from. | [
"Write",
"a",
"field",
".",
"The",
"field",
"param",
"must",
"be",
"a",
"FieldDefinition",
"and",
"the",
"context",
"should",
"be",
"the",
"record",
"which",
"is",
"being",
"read",
"from",
"."
] | 463f4719d9618f6d2406c0aab6028e0156f7c775 | https://github.com/bdurand/json_record/blob/463f4719d9618f6d2406c0aab6028e0156f7c775/lib/json_record/attribute_methods.rb#L26-L53 |
5,083 | jwoertink/tourets | lib/tourets/property.rb | TouRETS.Property.method_missing | def method_missing(method_name, *args, &block)
mapped_key = key_map[method_name.to_sym]
if attributes.has_key?(mapped_key)
attributes[mapped_key]
else
super
end
end | ruby | def method_missing(method_name, *args, &block)
mapped_key = key_map[method_name.to_sym]
if attributes.has_key?(mapped_key)
attributes[mapped_key]
else
super
end
end | [
"def",
"method_missing",
"(",
"method_name",
",",
"*",
"args",
",",
"&",
"block",
")",
"mapped_key",
"=",
"key_map",
"[",
"method_name",
".",
"to_sym",
"]",
"if",
"attributes",
".",
"has_key?",
"(",
"mapped_key",
")",
"attributes",
"[",
"mapped_key",
"]",
"else",
"super",
"end",
"end"
] | Look for one of the mapped keys, and return the value or throw method missing error. | [
"Look",
"for",
"one",
"of",
"the",
"mapped",
"keys",
"and",
"return",
"the",
"value",
"or",
"throw",
"method",
"missing",
"error",
"."
] | 1cf5b5b061702846d38a261ad256f1641d2553c1 | https://github.com/jwoertink/tourets/blob/1cf5b5b061702846d38a261ad256f1641d2553c1/lib/tourets/property.rb#L68-L75 |
5,084 | Kuniri/kuniri | lib/kuniri/language/container_data/structured_and_oo/file_element_data.rb | Languages.FileElementData.add_global_variable | def add_global_variable(*pVariable)
pVariable.flatten.each do |element|
next unless element.is_a?(Languages::VariableGlobalData)
@global_variables.push(element)
end
end | ruby | def add_global_variable(*pVariable)
pVariable.flatten.each do |element|
next unless element.is_a?(Languages::VariableGlobalData)
@global_variables.push(element)
end
end | [
"def",
"add_global_variable",
"(",
"*",
"pVariable",
")",
"pVariable",
".",
"flatten",
".",
"each",
"do",
"|",
"element",
"|",
"next",
"unless",
"element",
".",
"is_a?",
"(",
"Languages",
"::",
"VariableGlobalData",
")",
"@global_variables",
".",
"push",
"(",
"element",
")",
"end",
"end"
] | Add global variable inside file.
@param pVariable A single VariableGlobalData object or list to be added. | [
"Add",
"global",
"variable",
"inside",
"file",
"."
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/container_data/structured_and_oo/file_element_data.rb#L48-L53 |
5,085 | fuminori-ido/edgarj | app/models/edgarj/user_group.rb | Edgarj.UserGroup.permitted? | def permitted?(model_name, requested_flags = 0)
return false if self.kind != Kind::ROLE
return true if admin?
p = self.model_permissions.find_by_model(model_name)
if requested_flags == 0
p
else
p && p.permitted?(requested_flags)
end
end | ruby | def permitted?(model_name, requested_flags = 0)
return false if self.kind != Kind::ROLE
return true if admin?
p = self.model_permissions.find_by_model(model_name)
if requested_flags == 0
p
else
p && p.permitted?(requested_flags)
end
end | [
"def",
"permitted?",
"(",
"model_name",
",",
"requested_flags",
"=",
"0",
")",
"return",
"false",
"if",
"self",
".",
"kind",
"!=",
"Kind",
"::",
"ROLE",
"return",
"true",
"if",
"admin?",
"p",
"=",
"self",
".",
"model_permissions",
".",
"find_by_model",
"(",
"model_name",
")",
"if",
"requested_flags",
"==",
"0",
"p",
"else",
"p",
"&&",
"p",
".",
"permitted?",
"(",
"requested_flags",
")",
"end",
"end"
] | return true if the role has enough permission on the controller.
If user role is 'admin' then all operations are permitted.
Always return false if the user-group is not ROLE.
if requested_flags is omitted, just checks existence of
model_permissions and doesn't check CRUD level. | [
"return",
"true",
"if",
"the",
"role",
"has",
"enough",
"permission",
"on",
"the",
"controller",
"."
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/models/edgarj/user_group.rb#L41-L51 |
5,086 | loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.Auth.auth | def auth
# entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth"
# payload
payload = {
app: {
name: @client.app_info[:name],
version: @client.app_info[:version],
vendor: @client.app_info[:vendor],
id: @client.app_info[:id]
},
permissions: @client.app_info[:permissions]
}
# api call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'})
req.body = payload.to_json
res = http.request(req)
# return's parser
if res.code == "200"
response = JSON.parse(res.body)
# save it in conf.json
conf = response.dup
File.open(@client.app_info[:conf_path], "w") { |f| f << JSON.pretty_generate(conf) }
else
# puts "ERROR #{res.code}: #{res.message}"
response = nil
end
# return
response
end | ruby | def auth
# entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth"
# payload
payload = {
app: {
name: @client.app_info[:name],
version: @client.app_info[:version],
vendor: @client.app_info[:vendor],
id: @client.app_info[:id]
},
permissions: @client.app_info[:permissions]
}
# api call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'})
req.body = payload.to_json
res = http.request(req)
# return's parser
if res.code == "200"
response = JSON.parse(res.body)
# save it in conf.json
conf = response.dup
File.open(@client.app_info[:conf_path], "w") { |f| f << JSON.pretty_generate(conf) }
else
# puts "ERROR #{res.code}: #{res.message}"
response = nil
end
# return
response
end | [
"def",
"auth",
"# entry point",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/auth\"",
"# payload",
"payload",
"=",
"{",
"app",
":",
"{",
"name",
":",
"@client",
".",
"app_info",
"[",
":name",
"]",
",",
"version",
":",
"@client",
".",
"app_info",
"[",
":version",
"]",
",",
"vendor",
":",
"@client",
".",
"app_info",
"[",
":vendor",
"]",
",",
"id",
":",
"@client",
".",
"app_info",
"[",
":id",
"]",
"}",
",",
"permissions",
":",
"@client",
".",
"app_info",
"[",
":permissions",
"]",
"}",
"# api call",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"req",
".",
"body",
"=",
"payload",
".",
"to_json",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"# return's parser",
"if",
"res",
".",
"code",
"==",
"\"200\"",
"response",
"=",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"# save it in conf.json",
"conf",
"=",
"response",
".",
"dup",
"File",
".",
"open",
"(",
"@client",
".",
"app_info",
"[",
":conf_path",
"]",
",",
"\"w\"",
")",
"{",
"|",
"f",
"|",
"f",
"<<",
"JSON",
".",
"pretty_generate",
"(",
"conf",
")",
"}",
"else",
"# puts \"ERROR #{res.code}: #{res.message}\"",
"response",
"=",
"nil",
"end",
"# return",
"response",
"end"
] | Any application that wants to access API endpoints that require authorised
access must receive an authorisation token from SAFE Launcher.
Reading public data using the DNS API does not require an authorisation
token. All other API endpoints require authorised access.
The application will initiate the authorisation request with information
about the application itself and the required permissions. SAFE Launcher
will then display a prompt to the user with the application information
along with the requested permissions. Once the user authorises the
request, the application will receive an authorisation token. If the user
denies the request, the application will receive an unauthorised error
response.
Usage: my_client.auth.auth(["SAFE_DRIVE_ACCESS"])
Fail: nil
Success: {token: "1222", "permissions": []}
Reference: https://maidsafe.readme.io/docs/auth | [
"Any",
"application",
"that",
"wants",
"to",
"access",
"API",
"endpoints",
"that",
"require",
"authorised",
"access",
"must",
"receive",
"an",
"authorisation",
"token",
"from",
"SAFE",
"Launcher",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L105-L141 |
5,087 | loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.Auth.is_token_valid | def is_token_valid
# entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth"
# api call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Get.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_token()}"
})
res = http.request(req)
res.code == "200"
end | ruby | def is_token_valid
# entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth"
# api call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Get.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_token()}"
})
res = http.request(req)
res.code == "200"
end | [
"def",
"is_token_valid",
"# entry point",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/auth\"",
"# api call",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_token()}\"",
"}",
")",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"end"
] | Check whether the authorisation token obtained from SAFE Launcher is still
valid.
Usage: my_client.auth.is_token_valid()
Fail: false
Success: true
Reference: https://maidsafe.readme.io/docs/is-token-valid | [
"Check",
"whether",
"the",
"authorisation",
"token",
"obtained",
"from",
"SAFE",
"Launcher",
"is",
"still",
"valid",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L154-L166 |
5,088 | loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.Auth.revoke_token | def revoke_token
# entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth"
# api call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Delete.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}"
})
res = http.request(req)
res.code == "200"
end | ruby | def revoke_token
# entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth"
# api call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Delete.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}"
})
res = http.request(req)
res.code == "200"
end | [
"def",
"revoke_token",
"# entry point",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/auth\"",
"# api call",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Delete",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
"}",
")",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"end"
] | Revoke the authorisation token obtained from SAFE Launcher.
Usage: my_client.auth.revoke_token()
Fail: false
Success: true
Reference: https://maidsafe.readme.io/docs/revoke-token | [
"Revoke",
"the",
"authorisation",
"token",
"obtained",
"from",
"SAFE",
"Launcher",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L178-L190 |
5,089 | loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.create_directory | def create_directory(dir_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
options[:is_private] = true if ! options.has_key?(:is_private)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}"
# Payload
payload = {
isPrivate: options[:is_private],
}
# Optional
payload["metadata"] = Base64.strict_encode64(options[:meta]) if options.has_key?(:meta)
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
'Content-Type' => 'application/json'
})
req.body = payload.to_json
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | ruby | def create_directory(dir_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
options[:is_private] = true if ! options.has_key?(:is_private)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}"
# Payload
payload = {
isPrivate: options[:is_private],
}
# Optional
payload["metadata"] = Base64.strict_encode64(options[:meta]) if options.has_key?(:meta)
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
'Content-Type' => 'application/json'
})
req.body = payload.to_json
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | [
"def",
"create_directory",
"(",
"dir_path",
",",
"options",
"=",
"{",
"}",
")",
"# Default values",
"options",
"[",
":root_path",
"]",
"=",
"'app'",
"if",
"!",
"options",
".",
"has_key?",
"(",
":root_path",
")",
"options",
"[",
":is_private",
"]",
"=",
"true",
"if",
"!",
"options",
".",
"has_key?",
"(",
":is_private",
")",
"# Entry point",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}\"",
"# Payload",
"payload",
"=",
"{",
"isPrivate",
":",
"options",
"[",
":is_private",
"]",
",",
"}",
"# Optional",
"payload",
"[",
"\"metadata\"",
"]",
"=",
"Base64",
".",
"strict_encode64",
"(",
"options",
"[",
":meta",
"]",
")",
"if",
"options",
".",
"has_key?",
"(",
":meta",
")",
"# API call",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"req",
".",
"body",
"=",
"payload",
".",
"to_json",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"true",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Create a public or private directory either in the application's root
directory or in SAFE Drive.
Only authorised requests can create a directory.
Usage: my_client.nfs.create_directory("/photos")
Adv.Usage: my_client.nfs.create_directory("/photos", meta: "some meta", root_path: 'drive', is_private: true)
Fail: {"errorCode"=>-505, "description"=>"NfsError::FileAlreadyExistsWithSameName"}
Success: true
Reference: https://maidsafe.readme.io/docs/nfs-create-directory | [
"Create",
"a",
"public",
"or",
"private",
"directory",
"either",
"in",
"the",
"application",
"s",
"root",
"directory",
"or",
"in",
"SAFE",
"Drive",
".",
"Only",
"authorised",
"requests",
"can",
"create",
"a",
"directory",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L211-L237 |
5,090 | loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.get_directory | def get_directory(dir_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Get.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
})
res = http.request(req)
JSON.parse(res.body)
end | ruby | def get_directory(dir_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Get.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
})
res = http.request(req)
JSON.parse(res.body)
end | [
"def",
"get_directory",
"(",
"dir_path",
",",
"options",
"=",
"{",
"}",
")",
"# Default values",
"options",
"[",
":root_path",
"]",
"=",
"'app'",
"if",
"!",
"options",
".",
"has_key?",
"(",
":root_path",
")",
"# Entry point",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}\"",
"# API call",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"}",
")",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Fetch a directory.
Only authorised requests can invoke this API.
Usage: my_client.nfs.get_directory("/photos", root_path: 'drive')
Fail: {"errorCode"=>-1502, "description"=>"FfiError::PathNotFound"}
Success: {"info"=> {"name"=> "my_dir", ...}, ...}
Reference: https://maidsafe.readme.io/docs/nfs-get-directory | [
"Fetch",
"a",
"directory",
".",
"Only",
"authorised",
"requests",
"can",
"invoke",
"this",
"API",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L261-L276 |
5,091 | loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.create_file | def create_file(file_path, contents, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
contents ||= ""
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
}
headers["Metadata"] = Base64.strict_encode64(options[:meta]) if options.has_key?(:meta)
headers["Content-Type"] = options[:content_type] || 'text/plain'
headers["Content-Length"] = contents.size.to_s
req = Net::HTTP::Post.new(uri.path, headers)
req.body = contents
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | ruby | def create_file(file_path, contents, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
contents ||= ""
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
}
headers["Metadata"] = Base64.strict_encode64(options[:meta]) if options.has_key?(:meta)
headers["Content-Type"] = options[:content_type] || 'text/plain'
headers["Content-Length"] = contents.size.to_s
req = Net::HTTP::Post.new(uri.path, headers)
req.body = contents
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | [
"def",
"create_file",
"(",
"file_path",
",",
"contents",
",",
"options",
"=",
"{",
"}",
")",
"# Default values",
"options",
"[",
":root_path",
"]",
"=",
"'app'",
"if",
"!",
"options",
".",
"has_key?",
"(",
":root_path",
")",
"contents",
"||=",
"\"\"",
"# Entry point",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}\"",
"# API call",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"headers",
"=",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"}",
"headers",
"[",
"\"Metadata\"",
"]",
"=",
"Base64",
".",
"strict_encode64",
"(",
"options",
"[",
":meta",
"]",
")",
"if",
"options",
".",
"has_key?",
"(",
":meta",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"options",
"[",
":content_type",
"]",
"||",
"'text/plain'",
"headers",
"[",
"\"Content-Length\"",
"]",
"=",
"contents",
".",
"size",
".",
"to_s",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"headers",
")",
"req",
".",
"body",
"=",
"contents",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"true",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Create a file.
Only authorised requests can invoke the API.
Usage: my_client.nfs.create_file("/docs/hello.txt", "Hello World!")
Adv.Usage: my_client.nfs.create_file("/docs/hello.txt", meta: "some meta", root_path: "app", content_type: "text/plain")
Fail: {"errorCode"=>-505, "description"=>"NfsError::FileAlreadyExistsWithSameName"}
Success: true
Reference: https://maidsafe.readme.io/docs/nfsfile | [
"Create",
"a",
"file",
".",
"Only",
"authorised",
"requests",
"can",
"invoke",
"the",
"API",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L360-L381 |
5,092 | loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.get_file_meta | def get_file_meta(file_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
}
req = Net::HTTP::Head.new(uri.path, headers)
res = http.request(req)
res_headers = {}
res.response.each_header {|k,v| res_headers[k] = v}
res_headers["metadata"] = Base64.strict_decode64(res_headers["metadata"]) if res_headers.has_key?("metadata")
res.code == "200" ? {"headers" => res_headers, "body" => res.body} : JSON.parse(res.body)
end | ruby | def get_file_meta(file_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
}
req = Net::HTTP::Head.new(uri.path, headers)
res = http.request(req)
res_headers = {}
res.response.each_header {|k,v| res_headers[k] = v}
res_headers["metadata"] = Base64.strict_decode64(res_headers["metadata"]) if res_headers.has_key?("metadata")
res.code == "200" ? {"headers" => res_headers, "body" => res.body} : JSON.parse(res.body)
end | [
"def",
"get_file_meta",
"(",
"file_path",
",",
"options",
"=",
"{",
"}",
")",
"# Default values",
"options",
"[",
":root_path",
"]",
"=",
"'app'",
"if",
"!",
"options",
".",
"has_key?",
"(",
":root_path",
")",
"# Entry point",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}\"",
"# API call",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"headers",
"=",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"}",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Head",
".",
"new",
"(",
"uri",
".",
"path",
",",
"headers",
")",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res_headers",
"=",
"{",
"}",
"res",
".",
"response",
".",
"each_header",
"{",
"|",
"k",
",",
"v",
"|",
"res_headers",
"[",
"k",
"]",
"=",
"v",
"}",
"res_headers",
"[",
"\"metadata\"",
"]",
"=",
"Base64",
".",
"strict_decode64",
"(",
"res_headers",
"[",
"\"metadata\"",
"]",
")",
"if",
"res_headers",
".",
"has_key?",
"(",
"\"metadata\"",
")",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"{",
"\"headers\"",
"=>",
"res_headers",
",",
"\"body\"",
"=>",
"res",
".",
"body",
"}",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Fetch the metadata of a file.
Only authorised requests can invoke the API.
Usage: my_client.nfs.get_file_meta("/docs/hello.txt")
Adv.Usage: my_client.nfs.get_file_meta("/docs/hello.txt", root_path: "app")
Fail: {"errorCode"=>-505, "description"=>"NfsError::FileAlreadyExistsWithSameName"}
Success:
Reference: https://maidsafe.readme.io/docs/nfs-get-file-metadata | [
"Fetch",
"the",
"metadata",
"of",
"a",
"file",
".",
"Only",
"authorised",
"requests",
"can",
"invoke",
"the",
"API",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L395-L414 |
5,093 | loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.get_file | def get_file(file_path, options = {})
# Default values
options[:offset] = 0 if ! options.has_key?(:offset)
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}?"
# Query params
query = []
query << "offset=#{options[:offset]}"
query << "length=#{options[:length]}" if options.has_key?(:length) # length is optional
url = "#{url}#{query.join('&')}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
}
headers["Range"] = options[:range] if options.has_key?(:range)
req = Net::HTTP::Get.new(uri.path, headers)
res = http.request(req)
res_headers = {}
res.response.each_header {|k,v| res_headers[k] = v}
res.code == "200" ? {"headers" => res_headers, "body" => res.body} : JSON.parse(res.body)
end | ruby | def get_file(file_path, options = {})
# Default values
options[:offset] = 0 if ! options.has_key?(:offset)
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}?"
# Query params
query = []
query << "offset=#{options[:offset]}"
query << "length=#{options[:length]}" if options.has_key?(:length) # length is optional
url = "#{url}#{query.join('&')}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
}
headers["Range"] = options[:range] if options.has_key?(:range)
req = Net::HTTP::Get.new(uri.path, headers)
res = http.request(req)
res_headers = {}
res.response.each_header {|k,v| res_headers[k] = v}
res.code == "200" ? {"headers" => res_headers, "body" => res.body} : JSON.parse(res.body)
end | [
"def",
"get_file",
"(",
"file_path",
",",
"options",
"=",
"{",
"}",
")",
"# Default values",
"options",
"[",
":offset",
"]",
"=",
"0",
"if",
"!",
"options",
".",
"has_key?",
"(",
":offset",
")",
"options",
"[",
":root_path",
"]",
"=",
"'app'",
"if",
"!",
"options",
".",
"has_key?",
"(",
":root_path",
")",
"# Entry point",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}?\"",
"# Query params",
"query",
"=",
"[",
"]",
"query",
"<<",
"\"offset=#{options[:offset]}\"",
"query",
"<<",
"\"length=#{options[:length]}\"",
"if",
"options",
".",
"has_key?",
"(",
":length",
")",
"# length is optional",
"url",
"=",
"\"#{url}#{query.join('&')}\"",
"# API call",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"headers",
"=",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"}",
"headers",
"[",
"\"Range\"",
"]",
"=",
"options",
"[",
":range",
"]",
"if",
"options",
".",
"has_key?",
"(",
":range",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
".",
"path",
",",
"headers",
")",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res_headers",
"=",
"{",
"}",
"res",
".",
"response",
".",
"each_header",
"{",
"|",
"k",
",",
"v",
"|",
"res_headers",
"[",
"k",
"]",
"=",
"v",
"}",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"{",
"\"headers\"",
"=>",
"res_headers",
",",
"\"body\"",
"=>",
"res",
".",
"body",
"}",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Read a file.
The file can be streamed in chunks and also fetched as partial content
based on the range header specified in the request.
Only authorised requests can invoke the API.
Usage: my_client.nfs.get_file("/docs/hello.txt")
Adv.Usage: my_client.nfs.get_file("/docs/hello.txt", range: "bytes 0-1000", root_path: "app")
Fail: {"errorCode"=>-1503, "description"=>"FfiError::InvalidPath"}
Success: {"headers"=>{"x-powered-by"=>"Express", "content-range"=>"bytes 0-4/4", "accept-ranges"=>"bytes", "content-length"=>"4", "created-on"=>"2016-08-14T12:51:18.924Z", "last-modified"=>"2016-08-14T12:51:18.935Z", "content-type"=>"text/plain", "date"=>"Sun, 14 Aug 2016 13:30:07 GMT", "connection"=>"close"}, "body"=>"Test"}
Reference: https://maidsafe.readme.io/docs/nfs-get-file | [
"Read",
"a",
"file",
".",
"The",
"file",
"can",
"be",
"streamed",
"in",
"chunks",
"and",
"also",
"fetched",
"as",
"partial",
"content",
"based",
"on",
"the",
"range",
"header",
"specified",
"in",
"the",
"request",
".",
"Only",
"authorised",
"requests",
"can",
"invoke",
"the",
"API",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L430-L456 |
5,094 | loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.move_file | def move_file(src_root_path, src_path, dst_root_path, dst_path, action = 'move')
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/movefile"
# Payload
payload = {}
payload["srcRootPath"] = src_root_path # 'app' or 'drive'
payload["srcPath"] = src_path
payload["destRootPath"] = dst_root_path # 'app' or 'drive'
payload["destPath"] = dst_path
payload["action"] = action
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
'Content-Type' => 'application/json'
})
req.body = payload.to_json
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | ruby | def move_file(src_root_path, src_path, dst_root_path, dst_path, action = 'move')
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/movefile"
# Payload
payload = {}
payload["srcRootPath"] = src_root_path # 'app' or 'drive'
payload["srcPath"] = src_path
payload["destRootPath"] = dst_root_path # 'app' or 'drive'
payload["destPath"] = dst_path
payload["action"] = action
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
'Content-Type' => 'application/json'
})
req.body = payload.to_json
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | [
"def",
"move_file",
"(",
"src_root_path",
",",
"src_path",
",",
"dst_root_path",
",",
"dst_path",
",",
"action",
"=",
"'move'",
")",
"# Entry point",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/movefile\"",
"# Payload",
"payload",
"=",
"{",
"}",
"payload",
"[",
"\"srcRootPath\"",
"]",
"=",
"src_root_path",
"# 'app' or 'drive'",
"payload",
"[",
"\"srcPath\"",
"]",
"=",
"src_path",
"payload",
"[",
"\"destRootPath\"",
"]",
"=",
"dst_root_path",
"# 'app' or 'drive'",
"payload",
"[",
"\"destPath\"",
"]",
"=",
"dst_path",
"payload",
"[",
"\"action\"",
"]",
"=",
"action",
"# API call",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"req",
".",
"body",
"=",
"payload",
".",
"to_json",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"true",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Move or copy a file | [
"Move",
"or",
"copy",
"a",
"file"
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L502-L524 |
5,095 | loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.delete_file | def delete_file(file_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Delete.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
})
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | ruby | def delete_file(file_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Delete.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
})
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | [
"def",
"delete_file",
"(",
"file_path",
",",
"options",
"=",
"{",
"}",
")",
"# Default values",
"options",
"[",
":root_path",
"]",
"=",
"'app'",
"if",
"!",
"options",
".",
"has_key?",
"(",
":root_path",
")",
"# Entry point",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}\"",
"# API call",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Delete",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"}",
")",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"true",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Delete a file.
Only authorised requests can invoke the API.
Usage: my_client.nfs.delete_file("/docs/hello.txt")
Adv.Usage: my_client.nfs.delete_file("/docs/hello.txt", root_path: "app")
Fail: {"errorCode"=>-1503, "description"=>"FfiError::InvalidPath"}
Success: true
Reference: https://maidsafe.readme.io/docs/nfs-delete-file | [
"Delete",
"a",
"file",
".",
"Only",
"authorised",
"requests",
"can",
"invoke",
"the",
"API",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L537-L552 |
5,096 | loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.DNS.register_service | def register_service(long_name, service_name, service_home_dir_path, options = {})
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/dns"
# Payload
payload = {
longName: long_name,
serviceName: service_name,
rootPath: 'app',
serviceHomeDirPath: service_home_dir_path,
}
# Optional
payload["metadata"] = options[:meta] if options.has_key?(:meta)
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
'Content-Type' => 'application/json'
})
req.body = payload.to_json
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | ruby | def register_service(long_name, service_name, service_home_dir_path, options = {})
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/dns"
# Payload
payload = {
longName: long_name,
serviceName: service_name,
rootPath: 'app',
serviceHomeDirPath: service_home_dir_path,
}
# Optional
payload["metadata"] = options[:meta] if options.has_key?(:meta)
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
'Content-Type' => 'application/json'
})
req.body = payload.to_json
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | [
"def",
"register_service",
"(",
"long_name",
",",
"service_name",
",",
"service_home_dir_path",
",",
"options",
"=",
"{",
"}",
")",
"# Entry point",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/dns\"",
"# Payload",
"payload",
"=",
"{",
"longName",
":",
"long_name",
",",
"serviceName",
":",
"service_name",
",",
"rootPath",
":",
"'app'",
",",
"serviceHomeDirPath",
":",
"service_home_dir_path",
",",
"}",
"# Optional",
"payload",
"[",
"\"metadata\"",
"]",
"=",
"options",
"[",
":meta",
"]",
"if",
"options",
".",
"has_key?",
"(",
":meta",
")",
"# API call",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"req",
".",
"body",
"=",
"payload",
".",
"to_json",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"true",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Register a long name and a service.
Only authorised requests can invoke the API.
Usage: my_client.dns.register_service("my-domain", "www", "/sources")
Fail: {"errorCode"=>-1503, "description"=>"FfiError::InvalidPath"}
Success: true
Reference: https://maidsafe.readme.io/docs/dns-register-service | [
"Register",
"a",
"long",
"name",
"and",
"a",
"service",
".",
"Only",
"authorised",
"requests",
"can",
"invoke",
"the",
"API",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L597-L622 |
5,097 | loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.SD.set | def set(name, contents = '', type = 500)
sd = @client.sd.update(name, contents)
if sd.is_a?(Hash) && (sd["errorCode"] == -22) # doesn't exist
sd = @client.sd.create(name, contents)
end
sd
end | ruby | def set(name, contents = '', type = 500)
sd = @client.sd.update(name, contents)
if sd.is_a?(Hash) && (sd["errorCode"] == -22) # doesn't exist
sd = @client.sd.create(name, contents)
end
sd
end | [
"def",
"set",
"(",
"name",
",",
"contents",
"=",
"''",
",",
"type",
"=",
"500",
")",
"sd",
"=",
"@client",
".",
"sd",
".",
"update",
"(",
"name",
",",
"contents",
")",
"if",
"sd",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"(",
"sd",
"[",
"\"errorCode\"",
"]",
"==",
"-",
"22",
")",
"# doesn't exist",
"sd",
"=",
"@client",
".",
"sd",
".",
"create",
"(",
"name",
",",
"contents",
")",
"end",
"sd",
"end"
] | create or update | [
"create",
"or",
"update"
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L1049-L1055 |
5,098 | nathanstitt/erb_latex | lib/erb_latex/template.rb | ErbLatex.Template.to_file | def to_file( file = suggested_filename )
execute do | contents |
if file.is_a?(String)
FileUtils.mv contents, file
else
file.write contents.read
file.rewind
end
end
file
end | ruby | def to_file( file = suggested_filename )
execute do | contents |
if file.is_a?(String)
FileUtils.mv contents, file
else
file.write contents.read
file.rewind
end
end
file
end | [
"def",
"to_file",
"(",
"file",
"=",
"suggested_filename",
")",
"execute",
"do",
"|",
"contents",
"|",
"if",
"file",
".",
"is_a?",
"(",
"String",
")",
"FileUtils",
".",
"mv",
"contents",
",",
"file",
"else",
"file",
".",
"write",
"contents",
".",
"read",
"file",
".",
"rewind",
"end",
"end",
"file",
"end"
] | Save the PDF to the file
@param file [String,IO] if file is a String, the PDF is moved to the path indicated (most efficient).
Otherwise, file is considered an instance of IO, and write is called on it with the PDF contents
@return [String,IO] the file | [
"Save",
"the",
"PDF",
"to",
"the",
"file"
] | ea74677264b48b72913d5eae9eaac60f4151de8c | https://github.com/nathanstitt/erb_latex/blob/ea74677264b48b72913d5eae9eaac60f4151de8c/lib/erb_latex/template.rb#L68-L78 |
5,099 | nathanstitt/erb_latex | lib/erb_latex/template.rb | ErbLatex.Template.execute | def execute
latex = compile_latex
Dir.mktmpdir do | dir |
@pass_count = 0
@log = ''
success = false
while log_suggests_rerunning? && @pass_count < 5
@pass_count += 1
success = execute_xelatex(latex,dir)
end
pdf_file = Pathname.new(dir).join( "output.pdf" )
if success && pdf_file.exist?
yield pdf_file
else
errors = @log.scan(/\*\!\s(.*?)\n\s*\n/m).map{|e| e.first.gsub(/\n/,'') }.join("; ")
STDERR.puts @log, errors if ErbLatex.config.verbose_logs
raise LatexError.new( errors.empty? ? "xelatex compile error" : errors, @log )
end
end
end | ruby | def execute
latex = compile_latex
Dir.mktmpdir do | dir |
@pass_count = 0
@log = ''
success = false
while log_suggests_rerunning? && @pass_count < 5
@pass_count += 1
success = execute_xelatex(latex,dir)
end
pdf_file = Pathname.new(dir).join( "output.pdf" )
if success && pdf_file.exist?
yield pdf_file
else
errors = @log.scan(/\*\!\s(.*?)\n\s*\n/m).map{|e| e.first.gsub(/\n/,'') }.join("; ")
STDERR.puts @log, errors if ErbLatex.config.verbose_logs
raise LatexError.new( errors.empty? ? "xelatex compile error" : errors, @log )
end
end
end | [
"def",
"execute",
"latex",
"=",
"compile_latex",
"Dir",
".",
"mktmpdir",
"do",
"|",
"dir",
"|",
"@pass_count",
"=",
"0",
"@log",
"=",
"''",
"success",
"=",
"false",
"while",
"log_suggests_rerunning?",
"&&",
"@pass_count",
"<",
"5",
"@pass_count",
"+=",
"1",
"success",
"=",
"execute_xelatex",
"(",
"latex",
",",
"dir",
")",
"end",
"pdf_file",
"=",
"Pathname",
".",
"new",
"(",
"dir",
")",
".",
"join",
"(",
"\"output.pdf\"",
")",
"if",
"success",
"&&",
"pdf_file",
".",
"exist?",
"yield",
"pdf_file",
"else",
"errors",
"=",
"@log",
".",
"scan",
"(",
"/",
"\\*",
"\\!",
"\\s",
"\\n",
"\\s",
"\\n",
"/m",
")",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"first",
".",
"gsub",
"(",
"/",
"\\n",
"/",
",",
"''",
")",
"}",
".",
"join",
"(",
"\"; \"",
")",
"STDERR",
".",
"puts",
"@log",
",",
"errors",
"if",
"ErbLatex",
".",
"config",
".",
"verbose_logs",
"raise",
"LatexError",
".",
"new",
"(",
"errors",
".",
"empty?",
"?",
"\"xelatex compile error\"",
":",
"errors",
",",
"@log",
")",
"end",
"end",
"end"
] | Compile the Latex template into a PDF file
@yield [Pathname] complete path to the PDF file
@raise [LatexError] if the xelatex process does not complete successfully | [
"Compile",
"the",
"Latex",
"template",
"into",
"a",
"PDF",
"file"
] | ea74677264b48b72913d5eae9eaac60f4151de8c | https://github.com/nathanstitt/erb_latex/blob/ea74677264b48b72913d5eae9eaac60f4151de8c/lib/erb_latex/template.rb#L88-L107 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.