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
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
8,800
|
pdorrell/regenerate
|
lib/regenerate/web-page.rb
|
Regenerate.WebPage.initializePageObject
|
def initializePageObject(pageObject)
@pageObject = pageObject
pathDepth = @pathComponents.length-1
rootLinkPath = "../" * pathDepth
setPageObjectInstanceVar("@fileName", @fileName)
setPageObjectInstanceVar("@baseDir", File.dirname(@fileName))
setPageObjectInstanceVar("@baseFileName", File.basename(@fileName))
setPageObjectInstanceVar("@pathDepth", pathDepth)
setPageObjectInstanceVar("@pathComponents", @pathComponents)
setPageObjectInstanceVar("@rootLinkPath", rootLinkPath)
setPageObjectInstanceVar("@baseUrl", rootLinkPath)
setPageObjectInstanceVar("@site", @site)
@initialInstanceVariables = Set.new(@pageObject.instance_variables)
pageObject.postInitialize
end
|
ruby
|
def initializePageObject(pageObject)
@pageObject = pageObject
pathDepth = @pathComponents.length-1
rootLinkPath = "../" * pathDepth
setPageObjectInstanceVar("@fileName", @fileName)
setPageObjectInstanceVar("@baseDir", File.dirname(@fileName))
setPageObjectInstanceVar("@baseFileName", File.basename(@fileName))
setPageObjectInstanceVar("@pathDepth", pathDepth)
setPageObjectInstanceVar("@pathComponents", @pathComponents)
setPageObjectInstanceVar("@rootLinkPath", rootLinkPath)
setPageObjectInstanceVar("@baseUrl", rootLinkPath)
setPageObjectInstanceVar("@site", @site)
@initialInstanceVariables = Set.new(@pageObject.instance_variables)
pageObject.postInitialize
end
|
[
"def",
"initializePageObject",
"(",
"pageObject",
")",
"@pageObject",
"=",
"pageObject",
"pathDepth",
"=",
"@pathComponents",
".",
"length",
"-",
"1",
"rootLinkPath",
"=",
"\"../\"",
"*",
"pathDepth",
"setPageObjectInstanceVar",
"(",
"\"@fileName\"",
",",
"@fileName",
")",
"setPageObjectInstanceVar",
"(",
"\"@baseDir\"",
",",
"File",
".",
"dirname",
"(",
"@fileName",
")",
")",
"setPageObjectInstanceVar",
"(",
"\"@baseFileName\"",
",",
"File",
".",
"basename",
"(",
"@fileName",
")",
")",
"setPageObjectInstanceVar",
"(",
"\"@pathDepth\"",
",",
"pathDepth",
")",
"setPageObjectInstanceVar",
"(",
"\"@pathComponents\"",
",",
"@pathComponents",
")",
"setPageObjectInstanceVar",
"(",
"\"@rootLinkPath\"",
",",
"rootLinkPath",
")",
"setPageObjectInstanceVar",
"(",
"\"@baseUrl\"",
",",
"rootLinkPath",
")",
"setPageObjectInstanceVar",
"(",
"\"@site\"",
",",
"@site",
")",
"@initialInstanceVariables",
"=",
"Set",
".",
"new",
"(",
"@pageObject",
".",
"instance_variables",
")",
"pageObject",
".",
"postInitialize",
"end"
] |
The absolute name of the source file
initialise the "page object", which is the object that "owns" the defined instance variables,
and the object in whose context the Ruby components are evaluated
Three special instance variable values are set - @fileName, @baseDir, @baseFileName,
so that they can be accessed, if necessary, by Ruby code in the Ruby code components.
(if this is called a second time, it overrides whatever was set the first time)
Notes on special instance variables -
@fileName and @baseDir are the absolute paths of the source file and it's containing directory.
They would be used in Ruby code that looked for other files with names or locations relative to these two.
They would generally not be expected to appear in the output content.
@baseFileName is the name of the file without any directory path components. In some cases it might be
used within output content.
|
[
"The",
"absolute",
"name",
"of",
"the",
"source",
"file",
"initialise",
"the",
"page",
"object",
"which",
"is",
"the",
"object",
"that",
"owns",
"the",
"defined",
"instance",
"variables",
"and",
"the",
"object",
"in",
"whose",
"context",
"the",
"Ruby",
"components",
"are",
"evaluated",
"Three",
"special",
"instance",
"variable",
"values",
"are",
"set",
"-"
] |
31f3beb3ff9b45384a90f20fed61be20f39da0d4
|
https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L358-L372
|
8,801
|
pdorrell/regenerate
|
lib/regenerate/web-page.rb
|
Regenerate.WebPage.startNewComponent
|
def startNewComponent(component, startComment = nil)
component.parentPage = self
@currentComponent = component
#puts "startNewComponent, @currentComponent = #{@currentComponent.inspect}"
@components << component
if startComment
component.processStartComment(startComment)
end
end
|
ruby
|
def startNewComponent(component, startComment = nil)
component.parentPage = self
@currentComponent = component
#puts "startNewComponent, @currentComponent = #{@currentComponent.inspect}"
@components << component
if startComment
component.processStartComment(startComment)
end
end
|
[
"def",
"startNewComponent",
"(",
"component",
",",
"startComment",
"=",
"nil",
")",
"component",
".",
"parentPage",
"=",
"self",
"@currentComponent",
"=",
"component",
"#puts \"startNewComponent, @currentComponent = #{@currentComponent.inspect}\"",
"@components",
"<<",
"component",
"if",
"startComment",
"component",
".",
"processStartComment",
"(",
"startComment",
")",
"end",
"end"
] |
Add a newly started page component to this page
Also process the start comment, unless it was a static HTML component, in which case there is
not start comment.
|
[
"Add",
"a",
"newly",
"started",
"page",
"component",
"to",
"this",
"page",
"Also",
"process",
"the",
"start",
"comment",
"unless",
"it",
"was",
"a",
"static",
"HTML",
"component",
"in",
"which",
"case",
"there",
"is",
"not",
"start",
"comment",
"."
] |
31f3beb3ff9b45384a90f20fed61be20f39da0d4
|
https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L393-L401
|
8,802
|
pdorrell/regenerate
|
lib/regenerate/web-page.rb
|
Regenerate.WebPage.writeRegeneratedFile
|
def writeRegeneratedFile(outFile, makeBackup, checkNoChanges)
puts "writeRegeneratedFile, #{outFile}, makeBackup = #{makeBackup}, checkNoChanges = #{checkNoChanges}"
if makeBackup
backupFileName = makeBackupFile(outFile)
end
File.open(outFile, "w") do |f|
for component in @components do
f.write(component.output)
end
end
puts " wrote regenerated page to #{outFile}"
if checkNoChanges
if !makeBackup
raise Exception.new("writeRegeneratedFile #{outFile}: checkNoChanges specified, but no backup was made")
end
checkAndEnsureOutputFileUnchanged(outFile, backupFileName)
end
end
|
ruby
|
def writeRegeneratedFile(outFile, makeBackup, checkNoChanges)
puts "writeRegeneratedFile, #{outFile}, makeBackup = #{makeBackup}, checkNoChanges = #{checkNoChanges}"
if makeBackup
backupFileName = makeBackupFile(outFile)
end
File.open(outFile, "w") do |f|
for component in @components do
f.write(component.output)
end
end
puts " wrote regenerated page to #{outFile}"
if checkNoChanges
if !makeBackup
raise Exception.new("writeRegeneratedFile #{outFile}: checkNoChanges specified, but no backup was made")
end
checkAndEnsureOutputFileUnchanged(outFile, backupFileName)
end
end
|
[
"def",
"writeRegeneratedFile",
"(",
"outFile",
",",
"makeBackup",
",",
"checkNoChanges",
")",
"puts",
"\"writeRegeneratedFile, #{outFile}, makeBackup = #{makeBackup}, checkNoChanges = #{checkNoChanges}\"",
"if",
"makeBackup",
"backupFileName",
"=",
"makeBackupFile",
"(",
"outFile",
")",
"end",
"File",
".",
"open",
"(",
"outFile",
",",
"\"w\"",
")",
"do",
"|",
"f",
"|",
"for",
"component",
"in",
"@components",
"do",
"f",
".",
"write",
"(",
"component",
".",
"output",
")",
"end",
"end",
"puts",
"\" wrote regenerated page to #{outFile}\"",
"if",
"checkNoChanges",
"if",
"!",
"makeBackup",
"raise",
"Exception",
".",
"new",
"(",
"\"writeRegeneratedFile #{outFile}: checkNoChanges specified, but no backup was made\"",
")",
"end",
"checkAndEnsureOutputFileUnchanged",
"(",
"outFile",
",",
"backupFileName",
")",
"end",
"end"
] |
Write the output of the page components to the output file (optionally checking that
there are no differences between the new output and the existing output.
|
[
"Write",
"the",
"output",
"of",
"the",
"page",
"components",
"to",
"the",
"output",
"file",
"(",
"optionally",
"checking",
"that",
"there",
"are",
"no",
"differences",
"between",
"the",
"new",
"output",
"and",
"the",
"existing",
"output",
"."
] |
31f3beb3ff9b45384a90f20fed61be20f39da0d4
|
https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L519-L536
|
8,803
|
pdorrell/regenerate
|
lib/regenerate/web-page.rb
|
Regenerate.WebPage.readFileLines
|
def readFileLines
puts "Reading source file #{@fileName} ..."
lineNumber = 0
File.open(@fileName).each_line do |line|
line.chomp!
lineNumber += 1 # track line numbers for when Ruby code needs to be executed (i.e. to populate stack traces)
#puts "line #{lineNumber}: #{line}"
commentLineMatch = COMMENT_LINE_REGEX.match(line)
if commentLineMatch # it matches the Regenerate command line regex (but might not actually be a command ...)
parsedCommandLine = ParsedRegenerateCommentLine.new(line, commentLineMatch)
#puts "parsedCommandLine = #{parsedCommandLine}"
if parsedCommandLine.isRegenerateCommentLine # if it is a Regenerate command line
parsedCommandLine.checkIsValid # check it is valid, and then,
processCommandLine(parsedCommandLine, lineNumber) # process the command line
else
processTextLine(line, lineNumber) # process a text line which is not a Regenerate command line
end
else
processTextLine(line, lineNumber) # process a text line which is not a Regenerate command line
end
end
# After processing all source lines, the only unfinished page component permitted is a static HTML component.
finishAtEndOfSourceFile
#puts "Finished reading #{@fileName}."
end
|
ruby
|
def readFileLines
puts "Reading source file #{@fileName} ..."
lineNumber = 0
File.open(@fileName).each_line do |line|
line.chomp!
lineNumber += 1 # track line numbers for when Ruby code needs to be executed (i.e. to populate stack traces)
#puts "line #{lineNumber}: #{line}"
commentLineMatch = COMMENT_LINE_REGEX.match(line)
if commentLineMatch # it matches the Regenerate command line regex (but might not actually be a command ...)
parsedCommandLine = ParsedRegenerateCommentLine.new(line, commentLineMatch)
#puts "parsedCommandLine = #{parsedCommandLine}"
if parsedCommandLine.isRegenerateCommentLine # if it is a Regenerate command line
parsedCommandLine.checkIsValid # check it is valid, and then,
processCommandLine(parsedCommandLine, lineNumber) # process the command line
else
processTextLine(line, lineNumber) # process a text line which is not a Regenerate command line
end
else
processTextLine(line, lineNumber) # process a text line which is not a Regenerate command line
end
end
# After processing all source lines, the only unfinished page component permitted is a static HTML component.
finishAtEndOfSourceFile
#puts "Finished reading #{@fileName}."
end
|
[
"def",
"readFileLines",
"puts",
"\"Reading source file #{@fileName} ...\"",
"lineNumber",
"=",
"0",
"File",
".",
"open",
"(",
"@fileName",
")",
".",
"each_line",
"do",
"|",
"line",
"|",
"line",
".",
"chomp!",
"lineNumber",
"+=",
"1",
"# track line numbers for when Ruby code needs to be executed (i.e. to populate stack traces)",
"#puts \"line #{lineNumber}: #{line}\"",
"commentLineMatch",
"=",
"COMMENT_LINE_REGEX",
".",
"match",
"(",
"line",
")",
"if",
"commentLineMatch",
"# it matches the Regenerate command line regex (but might not actually be a command ...)",
"parsedCommandLine",
"=",
"ParsedRegenerateCommentLine",
".",
"new",
"(",
"line",
",",
"commentLineMatch",
")",
"#puts \"parsedCommandLine = #{parsedCommandLine}\"",
"if",
"parsedCommandLine",
".",
"isRegenerateCommentLine",
"# if it is a Regenerate command line",
"parsedCommandLine",
".",
"checkIsValid",
"# check it is valid, and then, ",
"processCommandLine",
"(",
"parsedCommandLine",
",",
"lineNumber",
")",
"# process the command line",
"else",
"processTextLine",
"(",
"line",
",",
"lineNumber",
")",
"# process a text line which is not a Regenerate command line",
"end",
"else",
"processTextLine",
"(",
"line",
",",
"lineNumber",
")",
"# process a text line which is not a Regenerate command line",
"end",
"end",
"# After processing all source lines, the only unfinished page component permitted is a static HTML component.",
"finishAtEndOfSourceFile",
"#puts \"Finished reading #{@fileName}.\"",
"end"
] |
Read in and parse lines from source file
|
[
"Read",
"in",
"and",
"parse",
"lines",
"from",
"source",
"file"
] |
31f3beb3ff9b45384a90f20fed61be20f39da0d4
|
https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L539-L563
|
8,804
|
pdorrell/regenerate
|
lib/regenerate/web-page.rb
|
Regenerate.WebPage.regenerateToOutputFile
|
def regenerateToOutputFile(outFile, checkNoChanges = false)
executeRubyComponents
@pageObject.process
writeRegeneratedFile(outFile, checkNoChanges, checkNoChanges)
end
|
ruby
|
def regenerateToOutputFile(outFile, checkNoChanges = false)
executeRubyComponents
@pageObject.process
writeRegeneratedFile(outFile, checkNoChanges, checkNoChanges)
end
|
[
"def",
"regenerateToOutputFile",
"(",
"outFile",
",",
"checkNoChanges",
"=",
"false",
")",
"executeRubyComponents",
"@pageObject",
".",
"process",
"writeRegeneratedFile",
"(",
"outFile",
",",
"checkNoChanges",
",",
"checkNoChanges",
")",
"end"
] |
Regenerate from the source file into the output file
|
[
"Regenerate",
"from",
"the",
"source",
"file",
"into",
"the",
"output",
"file"
] |
31f3beb3ff9b45384a90f20fed61be20f39da0d4
|
https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L574-L578
|
8,805
|
pdorrell/regenerate
|
lib/regenerate/web-page.rb
|
Regenerate.WebPage.executeRubyComponents
|
def executeRubyComponents
fileDir = File.dirname(@fileName)
#puts "Executing ruby components in directory #{fileDir} ..."
Dir.chdir(fileDir) do
for rubyComponent in @rubyComponents
rubyCode = rubyComponent.text
#puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
#puts "Executing ruby (line #{rubyComponent.lineNumber}) #{rubyCode.inspect} ..."
@pageObject.instance_eval(rubyCode, @fileName, rubyComponent.lineNumber)
#puts "Finished executing ruby at line #{rubyComponent.lineNumber}"
end
end
#puts "Finished executing ruby components."
end
|
ruby
|
def executeRubyComponents
fileDir = File.dirname(@fileName)
#puts "Executing ruby components in directory #{fileDir} ..."
Dir.chdir(fileDir) do
for rubyComponent in @rubyComponents
rubyCode = rubyComponent.text
#puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
#puts "Executing ruby (line #{rubyComponent.lineNumber}) #{rubyCode.inspect} ..."
@pageObject.instance_eval(rubyCode, @fileName, rubyComponent.lineNumber)
#puts "Finished executing ruby at line #{rubyComponent.lineNumber}"
end
end
#puts "Finished executing ruby components."
end
|
[
"def",
"executeRubyComponents",
"fileDir",
"=",
"File",
".",
"dirname",
"(",
"@fileName",
")",
"#puts \"Executing ruby components in directory #{fileDir} ...\"",
"Dir",
".",
"chdir",
"(",
"fileDir",
")",
"do",
"for",
"rubyComponent",
"in",
"@rubyComponents",
"rubyCode",
"=",
"rubyComponent",
".",
"text",
"#puts \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\"",
"#puts \"Executing ruby (line #{rubyComponent.lineNumber}) #{rubyCode.inspect} ...\"",
"@pageObject",
".",
"instance_eval",
"(",
"rubyCode",
",",
"@fileName",
",",
"rubyComponent",
".",
"lineNumber",
")",
"#puts \"Finished executing ruby at line #{rubyComponent.lineNumber}\"",
"end",
"end",
"#puts \"Finished executing ruby components.\"",
"end"
] |
Execute the Ruby components which consist of Ruby code to be evaluated in the context of the page object
|
[
"Execute",
"the",
"Ruby",
"components",
"which",
"consist",
"of",
"Ruby",
"code",
"to",
"be",
"evaluated",
"in",
"the",
"context",
"of",
"the",
"page",
"object"
] |
31f3beb3ff9b45384a90f20fed61be20f39da0d4
|
https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L581-L594
|
8,806
|
pdorrell/regenerate
|
lib/regenerate/web-page.rb
|
Regenerate.PageObject.erb
|
def erb(templateFileName)
@binding = binding
fullTemplateFilePath = relative_path(@rootLinkPath + templateFileName)
File.open(fullTemplateFilePath, "r") do |input|
templateText = input.read
template = ERB.new(templateText, nil, nil)
template.filename = templateFileName
result = template.result(@binding)
end
end
|
ruby
|
def erb(templateFileName)
@binding = binding
fullTemplateFilePath = relative_path(@rootLinkPath + templateFileName)
File.open(fullTemplateFilePath, "r") do |input|
templateText = input.read
template = ERB.new(templateText, nil, nil)
template.filename = templateFileName
result = template.result(@binding)
end
end
|
[
"def",
"erb",
"(",
"templateFileName",
")",
"@binding",
"=",
"binding",
"fullTemplateFilePath",
"=",
"relative_path",
"(",
"@rootLinkPath",
"+",
"templateFileName",
")",
"File",
".",
"open",
"(",
"fullTemplateFilePath",
",",
"\"r\"",
")",
"do",
"|",
"input",
"|",
"templateText",
"=",
"input",
".",
"read",
"template",
"=",
"ERB",
".",
"new",
"(",
"templateText",
",",
"nil",
",",
"nil",
")",
"template",
".",
"filename",
"=",
"templateFileName",
"result",
"=",
"template",
".",
"result",
"(",
"@binding",
")",
"end",
"end"
] |
Method to render an ERB template file in the context of this object
|
[
"Method",
"to",
"render",
"an",
"ERB",
"template",
"file",
"in",
"the",
"context",
"of",
"this",
"object"
] |
31f3beb3ff9b45384a90f20fed61be20f39da0d4
|
https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L618-L627
|
8,807
|
alexdean/where_was_i
|
lib/where_was_i/gpx.rb
|
WhereWasI.Gpx.add_tracks
|
def add_tracks
@tracks = []
doc = Nokogiri::XML(@gpx_data)
doc.css('xmlns|trk').each do |trk|
track = Track.new
trk.css('xmlns|trkpt').each do |trkpt|
# https://en.wikipedia.org/wiki/GPS_Exchange_Format#Units
# decimal degrees, wgs84.
# elevation in meters.
track.add_point(
lat: trkpt.attributes['lat'].text.to_f,
lon: trkpt.attributes['lon'].text.to_f,
elevation: trkpt.at_css('xmlns|ele').text.to_f,
time: Time.parse(trkpt.at_css('xmlns|time').text)
)
end
@tracks << track
end
@intersegments = []
@tracks.each_with_index do |track,i|
next if i == 0
this_track = track
prev_track = @tracks[i-1]
inter_track = Track.new
inter_track.add_point(
lat: prev_track.end_location[0],
lon: prev_track.end_location[1],
elevation: prev_track.end_location[2],
time: prev_track.end_time
)
inter_track.add_point(
lat: this_track.start_location[0],
lon: this_track.start_location[1],
elevation: this_track.start_location[2],
time: this_track.start_time
)
@intersegments << inter_track
end
@tracks_added = true
end
|
ruby
|
def add_tracks
@tracks = []
doc = Nokogiri::XML(@gpx_data)
doc.css('xmlns|trk').each do |trk|
track = Track.new
trk.css('xmlns|trkpt').each do |trkpt|
# https://en.wikipedia.org/wiki/GPS_Exchange_Format#Units
# decimal degrees, wgs84.
# elevation in meters.
track.add_point(
lat: trkpt.attributes['lat'].text.to_f,
lon: trkpt.attributes['lon'].text.to_f,
elevation: trkpt.at_css('xmlns|ele').text.to_f,
time: Time.parse(trkpt.at_css('xmlns|time').text)
)
end
@tracks << track
end
@intersegments = []
@tracks.each_with_index do |track,i|
next if i == 0
this_track = track
prev_track = @tracks[i-1]
inter_track = Track.new
inter_track.add_point(
lat: prev_track.end_location[0],
lon: prev_track.end_location[1],
elevation: prev_track.end_location[2],
time: prev_track.end_time
)
inter_track.add_point(
lat: this_track.start_location[0],
lon: this_track.start_location[1],
elevation: this_track.start_location[2],
time: this_track.start_time
)
@intersegments << inter_track
end
@tracks_added = true
end
|
[
"def",
"add_tracks",
"@tracks",
"=",
"[",
"]",
"doc",
"=",
"Nokogiri",
"::",
"XML",
"(",
"@gpx_data",
")",
"doc",
".",
"css",
"(",
"'xmlns|trk'",
")",
".",
"each",
"do",
"|",
"trk",
"|",
"track",
"=",
"Track",
".",
"new",
"trk",
".",
"css",
"(",
"'xmlns|trkpt'",
")",
".",
"each",
"do",
"|",
"trkpt",
"|",
"# https://en.wikipedia.org/wiki/GPS_Exchange_Format#Units",
"# decimal degrees, wgs84.",
"# elevation in meters.",
"track",
".",
"add_point",
"(",
"lat",
":",
"trkpt",
".",
"attributes",
"[",
"'lat'",
"]",
".",
"text",
".",
"to_f",
",",
"lon",
":",
"trkpt",
".",
"attributes",
"[",
"'lon'",
"]",
".",
"text",
".",
"to_f",
",",
"elevation",
":",
"trkpt",
".",
"at_css",
"(",
"'xmlns|ele'",
")",
".",
"text",
".",
"to_f",
",",
"time",
":",
"Time",
".",
"parse",
"(",
"trkpt",
".",
"at_css",
"(",
"'xmlns|time'",
")",
".",
"text",
")",
")",
"end",
"@tracks",
"<<",
"track",
"end",
"@intersegments",
"=",
"[",
"]",
"@tracks",
".",
"each_with_index",
"do",
"|",
"track",
",",
"i",
"|",
"next",
"if",
"i",
"==",
"0",
"this_track",
"=",
"track",
"prev_track",
"=",
"@tracks",
"[",
"i",
"-",
"1",
"]",
"inter_track",
"=",
"Track",
".",
"new",
"inter_track",
".",
"add_point",
"(",
"lat",
":",
"prev_track",
".",
"end_location",
"[",
"0",
"]",
",",
"lon",
":",
"prev_track",
".",
"end_location",
"[",
"1",
"]",
",",
"elevation",
":",
"prev_track",
".",
"end_location",
"[",
"2",
"]",
",",
"time",
":",
"prev_track",
".",
"end_time",
")",
"inter_track",
".",
"add_point",
"(",
"lat",
":",
"this_track",
".",
"start_location",
"[",
"0",
"]",
",",
"lon",
":",
"this_track",
".",
"start_location",
"[",
"1",
"]",
",",
"elevation",
":",
"this_track",
".",
"start_location",
"[",
"2",
"]",
",",
"time",
":",
"this_track",
".",
"start_time",
")",
"@intersegments",
"<<",
"inter_track",
"end",
"@tracks_added",
"=",
"true",
"end"
] |
extract track data from gpx data
it's not necessary to call this directly
|
[
"extract",
"track",
"data",
"from",
"gpx",
"data"
] |
10d1381d6e0b1a85de65678a540d4dbc6041321d
|
https://github.com/alexdean/where_was_i/blob/10d1381d6e0b1a85de65678a540d4dbc6041321d/lib/where_was_i/gpx.rb#L47-L91
|
8,808
|
alexdean/where_was_i
|
lib/where_was_i/gpx.rb
|
WhereWasI.Gpx.at
|
def at(time)
add_tracks if ! @tracks_added
if time.is_a?(String)
time = Time.parse(time)
end
time = time.to_i
location = nil
@tracks.each do |track|
location = track.at(time)
break if location
end
if ! location
case @intersegment_behavior
when :interpolate then
@intersegments.each do |track|
location = track.at(time)
break if location
end
when :nearest then
# hash is sorted in ascending time order.
# all start/end points for all segments
points = {}
@tracks.each do |t|
points[t.start_time.to_i] = t.start_location
points[t.end_time.to_i] = t.end_location
end
last_diff = Infinity
last_time = -1
points.each do |p_time,p_location|
this_diff = (p_time.to_i - time).abs
# as long as the differences keep getting smaller, we keep going
# as soon as we see a larger one, we step back one and use that value.
if this_diff > last_diff
l = points[last_time]
location = Track.array_to_hash(points[last_time])
break
else
last_diff = this_diff
last_time = p_time
end
end
# if we got here, time is > the end of the last segment
location = Track.array_to_hash(points[last_time])
end
end
# each segment has a begin and end time.
# which one is this time closest to?
# array of times in order. compute abs diff between time and each point.
# put times in order. abs diff to each, until we get a larger value or we run out of points. then back up one and use that.
# {time => [lat, lon, elev], time => [lat, lon, elev]}
location
end
|
ruby
|
def at(time)
add_tracks if ! @tracks_added
if time.is_a?(String)
time = Time.parse(time)
end
time = time.to_i
location = nil
@tracks.each do |track|
location = track.at(time)
break if location
end
if ! location
case @intersegment_behavior
when :interpolate then
@intersegments.each do |track|
location = track.at(time)
break if location
end
when :nearest then
# hash is sorted in ascending time order.
# all start/end points for all segments
points = {}
@tracks.each do |t|
points[t.start_time.to_i] = t.start_location
points[t.end_time.to_i] = t.end_location
end
last_diff = Infinity
last_time = -1
points.each do |p_time,p_location|
this_diff = (p_time.to_i - time).abs
# as long as the differences keep getting smaller, we keep going
# as soon as we see a larger one, we step back one and use that value.
if this_diff > last_diff
l = points[last_time]
location = Track.array_to_hash(points[last_time])
break
else
last_diff = this_diff
last_time = p_time
end
end
# if we got here, time is > the end of the last segment
location = Track.array_to_hash(points[last_time])
end
end
# each segment has a begin and end time.
# which one is this time closest to?
# array of times in order. compute abs diff between time and each point.
# put times in order. abs diff to each, until we get a larger value or we run out of points. then back up one and use that.
# {time => [lat, lon, elev], time => [lat, lon, elev]}
location
end
|
[
"def",
"at",
"(",
"time",
")",
"add_tracks",
"if",
"!",
"@tracks_added",
"if",
"time",
".",
"is_a?",
"(",
"String",
")",
"time",
"=",
"Time",
".",
"parse",
"(",
"time",
")",
"end",
"time",
"=",
"time",
".",
"to_i",
"location",
"=",
"nil",
"@tracks",
".",
"each",
"do",
"|",
"track",
"|",
"location",
"=",
"track",
".",
"at",
"(",
"time",
")",
"break",
"if",
"location",
"end",
"if",
"!",
"location",
"case",
"@intersegment_behavior",
"when",
":interpolate",
"then",
"@intersegments",
".",
"each",
"do",
"|",
"track",
"|",
"location",
"=",
"track",
".",
"at",
"(",
"time",
")",
"break",
"if",
"location",
"end",
"when",
":nearest",
"then",
"# hash is sorted in ascending time order.",
"# all start/end points for all segments",
"points",
"=",
"{",
"}",
"@tracks",
".",
"each",
"do",
"|",
"t",
"|",
"points",
"[",
"t",
".",
"start_time",
".",
"to_i",
"]",
"=",
"t",
".",
"start_location",
"points",
"[",
"t",
".",
"end_time",
".",
"to_i",
"]",
"=",
"t",
".",
"end_location",
"end",
"last_diff",
"=",
"Infinity",
"last_time",
"=",
"-",
"1",
"points",
".",
"each",
"do",
"|",
"p_time",
",",
"p_location",
"|",
"this_diff",
"=",
"(",
"p_time",
".",
"to_i",
"-",
"time",
")",
".",
"abs",
"# as long as the differences keep getting smaller, we keep going",
"# as soon as we see a larger one, we step back one and use that value.",
"if",
"this_diff",
">",
"last_diff",
"l",
"=",
"points",
"[",
"last_time",
"]",
"location",
"=",
"Track",
".",
"array_to_hash",
"(",
"points",
"[",
"last_time",
"]",
")",
"break",
"else",
"last_diff",
"=",
"this_diff",
"last_time",
"=",
"p_time",
"end",
"end",
"# if we got here, time is > the end of the last segment",
"location",
"=",
"Track",
".",
"array_to_hash",
"(",
"points",
"[",
"last_time",
"]",
")",
"end",
"end",
"# each segment has a begin and end time.",
"# which one is this time closest to?",
"# array of times in order. compute abs diff between time and each point.",
"# put times in order. abs diff to each, until we get a larger value or we run out of points. then back up one and use that.",
"# {time => [lat, lon, elev], time => [lat, lon, elev]}",
"location",
"end"
] |
infer a location from track data and a time
@param [Time,String,Fixnum] time
@return [Hash]
@see Track#at
|
[
"infer",
"a",
"location",
"from",
"track",
"data",
"and",
"a",
"time"
] |
10d1381d6e0b1a85de65678a540d4dbc6041321d
|
https://github.com/alexdean/where_was_i/blob/10d1381d6e0b1a85de65678a540d4dbc6041321d/lib/where_was_i/gpx.rb#L98-L158
|
8,809
|
rgeyer/rs_user_policy
|
lib/rs_user_policy/user.rb
|
RsUserPolicy.User.clear_permissions
|
def clear_permissions(account_href, client, options={})
options = {:dry_run => false}.merge(options)
current_permissions = get_api_permissions(account_href)
if options[:dry_run]
Hash[current_permissions.map{|p| [p.href, p.role_title]}]
else
retval = RsUserPolicy::RightApi::PermissionUtilities.destroy_permissions(
current_permissions,
client
)
@permissions.delete(account_href)
retval
end
end
|
ruby
|
def clear_permissions(account_href, client, options={})
options = {:dry_run => false}.merge(options)
current_permissions = get_api_permissions(account_href)
if options[:dry_run]
Hash[current_permissions.map{|p| [p.href, p.role_title]}]
else
retval = RsUserPolicy::RightApi::PermissionUtilities.destroy_permissions(
current_permissions,
client
)
@permissions.delete(account_href)
retval
end
end
|
[
"def",
"clear_permissions",
"(",
"account_href",
",",
"client",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":dry_run",
"=>",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"current_permissions",
"=",
"get_api_permissions",
"(",
"account_href",
")",
"if",
"options",
"[",
":dry_run",
"]",
"Hash",
"[",
"current_permissions",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"p",
".",
"href",
",",
"p",
".",
"role_title",
"]",
"}",
"]",
"else",
"retval",
"=",
"RsUserPolicy",
"::",
"RightApi",
"::",
"PermissionUtilities",
".",
"destroy_permissions",
"(",
"current_permissions",
",",
"client",
")",
"@permissions",
".",
"delete",
"(",
"account_href",
")",
"retval",
"end",
"end"
] |
Removes all permissions for the user in the specified rightscale account using the supplied client
@param [String] account_href The RightScale API href of the account
@param [RightApi::Client] client An active RightApi::Client instance for the account referenced in account_href
@param [Hash] options Optional parameters
@option options [Bool] :dry_run If true, no API calls will be made, but the return value will contain the actions which would have been taken
@raise [RightApi::ApiError] If an unrecoverable API error has occurred.
@return [Hash] A hash where the keys are the permission hrefs destroyed, and the keys are the role_title of those permissions
|
[
"Removes",
"all",
"permissions",
"for",
"the",
"user",
"in",
"the",
"specified",
"rightscale",
"account",
"using",
"the",
"supplied",
"client"
] |
bae3355f1471cc7d28de7992c5d5f4ac39fff68b
|
https://github.com/rgeyer/rs_user_policy/blob/bae3355f1471cc7d28de7992c5d5f4ac39fff68b/lib/rs_user_policy/user.rb#L75-L88
|
8,810
|
rgeyer/rs_user_policy
|
lib/rs_user_policy/user.rb
|
RsUserPolicy.User.set_api_permissions
|
def set_api_permissions(permissions, account_href, client, options={})
options = {:dry_run => false}.merge(options)
existing_api_permissions_response = get_api_permissions(account_href)
existing_api_permissions = Hash[existing_api_permissions_response.map{|p| [p.role_title, p] }]
if permissions.length == 0
removed = clear_permissions(account_href, client, options)
@permissions.delete(account_href)
return removed, {}
else
permissions_to_remove = (existing_api_permissions.keys - permissions).map{|p| existing_api_permissions[p]}
remove_response = Hash[permissions_to_remove.map{|p| [p.href, p.role_title]}]
unless options[:dry_run]
remove_response = RsUserPolicy::RightApi::PermissionUtilities.destroy_permissions(permissions_to_remove, client)
end
permissions_to_add = {
@href => Hash[(permissions - existing_api_permissions.keys).map{|p| [p,nil]}]
}
add_response = {}
if options[:dry_run]
href_idx = 0
add_response = {
@href => Hash[(permissions - existing_api_permissions.keys).map{|p| [p,(href_idx += 1)]}]
}
else
add_response = RsUserPolicy::RightApi::PermissionUtilities.create_permissions(permissions_to_add, client)
end
@permissions[account_href] = client.permissions.index(:filter => ["user_href==#{@href}"]) unless options[:dry_run]
return remove_response, Hash[add_response[@href].keys.map{|p| [add_response[@href][p],p]}]
end
end
|
ruby
|
def set_api_permissions(permissions, account_href, client, options={})
options = {:dry_run => false}.merge(options)
existing_api_permissions_response = get_api_permissions(account_href)
existing_api_permissions = Hash[existing_api_permissions_response.map{|p| [p.role_title, p] }]
if permissions.length == 0
removed = clear_permissions(account_href, client, options)
@permissions.delete(account_href)
return removed, {}
else
permissions_to_remove = (existing_api_permissions.keys - permissions).map{|p| existing_api_permissions[p]}
remove_response = Hash[permissions_to_remove.map{|p| [p.href, p.role_title]}]
unless options[:dry_run]
remove_response = RsUserPolicy::RightApi::PermissionUtilities.destroy_permissions(permissions_to_remove, client)
end
permissions_to_add = {
@href => Hash[(permissions - existing_api_permissions.keys).map{|p| [p,nil]}]
}
add_response = {}
if options[:dry_run]
href_idx = 0
add_response = {
@href => Hash[(permissions - existing_api_permissions.keys).map{|p| [p,(href_idx += 1)]}]
}
else
add_response = RsUserPolicy::RightApi::PermissionUtilities.create_permissions(permissions_to_add, client)
end
@permissions[account_href] = client.permissions.index(:filter => ["user_href==#{@href}"]) unless options[:dry_run]
return remove_response, Hash[add_response[@href].keys.map{|p| [add_response[@href][p],p]}]
end
end
|
[
"def",
"set_api_permissions",
"(",
"permissions",
",",
"account_href",
",",
"client",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":dry_run",
"=>",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"existing_api_permissions_response",
"=",
"get_api_permissions",
"(",
"account_href",
")",
"existing_api_permissions",
"=",
"Hash",
"[",
"existing_api_permissions_response",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"p",
".",
"role_title",
",",
"p",
"]",
"}",
"]",
"if",
"permissions",
".",
"length",
"==",
"0",
"removed",
"=",
"clear_permissions",
"(",
"account_href",
",",
"client",
",",
"options",
")",
"@permissions",
".",
"delete",
"(",
"account_href",
")",
"return",
"removed",
",",
"{",
"}",
"else",
"permissions_to_remove",
"=",
"(",
"existing_api_permissions",
".",
"keys",
"-",
"permissions",
")",
".",
"map",
"{",
"|",
"p",
"|",
"existing_api_permissions",
"[",
"p",
"]",
"}",
"remove_response",
"=",
"Hash",
"[",
"permissions_to_remove",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"p",
".",
"href",
",",
"p",
".",
"role_title",
"]",
"}",
"]",
"unless",
"options",
"[",
":dry_run",
"]",
"remove_response",
"=",
"RsUserPolicy",
"::",
"RightApi",
"::",
"PermissionUtilities",
".",
"destroy_permissions",
"(",
"permissions_to_remove",
",",
"client",
")",
"end",
"permissions_to_add",
"=",
"{",
"@href",
"=>",
"Hash",
"[",
"(",
"permissions",
"-",
"existing_api_permissions",
".",
"keys",
")",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"p",
",",
"nil",
"]",
"}",
"]",
"}",
"add_response",
"=",
"{",
"}",
"if",
"options",
"[",
":dry_run",
"]",
"href_idx",
"=",
"0",
"add_response",
"=",
"{",
"@href",
"=>",
"Hash",
"[",
"(",
"permissions",
"-",
"existing_api_permissions",
".",
"keys",
")",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"p",
",",
"(",
"href_idx",
"+=",
"1",
")",
"]",
"}",
"]",
"}",
"else",
"add_response",
"=",
"RsUserPolicy",
"::",
"RightApi",
"::",
"PermissionUtilities",
".",
"create_permissions",
"(",
"permissions_to_add",
",",
"client",
")",
"end",
"@permissions",
"[",
"account_href",
"]",
"=",
"client",
".",
"permissions",
".",
"index",
"(",
":filter",
"=>",
"[",
"\"user_href==#{@href}\"",
"]",
")",
"unless",
"options",
"[",
":dry_run",
"]",
"return",
"remove_response",
",",
"Hash",
"[",
"add_response",
"[",
"@href",
"]",
".",
"keys",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"add_response",
"[",
"@href",
"]",
"[",
"p",
"]",
",",
"p",
"]",
"}",
"]",
"end",
"end"
] |
Removes and adds permissions as appropriate so that the users current permissions reflect
the desired set passed in as "permissions"
@param [Array<String>] permissions The list of desired permissions for the user in the specified account
@param [String] account_href The RightScale API href of the account
@param [RightApi::Client] client An active RightApi::Client instance for the account referenced in account_href
@param [Hash] options Optional parameters
@option options [Bool] :dry_run If true, no API calls will be made, but the return value will contain the actions which would have been taken
@raise [RightApi::ApiError] If an unrecoverable API error has occurred.
@return [Hash,Hash] A tuple where two hashes are returned. The keys of the hashes are the href of the permission, and the values are the role_title of the permission. The first hash is the permissions removed, and the second hash is the permissions added
|
[
"Removes",
"and",
"adds",
"permissions",
"as",
"appropriate",
"so",
"that",
"the",
"users",
"current",
"permissions",
"reflect",
"the",
"desired",
"set",
"passed",
"in",
"as",
"permissions"
] |
bae3355f1471cc7d28de7992c5d5f4ac39fff68b
|
https://github.com/rgeyer/rs_user_policy/blob/bae3355f1471cc7d28de7992c5d5f4ac39fff68b/lib/rs_user_policy/user.rb#L102-L134
|
8,811
|
influenza/hosties
|
lib/hosties/reification.rb
|
Hosties.UsesAttributes.finish
|
def finish
retval = {}
# Ensure all required attributes have been set
@attributes.each do |attr|
val = instance_variable_get "@#{attr}"
raise ArgumentError, "Missing attribute #{attr}" if val.nil?
retval[attr] = val
end
retval
end
|
ruby
|
def finish
retval = {}
# Ensure all required attributes have been set
@attributes.each do |attr|
val = instance_variable_get "@#{attr}"
raise ArgumentError, "Missing attribute #{attr}" if val.nil?
retval[attr] = val
end
retval
end
|
[
"def",
"finish",
"retval",
"=",
"{",
"}",
"# Ensure all required attributes have been set",
"@attributes",
".",
"each",
"do",
"|",
"attr",
"|",
"val",
"=",
"instance_variable_get",
"\"@#{attr}\"",
"raise",
"ArgumentError",
",",
"\"Missing attribute #{attr}\"",
"if",
"val",
".",
"nil?",
"retval",
"[",
"attr",
"]",
"=",
"val",
"end",
"retval",
"end"
] |
Return a hash after verifying everything was set correctly
|
[
"Return",
"a",
"hash",
"after",
"verifying",
"everything",
"was",
"set",
"correctly"
] |
a3030cd4a23a23a0fcc2664c01a497b31e6e49fe
|
https://github.com/influenza/hosties/blob/a3030cd4a23a23a0fcc2664c01a497b31e6e49fe/lib/hosties/reification.rb#L29-L38
|
8,812
|
crapooze/em-xmpp
|
lib/em-xmpp/handler.rb
|
EM::Xmpp.Handler.run_xpath_handlers
|
def run_xpath_handlers(ctx, handlers, remover)
handlers.each do |h|
if (not ctx.done?) and (h.match?(ctx.stanza))
ctx['xpath.handler'] = h
ctx = h.call(ctx)
raise RuntimeError, "xpath handlers should return a Context" unless ctx.is_a?(Context)
send remover, h unless ctx.reuse_handler?
end
end
end
|
ruby
|
def run_xpath_handlers(ctx, handlers, remover)
handlers.each do |h|
if (not ctx.done?) and (h.match?(ctx.stanza))
ctx['xpath.handler'] = h
ctx = h.call(ctx)
raise RuntimeError, "xpath handlers should return a Context" unless ctx.is_a?(Context)
send remover, h unless ctx.reuse_handler?
end
end
end
|
[
"def",
"run_xpath_handlers",
"(",
"ctx",
",",
"handlers",
",",
"remover",
")",
"handlers",
".",
"each",
"do",
"|",
"h",
"|",
"if",
"(",
"not",
"ctx",
".",
"done?",
")",
"and",
"(",
"h",
".",
"match?",
"(",
"ctx",
".",
"stanza",
")",
")",
"ctx",
"[",
"'xpath.handler'",
"]",
"=",
"h",
"ctx",
"=",
"h",
".",
"call",
"(",
"ctx",
")",
"raise",
"RuntimeError",
",",
"\"xpath handlers should return a Context\"",
"unless",
"ctx",
".",
"is_a?",
"(",
"Context",
")",
"send",
"remover",
",",
"h",
"unless",
"ctx",
".",
"reuse_handler?",
"end",
"end",
"end"
] |
runs all handlers, calls the remover method if a handler should be removed
|
[
"runs",
"all",
"handlers",
"calls",
"the",
"remover",
"method",
"if",
"a",
"handler",
"should",
"be",
"removed"
] |
804e139944c88bc317b359754d5ad69b75f42319
|
https://github.com/crapooze/em-xmpp/blob/804e139944c88bc317b359754d5ad69b75f42319/lib/em-xmpp/handler.rb#L210-L219
|
8,813
|
mabako/mta_json
|
lib/mta_json/wrapper.rb
|
MtaJson.Wrapper.update_params
|
def update_params env, json
env[FORM_HASH] = json
env[BODY] = env[FORM_INPUT] = StringIO.new(Rack::Utils.build_query(json))
end
|
ruby
|
def update_params env, json
env[FORM_HASH] = json
env[BODY] = env[FORM_INPUT] = StringIO.new(Rack::Utils.build_query(json))
end
|
[
"def",
"update_params",
"env",
",",
"json",
"env",
"[",
"FORM_HASH",
"]",
"=",
"json",
"env",
"[",
"BODY",
"]",
"=",
"env",
"[",
"FORM_INPUT",
"]",
"=",
"StringIO",
".",
"new",
"(",
"Rack",
"::",
"Utils",
".",
"build_query",
"(",
"json",
")",
")",
"end"
] |
update all of the parameter-related values in the current request's environment
|
[
"update",
"all",
"of",
"the",
"parameter",
"-",
"related",
"values",
"in",
"the",
"current",
"request",
"s",
"environment"
] |
a9462c229ccc0e49c95bbb32b377afe082093fd7
|
https://github.com/mabako/mta_json/blob/a9462c229ccc0e49c95bbb32b377afe082093fd7/lib/mta_json/wrapper.rb#L105-L108
|
8,814
|
mabako/mta_json
|
lib/mta_json/wrapper.rb
|
MtaJson.Wrapper.verify_request_method
|
def verify_request_method env
allowed = ALLOWED_METHODS
allowed |= ALLOWED_METHODS_PRIVATE if whitelisted?(env)
if !allowed.include?(env[METHOD])
raise "Request method #{env[METHOD]} not allowed"
end
end
|
ruby
|
def verify_request_method env
allowed = ALLOWED_METHODS
allowed |= ALLOWED_METHODS_PRIVATE if whitelisted?(env)
if !allowed.include?(env[METHOD])
raise "Request method #{env[METHOD]} not allowed"
end
end
|
[
"def",
"verify_request_method",
"env",
"allowed",
"=",
"ALLOWED_METHODS",
"allowed",
"|=",
"ALLOWED_METHODS_PRIVATE",
"if",
"whitelisted?",
"(",
"env",
")",
"if",
"!",
"allowed",
".",
"include?",
"(",
"env",
"[",
"METHOD",
"]",
")",
"raise",
"\"Request method #{env[METHOD]} not allowed\"",
"end",
"end"
] |
make sure the request came from a whitelisted ip, or uses a publically accessible request method
|
[
"make",
"sure",
"the",
"request",
"came",
"from",
"a",
"whitelisted",
"ip",
"or",
"uses",
"a",
"publically",
"accessible",
"request",
"method"
] |
a9462c229ccc0e49c95bbb32b377afe082093fd7
|
https://github.com/mabako/mta_json/blob/a9462c229ccc0e49c95bbb32b377afe082093fd7/lib/mta_json/wrapper.rb#L111-L117
|
8,815
|
mabako/mta_json
|
lib/mta_json/wrapper.rb
|
MtaJson.Wrapper.update_options
|
def update_options env, options
if options[:method] and (ALLOWED_METHODS | ALLOWED_METHODS_PRIVATE).include?(options[:method])
# (possibly) TODO - pass parameters for GET instead of POST in update_params then?
# see https://github.com/rack/rack/blob/master/lib/rack/request.rb -> def GET
env[METHOD] = options[:method]
end
end
|
ruby
|
def update_options env, options
if options[:method] and (ALLOWED_METHODS | ALLOWED_METHODS_PRIVATE).include?(options[:method])
# (possibly) TODO - pass parameters for GET instead of POST in update_params then?
# see https://github.com/rack/rack/blob/master/lib/rack/request.rb -> def GET
env[METHOD] = options[:method]
end
end
|
[
"def",
"update_options",
"env",
",",
"options",
"if",
"options",
"[",
":method",
"]",
"and",
"(",
"ALLOWED_METHODS",
"|",
"ALLOWED_METHODS_PRIVATE",
")",
".",
"include?",
"(",
"options",
"[",
":method",
"]",
")",
"# (possibly) TODO - pass parameters for GET instead of POST in update_params then?",
"# see https://github.com/rack/rack/blob/master/lib/rack/request.rb -> def GET",
"env",
"[",
"METHOD",
"]",
"=",
"options",
"[",
":method",
"]",
"end",
"end"
] |
updates the options
|
[
"updates",
"the",
"options"
] |
a9462c229ccc0e49c95bbb32b377afe082093fd7
|
https://github.com/mabako/mta_json/blob/a9462c229ccc0e49c95bbb32b377afe082093fd7/lib/mta_json/wrapper.rb#L120-L126
|
8,816
|
mabako/mta_json
|
lib/mta_json/wrapper.rb
|
MtaJson.Wrapper.add_csrf_info
|
def add_csrf_info env
env[CSRF_TOKEN] = env[SESSION][:_csrf_token] = SecureRandom.base64(32).to_s if env[METHOD] != 'GET' and whitelisted?(env)
end
|
ruby
|
def add_csrf_info env
env[CSRF_TOKEN] = env[SESSION][:_csrf_token] = SecureRandom.base64(32).to_s if env[METHOD] != 'GET' and whitelisted?(env)
end
|
[
"def",
"add_csrf_info",
"env",
"env",
"[",
"CSRF_TOKEN",
"]",
"=",
"env",
"[",
"SESSION",
"]",
"[",
":_csrf_token",
"]",
"=",
"SecureRandom",
".",
"base64",
"(",
"32",
")",
".",
"to_s",
"if",
"env",
"[",
"METHOD",
"]",
"!=",
"'GET'",
"and",
"whitelisted?",
"(",
"env",
")",
"end"
] |
adds csrf info to non-GET requests of whitelisted IPs
|
[
"adds",
"csrf",
"info",
"to",
"non",
"-",
"GET",
"requests",
"of",
"whitelisted",
"IPs"
] |
a9462c229ccc0e49c95bbb32b377afe082093fd7
|
https://github.com/mabako/mta_json/blob/a9462c229ccc0e49c95bbb32b377afe082093fd7/lib/mta_json/wrapper.rb#L129-L131
|
8,817
|
polleverywhere/cerealizer
|
lib/cerealizer.rb
|
Cerealizer.Base.read_keys
|
def read_keys
self.class.keys.inject Hash.new do |hash, key|
hash[key.name] = proxy_reader(key.name) if readable?(key.name)
hash
end
end
|
ruby
|
def read_keys
self.class.keys.inject Hash.new do |hash, key|
hash[key.name] = proxy_reader(key.name) if readable?(key.name)
hash
end
end
|
[
"def",
"read_keys",
"self",
".",
"class",
".",
"keys",
".",
"inject",
"Hash",
".",
"new",
"do",
"|",
"hash",
",",
"key",
"|",
"hash",
"[",
"key",
".",
"name",
"]",
"=",
"proxy_reader",
"(",
"key",
".",
"name",
")",
"if",
"readable?",
"(",
"key",
".",
"name",
")",
"hash",
"end",
"end"
] |
Call methods on the object that's being presented and create a flat
hash for these mofos.
|
[
"Call",
"methods",
"on",
"the",
"object",
"that",
"s",
"being",
"presented",
"and",
"create",
"a",
"flat",
"hash",
"for",
"these",
"mofos",
"."
] |
f7a5ef6a543427e5fe7439da6fb9da08b7bc5caf
|
https://github.com/polleverywhere/cerealizer/blob/f7a5ef6a543427e5fe7439da6fb9da08b7bc5caf/lib/cerealizer.rb#L24-L29
|
8,818
|
polleverywhere/cerealizer
|
lib/cerealizer.rb
|
Cerealizer.Base.write_keys
|
def write_keys(attrs)
attrs.each { |key, value| proxy_writer(key, value) if writeable?(key) }
self
end
|
ruby
|
def write_keys(attrs)
attrs.each { |key, value| proxy_writer(key, value) if writeable?(key) }
self
end
|
[
"def",
"write_keys",
"(",
"attrs",
")",
"attrs",
".",
"each",
"{",
"|",
"key",
",",
"value",
"|",
"proxy_writer",
"(",
"key",
",",
"value",
")",
"if",
"writeable?",
"(",
"key",
")",
"}",
"self",
"end"
] |
Update the attrs on zie model.
|
[
"Update",
"the",
"attrs",
"on",
"zie",
"model",
"."
] |
f7a5ef6a543427e5fe7439da6fb9da08b7bc5caf
|
https://github.com/polleverywhere/cerealizer/blob/f7a5ef6a543427e5fe7439da6fb9da08b7bc5caf/lib/cerealizer.rb#L32-L35
|
8,819
|
polleverywhere/cerealizer
|
lib/cerealizer.rb
|
Cerealizer.Base.proxy_writer
|
def proxy_writer(key, *args)
meth = "#{key}="
if self.respond_to? meth
self.send(meth, *args)
else
object.send(meth, *args)
end
end
|
ruby
|
def proxy_writer(key, *args)
meth = "#{key}="
if self.respond_to? meth
self.send(meth, *args)
else
object.send(meth, *args)
end
end
|
[
"def",
"proxy_writer",
"(",
"key",
",",
"*",
"args",
")",
"meth",
"=",
"\"#{key}=\"",
"if",
"self",
".",
"respond_to?",
"meth",
"self",
".",
"send",
"(",
"meth",
",",
"args",
")",
"else",
"object",
".",
"send",
"(",
"meth",
",",
"args",
")",
"end",
"end"
] |
Proxy the writer to zie object.
|
[
"Proxy",
"the",
"writer",
"to",
"zie",
"object",
"."
] |
f7a5ef6a543427e5fe7439da6fb9da08b7bc5caf
|
https://github.com/polleverywhere/cerealizer/blob/f7a5ef6a543427e5fe7439da6fb9da08b7bc5caf/lib/cerealizer.rb#L76-L83
|
8,820
|
ktonon/code_node
|
spec/fixtures/activerecord/src/active_record/fixtures.rb
|
ActiveRecord.Fixtures.table_rows
|
def table_rows
now = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now
now = now.to_s(:db)
# allow a standard key to be used for doing defaults in YAML
fixtures.delete('DEFAULTS')
# track any join tables we need to insert later
rows = Hash.new { |h,table| h[table] = [] }
rows[table_name] = fixtures.map do |label, fixture|
row = fixture.to_hash
if model_class && model_class < ActiveRecord::Base
# fill in timestamp columns if they aren't specified and the model is set to record_timestamps
if model_class.record_timestamps
timestamp_column_names.each do |name|
row[name] = now unless row.key?(name)
end
end
# interpolate the fixture label
row.each do |key, value|
row[key] = label if value == "$LABEL"
end
# generate a primary key if necessary
if has_primary_key_column? && !row.include?(primary_key_name)
row[primary_key_name] = ActiveRecord::Fixtures.identify(label)
end
# If STI is used, find the correct subclass for association reflection
reflection_class =
if row.include?(inheritance_column_name)
row[inheritance_column_name].constantize rescue model_class
else
model_class
end
reflection_class.reflect_on_all_associations.each do |association|
case association.macro
when :belongs_to
# Do not replace association name with association foreign key if they are named the same
fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s
if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
if association.options[:polymorphic] && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
# support polymorphic belongs_to as "label (Type)"
row[association.foreign_type] = $1
end
row[fk_name] = ActiveRecord::Fixtures.identify(value)
end
when :has_and_belongs_to_many
if (targets = row.delete(association.name.to_s))
targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
table_name = association.options[:join_table]
rows[table_name].concat targets.map { |target|
{ association.foreign_key => row[primary_key_name],
association.association_foreign_key => ActiveRecord::Fixtures.identify(target) }
}
end
end
end
end
row
end
rows
end
|
ruby
|
def table_rows
now = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now
now = now.to_s(:db)
# allow a standard key to be used for doing defaults in YAML
fixtures.delete('DEFAULTS')
# track any join tables we need to insert later
rows = Hash.new { |h,table| h[table] = [] }
rows[table_name] = fixtures.map do |label, fixture|
row = fixture.to_hash
if model_class && model_class < ActiveRecord::Base
# fill in timestamp columns if they aren't specified and the model is set to record_timestamps
if model_class.record_timestamps
timestamp_column_names.each do |name|
row[name] = now unless row.key?(name)
end
end
# interpolate the fixture label
row.each do |key, value|
row[key] = label if value == "$LABEL"
end
# generate a primary key if necessary
if has_primary_key_column? && !row.include?(primary_key_name)
row[primary_key_name] = ActiveRecord::Fixtures.identify(label)
end
# If STI is used, find the correct subclass for association reflection
reflection_class =
if row.include?(inheritance_column_name)
row[inheritance_column_name].constantize rescue model_class
else
model_class
end
reflection_class.reflect_on_all_associations.each do |association|
case association.macro
when :belongs_to
# Do not replace association name with association foreign key if they are named the same
fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s
if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
if association.options[:polymorphic] && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
# support polymorphic belongs_to as "label (Type)"
row[association.foreign_type] = $1
end
row[fk_name] = ActiveRecord::Fixtures.identify(value)
end
when :has_and_belongs_to_many
if (targets = row.delete(association.name.to_s))
targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
table_name = association.options[:join_table]
rows[table_name].concat targets.map { |target|
{ association.foreign_key => row[primary_key_name],
association.association_foreign_key => ActiveRecord::Fixtures.identify(target) }
}
end
end
end
end
row
end
rows
end
|
[
"def",
"table_rows",
"now",
"=",
"ActiveRecord",
"::",
"Base",
".",
"default_timezone",
"==",
":utc",
"?",
"Time",
".",
"now",
".",
"utc",
":",
"Time",
".",
"now",
"now",
"=",
"now",
".",
"to_s",
"(",
":db",
")",
"# allow a standard key to be used for doing defaults in YAML",
"fixtures",
".",
"delete",
"(",
"'DEFAULTS'",
")",
"# track any join tables we need to insert later",
"rows",
"=",
"Hash",
".",
"new",
"{",
"|",
"h",
",",
"table",
"|",
"h",
"[",
"table",
"]",
"=",
"[",
"]",
"}",
"rows",
"[",
"table_name",
"]",
"=",
"fixtures",
".",
"map",
"do",
"|",
"label",
",",
"fixture",
"|",
"row",
"=",
"fixture",
".",
"to_hash",
"if",
"model_class",
"&&",
"model_class",
"<",
"ActiveRecord",
"::",
"Base",
"# fill in timestamp columns if they aren't specified and the model is set to record_timestamps",
"if",
"model_class",
".",
"record_timestamps",
"timestamp_column_names",
".",
"each",
"do",
"|",
"name",
"|",
"row",
"[",
"name",
"]",
"=",
"now",
"unless",
"row",
".",
"key?",
"(",
"name",
")",
"end",
"end",
"# interpolate the fixture label",
"row",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"row",
"[",
"key",
"]",
"=",
"label",
"if",
"value",
"==",
"\"$LABEL\"",
"end",
"# generate a primary key if necessary",
"if",
"has_primary_key_column?",
"&&",
"!",
"row",
".",
"include?",
"(",
"primary_key_name",
")",
"row",
"[",
"primary_key_name",
"]",
"=",
"ActiveRecord",
"::",
"Fixtures",
".",
"identify",
"(",
"label",
")",
"end",
"# If STI is used, find the correct subclass for association reflection",
"reflection_class",
"=",
"if",
"row",
".",
"include?",
"(",
"inheritance_column_name",
")",
"row",
"[",
"inheritance_column_name",
"]",
".",
"constantize",
"rescue",
"model_class",
"else",
"model_class",
"end",
"reflection_class",
".",
"reflect_on_all_associations",
".",
"each",
"do",
"|",
"association",
"|",
"case",
"association",
".",
"macro",
"when",
":belongs_to",
"# Do not replace association name with association foreign key if they are named the same",
"fk_name",
"=",
"(",
"association",
".",
"options",
"[",
":foreign_key",
"]",
"||",
"\"#{association.name}_id\"",
")",
".",
"to_s",
"if",
"association",
".",
"name",
".",
"to_s",
"!=",
"fk_name",
"&&",
"value",
"=",
"row",
".",
"delete",
"(",
"association",
".",
"name",
".",
"to_s",
")",
"if",
"association",
".",
"options",
"[",
":polymorphic",
"]",
"&&",
"value",
".",
"sub!",
"(",
"/",
"\\s",
"\\(",
"\\)",
"\\)",
"\\s",
"/",
",",
"\"\"",
")",
"# support polymorphic belongs_to as \"label (Type)\"",
"row",
"[",
"association",
".",
"foreign_type",
"]",
"=",
"$1",
"end",
"row",
"[",
"fk_name",
"]",
"=",
"ActiveRecord",
"::",
"Fixtures",
".",
"identify",
"(",
"value",
")",
"end",
"when",
":has_and_belongs_to_many",
"if",
"(",
"targets",
"=",
"row",
".",
"delete",
"(",
"association",
".",
"name",
".",
"to_s",
")",
")",
"targets",
"=",
"targets",
".",
"is_a?",
"(",
"Array",
")",
"?",
"targets",
":",
"targets",
".",
"split",
"(",
"/",
"\\s",
"\\s",
"/",
")",
"table_name",
"=",
"association",
".",
"options",
"[",
":join_table",
"]",
"rows",
"[",
"table_name",
"]",
".",
"concat",
"targets",
".",
"map",
"{",
"|",
"target",
"|",
"{",
"association",
".",
"foreign_key",
"=>",
"row",
"[",
"primary_key_name",
"]",
",",
"association",
".",
"association_foreign_key",
"=>",
"ActiveRecord",
"::",
"Fixtures",
".",
"identify",
"(",
"target",
")",
"}",
"}",
"end",
"end",
"end",
"end",
"row",
"end",
"rows",
"end"
] |
Return a hash of rows to be inserted. The key is the table, the value is
a list of rows to insert to that table.
|
[
"Return",
"a",
"hash",
"of",
"rows",
"to",
"be",
"inserted",
".",
"The",
"key",
"is",
"the",
"table",
"the",
"value",
"is",
"a",
"list",
"of",
"rows",
"to",
"insert",
"to",
"that",
"table",
"."
] |
48d5d1a7442d9cade602be4fb782a1b56c7677f5
|
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/fixtures.rb#L569-L638
|
8,821
|
kukushkin/mimi-core
|
lib/mimi/core.rb
|
Mimi.Core.use
|
def use(mod, opts = {})
raise ArgumentError, "#{mod} is not a Mimi module" unless mod < Mimi::Core::Module
mod.configure(opts)
used_modules << mod unless used_modules.include?(mod)
true
end
|
ruby
|
def use(mod, opts = {})
raise ArgumentError, "#{mod} is not a Mimi module" unless mod < Mimi::Core::Module
mod.configure(opts)
used_modules << mod unless used_modules.include?(mod)
true
end
|
[
"def",
"use",
"(",
"mod",
",",
"opts",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"#{mod} is not a Mimi module\"",
"unless",
"mod",
"<",
"Mimi",
"::",
"Core",
"::",
"Module",
"mod",
".",
"configure",
"(",
"opts",
")",
"used_modules",
"<<",
"mod",
"unless",
"used_modules",
".",
"include?",
"(",
"mod",
")",
"true",
"end"
] |
Use the given module
|
[
"Use",
"the",
"given",
"module"
] |
c483360a23a373d56511c3d23e0551e690dfaf17
|
https://github.com/kukushkin/mimi-core/blob/c483360a23a373d56511c3d23e0551e690dfaf17/lib/mimi/core.rb#L33-L38
|
8,822
|
kukushkin/mimi-core
|
lib/mimi/core.rb
|
Mimi.Core.require_files
|
def require_files(glob, root_path = app_root_path)
Pathname.glob(root_path.join(glob)).each do |filename|
require filename.expand_path
end
end
|
ruby
|
def require_files(glob, root_path = app_root_path)
Pathname.glob(root_path.join(glob)).each do |filename|
require filename.expand_path
end
end
|
[
"def",
"require_files",
"(",
"glob",
",",
"root_path",
"=",
"app_root_path",
")",
"Pathname",
".",
"glob",
"(",
"root_path",
".",
"join",
"(",
"glob",
")",
")",
".",
"each",
"do",
"|",
"filename",
"|",
"require",
"filename",
".",
"expand_path",
"end",
"end"
] |
Requires all files that match the glob.
|
[
"Requires",
"all",
"files",
"that",
"match",
"the",
"glob",
"."
] |
c483360a23a373d56511c3d23e0551e690dfaf17
|
https://github.com/kukushkin/mimi-core/blob/c483360a23a373d56511c3d23e0551e690dfaf17/lib/mimi/core.rb#L60-L64
|
8,823
|
davidan1981/rails-identity
|
app/models/rails_identity/user.rb
|
RailsIdentity.User.valid_user
|
def valid_user
if (self.username.blank? || self.password_digest.blank?) &&
(self.oauth_provider.blank? || self.oauth_uid.blank?)
errors.add(:username, " and password OR oauth must be specified")
end
end
|
ruby
|
def valid_user
if (self.username.blank? || self.password_digest.blank?) &&
(self.oauth_provider.blank? || self.oauth_uid.blank?)
errors.add(:username, " and password OR oauth must be specified")
end
end
|
[
"def",
"valid_user",
"if",
"(",
"self",
".",
"username",
".",
"blank?",
"||",
"self",
".",
"password_digest",
".",
"blank?",
")",
"&&",
"(",
"self",
".",
"oauth_provider",
".",
"blank?",
"||",
"self",
".",
"oauth_uid",
".",
"blank?",
")",
"errors",
".",
"add",
"(",
":username",
",",
"\" and password OR oauth must be specified\"",
")",
"end",
"end"
] |
This method validates if the user object is valid. A user is valid if
username and password exist OR oauth integration exists.
|
[
"This",
"method",
"validates",
"if",
"the",
"user",
"object",
"is",
"valid",
".",
"A",
"user",
"is",
"valid",
"if",
"username",
"and",
"password",
"exist",
"OR",
"oauth",
"integration",
"exists",
"."
] |
12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0
|
https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/models/rails_identity/user.rb#L20-L25
|
8,824
|
davidan1981/rails-identity
|
app/models/rails_identity/user.rb
|
RailsIdentity.User.issue_token
|
def issue_token(kind)
session = Session.new(user: self, seconds: 3600)
session.save
if kind == :reset_token
self.reset_token = session.token
elsif kind == :verification_token
self.verification_token = session.token
end
end
|
ruby
|
def issue_token(kind)
session = Session.new(user: self, seconds: 3600)
session.save
if kind == :reset_token
self.reset_token = session.token
elsif kind == :verification_token
self.verification_token = session.token
end
end
|
[
"def",
"issue_token",
"(",
"kind",
")",
"session",
"=",
"Session",
".",
"new",
"(",
"user",
":",
"self",
",",
"seconds",
":",
"3600",
")",
"session",
".",
"save",
"if",
"kind",
"==",
":reset_token",
"self",
".",
"reset_token",
"=",
"session",
".",
"token",
"elsif",
"kind",
"==",
":verification_token",
"self",
".",
"verification_token",
"=",
"session",
".",
"token",
"end",
"end"
] |
This method will generate a reset token that lasts for an hour.
|
[
"This",
"method",
"will",
"generate",
"a",
"reset",
"token",
"that",
"lasts",
"for",
"an",
"hour",
"."
] |
12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0
|
https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/models/rails_identity/user.rb#L66-L74
|
8,825
|
jeremyd/virtualmonkey
|
lib/virtualmonkey/elb_runner.rb
|
VirtualMonkey.ELBRunner.lookup_scripts
|
def lookup_scripts
scripts = [
[ 'connect', 'ELB connect' ],
[ 'disconnect', 'ELB disconnect' ]
]
# @scripts_to_run = {}
server = @servers.first
server.settings
st = ServerTemplate.find(server.server_template_href)
lookup_scripts_table(st,scripts)
# @scripts_to_run['connect'] = st.executables.detect { |ex| ex.name =~ /ELB connect/i }
# @scripts_to_run['disconnect'] = st.executables.detect { |ex| ex.name =~ /ELB disconnect/i }
end
|
ruby
|
def lookup_scripts
scripts = [
[ 'connect', 'ELB connect' ],
[ 'disconnect', 'ELB disconnect' ]
]
# @scripts_to_run = {}
server = @servers.first
server.settings
st = ServerTemplate.find(server.server_template_href)
lookup_scripts_table(st,scripts)
# @scripts_to_run['connect'] = st.executables.detect { |ex| ex.name =~ /ELB connect/i }
# @scripts_to_run['disconnect'] = st.executables.detect { |ex| ex.name =~ /ELB disconnect/i }
end
|
[
"def",
"lookup_scripts",
"scripts",
"=",
"[",
"[",
"'connect'",
",",
"'ELB connect'",
"]",
",",
"[",
"'disconnect'",
",",
"'ELB disconnect'",
"]",
"]",
"# @scripts_to_run = {}",
"server",
"=",
"@servers",
".",
"first",
"server",
".",
"settings",
"st",
"=",
"ServerTemplate",
".",
"find",
"(",
"server",
".",
"server_template_href",
")",
"lookup_scripts_table",
"(",
"st",
",",
"scripts",
")",
"# @scripts_to_run['connect'] = st.executables.detect { |ex| ex.name =~ /ELB connect/i }",
"# @scripts_to_run['disconnect'] = st.executables.detect { |ex| ex.name =~ /ELB disconnect/i }",
"end"
] |
Grab the scripts we plan to excersize
|
[
"Grab",
"the",
"scripts",
"we",
"plan",
"to",
"excersize"
] |
b2c7255f20ac5ec881eb90afbb5e712160db0dcb
|
https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/elb_runner.rb#L110-L122
|
8,826
|
jeremyd/virtualmonkey
|
lib/virtualmonkey/elb_runner.rb
|
VirtualMonkey.ELBRunner.log_rotation_checks
|
def log_rotation_checks
detect_os
# this works for php
app_servers.each do |server|
server.settings
force_log_rotation(server)
log_check(server,"/mnt/log/#{server.apache_str}/access.log.1")
end
end
|
ruby
|
def log_rotation_checks
detect_os
# this works for php
app_servers.each do |server|
server.settings
force_log_rotation(server)
log_check(server,"/mnt/log/#{server.apache_str}/access.log.1")
end
end
|
[
"def",
"log_rotation_checks",
"detect_os",
"# this works for php",
"app_servers",
".",
"each",
"do",
"|",
"server",
"|",
"server",
".",
"settings",
"force_log_rotation",
"(",
"server",
")",
"log_check",
"(",
"server",
",",
"\"/mnt/log/#{server.apache_str}/access.log.1\"",
")",
"end",
"end"
] |
This is really just a PHP server check. relocate?
|
[
"This",
"is",
"really",
"just",
"a",
"PHP",
"server",
"check",
".",
"relocate?"
] |
b2c7255f20ac5ec881eb90afbb5e712160db0dcb
|
https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/elb_runner.rb#L125-L134
|
8,827
|
ecbypi/guise
|
lib/guise/introspection.rb
|
Guise.Introspection.has_guise?
|
def has_guise?(value)
value = value.to_s.classify
unless guise_options.values.include?(value)
raise ArgumentError, "no such guise #{value}"
end
association(guise_options.association_name).reader.any? do |record|
!record.marked_for_destruction? &&
record[guise_options.attribute] == value
end
end
|
ruby
|
def has_guise?(value)
value = value.to_s.classify
unless guise_options.values.include?(value)
raise ArgumentError, "no such guise #{value}"
end
association(guise_options.association_name).reader.any? do |record|
!record.marked_for_destruction? &&
record[guise_options.attribute] == value
end
end
|
[
"def",
"has_guise?",
"(",
"value",
")",
"value",
"=",
"value",
".",
"to_s",
".",
"classify",
"unless",
"guise_options",
".",
"values",
".",
"include?",
"(",
"value",
")",
"raise",
"ArgumentError",
",",
"\"no such guise #{value}\"",
"end",
"association",
"(",
"guise_options",
".",
"association_name",
")",
".",
"reader",
".",
"any?",
"do",
"|",
"record",
"|",
"!",
"record",
".",
"marked_for_destruction?",
"&&",
"record",
"[",
"guise_options",
".",
"attribute",
"]",
"==",
"value",
"end",
"end"
] |
Checks if the record has a `guise` record identified by on the specified
`value`.
@param [String, Class, Symbol] value `guise` to check
@return [true, false]
|
[
"Checks",
"if",
"the",
"record",
"has",
"a",
"guise",
"record",
"identified",
"by",
"on",
"the",
"specified",
"value",
"."
] |
f202fdec5a01514bde536b6f37b1129b9351fa00
|
https://github.com/ecbypi/guise/blob/f202fdec5a01514bde536b6f37b1129b9351fa00/lib/guise/introspection.rb#L12-L23
|
8,828
|
koffeinfrei/technologist
|
lib/technologist/yaml_parser.rb
|
Technologist.YamlParser.instancify
|
def instancify(technology, rule)
class_name, attributes = send("parse_rule_of_type_#{rule.class.name.downcase}", rule)
Rule.const_get("#{class_name}Rule").new(technology, attributes)
end
|
ruby
|
def instancify(technology, rule)
class_name, attributes = send("parse_rule_of_type_#{rule.class.name.downcase}", rule)
Rule.const_get("#{class_name}Rule").new(technology, attributes)
end
|
[
"def",
"instancify",
"(",
"technology",
",",
"rule",
")",
"class_name",
",",
"attributes",
"=",
"send",
"(",
"\"parse_rule_of_type_#{rule.class.name.downcase}\"",
",",
"rule",
")",
"Rule",
".",
"const_get",
"(",
"\"#{class_name}Rule\"",
")",
".",
"new",
"(",
"technology",
",",
"attributes",
")",
"end"
] |
Create a class instance for a rule entry
|
[
"Create",
"a",
"class",
"instance",
"for",
"a",
"rule",
"entry"
] |
0fd1d5c07c6d73ac5a184b26ad6db40981388573
|
https://github.com/koffeinfrei/technologist/blob/0fd1d5c07c6d73ac5a184b26ad6db40981388573/lib/technologist/yaml_parser.rb#L33-L37
|
8,829
|
linrock/favicon_party
|
lib/favicon_party/fetcher.rb
|
FaviconParty.Fetcher.find_favicon_urls_in_html
|
def find_favicon_urls_in_html(html)
doc = Nokogiri.parse html
candidate_urls = doc.css(ICON_SELECTORS.join(",")).map {|e| e.attr('href') }.compact
candidate_urls.sort_by! {|href|
if href =~ /\.ico/
0
elsif href =~ /\.png/
1
else
2
end
}
uri = URI final_url
candidate_urls.map! do |href|
href = URI.encode(URI.decode(href.strip))
if href =~ /\A\/\//
href = "#{uri.scheme}:#{href}"
elsif href !~ /\Ahttp/
# Ignore invalid URLS - ex. {http://i50.tinypic.com/wbuzcn.png}
href = URI.join(url_root, href).to_s rescue nil
end
href
end.compact.uniq
end
|
ruby
|
def find_favicon_urls_in_html(html)
doc = Nokogiri.parse html
candidate_urls = doc.css(ICON_SELECTORS.join(",")).map {|e| e.attr('href') }.compact
candidate_urls.sort_by! {|href|
if href =~ /\.ico/
0
elsif href =~ /\.png/
1
else
2
end
}
uri = URI final_url
candidate_urls.map! do |href|
href = URI.encode(URI.decode(href.strip))
if href =~ /\A\/\//
href = "#{uri.scheme}:#{href}"
elsif href !~ /\Ahttp/
# Ignore invalid URLS - ex. {http://i50.tinypic.com/wbuzcn.png}
href = URI.join(url_root, href).to_s rescue nil
end
href
end.compact.uniq
end
|
[
"def",
"find_favicon_urls_in_html",
"(",
"html",
")",
"doc",
"=",
"Nokogiri",
".",
"parse",
"html",
"candidate_urls",
"=",
"doc",
".",
"css",
"(",
"ICON_SELECTORS",
".",
"join",
"(",
"\",\"",
")",
")",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"attr",
"(",
"'href'",
")",
"}",
".",
"compact",
"candidate_urls",
".",
"sort_by!",
"{",
"|",
"href",
"|",
"if",
"href",
"=~",
"/",
"\\.",
"/",
"0",
"elsif",
"href",
"=~",
"/",
"\\.",
"/",
"1",
"else",
"2",
"end",
"}",
"uri",
"=",
"URI",
"final_url",
"candidate_urls",
".",
"map!",
"do",
"|",
"href",
"|",
"href",
"=",
"URI",
".",
"encode",
"(",
"URI",
".",
"decode",
"(",
"href",
".",
"strip",
")",
")",
"if",
"href",
"=~",
"/",
"\\A",
"\\/",
"\\/",
"/",
"href",
"=",
"\"#{uri.scheme}:#{href}\"",
"elsif",
"href",
"!~",
"/",
"\\A",
"/",
"# Ignore invalid URLS - ex. {http://i50.tinypic.com/wbuzcn.png}",
"href",
"=",
"URI",
".",
"join",
"(",
"url_root",
",",
"href",
")",
".",
"to_s",
"rescue",
"nil",
"end",
"href",
"end",
".",
"compact",
".",
"uniq",
"end"
] |
Tries to find favicon urls from the html content of query_url
|
[
"Tries",
"to",
"find",
"favicon",
"urls",
"from",
"the",
"html",
"content",
"of",
"query_url"
] |
645d3c6f4a7152bf705ac092976a74f405f83ca1
|
https://github.com/linrock/favicon_party/blob/645d3c6f4a7152bf705ac092976a74f405f83ca1/lib/favicon_party/fetcher.rb#L70-L93
|
8,830
|
linrock/favicon_party
|
lib/favicon_party/fetcher.rb
|
FaviconParty.Fetcher.final_url
|
def final_url
return @final_url if !@final_url.nil?
location = final_location(FaviconParty::HTTPClient.head(@query_url))
if !location.nil?
if location =~ /\Ahttp/
@final_url = URI.encode location
else
uri = URI @query_url
root = "#{uri.scheme}://#{uri.host}"
@final_url = URI.encode URI.join(root, location).to_s
end
end
if !@final_url.nil?
if %w( 127.0.0.1 localhost ).any? {|host| @final_url.include? host }
# TODO Exception for invalid final urls
@final_url = @query_url
end
return @final_url
end
@final_url = @query_url
end
|
ruby
|
def final_url
return @final_url if !@final_url.nil?
location = final_location(FaviconParty::HTTPClient.head(@query_url))
if !location.nil?
if location =~ /\Ahttp/
@final_url = URI.encode location
else
uri = URI @query_url
root = "#{uri.scheme}://#{uri.host}"
@final_url = URI.encode URI.join(root, location).to_s
end
end
if !@final_url.nil?
if %w( 127.0.0.1 localhost ).any? {|host| @final_url.include? host }
# TODO Exception for invalid final urls
@final_url = @query_url
end
return @final_url
end
@final_url = @query_url
end
|
[
"def",
"final_url",
"return",
"@final_url",
"if",
"!",
"@final_url",
".",
"nil?",
"location",
"=",
"final_location",
"(",
"FaviconParty",
"::",
"HTTPClient",
".",
"head",
"(",
"@query_url",
")",
")",
"if",
"!",
"location",
".",
"nil?",
"if",
"location",
"=~",
"/",
"\\A",
"/",
"@final_url",
"=",
"URI",
".",
"encode",
"location",
"else",
"uri",
"=",
"URI",
"@query_url",
"root",
"=",
"\"#{uri.scheme}://#{uri.host}\"",
"@final_url",
"=",
"URI",
".",
"encode",
"URI",
".",
"join",
"(",
"root",
",",
"location",
")",
".",
"to_s",
"end",
"end",
"if",
"!",
"@final_url",
".",
"nil?",
"if",
"%w(",
"127.0.0.1",
"localhost",
")",
".",
"any?",
"{",
"|",
"host",
"|",
"@final_url",
".",
"include?",
"host",
"}",
"# TODO Exception for invalid final urls",
"@final_url",
"=",
"@query_url",
"end",
"return",
"@final_url",
"end",
"@final_url",
"=",
"@query_url",
"end"
] |
Follow redirects from the query url to get to the last url
|
[
"Follow",
"redirects",
"from",
"the",
"query",
"url",
"to",
"get",
"to",
"the",
"last",
"url"
] |
645d3c6f4a7152bf705ac092976a74f405f83ca1
|
https://github.com/linrock/favicon_party/blob/645d3c6f4a7152bf705ac092976a74f405f83ca1/lib/favicon_party/fetcher.rb#L108-L128
|
8,831
|
bilus/kawaii
|
lib/kawaii/routing_methods.rb
|
Kawaii.RoutingMethods.context
|
def context(path, &block)
ctx = RouteContext.new(self, path)
# @todo Is there a better way to keep ordering of routes?
# An alternative would be to enter each route in a context only once
# (with 'prefix' based on containing contexts).
# On the other hand, we're only doing that when compiling routes, further
# processing is faster this way.
ctx.instance_eval(&block)
ctx.methods_used.each do |meth|
add_route!(meth, ctx)
end
end
|
ruby
|
def context(path, &block)
ctx = RouteContext.new(self, path)
# @todo Is there a better way to keep ordering of routes?
# An alternative would be to enter each route in a context only once
# (with 'prefix' based on containing contexts).
# On the other hand, we're only doing that when compiling routes, further
# processing is faster this way.
ctx.instance_eval(&block)
ctx.methods_used.each do |meth|
add_route!(meth, ctx)
end
end
|
[
"def",
"context",
"(",
"path",
",",
"&",
"block",
")",
"ctx",
"=",
"RouteContext",
".",
"new",
"(",
"self",
",",
"path",
")",
"# @todo Is there a better way to keep ordering of routes?",
"# An alternative would be to enter each route in a context only once",
"# (with 'prefix' based on containing contexts).",
"# On the other hand, we're only doing that when compiling routes, further",
"# processing is faster this way.",
"ctx",
".",
"instance_eval",
"(",
"block",
")",
"ctx",
".",
"methods_used",
".",
"each",
"do",
"|",
"meth",
"|",
"add_route!",
"(",
"meth",
",",
"ctx",
")",
"end",
"end"
] |
Create a context for route nesting.
@param path [String, Regexp, Matcher] any path specification which can
be consumed by {Matcher.compile}
@param block the route handler
@yield to the given block
@example A simple context
context '/foo' do
get '/bar' do
end
end
|
[
"Create",
"a",
"context",
"for",
"route",
"nesting",
"."
] |
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
|
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/routing_methods.rb#L80-L91
|
8,832
|
bilus/kawaii
|
lib/kawaii/routing_methods.rb
|
Kawaii.RoutingMethods.match
|
def match(env)
routes[env[Rack::REQUEST_METHOD]]
.lazy # Lazy to avoid unnecessary calls to #match.
.map { |r| r.match(env) }
.find { |r| !r.nil? }
end
|
ruby
|
def match(env)
routes[env[Rack::REQUEST_METHOD]]
.lazy # Lazy to avoid unnecessary calls to #match.
.map { |r| r.match(env) }
.find { |r| !r.nil? }
end
|
[
"def",
"match",
"(",
"env",
")",
"routes",
"[",
"env",
"[",
"Rack",
"::",
"REQUEST_METHOD",
"]",
"]",
".",
"lazy",
"# Lazy to avoid unnecessary calls to #match.",
".",
"map",
"{",
"|",
"r",
"|",
"r",
".",
"match",
"(",
"env",
")",
"}",
".",
"find",
"{",
"|",
"r",
"|",
"!",
"r",
".",
"nil?",
"}",
"end"
] |
Tries to match against a Rack environment.
@param env [Hash] Rack environment
@return [Route] matching route. Can be nil if no match found.
|
[
"Tries",
"to",
"match",
"against",
"a",
"Rack",
"environment",
"."
] |
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
|
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/routing_methods.rb#L96-L101
|
8,833
|
thedamfr/glass
|
lib/glass/timeline/timeline_item.rb
|
Glass.TimelineItem.insert!
|
def insert!(mirror=@client)
timeline_item = self
result = []
if file_upload?
for file in file_to_upload
media = Google::APIClient::UploadIO.new(file.contentUrl, file.content_type)
result << client.execute!(
:api_method => mirror.timeline.insert,
:body_object => timeline_item,
:media => media,
:parameters => {
:uploadType => 'multipart',
:alt => 'json'})
end
else
result << client.execute(
:api_method => mirror.timeline.insert,
:body_object => timeline_item)
end
return result.data
end
|
ruby
|
def insert!(mirror=@client)
timeline_item = self
result = []
if file_upload?
for file in file_to_upload
media = Google::APIClient::UploadIO.new(file.contentUrl, file.content_type)
result << client.execute!(
:api_method => mirror.timeline.insert,
:body_object => timeline_item,
:media => media,
:parameters => {
:uploadType => 'multipart',
:alt => 'json'})
end
else
result << client.execute(
:api_method => mirror.timeline.insert,
:body_object => timeline_item)
end
return result.data
end
|
[
"def",
"insert!",
"(",
"mirror",
"=",
"@client",
")",
"timeline_item",
"=",
"self",
"result",
"=",
"[",
"]",
"if",
"file_upload?",
"for",
"file",
"in",
"file_to_upload",
"media",
"=",
"Google",
"::",
"APIClient",
"::",
"UploadIO",
".",
"new",
"(",
"file",
".",
"contentUrl",
",",
"file",
".",
"content_type",
")",
"result",
"<<",
"client",
".",
"execute!",
"(",
":api_method",
"=>",
"mirror",
".",
"timeline",
".",
"insert",
",",
":body_object",
"=>",
"timeline_item",
",",
":media",
"=>",
"media",
",",
":parameters",
"=>",
"{",
":uploadType",
"=>",
"'multipart'",
",",
":alt",
"=>",
"'json'",
"}",
")",
"end",
"else",
"result",
"<<",
"client",
".",
"execute",
"(",
":api_method",
"=>",
"mirror",
".",
"timeline",
".",
"insert",
",",
":body_object",
"=>",
"timeline_item",
")",
"end",
"return",
"result",
".",
"data",
"end"
] |
Insert a new Timeline Item in the user's glass.
@param [Google::APIClient::API] client
Authorized client instance.
@return Array[Google::APIClient::Schema::Mirror::V1::TimelineItem]
Timeline item instance if successful, nil otherwise.
|
[
"Insert",
"a",
"new",
"Timeline",
"Item",
"in",
"the",
"user",
"s",
"glass",
"."
] |
dbbd39d3a3f3d18bd36bd5fbf59d8a9fe2f6d040
|
https://github.com/thedamfr/glass/blob/dbbd39d3a3f3d18bd36bd5fbf59d8a9fe2f6d040/lib/glass/timeline/timeline_item.rb#L359-L379
|
8,834
|
sugaryourcoffee/syclink
|
lib/syclink/link.rb
|
SycLink.Link.select_defined
|
def select_defined(args)
args.select { |k, v| (ATTRS.include? k) && !v.nil? }
end
|
ruby
|
def select_defined(args)
args.select { |k, v| (ATTRS.include? k) && !v.nil? }
end
|
[
"def",
"select_defined",
"(",
"args",
")",
"args",
".",
"select",
"{",
"|",
"k",
",",
"v",
"|",
"(",
"ATTRS",
".",
"include?",
"k",
")",
"&&",
"!",
"v",
".",
"nil?",
"}",
"end"
] |
Based on the ATTRS the args are returned that are included in the ATTRS.
args with nil values are omitted
|
[
"Based",
"on",
"the",
"ATTRS",
"the",
"args",
"are",
"returned",
"that",
"are",
"included",
"in",
"the",
"ATTRS",
".",
"args",
"with",
"nil",
"values",
"are",
"omitted"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/link.rb#L86-L88
|
8,835
|
jeremyvdw/disqussion
|
lib/disqussion/client/exports.rb
|
Disqussion.Exports.exportForum
|
def exportForum(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if args.size == 1
options.merge!(:forum => args[0])
response = post('exports/exportForum', options)
else
puts "#{Kernel.caller.first}: exports.exportForum expects an arguments: forum"
end
end
|
ruby
|
def exportForum(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if args.size == 1
options.merge!(:forum => args[0])
response = post('exports/exportForum', options)
else
puts "#{Kernel.caller.first}: exports.exportForum expects an arguments: forum"
end
end
|
[
"def",
"exportForum",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"if",
"args",
".",
"size",
"==",
"1",
"options",
".",
"merge!",
"(",
":forum",
"=>",
"args",
"[",
"0",
"]",
")",
"response",
"=",
"post",
"(",
"'exports/exportForum'",
",",
"options",
")",
"else",
"puts",
"\"#{Kernel.caller.first}: exports.exportForum expects an arguments: forum\"",
"end",
"end"
] |
Export a forum
@accessibility: public key, secret key
@methods: POST
@format: json, jsonp
@authenticated: true
@limited: false
@param forum [String] Forum short name (aka forum id).
@return [Hashie::Rash] Export infos
@param options [Hash] A customizable set of options.
@option options [String] :format. Defaults to "xml". Choices: xml, xml-old
@example Export forum "the88"
Disqussion::Client.exports.exportForum("the88")
@see: http://disqus.com/api/3.0/exports/exportForum.json
|
[
"Export",
"a",
"forum"
] |
5ad1b0325b7630daf41eb59fc8acbcb785cbc387
|
https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/exports.rb#L16-L24
|
8,836
|
ktonon/code_node
|
spec/fixtures/activerecord/src/active_record/persistence.rb
|
ActiveRecord.Persistence.update_column
|
def update_column(name, value)
name = name.to_s
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
raise ActiveRecordError, "can not update on a new record object" unless persisted?
updated_count = self.class.update_all({ name => value }, self.class.primary_key => id)
raw_write_attribute(name, value)
updated_count == 1
end
|
ruby
|
def update_column(name, value)
name = name.to_s
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
raise ActiveRecordError, "can not update on a new record object" unless persisted?
updated_count = self.class.update_all({ name => value }, self.class.primary_key => id)
raw_write_attribute(name, value)
updated_count == 1
end
|
[
"def",
"update_column",
"(",
"name",
",",
"value",
")",
"name",
"=",
"name",
".",
"to_s",
"raise",
"ActiveRecordError",
",",
"\"#{name} is marked as readonly\"",
"if",
"self",
".",
"class",
".",
"readonly_attributes",
".",
"include?",
"(",
"name",
")",
"raise",
"ActiveRecordError",
",",
"\"can not update on a new record object\"",
"unless",
"persisted?",
"updated_count",
"=",
"self",
".",
"class",
".",
"update_all",
"(",
"{",
"name",
"=>",
"value",
"}",
",",
"self",
".",
"class",
".",
"primary_key",
"=>",
"id",
")",
"raw_write_attribute",
"(",
"name",
",",
"value",
")",
"updated_count",
"==",
"1",
"end"
] |
Updates a single attribute of an object, without calling save.
* Validation is skipped.
* Callbacks are skipped.
* updated_at/updated_on column is not updated if that column is available.
Raises an +ActiveRecordError+ when called on new objects, or when the +name+
attribute is marked as readonly.
|
[
"Updates",
"a",
"single",
"attribute",
"of",
"an",
"object",
"without",
"calling",
"save",
"."
] |
48d5d1a7442d9cade602be4fb782a1b56c7677f5
|
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/persistence.rb#L192-L202
|
8,837
|
tubbo/active_copy
|
lib/active_copy/paths.rb
|
ActiveCopy.Paths.source_path
|
def source_path options={}
@source_path ||= if options[:relative]
File.join collection_path, "#{self.id}.md"
else
File.join root_path, collection_path, "#{self.id}.md"
end
end
|
ruby
|
def source_path options={}
@source_path ||= if options[:relative]
File.join collection_path, "#{self.id}.md"
else
File.join root_path, collection_path, "#{self.id}.md"
end
end
|
[
"def",
"source_path",
"options",
"=",
"{",
"}",
"@source_path",
"||=",
"if",
"options",
"[",
":relative",
"]",
"File",
".",
"join",
"collection_path",
",",
"\"#{self.id}.md\"",
"else",
"File",
".",
"join",
"root_path",
",",
"collection_path",
",",
"\"#{self.id}.md\"",
"end",
"end"
] |
Return absolute path to Markdown file on this machine.
|
[
"Return",
"absolute",
"path",
"to",
"Markdown",
"file",
"on",
"this",
"machine",
"."
] |
63716fdd9283231e9ed0d8ac6af97633d3e97210
|
https://github.com/tubbo/active_copy/blob/63716fdd9283231e9ed0d8ac6af97633d3e97210/lib/active_copy/paths.rb#L40-L46
|
8,838
|
mobyinc/Cathode
|
lib/cathode/update_request.rb
|
Cathode.UpdateRequest.default_action_block
|
def default_action_block
proc do
begin
record = if resource.singular
parent_model = resource.parent.model.find(parent_resource_id)
parent_model.send resource.name
else
record = model.find(params[:id])
end
record.update(instance_eval(&@strong_params))
body record.reload
rescue ActionController::ParameterMissing => error
body error.message
status :bad_request
end
end
end
|
ruby
|
def default_action_block
proc do
begin
record = if resource.singular
parent_model = resource.parent.model.find(parent_resource_id)
parent_model.send resource.name
else
record = model.find(params[:id])
end
record.update(instance_eval(&@strong_params))
body record.reload
rescue ActionController::ParameterMissing => error
body error.message
status :bad_request
end
end
end
|
[
"def",
"default_action_block",
"proc",
"do",
"begin",
"record",
"=",
"if",
"resource",
".",
"singular",
"parent_model",
"=",
"resource",
".",
"parent",
".",
"model",
".",
"find",
"(",
"parent_resource_id",
")",
"parent_model",
".",
"send",
"resource",
".",
"name",
"else",
"record",
"=",
"model",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"end",
"record",
".",
"update",
"(",
"instance_eval",
"(",
"@strong_params",
")",
")",
"body",
"record",
".",
"reload",
"rescue",
"ActionController",
"::",
"ParameterMissing",
"=>",
"error",
"body",
"error",
".",
"message",
"status",
":bad_request",
"end",
"end",
"end"
] |
Sets the default action to update a resource. If the resource is
singular, updates the parent's associated resource. Otherwise, updates the
resource directly.
|
[
"Sets",
"the",
"default",
"action",
"to",
"update",
"a",
"resource",
".",
"If",
"the",
"resource",
"is",
"singular",
"updates",
"the",
"parent",
"s",
"associated",
"resource",
".",
"Otherwise",
"updates",
"the",
"resource",
"directly",
"."
] |
e17be4fb62ad61417e2a3a0a77406459015468a1
|
https://github.com/mobyinc/Cathode/blob/e17be4fb62ad61417e2a3a0a77406459015468a1/lib/cathode/update_request.rb#L7-L24
|
8,839
|
groupdocs-signature-cloud/groupdocs-signature-cloud-ruby
|
lib/groupdocs_signature_cloud/api_client.rb
|
GroupDocsSignatureCloud.ApiClient.deserialize
|
def deserialize(response, return_type)
body = response.body
# handle file downloading - return the File instance processed in request callbacks
# note that response body is empty when the file is written in chunks in request on_body callback
return @tempfile if return_type == 'File'
return nil if body.nil? || body.empty?
# return response body directly for String return type
return body if return_type == 'String'
# ensuring a default content type
content_type = response.headers['Content-Type'] || 'application/json'
raise "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w[String Date DateTime].include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
|
ruby
|
def deserialize(response, return_type)
body = response.body
# handle file downloading - return the File instance processed in request callbacks
# note that response body is empty when the file is written in chunks in request on_body callback
return @tempfile if return_type == 'File'
return nil if body.nil? || body.empty?
# return response body directly for String return type
return body if return_type == 'String'
# ensuring a default content type
content_type = response.headers['Content-Type'] || 'application/json'
raise "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w[String Date DateTime].include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
|
[
"def",
"deserialize",
"(",
"response",
",",
"return_type",
")",
"body",
"=",
"response",
".",
"body",
"# handle file downloading - return the File instance processed in request callbacks",
"# note that response body is empty when the file is written in chunks in request on_body callback",
"return",
"@tempfile",
"if",
"return_type",
"==",
"'File'",
"return",
"nil",
"if",
"body",
".",
"nil?",
"||",
"body",
".",
"empty?",
"# return response body directly for String return type",
"return",
"body",
"if",
"return_type",
"==",
"'String'",
"# ensuring a default content type",
"content_type",
"=",
"response",
".",
"headers",
"[",
"'Content-Type'",
"]",
"||",
"'application/json'",
"raise",
"\"Content-Type is not supported: #{content_type}\"",
"unless",
"json_mime?",
"(",
"content_type",
")",
"begin",
"data",
"=",
"JSON",
".",
"parse",
"(",
"\"[#{body}]\"",
",",
":symbolize_names",
"=>",
"true",
")",
"[",
"0",
"]",
"rescue",
"JSON",
"::",
"ParserError",
"=>",
"e",
"if",
"%w[",
"String",
"Date",
"DateTime",
"]",
".",
"include?",
"(",
"return_type",
")",
"data",
"=",
"body",
"else",
"raise",
"e",
"end",
"end",
"convert_to_type",
"data",
",",
"return_type",
"end"
] |
Deserialize the response to the given return type.
@param [Response] response HTTP response
@param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
|
[
"Deserialize",
"the",
"response",
"to",
"the",
"given",
"return",
"type",
"."
] |
d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0
|
https://github.com/groupdocs-signature-cloud/groupdocs-signature-cloud-ruby/blob/d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0/lib/groupdocs_signature_cloud/api_client.rb#L150-L178
|
8,840
|
davidan1981/rails-identity
|
app/controllers/rails_identity/sessions_controller.rb
|
RailsIdentity.SessionsController.index
|
def index
@sessions = Session.where(user: @user)
expired = []
active = []
@sessions.each do |session|
if session.expired?
expired << session.uuid
else
active << session
end
end
SessionsCleanupJob.perform_later(*expired)
render json: active, except: [:secret]
end
|
ruby
|
def index
@sessions = Session.where(user: @user)
expired = []
active = []
@sessions.each do |session|
if session.expired?
expired << session.uuid
else
active << session
end
end
SessionsCleanupJob.perform_later(*expired)
render json: active, except: [:secret]
end
|
[
"def",
"index",
"@sessions",
"=",
"Session",
".",
"where",
"(",
"user",
":",
"@user",
")",
"expired",
"=",
"[",
"]",
"active",
"=",
"[",
"]",
"@sessions",
".",
"each",
"do",
"|",
"session",
"|",
"if",
"session",
".",
"expired?",
"expired",
"<<",
"session",
".",
"uuid",
"else",
"active",
"<<",
"session",
"end",
"end",
"SessionsCleanupJob",
".",
"perform_later",
"(",
"expired",
")",
"render",
"json",
":",
"active",
",",
"except",
":",
"[",
":secret",
"]",
"end"
] |
Lists all sessions that belong to the specified or authenticated user.
|
[
"Lists",
"all",
"sessions",
"that",
"belong",
"to",
"the",
"specified",
"or",
"authenticated",
"user",
"."
] |
12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0
|
https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/controllers/rails_identity/sessions_controller.rb#L19-L32
|
8,841
|
davidan1981/rails-identity
|
app/controllers/rails_identity/sessions_controller.rb
|
RailsIdentity.SessionsController.create
|
def create
# See if OAuth is used first. When authenticated successfully, either
# the existing user will be found or a new user will be created.
# Failure will be redirected to this action but will not match this
# branch.
if (omniauth_hash = request.env["omniauth.auth"])
@user = User.from_omniauth_hash(omniauth_hash)
# Then see if the request already has authentication. Note that if the
# user does not have access to the specified session owner, 401 will
# be thrown.
elsif accept_auth
@user = @auth_user
# Otherwise, it's a normal login process. Use username and password to
# authenticate. The user must exist, the password must be vaild, and
# the email must have been verified.
else
@user = User.find_by_username(session_params[:username])
if (@user.nil? || !@user.authenticate(session_params[:password]) ||
!@user.verified)
raise ApplicationController::UNAUTHORIZED_ERROR
end
end
# Finally, create session regardless of the method and store it.
@session = Session.new(user: @user)
if @session.save
if omniauth_hash
# redirect_to the app page that accepts new session token
url = Rails.application.config.oauth_landing_page_url
url = "#{url}?token=#{@session.token}"
render inline: "", status: 302, location: url
else
render json: @session, except: [:secret], status: 201
end
else
# :nocov:
render_errors 400, @session.full_error_messages
# :nocov:
end
end
|
ruby
|
def create
# See if OAuth is used first. When authenticated successfully, either
# the existing user will be found or a new user will be created.
# Failure will be redirected to this action but will not match this
# branch.
if (omniauth_hash = request.env["omniauth.auth"])
@user = User.from_omniauth_hash(omniauth_hash)
# Then see if the request already has authentication. Note that if the
# user does not have access to the specified session owner, 401 will
# be thrown.
elsif accept_auth
@user = @auth_user
# Otherwise, it's a normal login process. Use username and password to
# authenticate. The user must exist, the password must be vaild, and
# the email must have been verified.
else
@user = User.find_by_username(session_params[:username])
if (@user.nil? || !@user.authenticate(session_params[:password]) ||
!@user.verified)
raise ApplicationController::UNAUTHORIZED_ERROR
end
end
# Finally, create session regardless of the method and store it.
@session = Session.new(user: @user)
if @session.save
if omniauth_hash
# redirect_to the app page that accepts new session token
url = Rails.application.config.oauth_landing_page_url
url = "#{url}?token=#{@session.token}"
render inline: "", status: 302, location: url
else
render json: @session, except: [:secret], status: 201
end
else
# :nocov:
render_errors 400, @session.full_error_messages
# :nocov:
end
end
|
[
"def",
"create",
"# See if OAuth is used first. When authenticated successfully, either",
"# the existing user will be found or a new user will be created.",
"# Failure will be redirected to this action but will not match this",
"# branch.",
"if",
"(",
"omniauth_hash",
"=",
"request",
".",
"env",
"[",
"\"omniauth.auth\"",
"]",
")",
"@user",
"=",
"User",
".",
"from_omniauth_hash",
"(",
"omniauth_hash",
")",
"# Then see if the request already has authentication. Note that if the",
"# user does not have access to the specified session owner, 401 will",
"# be thrown.",
"elsif",
"accept_auth",
"@user",
"=",
"@auth_user",
"# Otherwise, it's a normal login process. Use username and password to",
"# authenticate. The user must exist, the password must be vaild, and",
"# the email must have been verified.",
"else",
"@user",
"=",
"User",
".",
"find_by_username",
"(",
"session_params",
"[",
":username",
"]",
")",
"if",
"(",
"@user",
".",
"nil?",
"||",
"!",
"@user",
".",
"authenticate",
"(",
"session_params",
"[",
":password",
"]",
")",
"||",
"!",
"@user",
".",
"verified",
")",
"raise",
"ApplicationController",
"::",
"UNAUTHORIZED_ERROR",
"end",
"end",
"# Finally, create session regardless of the method and store it.",
"@session",
"=",
"Session",
".",
"new",
"(",
"user",
":",
"@user",
")",
"if",
"@session",
".",
"save",
"if",
"omniauth_hash",
"# redirect_to the app page that accepts new session token",
"url",
"=",
"Rails",
".",
"application",
".",
"config",
".",
"oauth_landing_page_url",
"url",
"=",
"\"#{url}?token=#{@session.token}\"",
"render",
"inline",
":",
"\"\"",
",",
"status",
":",
"302",
",",
"location",
":",
"url",
"else",
"render",
"json",
":",
"@session",
",",
"except",
":",
"[",
":secret",
"]",
",",
"status",
":",
"201",
"end",
"else",
"# :nocov:",
"render_errors",
"400",
",",
"@session",
".",
"full_error_messages",
"# :nocov:",
"end",
"end"
] |
This action is essentially the login action. Note that get_user is not
triggered for this action because we will look at username first. That
would be the "normal" way to login. The alternative would be with the
token based authentication. If the latter doesn't make sense, just use
the username and password approach.
A ApplicationController::UNAUTHORIZED_ERROR is thrown if user is not
verified.
|
[
"This",
"action",
"is",
"essentially",
"the",
"login",
"action",
".",
"Note",
"that",
"get_user",
"is",
"not",
"triggered",
"for",
"this",
"action",
"because",
"we",
"will",
"look",
"at",
"username",
"first",
".",
"That",
"would",
"be",
"the",
"normal",
"way",
"to",
"login",
".",
"The",
"alternative",
"would",
"be",
"with",
"the",
"token",
"based",
"authentication",
".",
"If",
"the",
"latter",
"doesn",
"t",
"make",
"sense",
"just",
"use",
"the",
"username",
"and",
"password",
"approach",
"."
] |
12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0
|
https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/controllers/rails_identity/sessions_controller.rb#L44-L86
|
8,842
|
davidan1981/rails-identity
|
app/controllers/rails_identity/sessions_controller.rb
|
RailsIdentity.SessionsController.get_session
|
def get_session
session_id = params[:id]
if session_id == "current"
if @auth_session.nil?
raise Repia::Errors::NotFound
end
session_id = @auth_session.id
end
@session = find_object(Session, session_id)
authorize_for!(@session)
if @session.expired?
@session.destroy
raise Repia::Errors::NotFound
end
end
|
ruby
|
def get_session
session_id = params[:id]
if session_id == "current"
if @auth_session.nil?
raise Repia::Errors::NotFound
end
session_id = @auth_session.id
end
@session = find_object(Session, session_id)
authorize_for!(@session)
if @session.expired?
@session.destroy
raise Repia::Errors::NotFound
end
end
|
[
"def",
"get_session",
"session_id",
"=",
"params",
"[",
":id",
"]",
"if",
"session_id",
"==",
"\"current\"",
"if",
"@auth_session",
".",
"nil?",
"raise",
"Repia",
"::",
"Errors",
"::",
"NotFound",
"end",
"session_id",
"=",
"@auth_session",
".",
"id",
"end",
"@session",
"=",
"find_object",
"(",
"Session",
",",
"session_id",
")",
"authorize_for!",
"(",
"@session",
")",
"if",
"@session",
".",
"expired?",
"@session",
".",
"destroy",
"raise",
"Repia",
"::",
"Errors",
"::",
"NotFound",
"end",
"end"
] |
Get the specified or current session.
A Repia::Errors::NotFound is raised if the session does not
exist (or deleted due to expiration).
A ApplicationController::UNAUTHORIZED_ERROR is raised if the
authenticated user does not have authorization for the specified
session.
|
[
"Get",
"the",
"specified",
"or",
"current",
"session",
"."
] |
12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0
|
https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/controllers/rails_identity/sessions_controller.rb#L120-L134
|
8,843
|
gregspurrier/has_enumeration
|
lib/has_enumeration/class_methods.rb
|
HasEnumeration.ClassMethods.has_enumeration
|
def has_enumeration(enumeration, mapping, options = {})
unless mapping.is_a?(Hash)
# Recast the mapping as a symbol -> string hash
mapping_hash = {}
mapping.each {|m| mapping_hash[m] = m.to_s}
mapping = mapping_hash
end
# The underlying attribute
attribute = options[:attribute] || enumeration
# ActiveRecord's composed_of method will do most of the work for us.
# All we have to do is cons up a class that implements the bidirectional
# mapping described by the provided hash.
klass = create_enumeration_mapping_class(mapping)
attr_enumeration_mapping_classes[enumeration] = klass
# Bind the class to a name within the scope of this class
mapping_class_name = enumeration.to_s.camelize
const_set(mapping_class_name, klass)
scoped_class_name = [self.name, mapping_class_name].join('::')
composed_of(enumeration,
:class_name => scoped_class_name,
:mapping => [attribute.to_s, 'raw_value'],
:converter => :from_sym,
:allow_nil => true
)
if ActiveRecord::VERSION::MAJOR >= 3 && ActiveRecord::VERSION::MINOR == 0
# Install this attributes mapping for use later when extending
# Arel attributes on the fly.
::Arel::Table.has_enumeration_mappings[table_name][attribute] = mapping
else
# Install our aggregate condition handling override, but only once
unless @aggregate_conditions_override_installed
extend HasEnumeration::AggregateConditionsOverride
@aggregate_conditions_override_installed = true
end
end
end
|
ruby
|
def has_enumeration(enumeration, mapping, options = {})
unless mapping.is_a?(Hash)
# Recast the mapping as a symbol -> string hash
mapping_hash = {}
mapping.each {|m| mapping_hash[m] = m.to_s}
mapping = mapping_hash
end
# The underlying attribute
attribute = options[:attribute] || enumeration
# ActiveRecord's composed_of method will do most of the work for us.
# All we have to do is cons up a class that implements the bidirectional
# mapping described by the provided hash.
klass = create_enumeration_mapping_class(mapping)
attr_enumeration_mapping_classes[enumeration] = klass
# Bind the class to a name within the scope of this class
mapping_class_name = enumeration.to_s.camelize
const_set(mapping_class_name, klass)
scoped_class_name = [self.name, mapping_class_name].join('::')
composed_of(enumeration,
:class_name => scoped_class_name,
:mapping => [attribute.to_s, 'raw_value'],
:converter => :from_sym,
:allow_nil => true
)
if ActiveRecord::VERSION::MAJOR >= 3 && ActiveRecord::VERSION::MINOR == 0
# Install this attributes mapping for use later when extending
# Arel attributes on the fly.
::Arel::Table.has_enumeration_mappings[table_name][attribute] = mapping
else
# Install our aggregate condition handling override, but only once
unless @aggregate_conditions_override_installed
extend HasEnumeration::AggregateConditionsOverride
@aggregate_conditions_override_installed = true
end
end
end
|
[
"def",
"has_enumeration",
"(",
"enumeration",
",",
"mapping",
",",
"options",
"=",
"{",
"}",
")",
"unless",
"mapping",
".",
"is_a?",
"(",
"Hash",
")",
"# Recast the mapping as a symbol -> string hash",
"mapping_hash",
"=",
"{",
"}",
"mapping",
".",
"each",
"{",
"|",
"m",
"|",
"mapping_hash",
"[",
"m",
"]",
"=",
"m",
".",
"to_s",
"}",
"mapping",
"=",
"mapping_hash",
"end",
"# The underlying attribute",
"attribute",
"=",
"options",
"[",
":attribute",
"]",
"||",
"enumeration",
"# ActiveRecord's composed_of method will do most of the work for us.",
"# All we have to do is cons up a class that implements the bidirectional",
"# mapping described by the provided hash.",
"klass",
"=",
"create_enumeration_mapping_class",
"(",
"mapping",
")",
"attr_enumeration_mapping_classes",
"[",
"enumeration",
"]",
"=",
"klass",
"# Bind the class to a name within the scope of this class",
"mapping_class_name",
"=",
"enumeration",
".",
"to_s",
".",
"camelize",
"const_set",
"(",
"mapping_class_name",
",",
"klass",
")",
"scoped_class_name",
"=",
"[",
"self",
".",
"name",
",",
"mapping_class_name",
"]",
".",
"join",
"(",
"'::'",
")",
"composed_of",
"(",
"enumeration",
",",
":class_name",
"=>",
"scoped_class_name",
",",
":mapping",
"=>",
"[",
"attribute",
".",
"to_s",
",",
"'raw_value'",
"]",
",",
":converter",
"=>",
":from_sym",
",",
":allow_nil",
"=>",
"true",
")",
"if",
"ActiveRecord",
"::",
"VERSION",
"::",
"MAJOR",
">=",
"3",
"&&",
"ActiveRecord",
"::",
"VERSION",
"::",
"MINOR",
"==",
"0",
"# Install this attributes mapping for use later when extending",
"# Arel attributes on the fly.",
"::",
"Arel",
"::",
"Table",
".",
"has_enumeration_mappings",
"[",
"table_name",
"]",
"[",
"attribute",
"]",
"=",
"mapping",
"else",
"# Install our aggregate condition handling override, but only once",
"unless",
"@aggregate_conditions_override_installed",
"extend",
"HasEnumeration",
"::",
"AggregateConditionsOverride",
"@aggregate_conditions_override_installed",
"=",
"true",
"end",
"end",
"end"
] |
Declares an enumerated attribute called +enumeration+ consisting of
the symbols defined in +mapping+.
When the database representation of the attribute is a string, +mapping+
can be an array of symbols. The string representation of the symbol
will be stored in the databased. E.g.:
has_enumeration :color, [:red, :green, :blue]
When the database representation of the attribute is not a string, or
if its values do not match up with the string versions of its symbols,
an hash mapping symbols to their underlying values may be used:
has_enumeration :color, :red => 1, :green => 2, :blue => 3
By default, has_enumeration assumes that the column in the database
has the same name as the enumeration. If this is not the case, the
column can be specified with the :attribute option:
has_enumeration :color, [:red, :green, :blue], :attribute => :hue
|
[
"Declares",
"an",
"enumerated",
"attribute",
"called",
"+",
"enumeration",
"+",
"consisting",
"of",
"the",
"symbols",
"defined",
"in",
"+",
"mapping",
"+",
"."
] |
40487c5b4958364ca6acaab3f05561ae0dca073e
|
https://github.com/gregspurrier/has_enumeration/blob/40487c5b4958364ca6acaab3f05561ae0dca073e/lib/has_enumeration/class_methods.rb#L24-L64
|
8,844
|
kmewhort/similarity_tree
|
lib/similarity_tree/node.rb
|
SimilarityTree.Node.depth_first_recurse
|
def depth_first_recurse(node = nil, depth = 0, &block)
node = self if node == nil
yield node, depth
node.children.each do |child|
depth_first_recurse(child, depth+1, &block)
end
end
|
ruby
|
def depth_first_recurse(node = nil, depth = 0, &block)
node = self if node == nil
yield node, depth
node.children.each do |child|
depth_first_recurse(child, depth+1, &block)
end
end
|
[
"def",
"depth_first_recurse",
"(",
"node",
"=",
"nil",
",",
"depth",
"=",
"0",
",",
"&",
"block",
")",
"node",
"=",
"self",
"if",
"node",
"==",
"nil",
"yield",
"node",
",",
"depth",
"node",
".",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"depth_first_recurse",
"(",
"child",
",",
"depth",
"+",
"1",
",",
"block",
")",
"end",
"end"
] |
helper for recursion into descendents
|
[
"helper",
"for",
"recursion",
"into",
"descendents"
] |
d688c6d86e2a5a81ff71e81ef805c9af6cb8c8e7
|
https://github.com/kmewhort/similarity_tree/blob/d688c6d86e2a5a81ff71e81ef805c9af6cb8c8e7/lib/similarity_tree/node.rb#L45-L51
|
8,845
|
chetan/curb_threadpool
|
lib/curb_threadpool.rb
|
Curl.ThreadPool.perform
|
def perform(async=false, &block)
@results = {}
@clients.each do |client|
@threads << Thread.new do
loop do
break if @reqs.empty?
req = @reqs.shift
break if req.nil? # can sometimes reach here due to a race condition. saw it a lot on travis
client.url = req.uri
args = ["http_#{req.method}"]
if [:put, :post].include? req.method
# add body to args for these methods
if req.body then
if req.body.kind_of? Array then
args += req.body
else
args << req.body
end
else
args << ""
end
end
client.send(*args)
if block then
yield(req, client.body_str)
else
@results[req.key] = client.body_str
end
end
end
end
if async then
# don't wait for threads to join, just return
return true
end
join()
return true if block
return @results
end
|
ruby
|
def perform(async=false, &block)
@results = {}
@clients.each do |client|
@threads << Thread.new do
loop do
break if @reqs.empty?
req = @reqs.shift
break if req.nil? # can sometimes reach here due to a race condition. saw it a lot on travis
client.url = req.uri
args = ["http_#{req.method}"]
if [:put, :post].include? req.method
# add body to args for these methods
if req.body then
if req.body.kind_of? Array then
args += req.body
else
args << req.body
end
else
args << ""
end
end
client.send(*args)
if block then
yield(req, client.body_str)
else
@results[req.key] = client.body_str
end
end
end
end
if async then
# don't wait for threads to join, just return
return true
end
join()
return true if block
return @results
end
|
[
"def",
"perform",
"(",
"async",
"=",
"false",
",",
"&",
"block",
")",
"@results",
"=",
"{",
"}",
"@clients",
".",
"each",
"do",
"|",
"client",
"|",
"@threads",
"<<",
"Thread",
".",
"new",
"do",
"loop",
"do",
"break",
"if",
"@reqs",
".",
"empty?",
"req",
"=",
"@reqs",
".",
"shift",
"break",
"if",
"req",
".",
"nil?",
"# can sometimes reach here due to a race condition. saw it a lot on travis",
"client",
".",
"url",
"=",
"req",
".",
"uri",
"args",
"=",
"[",
"\"http_#{req.method}\"",
"]",
"if",
"[",
":put",
",",
":post",
"]",
".",
"include?",
"req",
".",
"method",
"# add body to args for these methods",
"if",
"req",
".",
"body",
"then",
"if",
"req",
".",
"body",
".",
"kind_of?",
"Array",
"then",
"args",
"+=",
"req",
".",
"body",
"else",
"args",
"<<",
"req",
".",
"body",
"end",
"else",
"args",
"<<",
"\"\"",
"end",
"end",
"client",
".",
"send",
"(",
"args",
")",
"if",
"block",
"then",
"yield",
"(",
"req",
",",
"client",
".",
"body_str",
")",
"else",
"@results",
"[",
"req",
".",
"key",
"]",
"=",
"client",
".",
"body_str",
"end",
"end",
"end",
"end",
"if",
"async",
"then",
"# don't wait for threads to join, just return",
"return",
"true",
"end",
"join",
"(",
")",
"return",
"true",
"if",
"block",
"return",
"@results",
"end"
] |
Execute requests. By default, will block until complete and return results.
@param [Boolean] async If true, will not wait for requests to finish.
(Default=false)
@param [Block] block If passed, responses will be passed into the callback
instead of being returned directly
@yield [Request, String] Passes to the block the request and the response body
@return [Hash<Key, String>] Hash of responses, if no block given. Returns true otherwise
|
[
"Execute",
"requests",
".",
"By",
"default",
"will",
"block",
"until",
"complete",
"and",
"return",
"results",
"."
] |
4bea2ac49c67fe2545cc587c7a255224ff9bb477
|
https://github.com/chetan/curb_threadpool/blob/4bea2ac49c67fe2545cc587c7a255224ff9bb477/lib/curb_threadpool.rb#L107-L154
|
8,846
|
chetan/curb_threadpool
|
lib/curb_threadpool.rb
|
Curl.ThreadPool.collate_results
|
def collate_results(results)
ret = []
results.size.times do |i|
ret << results[i]
end
return ret
end
|
ruby
|
def collate_results(results)
ret = []
results.size.times do |i|
ret << results[i]
end
return ret
end
|
[
"def",
"collate_results",
"(",
"results",
")",
"ret",
"=",
"[",
"]",
"results",
".",
"size",
".",
"times",
"do",
"|",
"i",
"|",
"ret",
"<<",
"results",
"[",
"i",
"]",
"end",
"return",
"ret",
"end"
] |
Create ordered array from hash of results
|
[
"Create",
"ordered",
"array",
"from",
"hash",
"of",
"results"
] |
4bea2ac49c67fe2545cc587c7a255224ff9bb477
|
https://github.com/chetan/curb_threadpool/blob/4bea2ac49c67fe2545cc587c7a255224ff9bb477/lib/curb_threadpool.rb#L160-L166
|
8,847
|
wapcaplet/kelp
|
lib/kelp/xpath.rb
|
Kelp.XPaths.xpath_row_containing
|
def xpath_row_containing(texts)
texts = [texts] if texts.class == String
conditions = texts.collect do |text|
"contains(., #{xpath_sanitize(text)})"
end.join(' and ')
return ".//tr[#{conditions}]"
end
|
ruby
|
def xpath_row_containing(texts)
texts = [texts] if texts.class == String
conditions = texts.collect do |text|
"contains(., #{xpath_sanitize(text)})"
end.join(' and ')
return ".//tr[#{conditions}]"
end
|
[
"def",
"xpath_row_containing",
"(",
"texts",
")",
"texts",
"=",
"[",
"texts",
"]",
"if",
"texts",
".",
"class",
"==",
"String",
"conditions",
"=",
"texts",
".",
"collect",
"do",
"|",
"text",
"|",
"\"contains(., #{xpath_sanitize(text)})\"",
"end",
".",
"join",
"(",
"' and '",
")",
"return",
"\".//tr[#{conditions}]\"",
"end"
] |
Return an XPath for any table row containing all strings in `texts`,
within the current context.
|
[
"Return",
"an",
"XPath",
"for",
"any",
"table",
"row",
"containing",
"all",
"strings",
"in",
"texts",
"within",
"the",
"current",
"context",
"."
] |
592fe188db5a3d05e6120ed2157ad8d781601b7a
|
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/xpath.rb#L7-L13
|
8,848
|
ianwhite/response_for
|
lib/response_for/action_controller.rb
|
ResponseFor.ActionController.respond_to_action_responses
|
def respond_to_action_responses
if !respond_to_performed? && action_responses.any?
respond_to do |responder|
action_responses.each {|response| instance_exec(responder, &response) }
end
end
end
|
ruby
|
def respond_to_action_responses
if !respond_to_performed? && action_responses.any?
respond_to do |responder|
action_responses.each {|response| instance_exec(responder, &response) }
end
end
end
|
[
"def",
"respond_to_action_responses",
"if",
"!",
"respond_to_performed?",
"&&",
"action_responses",
".",
"any?",
"respond_to",
"do",
"|",
"responder",
"|",
"action_responses",
".",
"each",
"{",
"|",
"response",
"|",
"instance_exec",
"(",
"responder",
",",
"response",
")",
"}",
"end",
"end",
"end"
] |
if the response.content_type has not been set (if it has, then responthere are responses for the current action, then respond_to them
we rescue the case where there were no responses, so that the default_render
action will be performed
|
[
"if",
"the",
"response",
".",
"content_type",
"has",
"not",
"been",
"set",
"(",
"if",
"it",
"has",
"then",
"responthere",
"are",
"responses",
"for",
"the",
"current",
"action",
"then",
"respond_to",
"them"
] |
76c8b451868c4ddc48fa51410a391e614192a6a9
|
https://github.com/ianwhite/response_for/blob/76c8b451868c4ddc48fa51410a391e614192a6a9/lib/response_for/action_controller.rb#L135-L141
|
8,849
|
sue445/sengiri_yaml
|
lib/sengiri_yaml/loader.rb
|
SengiriYaml.Loader.load_dir
|
def load_dir(src_dir)
merged_content = ""
Pathname.glob("#{src_dir}/*.yml").sort.each do |yaml_path|
content = yaml_path.read.gsub(/^---$/, "")
merged_content << content
end
YAML.load(merged_content)
end
|
ruby
|
def load_dir(src_dir)
merged_content = ""
Pathname.glob("#{src_dir}/*.yml").sort.each do |yaml_path|
content = yaml_path.read.gsub(/^---$/, "")
merged_content << content
end
YAML.load(merged_content)
end
|
[
"def",
"load_dir",
"(",
"src_dir",
")",
"merged_content",
"=",
"\"\"",
"Pathname",
".",
"glob",
"(",
"\"#{src_dir}/*.yml\"",
")",
".",
"sort",
".",
"each",
"do",
"|",
"yaml_path",
"|",
"content",
"=",
"yaml_path",
".",
"read",
".",
"gsub",
"(",
"/",
"/",
",",
"\"\"",
")",
"merged_content",
"<<",
"content",
"end",
"YAML",
".",
"load",
"(",
"merged_content",
")",
"end"
] |
load divided yaml files
@param src_dir [String] divided yaml dir
@return [Hash] merged yaml hash
|
[
"load",
"divided",
"yaml",
"files"
] |
f9595c5c05802bbbdd5228e808e7cb2b9cc3a049
|
https://github.com/sue445/sengiri_yaml/blob/f9595c5c05802bbbdd5228e808e7cb2b9cc3a049/lib/sengiri_yaml/loader.rb#L9-L18
|
8,850
|
samlown/translate_columns
|
lib/translate_columns.rb
|
TranslateColumns.InstanceMethods.translation_locale
|
def translation_locale
locale = @translation_locale || I18n.locale.to_s
locale == I18n.default_locale.to_s ? nil : locale
end
|
ruby
|
def translation_locale
locale = @translation_locale || I18n.locale.to_s
locale == I18n.default_locale.to_s ? nil : locale
end
|
[
"def",
"translation_locale",
"locale",
"=",
"@translation_locale",
"||",
"I18n",
".",
"locale",
".",
"to_s",
"locale",
"==",
"I18n",
".",
"default_locale",
".",
"to_s",
"?",
"nil",
":",
"locale",
"end"
] |
Provide the locale which is currently in use with the object or the current global locale.
If the default is in use, always return nil.
|
[
"Provide",
"the",
"locale",
"which",
"is",
"currently",
"in",
"use",
"with",
"the",
"object",
"or",
"the",
"current",
"global",
"locale",
".",
"If",
"the",
"default",
"is",
"in",
"use",
"always",
"return",
"nil",
"."
] |
799d7cd4a0c3ad8d2dd1512be0129daef3643cac
|
https://github.com/samlown/translate_columns/blob/799d7cd4a0c3ad8d2dd1512be0129daef3643cac/lib/translate_columns.rb#L130-L133
|
8,851
|
samlown/translate_columns
|
lib/translate_columns.rb
|
TranslateColumns.InstanceMethods.translation
|
def translation
if translation_enabled?
if !@translation || (@translation.locale != translation_locale)
raise MissingParent, "Cannot create translations without a stored parent" if new_record?
# try to find translation or build a new one
@translation = translations.where(:locale => translation_locale).first || translations.build(:locale => translation_locale)
end
@translation
else
nil
end
end
|
ruby
|
def translation
if translation_enabled?
if !@translation || (@translation.locale != translation_locale)
raise MissingParent, "Cannot create translations without a stored parent" if new_record?
# try to find translation or build a new one
@translation = translations.where(:locale => translation_locale).first || translations.build(:locale => translation_locale)
end
@translation
else
nil
end
end
|
[
"def",
"translation",
"if",
"translation_enabled?",
"if",
"!",
"@translation",
"||",
"(",
"@translation",
".",
"locale",
"!=",
"translation_locale",
")",
"raise",
"MissingParent",
",",
"\"Cannot create translations without a stored parent\"",
"if",
"new_record?",
"# try to find translation or build a new one",
"@translation",
"=",
"translations",
".",
"where",
"(",
":locale",
"=>",
"translation_locale",
")",
".",
"first",
"||",
"translations",
".",
"build",
"(",
":locale",
"=>",
"translation_locale",
")",
"end",
"@translation",
"else",
"nil",
"end",
"end"
] |
Provide a translation object based on the parent and the translation_locale
current value.
|
[
"Provide",
"a",
"translation",
"object",
"based",
"on",
"the",
"parent",
"and",
"the",
"translation_locale",
"current",
"value",
"."
] |
799d7cd4a0c3ad8d2dd1512be0129daef3643cac
|
https://github.com/samlown/translate_columns/blob/799d7cd4a0c3ad8d2dd1512be0129daef3643cac/lib/translate_columns.rb#L165-L176
|
8,852
|
samlown/translate_columns
|
lib/translate_columns.rb
|
TranslateColumns.InstanceMethods.attributes_with_locale=
|
def attributes_with_locale=(new_attributes, guard_protected_attributes = true)
return if new_attributes.nil?
attributes = new_attributes.dup
attributes.stringify_keys!
attributes = sanitize_for_mass_assignment(attributes) if guard_protected_attributes
send(:locale=, attributes["locale"]) if attributes.has_key?("locale") and respond_to?(:locale=)
send(:attributes_without_locale=, attributes, guard_protected_attributes)
end
|
ruby
|
def attributes_with_locale=(new_attributes, guard_protected_attributes = true)
return if new_attributes.nil?
attributes = new_attributes.dup
attributes.stringify_keys!
attributes = sanitize_for_mass_assignment(attributes) if guard_protected_attributes
send(:locale=, attributes["locale"]) if attributes.has_key?("locale") and respond_to?(:locale=)
send(:attributes_without_locale=, attributes, guard_protected_attributes)
end
|
[
"def",
"attributes_with_locale",
"=",
"(",
"new_attributes",
",",
"guard_protected_attributes",
"=",
"true",
")",
"return",
"if",
"new_attributes",
".",
"nil?",
"attributes",
"=",
"new_attributes",
".",
"dup",
"attributes",
".",
"stringify_keys!",
"attributes",
"=",
"sanitize_for_mass_assignment",
"(",
"attributes",
")",
"if",
"guard_protected_attributes",
"send",
"(",
":locale=",
",",
"attributes",
"[",
"\"locale\"",
"]",
")",
"if",
"attributes",
".",
"has_key?",
"(",
"\"locale\"",
")",
"and",
"respond_to?",
"(",
":locale=",
")",
"send",
"(",
":attributes_without_locale=",
",",
"attributes",
",",
"guard_protected_attributes",
")",
"end"
] |
Override the default mass assignment method so that the locale variable is always
given preference.
|
[
"Override",
"the",
"default",
"mass",
"assignment",
"method",
"so",
"that",
"the",
"locale",
"variable",
"is",
"always",
"given",
"preference",
"."
] |
799d7cd4a0c3ad8d2dd1512be0129daef3643cac
|
https://github.com/samlown/translate_columns/blob/799d7cd4a0c3ad8d2dd1512be0129daef3643cac/lib/translate_columns.rb#L216-L225
|
8,853
|
mkristian/ixtlan-datamapper
|
lib/ixtlan/datamapper/validations_ext.rb
|
DataMapper.ValidationsExt.validate_parents
|
def validate_parents
parent_relationships.each do |relationship|
parent = relationship.get(self)
unless parent.valid?
unless errors[relationship.name].include?(parent.errors)
errors[relationship.name] = parent.errors
end
end
end
end
|
ruby
|
def validate_parents
parent_relationships.each do |relationship|
parent = relationship.get(self)
unless parent.valid?
unless errors[relationship.name].include?(parent.errors)
errors[relationship.name] = parent.errors
end
end
end
end
|
[
"def",
"validate_parents",
"parent_relationships",
".",
"each",
"do",
"|",
"relationship",
"|",
"parent",
"=",
"relationship",
".",
"get",
"(",
"self",
")",
"unless",
"parent",
".",
"valid?",
"unless",
"errors",
"[",
"relationship",
".",
"name",
"]",
".",
"include?",
"(",
"parent",
".",
"errors",
")",
"errors",
"[",
"relationship",
".",
"name",
"]",
"=",
"parent",
".",
"errors",
"end",
"end",
"end",
"end"
] |
Run validations on the associated parent resources
@api semipublic
|
[
"Run",
"validations",
"on",
"the",
"associated",
"parent",
"resources"
] |
f7b39d4bbfea3d3c45dd697fc566b2d79c73f34e
|
https://github.com/mkristian/ixtlan-datamapper/blob/f7b39d4bbfea3d3c45dd697fc566b2d79c73f34e/lib/ixtlan/datamapper/validations_ext.rb#L30-L39
|
8,854
|
mkristian/ixtlan-datamapper
|
lib/ixtlan/datamapper/validations_ext.rb
|
DataMapper.ValidationsExt.validate_children
|
def validate_children
child_associations.each do |collection|
if collection.dirty?
collection.each do |child|
unless child.valid?
relationship_errors = (errors[collection.relationship.name] ||= [])
unless relationship_errors.include?(child.errors)
relationship_errors << child.errors
end
end
end
end
end
end
|
ruby
|
def validate_children
child_associations.each do |collection|
if collection.dirty?
collection.each do |child|
unless child.valid?
relationship_errors = (errors[collection.relationship.name] ||= [])
unless relationship_errors.include?(child.errors)
relationship_errors << child.errors
end
end
end
end
end
end
|
[
"def",
"validate_children",
"child_associations",
".",
"each",
"do",
"|",
"collection",
"|",
"if",
"collection",
".",
"dirty?",
"collection",
".",
"each",
"do",
"|",
"child",
"|",
"unless",
"child",
".",
"valid?",
"relationship_errors",
"=",
"(",
"errors",
"[",
"collection",
".",
"relationship",
".",
"name",
"]",
"||=",
"[",
"]",
")",
"unless",
"relationship_errors",
".",
"include?",
"(",
"child",
".",
"errors",
")",
"relationship_errors",
"<<",
"child",
".",
"errors",
"end",
"end",
"end",
"end",
"end",
"end"
] |
Run validations on the associated child resources
@api semipublic
|
[
"Run",
"validations",
"on",
"the",
"associated",
"child",
"resources"
] |
f7b39d4bbfea3d3c45dd697fc566b2d79c73f34e
|
https://github.com/mkristian/ixtlan-datamapper/blob/f7b39d4bbfea3d3c45dd697fc566b2d79c73f34e/lib/ixtlan/datamapper/validations_ext.rb#L44-L57
|
8,855
|
dyoung522/nosequel
|
lib/nosequel/container.rb
|
NoSequel.Container.method_missing
|
def method_missing(meth, *args, &block)
db.to_hash(:key, :value).send(meth, *args, &block)
end
|
ruby
|
def method_missing(meth, *args, &block)
db.to_hash(:key, :value).send(meth, *args, &block)
end
|
[
"def",
"method_missing",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"block",
")",
"db",
".",
"to_hash",
"(",
":key",
",",
":value",
")",
".",
"send",
"(",
"meth",
",",
"args",
",",
"block",
")",
"end"
] |
Handle all other Hash methods
|
[
"Handle",
"all",
"other",
"Hash",
"methods"
] |
b8788846a36ce03d426bfe3e575a81a6fb3c5c76
|
https://github.com/dyoung522/nosequel/blob/b8788846a36ce03d426bfe3e575a81a6fb3c5c76/lib/nosequel/container.rb#L68-L70
|
8,856
|
dyoung522/nosequel
|
lib/nosequel/container.rb
|
NoSequel.Container.validate_key
|
def validate_key(key)
unless key.is_a?(Symbol) || key.is_a?(String)
raise ArgumentError, 'Key must be a string or symbol'
end
key
end
|
ruby
|
def validate_key(key)
unless key.is_a?(Symbol) || key.is_a?(String)
raise ArgumentError, 'Key must be a string or symbol'
end
key
end
|
[
"def",
"validate_key",
"(",
"key",
")",
"unless",
"key",
".",
"is_a?",
"(",
"Symbol",
")",
"||",
"key",
".",
"is_a?",
"(",
"String",
")",
"raise",
"ArgumentError",
",",
"'Key must be a string or symbol'",
"end",
"key",
"end"
] |
Make sure the key is valid
|
[
"Make",
"sure",
"the",
"key",
"is",
"valid"
] |
b8788846a36ce03d426bfe3e575a81a6fb3c5c76
|
https://github.com/dyoung522/nosequel/blob/b8788846a36ce03d426bfe3e575a81a6fb3c5c76/lib/nosequel/container.rb#L88-L93
|
8,857
|
boza/interaction
|
lib/simple_interaction/class_methods.rb
|
SimpleInteraction.ClassMethods.run
|
def run(**options)
@options = options
fail RequirementsNotMet.new("#{self} requires the following parameters #{requirements}") unless requirements_met?
new(@options).tap do |interaction|
interaction.__send__(:run)
end
end
|
ruby
|
def run(**options)
@options = options
fail RequirementsNotMet.new("#{self} requires the following parameters #{requirements}") unless requirements_met?
new(@options).tap do |interaction|
interaction.__send__(:run)
end
end
|
[
"def",
"run",
"(",
"**",
"options",
")",
"@options",
"=",
"options",
"fail",
"RequirementsNotMet",
".",
"new",
"(",
"\"#{self} requires the following parameters #{requirements}\"",
")",
"unless",
"requirements_met?",
"new",
"(",
"@options",
")",
".",
"tap",
"do",
"|",
"interaction",
"|",
"interaction",
".",
"__send__",
"(",
":run",
")",
"end",
"end"
] |
checks if requirements are met from the requires params
creates an instance of the interaction
calls run on the instance
|
[
"checks",
"if",
"requirements",
"are",
"met",
"from",
"the",
"requires",
"params",
"creates",
"an",
"instance",
"of",
"the",
"interaction",
"calls",
"run",
"on",
"the",
"instance"
] |
e2afc7d127795a957e76da05ed053b4a38a78070
|
https://github.com/boza/interaction/blob/e2afc7d127795a957e76da05ed053b4a38a78070/lib/simple_interaction/class_methods.rb#L29-L35
|
8,858
|
boza/interaction
|
lib/simple_interaction/class_methods.rb
|
SimpleInteraction.ClassMethods.run!
|
def run!(**options)
interaction = run(options)
raise error_class.new(interaction.error) unless interaction.success?
interaction.result
end
|
ruby
|
def run!(**options)
interaction = run(options)
raise error_class.new(interaction.error) unless interaction.success?
interaction.result
end
|
[
"def",
"run!",
"(",
"**",
"options",
")",
"interaction",
"=",
"run",
"(",
"options",
")",
"raise",
"error_class",
".",
"new",
"(",
"interaction",
".",
"error",
")",
"unless",
"interaction",
".",
"success?",
"interaction",
".",
"result",
"end"
] |
runs interaction raises if any error or returns the interaction result
|
[
"runs",
"interaction",
"raises",
"if",
"any",
"error",
"or",
"returns",
"the",
"interaction",
"result"
] |
e2afc7d127795a957e76da05ed053b4a38a78070
|
https://github.com/boza/interaction/blob/e2afc7d127795a957e76da05ed053b4a38a78070/lib/simple_interaction/class_methods.rb#L38-L42
|
8,859
|
lokalportal/chain_options
|
lib/chain_options/option_set.rb
|
ChainOptions.OptionSet.add_option
|
def add_option(name, parameters)
self.class.handle_warnings(name, **parameters.dup)
chain_options.merge(name => parameters.merge(method_hash(parameters)))
end
|
ruby
|
def add_option(name, parameters)
self.class.handle_warnings(name, **parameters.dup)
chain_options.merge(name => parameters.merge(method_hash(parameters)))
end
|
[
"def",
"add_option",
"(",
"name",
",",
"parameters",
")",
"self",
".",
"class",
".",
"handle_warnings",
"(",
"name",
",",
"**",
"parameters",
".",
"dup",
")",
"chain_options",
".",
"merge",
"(",
"name",
"=>",
"parameters",
".",
"merge",
"(",
"method_hash",
"(",
"parameters",
")",
")",
")",
"end"
] |
Checks the given option-parameters for incompatibilities and registers a
new option.
|
[
"Checks",
"the",
"given",
"option",
"-",
"parameters",
"for",
"incompatibilities",
"and",
"registers",
"a",
"new",
"option",
"."
] |
b42cd6c03aeca8938b274225ebaa38fe3803866a
|
https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option_set.rb#L49-L52
|
8,860
|
lokalportal/chain_options
|
lib/chain_options/option_set.rb
|
ChainOptions.OptionSet.option
|
def option(name)
config = chain_options[name] || raise_no_option_error(name)
Option.new(config).tap { |o| o.initial_value(values[name]) if values.key?(name) }
end
|
ruby
|
def option(name)
config = chain_options[name] || raise_no_option_error(name)
Option.new(config).tap { |o| o.initial_value(values[name]) if values.key?(name) }
end
|
[
"def",
"option",
"(",
"name",
")",
"config",
"=",
"chain_options",
"[",
"name",
"]",
"||",
"raise_no_option_error",
"(",
"name",
")",
"Option",
".",
"new",
"(",
"config",
")",
".",
"tap",
"{",
"|",
"o",
"|",
"o",
".",
"initial_value",
"(",
"values",
"[",
"name",
"]",
")",
"if",
"values",
".",
"key?",
"(",
"name",
")",
"}",
"end"
] |
Returns an option registered under `name`.
|
[
"Returns",
"an",
"option",
"registered",
"under",
"name",
"."
] |
b42cd6c03aeca8938b274225ebaa38fe3803866a
|
https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option_set.rb#L64-L67
|
8,861
|
jhliberty/brat-cli
|
lib/brat/request.rb
|
Brat.Request.set_request_defaults
|
def set_request_defaults(endpoint, private_token, sudo=nil)
raise Error::MissingCredentials.new("Please set an endpoint to API") unless endpoint
@private_token = private_token
self.class.base_uri endpoint
self.class.default_params :sudo => sudo
self.class.default_params.delete(:sudo) if sudo.nil?
end
|
ruby
|
def set_request_defaults(endpoint, private_token, sudo=nil)
raise Error::MissingCredentials.new("Please set an endpoint to API") unless endpoint
@private_token = private_token
self.class.base_uri endpoint
self.class.default_params :sudo => sudo
self.class.default_params.delete(:sudo) if sudo.nil?
end
|
[
"def",
"set_request_defaults",
"(",
"endpoint",
",",
"private_token",
",",
"sudo",
"=",
"nil",
")",
"raise",
"Error",
"::",
"MissingCredentials",
".",
"new",
"(",
"\"Please set an endpoint to API\"",
")",
"unless",
"endpoint",
"@private_token",
"=",
"private_token",
"self",
".",
"class",
".",
"base_uri",
"endpoint",
"self",
".",
"class",
".",
"default_params",
":sudo",
"=>",
"sudo",
"self",
".",
"class",
".",
"default_params",
".",
"delete",
"(",
":sudo",
")",
"if",
"sudo",
".",
"nil?",
"end"
] |
Sets a base_uri and default_params for requests.
@raise [Error::MissingCredentials] if endpoint not set.
|
[
"Sets",
"a",
"base_uri",
"and",
"default_params",
"for",
"requests",
"."
] |
36183e543fd0e11b1840da2db4f41aa425404b8d
|
https://github.com/jhliberty/brat-cli/blob/36183e543fd0e11b1840da2db4f41aa425404b8d/lib/brat/request.rb#L76-L83
|
8,862
|
J3RN/spellrb
|
lib/spell/spell.rb
|
Spell.Spell.best_match
|
def best_match(given_word)
words = (@word_list.is_a? Array) ? @word_list : @word_list.keys
word_bigrams = bigramate(given_word)
word_hash = words.map do |key|
[key, bigram_compare(word_bigrams, bigramate(key))]
end
word_hash = Hash[word_hash]
# Weight by word usage, if logical
word_hash = apply_usage_weights(word_hash) if @word_list.is_a? Hash
word_hash.max_by { |_key, value| value }.first
end
|
ruby
|
def best_match(given_word)
words = (@word_list.is_a? Array) ? @word_list : @word_list.keys
word_bigrams = bigramate(given_word)
word_hash = words.map do |key|
[key, bigram_compare(word_bigrams, bigramate(key))]
end
word_hash = Hash[word_hash]
# Weight by word usage, if logical
word_hash = apply_usage_weights(word_hash) if @word_list.is_a? Hash
word_hash.max_by { |_key, value| value }.first
end
|
[
"def",
"best_match",
"(",
"given_word",
")",
"words",
"=",
"(",
"@word_list",
".",
"is_a?",
"Array",
")",
"?",
"@word_list",
":",
"@word_list",
".",
"keys",
"word_bigrams",
"=",
"bigramate",
"(",
"given_word",
")",
"word_hash",
"=",
"words",
".",
"map",
"do",
"|",
"key",
"|",
"[",
"key",
",",
"bigram_compare",
"(",
"word_bigrams",
",",
"bigramate",
"(",
"key",
")",
")",
"]",
"end",
"word_hash",
"=",
"Hash",
"[",
"word_hash",
"]",
"# Weight by word usage, if logical",
"word_hash",
"=",
"apply_usage_weights",
"(",
"word_hash",
")",
"if",
"@word_list",
".",
"is_a?",
"Hash",
"word_hash",
".",
"max_by",
"{",
"|",
"_key",
",",
"value",
"|",
"value",
"}",
".",
"first",
"end"
] |
Returns the closest matching word in the dictionary
|
[
"Returns",
"the",
"closest",
"matching",
"word",
"in",
"the",
"dictionary"
] |
0c9a187489428c4b441d2555c05d87ef3af0df8e
|
https://github.com/J3RN/spellrb/blob/0c9a187489428c4b441d2555c05d87ef3af0df8e/lib/spell/spell.rb#L18-L31
|
8,863
|
J3RN/spellrb
|
lib/spell/spell.rb
|
Spell.Spell.num_matching
|
def num_matching(one_bigrams, two_bigrams, acc = 0)
return acc if one_bigrams.empty? || two_bigrams.empty?
one_two = one_bigrams.index(two_bigrams[0])
two_one = two_bigrams.index(one_bigrams[0])
if one_two.nil? && two_one.nil?
num_matching(one_bigrams.drop(1), two_bigrams.drop(1), acc)
else
# If one is nil, it is set to the other
two_one ||= one_two
one_two ||= two_one
if one_two < two_one
num_matching(one_bigrams.drop(one_two + 1),
two_bigrams.drop(1), acc + 1)
else
num_matching(one_bigrams.drop(1),
two_bigrams.drop(two_one + 1), acc + 1)
end
end
end
|
ruby
|
def num_matching(one_bigrams, two_bigrams, acc = 0)
return acc if one_bigrams.empty? || two_bigrams.empty?
one_two = one_bigrams.index(two_bigrams[0])
two_one = two_bigrams.index(one_bigrams[0])
if one_two.nil? && two_one.nil?
num_matching(one_bigrams.drop(1), two_bigrams.drop(1), acc)
else
# If one is nil, it is set to the other
two_one ||= one_two
one_two ||= two_one
if one_two < two_one
num_matching(one_bigrams.drop(one_two + 1),
two_bigrams.drop(1), acc + 1)
else
num_matching(one_bigrams.drop(1),
two_bigrams.drop(two_one + 1), acc + 1)
end
end
end
|
[
"def",
"num_matching",
"(",
"one_bigrams",
",",
"two_bigrams",
",",
"acc",
"=",
"0",
")",
"return",
"acc",
"if",
"one_bigrams",
".",
"empty?",
"||",
"two_bigrams",
".",
"empty?",
"one_two",
"=",
"one_bigrams",
".",
"index",
"(",
"two_bigrams",
"[",
"0",
"]",
")",
"two_one",
"=",
"two_bigrams",
".",
"index",
"(",
"one_bigrams",
"[",
"0",
"]",
")",
"if",
"one_two",
".",
"nil?",
"&&",
"two_one",
".",
"nil?",
"num_matching",
"(",
"one_bigrams",
".",
"drop",
"(",
"1",
")",
",",
"two_bigrams",
".",
"drop",
"(",
"1",
")",
",",
"acc",
")",
"else",
"# If one is nil, it is set to the other",
"two_one",
"||=",
"one_two",
"one_two",
"||=",
"two_one",
"if",
"one_two",
"<",
"two_one",
"num_matching",
"(",
"one_bigrams",
".",
"drop",
"(",
"one_two",
"+",
"1",
")",
",",
"two_bigrams",
".",
"drop",
"(",
"1",
")",
",",
"acc",
"+",
"1",
")",
"else",
"num_matching",
"(",
"one_bigrams",
".",
"drop",
"(",
"1",
")",
",",
"two_bigrams",
".",
"drop",
"(",
"two_one",
"+",
"1",
")",
",",
"acc",
"+",
"1",
")",
"end",
"end",
"end"
] |
Returns the number of matching bigrams between the two sets of bigrams
|
[
"Returns",
"the",
"number",
"of",
"matching",
"bigrams",
"between",
"the",
"two",
"sets",
"of",
"bigrams"
] |
0c9a187489428c4b441d2555c05d87ef3af0df8e
|
https://github.com/J3RN/spellrb/blob/0c9a187489428c4b441d2555c05d87ef3af0df8e/lib/spell/spell.rb#L50-L71
|
8,864
|
J3RN/spellrb
|
lib/spell/spell.rb
|
Spell.Spell.bigram_compare
|
def bigram_compare(word1_bigrams, word2_bigrams)
most_bigrams = [word1_bigrams.count, word2_bigrams.count].max
num_matching(word1_bigrams, word2_bigrams).to_f / most_bigrams
end
|
ruby
|
def bigram_compare(word1_bigrams, word2_bigrams)
most_bigrams = [word1_bigrams.count, word2_bigrams.count].max
num_matching(word1_bigrams, word2_bigrams).to_f / most_bigrams
end
|
[
"def",
"bigram_compare",
"(",
"word1_bigrams",
",",
"word2_bigrams",
")",
"most_bigrams",
"=",
"[",
"word1_bigrams",
".",
"count",
",",
"word2_bigrams",
".",
"count",
"]",
".",
"max",
"num_matching",
"(",
"word1_bigrams",
",",
"word2_bigrams",
")",
".",
"to_f",
"/",
"most_bigrams",
"end"
] |
Returns a value from 0 to 1 for how likely these two words are to be a
match
|
[
"Returns",
"a",
"value",
"from",
"0",
"to",
"1",
"for",
"how",
"likely",
"these",
"two",
"words",
"are",
"to",
"be",
"a",
"match"
] |
0c9a187489428c4b441d2555c05d87ef3af0df8e
|
https://github.com/J3RN/spellrb/blob/0c9a187489428c4b441d2555c05d87ef3af0df8e/lib/spell/spell.rb#L80-L83
|
8,865
|
J3RN/spellrb
|
lib/spell/spell.rb
|
Spell.Spell.apply_usage_weights
|
def apply_usage_weights(word_hash)
max_usage = @word_list.values.max.to_f
max_usage = 1 if max_usage == 0
weighted_array = word_hash.map do |word, bigram_score|
usage_score = @word_list[word].to_f / max_usage
[word, (bigram_score * (1 - @alpha)) + (usage_score * @alpha)]
end
Hash[weighted_array]
end
|
ruby
|
def apply_usage_weights(word_hash)
max_usage = @word_list.values.max.to_f
max_usage = 1 if max_usage == 0
weighted_array = word_hash.map do |word, bigram_score|
usage_score = @word_list[word].to_f / max_usage
[word, (bigram_score * (1 - @alpha)) + (usage_score * @alpha)]
end
Hash[weighted_array]
end
|
[
"def",
"apply_usage_weights",
"(",
"word_hash",
")",
"max_usage",
"=",
"@word_list",
".",
"values",
".",
"max",
".",
"to_f",
"max_usage",
"=",
"1",
"if",
"max_usage",
"==",
"0",
"weighted_array",
"=",
"word_hash",
".",
"map",
"do",
"|",
"word",
",",
"bigram_score",
"|",
"usage_score",
"=",
"@word_list",
"[",
"word",
"]",
".",
"to_f",
"/",
"max_usage",
"[",
"word",
",",
"(",
"bigram_score",
"*",
"(",
"1",
"-",
"@alpha",
")",
")",
"+",
"(",
"usage_score",
"*",
"@alpha",
")",
"]",
"end",
"Hash",
"[",
"weighted_array",
"]",
"end"
] |
For each word, adjust it's score by usage
v = s * (1 - a) + u * a
Where v is the new value
a is @alpha
s is the bigram score (0..1)
u is the usage score (0..1)
|
[
"For",
"each",
"word",
"adjust",
"it",
"s",
"score",
"by",
"usage"
] |
0c9a187489428c4b441d2555c05d87ef3af0df8e
|
https://github.com/J3RN/spellrb/blob/0c9a187489428c4b441d2555c05d87ef3af0df8e/lib/spell/spell.rb#L92-L102
|
8,866
|
NUBIC/aker
|
lib/aker/rack/failure.rb
|
Aker::Rack.Failure.call
|
def call(env)
conf = configuration(env)
if login_required?(env)
if interactive?(env)
::Warden::Strategies[conf.ui_mode].new(env).on_ui_failure.finish
else
headers = {}
headers["WWW-Authenticate"] =
conf.api_modes.collect { |mode_key|
::Warden::Strategies[mode_key].new(env).challenge
}.join("\n")
headers["Content-Type"] = "text/plain"
[401, headers, ["Authentication required"]]
end
else
log_authorization_failure(env)
msg = "#{user(env).username} may not use this page."
Rack::Response.
new("<html><head><title>Authorization denied</title></head><body>#{msg}</body></html>",
403,
"Content-Type" => "text/html").finish
end
end
|
ruby
|
def call(env)
conf = configuration(env)
if login_required?(env)
if interactive?(env)
::Warden::Strategies[conf.ui_mode].new(env).on_ui_failure.finish
else
headers = {}
headers["WWW-Authenticate"] =
conf.api_modes.collect { |mode_key|
::Warden::Strategies[mode_key].new(env).challenge
}.join("\n")
headers["Content-Type"] = "text/plain"
[401, headers, ["Authentication required"]]
end
else
log_authorization_failure(env)
msg = "#{user(env).username} may not use this page."
Rack::Response.
new("<html><head><title>Authorization denied</title></head><body>#{msg}</body></html>",
403,
"Content-Type" => "text/html").finish
end
end
|
[
"def",
"call",
"(",
"env",
")",
"conf",
"=",
"configuration",
"(",
"env",
")",
"if",
"login_required?",
"(",
"env",
")",
"if",
"interactive?",
"(",
"env",
")",
"::",
"Warden",
"::",
"Strategies",
"[",
"conf",
".",
"ui_mode",
"]",
".",
"new",
"(",
"env",
")",
".",
"on_ui_failure",
".",
"finish",
"else",
"headers",
"=",
"{",
"}",
"headers",
"[",
"\"WWW-Authenticate\"",
"]",
"=",
"conf",
".",
"api_modes",
".",
"collect",
"{",
"|",
"mode_key",
"|",
"::",
"Warden",
"::",
"Strategies",
"[",
"mode_key",
"]",
".",
"new",
"(",
"env",
")",
".",
"challenge",
"}",
".",
"join",
"(",
"\"\\n\"",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"text/plain\"",
"[",
"401",
",",
"headers",
",",
"[",
"\"Authentication required\"",
"]",
"]",
"end",
"else",
"log_authorization_failure",
"(",
"env",
")",
"msg",
"=",
"\"#{user(env).username} may not use this page.\"",
"Rack",
"::",
"Response",
".",
"new",
"(",
"\"<html><head><title>Authorization denied</title></head><body>#{msg}</body></html>\"",
",",
"403",
",",
"\"Content-Type\"",
"=>",
"\"text/html\"",
")",
".",
"finish",
"end",
"end"
] |
Receives the rack environment in case of a failure and renders a
response based on the interactiveness of the request and the
nature of the configured modes.
@param [Hash] env a rack environment
@return [Array] a rack response
|
[
"Receives",
"the",
"rack",
"environment",
"in",
"case",
"of",
"a",
"failure",
"and",
"renders",
"a",
"response",
"based",
"on",
"the",
"interactiveness",
"of",
"the",
"request",
"and",
"the",
"nature",
"of",
"the",
"configured",
"modes",
"."
] |
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
|
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/rack/failure.rb#L22-L44
|
8,867
|
mwatts15/xmms2_utils
|
lib/xmms2_utils.rb
|
Xmms.Client.shuffle_by
|
def shuffle_by(playlist, field)
pl = playlist.entries.wait.value
artists = Hash.new
rnd = Random.new
playlist.clear.wait
field = field.to_sym
pl.each do |id|
infos = self.medialib_get_info(id).wait.value
a = infos[field].first[1]
if artists.has_key?(a)
artists[a].insert(0,id)
else
artists[a] = [id]
end
end
artist_names = artists.keys
for _ in pl
artist_idx = (rnd.rand * artist_names.length).to_i
artist = artist_names[artist_idx]
songs = artists[artist]
song_idx = rnd.rand * songs.length
song = songs[song_idx]
playlist.add_entry(song).wait
songs.delete(song)
if songs.empty?
artists.delete(artist)
artist_names.delete(artist)
end
end
end
|
ruby
|
def shuffle_by(playlist, field)
pl = playlist.entries.wait.value
artists = Hash.new
rnd = Random.new
playlist.clear.wait
field = field.to_sym
pl.each do |id|
infos = self.medialib_get_info(id).wait.value
a = infos[field].first[1]
if artists.has_key?(a)
artists[a].insert(0,id)
else
artists[a] = [id]
end
end
artist_names = artists.keys
for _ in pl
artist_idx = (rnd.rand * artist_names.length).to_i
artist = artist_names[artist_idx]
songs = artists[artist]
song_idx = rnd.rand * songs.length
song = songs[song_idx]
playlist.add_entry(song).wait
songs.delete(song)
if songs.empty?
artists.delete(artist)
artist_names.delete(artist)
end
end
end
|
[
"def",
"shuffle_by",
"(",
"playlist",
",",
"field",
")",
"pl",
"=",
"playlist",
".",
"entries",
".",
"wait",
".",
"value",
"artists",
"=",
"Hash",
".",
"new",
"rnd",
"=",
"Random",
".",
"new",
"playlist",
".",
"clear",
".",
"wait",
"field",
"=",
"field",
".",
"to_sym",
"pl",
".",
"each",
"do",
"|",
"id",
"|",
"infos",
"=",
"self",
".",
"medialib_get_info",
"(",
"id",
")",
".",
"wait",
".",
"value",
"a",
"=",
"infos",
"[",
"field",
"]",
".",
"first",
"[",
"1",
"]",
"if",
"artists",
".",
"has_key?",
"(",
"a",
")",
"artists",
"[",
"a",
"]",
".",
"insert",
"(",
"0",
",",
"id",
")",
"else",
"artists",
"[",
"a",
"]",
"=",
"[",
"id",
"]",
"end",
"end",
"artist_names",
"=",
"artists",
".",
"keys",
"for",
"_",
"in",
"pl",
"artist_idx",
"=",
"(",
"rnd",
".",
"rand",
"*",
"artist_names",
".",
"length",
")",
".",
"to_i",
"artist",
"=",
"artist_names",
"[",
"artist_idx",
"]",
"songs",
"=",
"artists",
"[",
"artist",
"]",
"song_idx",
"=",
"rnd",
".",
"rand",
"*",
"songs",
".",
"length",
"song",
"=",
"songs",
"[",
"song_idx",
"]",
"playlist",
".",
"add_entry",
"(",
"song",
")",
".",
"wait",
"songs",
".",
"delete",
"(",
"song",
")",
"if",
"songs",
".",
"empty?",
"artists",
".",
"delete",
"(",
"artist",
")",
"artist_names",
".",
"delete",
"(",
"artist",
")",
"end",
"end",
"end"
] |
Shuffles the playlist by selecting randomly among the tracks as
grouped by the given field
shuffle_by is intended to change between different
artists/albums/genres more frequently than if all tracks were
shuffled based on a uniform distribution. In particular, it works
well at preventing one very large group of songs (like A. R.
Rahman's full discography) from dominating your playlist, but
leaves many such entries at the end of the playlist.
|
[
"Shuffles",
"the",
"playlist",
"by",
"selecting",
"randomly",
"among",
"the",
"tracks",
"as",
"grouped",
"by",
"the",
"given",
"field"
] |
f549ab65c50a2bce7922c8c75621fb218885e460
|
https://github.com/mwatts15/xmms2_utils/blob/f549ab65c50a2bce7922c8c75621fb218885e460/lib/xmms2_utils.rb#L77-L107
|
8,868
|
mwatts15/xmms2_utils
|
lib/xmms2_utils.rb
|
Xmms.Client.extract_medialib_info
|
def extract_medialib_info(id, *fields)
infos = self.medialib_get_info(id).wait.value
res = Hash.new
if !infos.nil?
fields = fields.map! {|f| f.to_sym }
fields.each do |field|
values = infos[field]
if not values.nil?
my_value = values.first[1] # actual value from the top source [0]
if field == :url
my_value = Xmms::decode_xmms2_url(my_value)
end
res[field] = my_value.to_s.force_encoding("utf-8")
end
end
end
res
end
|
ruby
|
def extract_medialib_info(id, *fields)
infos = self.medialib_get_info(id).wait.value
res = Hash.new
if !infos.nil?
fields = fields.map! {|f| f.to_sym }
fields.each do |field|
values = infos[field]
if not values.nil?
my_value = values.first[1] # actual value from the top source [0]
if field == :url
my_value = Xmms::decode_xmms2_url(my_value)
end
res[field] = my_value.to_s.force_encoding("utf-8")
end
end
end
res
end
|
[
"def",
"extract_medialib_info",
"(",
"id",
",",
"*",
"fields",
")",
"infos",
"=",
"self",
".",
"medialib_get_info",
"(",
"id",
")",
".",
"wait",
".",
"value",
"res",
"=",
"Hash",
".",
"new",
"if",
"!",
"infos",
".",
"nil?",
"fields",
"=",
"fields",
".",
"map!",
"{",
"|",
"f",
"|",
"f",
".",
"to_sym",
"}",
"fields",
".",
"each",
"do",
"|",
"field",
"|",
"values",
"=",
"infos",
"[",
"field",
"]",
"if",
"not",
"values",
".",
"nil?",
"my_value",
"=",
"values",
".",
"first",
"[",
"1",
"]",
"# actual value from the top source [0]",
"if",
"field",
"==",
":url",
"my_value",
"=",
"Xmms",
"::",
"decode_xmms2_url",
"(",
"my_value",
")",
"end",
"res",
"[",
"field",
"]",
"=",
"my_value",
".",
"to_s",
".",
"force_encoding",
"(",
"\"utf-8\"",
")",
"end",
"end",
"end",
"res",
"end"
] |
returns a hash of the passed in fields
with the first-found values for the fields
|
[
"returns",
"a",
"hash",
"of",
"the",
"passed",
"in",
"fields",
"with",
"the",
"first",
"-",
"found",
"values",
"for",
"the",
"fields"
] |
f549ab65c50a2bce7922c8c75621fb218885e460
|
https://github.com/mwatts15/xmms2_utils/blob/f549ab65c50a2bce7922c8c75621fb218885e460/lib/xmms2_utils.rb#L111-L128
|
8,869
|
iv-mexx/git-releaselog
|
lib/git-releaselog/change.rb
|
Releaselog.Change.check_scope
|
def check_scope(scope = nil)
# If no scope is requested or the change has no scope include this change unchanged
return self unless scope
change_scope = /^\s*\[\w+\]/.match(@note)
return self unless change_scope
# change_scope is a string of format `[scope]`, need to strip the `[]` to compare the scope
if change_scope[0][1..-2] == scope
# Change has the scope that is requested, strip the whole scope scope from the change note
@note = change_scope.post_match.strip
return self
else
# Change has a different scope than requested
return nil
end
end
|
ruby
|
def check_scope(scope = nil)
# If no scope is requested or the change has no scope include this change unchanged
return self unless scope
change_scope = /^\s*\[\w+\]/.match(@note)
return self unless change_scope
# change_scope is a string of format `[scope]`, need to strip the `[]` to compare the scope
if change_scope[0][1..-2] == scope
# Change has the scope that is requested, strip the whole scope scope from the change note
@note = change_scope.post_match.strip
return self
else
# Change has a different scope than requested
return nil
end
end
|
[
"def",
"check_scope",
"(",
"scope",
"=",
"nil",
")",
"# If no scope is requested or the change has no scope include this change unchanged",
"return",
"self",
"unless",
"scope",
"change_scope",
"=",
"/",
"\\s",
"\\[",
"\\w",
"\\]",
"/",
".",
"match",
"(",
"@note",
")",
"return",
"self",
"unless",
"change_scope",
"# change_scope is a string of format `[scope]`, need to strip the `[]` to compare the scope",
"if",
"change_scope",
"[",
"0",
"]",
"[",
"1",
"..",
"-",
"2",
"]",
"==",
"scope",
"# Change has the scope that is requested, strip the whole scope scope from the change note",
"@note",
"=",
"change_scope",
".",
"post_match",
".",
"strip",
"return",
"self",
"else",
"# Change has a different scope than requested",
"return",
"nil",
"end",
"end"
] |
Checks the scope of the `Change` and the change out if the scope does not match.
|
[
"Checks",
"the",
"scope",
"of",
"the",
"Change",
"and",
"the",
"change",
"out",
"if",
"the",
"scope",
"does",
"not",
"match",
"."
] |
393d5d9b12f9dd808ccb2d13ab0ada12d72d2849
|
https://github.com/iv-mexx/git-releaselog/blob/393d5d9b12f9dd808ccb2d13ab0ada12d72d2849/lib/git-releaselog/change.rb#L48-L63
|
8,870
|
m-31/vcenter_lib
|
lib/vcenter_lib/vcenter.rb
|
VcenterLib.Vcenter.vms
|
def vms
logger.debug "get all VMs in all datacenters: begin"
result = dcs.inject([]) do |r, dc|
r + serviceContent.viewManager.CreateContainerView(
container: dc.vmFolder,
type: ['VirtualMachine'],
recursive: true
).view
end
logger.debug "get all VMs in all datacenters: end"
result
end
|
ruby
|
def vms
logger.debug "get all VMs in all datacenters: begin"
result = dcs.inject([]) do |r, dc|
r + serviceContent.viewManager.CreateContainerView(
container: dc.vmFolder,
type: ['VirtualMachine'],
recursive: true
).view
end
logger.debug "get all VMs in all datacenters: end"
result
end
|
[
"def",
"vms",
"logger",
".",
"debug",
"\"get all VMs in all datacenters: begin\"",
"result",
"=",
"dcs",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"r",
",",
"dc",
"|",
"r",
"+",
"serviceContent",
".",
"viewManager",
".",
"CreateContainerView",
"(",
"container",
":",
"dc",
".",
"vmFolder",
",",
"type",
":",
"[",
"'VirtualMachine'",
"]",
",",
"recursive",
":",
"true",
")",
".",
"view",
"end",
"logger",
".",
"debug",
"\"get all VMs in all datacenters: end\"",
"result",
"end"
] |
get all vms in all datacenters
|
[
"get",
"all",
"vms",
"in",
"all",
"datacenters"
] |
28ed325c73a1faaa5347919006d5a63c1bef6588
|
https://github.com/m-31/vcenter_lib/blob/28ed325c73a1faaa5347919006d5a63c1bef6588/lib/vcenter_lib/vcenter.rb#L21-L32
|
8,871
|
filip-d/7digital
|
lib/sevendigital/model/artist.rb
|
Sevendigital.Artist.various?
|
def various?
joined_names = "#{name} #{appears_as}".downcase
various_variations = ["vario", "v???????????????rio", "v.a", "vaious", "varios" "vaious", "varoius", "variuos", \
"soundtrack", "karaoke", "original cast", "diverse artist"]
various_variations.each{|various_variation| return true if joined_names.include?(various_variation)}
return false
end
|
ruby
|
def various?
joined_names = "#{name} #{appears_as}".downcase
various_variations = ["vario", "v???????????????rio", "v.a", "vaious", "varios" "vaious", "varoius", "variuos", \
"soundtrack", "karaoke", "original cast", "diverse artist"]
various_variations.each{|various_variation| return true if joined_names.include?(various_variation)}
return false
end
|
[
"def",
"various?",
"joined_names",
"=",
"\"#{name} #{appears_as}\"",
".",
"downcase",
"various_variations",
"=",
"[",
"\"vario\"",
",",
"\"v???????????????rio\"",
",",
"\"v.a\"",
",",
"\"vaious\"",
",",
"\"varios\"",
"\"vaious\"",
",",
"\"varoius\"",
",",
"\"variuos\"",
",",
"\"soundtrack\"",
",",
"\"karaoke\"",
",",
"\"original cast\"",
",",
"\"diverse artist\"",
"]",
"various_variations",
".",
"each",
"{",
"|",
"various_variation",
"|",
"return",
"true",
"if",
"joined_names",
".",
"include?",
"(",
"various_variation",
")",
"}",
"return",
"false",
"end"
] |
does this artist represents various artists?
@return [Boolean]
|
[
"does",
"this",
"artist",
"represents",
"various",
"artists?"
] |
20373ab8664c7c4ebe5dcb4719017c25dde90736
|
https://github.com/filip-d/7digital/blob/20373ab8664c7c4ebe5dcb4719017c25dde90736/lib/sevendigital/model/artist.rb#L94-L101
|
8,872
|
dominikh/weechat-ruby
|
lib/weechat.rb
|
Weechat.Helper.command_callback
|
def command_callback(id, buffer, args)
Weechat::Command.find_by_id(id).call(Weechat::Buffer.from_ptr(buffer), args)
end
|
ruby
|
def command_callback(id, buffer, args)
Weechat::Command.find_by_id(id).call(Weechat::Buffer.from_ptr(buffer), args)
end
|
[
"def",
"command_callback",
"(",
"id",
",",
"buffer",
",",
"args",
")",
"Weechat",
"::",
"Command",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"Weechat",
"::",
"Buffer",
".",
"from_ptr",
"(",
"buffer",
")",
",",
"args",
")",
"end"
] |
low level Callback method used for commands
|
[
"low",
"level",
"Callback",
"method",
"used",
"for",
"commands"
] |
b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb
|
https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L48-L50
|
8,873
|
dominikh/weechat-ruby
|
lib/weechat.rb
|
Weechat.Helper.command_run_callback
|
def command_run_callback(id, buffer, command)
Weechat::Hooks::CommandRunHook.find_by_id(id).call(Weechat::Buffer.from_ptr(buffer), command)
end
|
ruby
|
def command_run_callback(id, buffer, command)
Weechat::Hooks::CommandRunHook.find_by_id(id).call(Weechat::Buffer.from_ptr(buffer), command)
end
|
[
"def",
"command_run_callback",
"(",
"id",
",",
"buffer",
",",
"command",
")",
"Weechat",
"::",
"Hooks",
"::",
"CommandRunHook",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"Weechat",
"::",
"Buffer",
".",
"from_ptr",
"(",
"buffer",
")",
",",
"command",
")",
"end"
] |
low level Callback used for running commands
|
[
"low",
"level",
"Callback",
"used",
"for",
"running",
"commands"
] |
b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb
|
https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L53-L55
|
8,874
|
dominikh/weechat-ruby
|
lib/weechat.rb
|
Weechat.Helper.timer_callback
|
def timer_callback(id, remaining)
Weechat::Timer.find_by_id(id).call(remaining.to_i)
end
|
ruby
|
def timer_callback(id, remaining)
Weechat::Timer.find_by_id(id).call(remaining.to_i)
end
|
[
"def",
"timer_callback",
"(",
"id",
",",
"remaining",
")",
"Weechat",
"::",
"Timer",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"remaining",
".",
"to_i",
")",
"end"
] |
low level Timer callback
|
[
"low",
"level",
"Timer",
"callback"
] |
b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb
|
https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L58-L60
|
8,875
|
dominikh/weechat-ruby
|
lib/weechat.rb
|
Weechat.Helper.input_callback
|
def input_callback(method, buffer, input)
Weechat::Buffer.call_input_callback(method, buffer, input)
end
|
ruby
|
def input_callback(method, buffer, input)
Weechat::Buffer.call_input_callback(method, buffer, input)
end
|
[
"def",
"input_callback",
"(",
"method",
",",
"buffer",
",",
"input",
")",
"Weechat",
"::",
"Buffer",
".",
"call_input_callback",
"(",
"method",
",",
"buffer",
",",
"input",
")",
"end"
] |
low level buffer input callback
|
[
"low",
"level",
"buffer",
"input",
"callback"
] |
b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb
|
https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L63-L65
|
8,876
|
dominikh/weechat-ruby
|
lib/weechat.rb
|
Weechat.Helper.bar_build_callback
|
def bar_build_callback(id, item, window)
Weechat::Bar::Item.call_build_callback(id, window)
end
|
ruby
|
def bar_build_callback(id, item, window)
Weechat::Bar::Item.call_build_callback(id, window)
end
|
[
"def",
"bar_build_callback",
"(",
"id",
",",
"item",
",",
"window",
")",
"Weechat",
"::",
"Bar",
"::",
"Item",
".",
"call_build_callback",
"(",
"id",
",",
"window",
")",
"end"
] |
low level bar build callback
|
[
"low",
"level",
"bar",
"build",
"callback"
] |
b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb
|
https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L73-L75
|
8,877
|
dominikh/weechat-ruby
|
lib/weechat.rb
|
Weechat.Helper.info_callback
|
def info_callback(id, info, arguments)
Weechat::Info.find_by_id(id).call(arguments).to_s
end
|
ruby
|
def info_callback(id, info, arguments)
Weechat::Info.find_by_id(id).call(arguments).to_s
end
|
[
"def",
"info_callback",
"(",
"id",
",",
"info",
",",
"arguments",
")",
"Weechat",
"::",
"Info",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"arguments",
")",
".",
"to_s",
"end"
] |
low level info callback
|
[
"low",
"level",
"info",
"callback"
] |
b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb
|
https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L78-L80
|
8,878
|
dominikh/weechat-ruby
|
lib/weechat.rb
|
Weechat.Helper.print_callback
|
def print_callback(id, buffer, date, tags, displayed, highlight, prefix, message)
buffer = Weechat::Buffer.from_ptr(buffer)
date = Time.at(date.to_i)
tags = tags.split(",")
displayed = Weechat.integer_to_bool(displayed)
highlight = Weechat.integer_to_bool(highlight)
line = PrintedLine.new(buffer, date, tags, displayed, highlight, prefix, message)
Weechat::Hooks::Print.find_by_id(id).call(line)
end
|
ruby
|
def print_callback(id, buffer, date, tags, displayed, highlight, prefix, message)
buffer = Weechat::Buffer.from_ptr(buffer)
date = Time.at(date.to_i)
tags = tags.split(",")
displayed = Weechat.integer_to_bool(displayed)
highlight = Weechat.integer_to_bool(highlight)
line = PrintedLine.new(buffer, date, tags, displayed, highlight, prefix, message)
Weechat::Hooks::Print.find_by_id(id).call(line)
end
|
[
"def",
"print_callback",
"(",
"id",
",",
"buffer",
",",
"date",
",",
"tags",
",",
"displayed",
",",
"highlight",
",",
"prefix",
",",
"message",
")",
"buffer",
"=",
"Weechat",
"::",
"Buffer",
".",
"from_ptr",
"(",
"buffer",
")",
"date",
"=",
"Time",
".",
"at",
"(",
"date",
".",
"to_i",
")",
"tags",
"=",
"tags",
".",
"split",
"(",
"\",\"",
")",
"displayed",
"=",
"Weechat",
".",
"integer_to_bool",
"(",
"displayed",
")",
"highlight",
"=",
"Weechat",
".",
"integer_to_bool",
"(",
"highlight",
")",
"line",
"=",
"PrintedLine",
".",
"new",
"(",
"buffer",
",",
"date",
",",
"tags",
",",
"displayed",
",",
"highlight",
",",
"prefix",
",",
"message",
")",
"Weechat",
"::",
"Hooks",
"::",
"Print",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"line",
")",
"end"
] |
low level print callback
|
[
"low",
"level",
"print",
"callback"
] |
b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb
|
https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L83-L91
|
8,879
|
dominikh/weechat-ruby
|
lib/weechat.rb
|
Weechat.Helper.signal_callback
|
def signal_callback(id, signal, data)
data = Weechat::Utilities.apply_transformation(signal, data, SignalCallbackTransformations)
Weechat::Hooks::Signal.find_by_id(id).call(signal, data)
end
|
ruby
|
def signal_callback(id, signal, data)
data = Weechat::Utilities.apply_transformation(signal, data, SignalCallbackTransformations)
Weechat::Hooks::Signal.find_by_id(id).call(signal, data)
end
|
[
"def",
"signal_callback",
"(",
"id",
",",
"signal",
",",
"data",
")",
"data",
"=",
"Weechat",
"::",
"Utilities",
".",
"apply_transformation",
"(",
"signal",
",",
"data",
",",
"SignalCallbackTransformations",
")",
"Weechat",
"::",
"Hooks",
"::",
"Signal",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"signal",
",",
"data",
")",
"end"
] |
low level callback for signal hooks
|
[
"low",
"level",
"callback",
"for",
"signal",
"hooks"
] |
b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb
|
https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L114-L117
|
8,880
|
dominikh/weechat-ruby
|
lib/weechat.rb
|
Weechat.Helper.config_callback
|
def config_callback(id, option, value)
ret = Weechat::Hooks::Config.find_by_id(id).call(option, value)
end
|
ruby
|
def config_callback(id, option, value)
ret = Weechat::Hooks::Config.find_by_id(id).call(option, value)
end
|
[
"def",
"config_callback",
"(",
"id",
",",
"option",
",",
"value",
")",
"ret",
"=",
"Weechat",
"::",
"Hooks",
"::",
"Config",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"option",
",",
"value",
")",
"end"
] |
low level config callback
|
[
"low",
"level",
"config",
"callback"
] |
b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb
|
https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L120-L122
|
8,881
|
dominikh/weechat-ruby
|
lib/weechat.rb
|
Weechat.Helper.process_callback
|
def process_callback(id, command, code, stdout, stderr)
code = case code
when Weechat::WEECHAT_HOOK_PROCESS_RUNNING
:running
when Weechat::WEECHAT_HOOK_PROCESS_ERROR
:error
else
code
end
process = Weechat::Process.find_by_id(id)
if process.collect?
process.buffer(stdout, stderr)
if code == :error || code != :running
process.call(code, process.stdout, process.stderr)
end
else
process.call(code, stdout, stderr)
end
end
|
ruby
|
def process_callback(id, command, code, stdout, stderr)
code = case code
when Weechat::WEECHAT_HOOK_PROCESS_RUNNING
:running
when Weechat::WEECHAT_HOOK_PROCESS_ERROR
:error
else
code
end
process = Weechat::Process.find_by_id(id)
if process.collect?
process.buffer(stdout, stderr)
if code == :error || code != :running
process.call(code, process.stdout, process.stderr)
end
else
process.call(code, stdout, stderr)
end
end
|
[
"def",
"process_callback",
"(",
"id",
",",
"command",
",",
"code",
",",
"stdout",
",",
"stderr",
")",
"code",
"=",
"case",
"code",
"when",
"Weechat",
"::",
"WEECHAT_HOOK_PROCESS_RUNNING",
":running",
"when",
"Weechat",
"::",
"WEECHAT_HOOK_PROCESS_ERROR",
":error",
"else",
"code",
"end",
"process",
"=",
"Weechat",
"::",
"Process",
".",
"find_by_id",
"(",
"id",
")",
"if",
"process",
".",
"collect?",
"process",
".",
"buffer",
"(",
"stdout",
",",
"stderr",
")",
"if",
"code",
"==",
":error",
"||",
"code",
"!=",
":running",
"process",
".",
"call",
"(",
"code",
",",
"process",
".",
"stdout",
",",
"process",
".",
"stderr",
")",
"end",
"else",
"process",
".",
"call",
"(",
"code",
",",
"stdout",
",",
"stderr",
")",
"end",
"end"
] |
low level process callback
|
[
"low",
"level",
"process",
"callback"
] |
b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb
|
https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L125-L144
|
8,882
|
dominikh/weechat-ruby
|
lib/weechat.rb
|
Weechat.Helper.modifier_callback
|
def modifier_callback(id, modifier, modifier_data, s)
classes = Weechat::Hook.hook_classes
modifier_data = Weechat::Utilities.apply_transformation(modifier, modifier_data, ModifierCallbackTransformations)
modifier_data = [modifier_data] unless modifier_data.is_a?(Array)
args = modifier_data + [Weechat::Line.parse(s)]
callback = classes.map {|cls| cls.find_by_id(id)}.compact.first
ret = callback.call(*args)
return Weechat::Utilities.apply_transformation(modifier, ret, ModifierCallbackRTransformations).to_s
end
|
ruby
|
def modifier_callback(id, modifier, modifier_data, s)
classes = Weechat::Hook.hook_classes
modifier_data = Weechat::Utilities.apply_transformation(modifier, modifier_data, ModifierCallbackTransformations)
modifier_data = [modifier_data] unless modifier_data.is_a?(Array)
args = modifier_data + [Weechat::Line.parse(s)]
callback = classes.map {|cls| cls.find_by_id(id)}.compact.first
ret = callback.call(*args)
return Weechat::Utilities.apply_transformation(modifier, ret, ModifierCallbackRTransformations).to_s
end
|
[
"def",
"modifier_callback",
"(",
"id",
",",
"modifier",
",",
"modifier_data",
",",
"s",
")",
"classes",
"=",
"Weechat",
"::",
"Hook",
".",
"hook_classes",
"modifier_data",
"=",
"Weechat",
"::",
"Utilities",
".",
"apply_transformation",
"(",
"modifier",
",",
"modifier_data",
",",
"ModifierCallbackTransformations",
")",
"modifier_data",
"=",
"[",
"modifier_data",
"]",
"unless",
"modifier_data",
".",
"is_a?",
"(",
"Array",
")",
"args",
"=",
"modifier_data",
"+",
"[",
"Weechat",
"::",
"Line",
".",
"parse",
"(",
"s",
")",
"]",
"callback",
"=",
"classes",
".",
"map",
"{",
"|",
"cls",
"|",
"cls",
".",
"find_by_id",
"(",
"id",
")",
"}",
".",
"compact",
".",
"first",
"ret",
"=",
"callback",
".",
"call",
"(",
"args",
")",
"return",
"Weechat",
"::",
"Utilities",
".",
"apply_transformation",
"(",
"modifier",
",",
"ret",
",",
"ModifierCallbackRTransformations",
")",
".",
"to_s",
"end"
] |
low level modifier hook callback
|
[
"low",
"level",
"modifier",
"hook",
"callback"
] |
b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb
|
https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L172-L182
|
8,883
|
alexggordon/basecampeverest
|
lib/basecampeverest/connect.rb
|
Basecampeverest.Connect.auth=
|
def auth=(authorization)
clensed_auth_hash = {}
authorization.each {|k, v|
clensed_auth_hash[k.to_sym] = v
}
# nice and pretty now
authorization = clensed_auth_hash
if authorization.has_key? :access_token
# clear the basic_auth, if it's set
self.class.default_options.reject!{ |k| k == :basic_auth }
# set the Authorization headers
self.class.headers.merge!("Authorization" => "Bearer #{authorization[:access_token]}")
elsif authorization.has_key?(:username) && authorization.has_key?(:password)
# ... then we pass it off to basic auth
self.class.basic_auth authorization[:username], authorization[:password]
# check if the user tried passing in some other stupid stuff.
# this should never be the case if the user follows instructions.
self.class.headers.reject!{ |k, v| k == "Authorization" }
else
# something inportant is missing if we get here.
raise "Incomplete Authorization hash. Please check the Authentication Hash."
#end else
end
# end method
end
|
ruby
|
def auth=(authorization)
clensed_auth_hash = {}
authorization.each {|k, v|
clensed_auth_hash[k.to_sym] = v
}
# nice and pretty now
authorization = clensed_auth_hash
if authorization.has_key? :access_token
# clear the basic_auth, if it's set
self.class.default_options.reject!{ |k| k == :basic_auth }
# set the Authorization headers
self.class.headers.merge!("Authorization" => "Bearer #{authorization[:access_token]}")
elsif authorization.has_key?(:username) && authorization.has_key?(:password)
# ... then we pass it off to basic auth
self.class.basic_auth authorization[:username], authorization[:password]
# check if the user tried passing in some other stupid stuff.
# this should never be the case if the user follows instructions.
self.class.headers.reject!{ |k, v| k == "Authorization" }
else
# something inportant is missing if we get here.
raise "Incomplete Authorization hash. Please check the Authentication Hash."
#end else
end
# end method
end
|
[
"def",
"auth",
"=",
"(",
"authorization",
")",
"clensed_auth_hash",
"=",
"{",
"}",
"authorization",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"clensed_auth_hash",
"[",
"k",
".",
"to_sym",
"]",
"=",
"v",
"}",
"# nice and pretty now",
"authorization",
"=",
"clensed_auth_hash",
"if",
"authorization",
".",
"has_key?",
":access_token",
"# clear the basic_auth, if it's set",
"self",
".",
"class",
".",
"default_options",
".",
"reject!",
"{",
"|",
"k",
"|",
"k",
"==",
":basic_auth",
"}",
"# set the Authorization headers",
"self",
".",
"class",
".",
"headers",
".",
"merge!",
"(",
"\"Authorization\"",
"=>",
"\"Bearer #{authorization[:access_token]}\"",
")",
"elsif",
"authorization",
".",
"has_key?",
"(",
":username",
")",
"&&",
"authorization",
".",
"has_key?",
"(",
":password",
")",
"# ... then we pass it off to basic auth",
"self",
".",
"class",
".",
"basic_auth",
"authorization",
"[",
":username",
"]",
",",
"authorization",
"[",
":password",
"]",
"# check if the user tried passing in some other stupid stuff.",
"# this should never be the case if the user follows instructions. ",
"self",
".",
"class",
".",
"headers",
".",
"reject!",
"{",
"|",
"k",
",",
"v",
"|",
"k",
"==",
"\"Authorization\"",
"}",
"else",
"# something inportant is missing if we get here. ",
"raise",
"\"Incomplete Authorization hash. Please check the Authentication Hash.\"",
"#end else ",
"end",
"# end method",
"end"
] |
Initializes the connection to Basecamp using httparty.
@param basecamp_id [String] the Basecamp company ID
@param authorization [Hash] authorization hash consisting of a username and password combination (:username, :password) or an access_token (:access_token)
@param user_agent [String] the user-agent string to include in header of requests
Sets the authorization information.
Need to
@param authorization [Hash] authorization hash consisting of a username and password combination (:username, :password) or an access_token (:access_token)
|
[
"Initializes",
"the",
"connection",
"to",
"Basecamp",
"using",
"httparty",
"."
] |
dd6aede7c43f9ea81c4e8a80103c1d2f01d61fb0
|
https://github.com/alexggordon/basecampeverest/blob/dd6aede7c43f9ea81c4e8a80103c1d2f01d61fb0/lib/basecampeverest/connect.rb#L83-L117
|
8,884
|
tbuehlmann/ponder
|
lib/ponder/user_list.rb
|
Ponder.UserList.kill_zombie_users
|
def kill_zombie_users(users)
@mutex.synchronize do
(@users - users - Set.new([@thaum_user])).each do |user|
@users.delete(user)
end
end
end
|
ruby
|
def kill_zombie_users(users)
@mutex.synchronize do
(@users - users - Set.new([@thaum_user])).each do |user|
@users.delete(user)
end
end
end
|
[
"def",
"kill_zombie_users",
"(",
"users",
")",
"@mutex",
".",
"synchronize",
"do",
"(",
"@users",
"-",
"users",
"-",
"Set",
".",
"new",
"(",
"[",
"@thaum_user",
"]",
")",
")",
".",
"each",
"do",
"|",
"user",
"|",
"@users",
".",
"delete",
"(",
"user",
")",
"end",
"end",
"end"
] |
Removes all users from the UserList that don't share channels with the
Thaum.
|
[
"Removes",
"all",
"users",
"from",
"the",
"UserList",
"that",
"don",
"t",
"share",
"channels",
"with",
"the",
"Thaum",
"."
] |
930912e1b78b41afa1359121aca46197e9edff9c
|
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/user_list.rb#L44-L50
|
8,885
|
tech-angels/annotator
|
lib/annotator/attributes.rb
|
Annotator.Attributes.lines
|
def lines
ret = [Attributes::HEADER]
# Sort by name, but id goes first
@attrs.sort_by{|x| x[:name] == 'id' ? '_' : x[:name]}.each do |row|
line = "# * #{row[:name]} [#{row[:type]}]#{row[:desc].to_s.empty? ? "" : " - #{row[:desc]}"}"
# split into lines that don't exceed 80 chars
lt = wrap_text(line, MAX_CHARS_PER_LINE-3).split("\n")
line = ([lt[0]] + lt[1..-1].map{|x| "# #{x}"}).join("\n")
ret << line
end
ret
end
|
ruby
|
def lines
ret = [Attributes::HEADER]
# Sort by name, but id goes first
@attrs.sort_by{|x| x[:name] == 'id' ? '_' : x[:name]}.each do |row|
line = "# * #{row[:name]} [#{row[:type]}]#{row[:desc].to_s.empty? ? "" : " - #{row[:desc]}"}"
# split into lines that don't exceed 80 chars
lt = wrap_text(line, MAX_CHARS_PER_LINE-3).split("\n")
line = ([lt[0]] + lt[1..-1].map{|x| "# #{x}"}).join("\n")
ret << line
end
ret
end
|
[
"def",
"lines",
"ret",
"=",
"[",
"Attributes",
"::",
"HEADER",
"]",
"# Sort by name, but id goes first",
"@attrs",
".",
"sort_by",
"{",
"|",
"x",
"|",
"x",
"[",
":name",
"]",
"==",
"'id'",
"?",
"'_'",
":",
"x",
"[",
":name",
"]",
"}",
".",
"each",
"do",
"|",
"row",
"|",
"line",
"=",
"\"# * #{row[:name]} [#{row[:type]}]#{row[:desc].to_s.empty? ? \"\" : \" - #{row[:desc]}\"}\"",
"# split into lines that don't exceed 80 chars",
"lt",
"=",
"wrap_text",
"(",
"line",
",",
"MAX_CHARS_PER_LINE",
"-",
"3",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"line",
"=",
"(",
"[",
"lt",
"[",
"0",
"]",
"]",
"+",
"lt",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"map",
"{",
"|",
"x",
"|",
"\"# #{x}\"",
"}",
")",
".",
"join",
"(",
"\"\\n\"",
")",
"ret",
"<<",
"line",
"end",
"ret",
"end"
] |
Convert attributes array back to attributes lines representation to be put into file
|
[
"Convert",
"attributes",
"array",
"back",
"to",
"attributes",
"lines",
"representation",
"to",
"be",
"put",
"into",
"file"
] |
ad8f203635633eb3428105be7c39b80694184a2b
|
https://github.com/tech-angels/annotator/blob/ad8f203635633eb3428105be7c39b80694184a2b/lib/annotator/attributes.rb#L20-L31
|
8,886
|
tech-angels/annotator
|
lib/annotator/attributes.rb
|
Annotator.Attributes.update!
|
def update!
@model.columns.each do |column|
if row = @attrs.find {|x| x[:name] == column.name}
if row[:type] != type_str(column)
puts " M #{@model}##{column.name} [#{row[:type]} -> #{type_str(column)}]"
row[:type] = type_str(column)
elsif row[:desc] == InitialDescription::DEFAULT_DESCRIPTION
new_desc = InitialDescription.for(@model, column.name)
if row[:desc] != new_desc
puts " M #{@model}##{column.name} description updated"
row[:desc] = new_desc
end
end
else
puts " A #{@model}##{column.name} [#{type_str(column)}]"
@attrs << {
:name => column.name,
:type => type_str(column),
:desc => InitialDescription.for(@model, column.name)
}
end
end
# find columns that no more exist in db
orphans = @attrs.map{|x| x[:name]} - @model.columns.map(&:name)
unless orphans.empty?
orphans.each do |orphan|
puts " D #{@model}##{orphan}"
@attrs = @attrs.select {|x| x[:name] != orphan}
end
end
@attrs
end
|
ruby
|
def update!
@model.columns.each do |column|
if row = @attrs.find {|x| x[:name] == column.name}
if row[:type] != type_str(column)
puts " M #{@model}##{column.name} [#{row[:type]} -> #{type_str(column)}]"
row[:type] = type_str(column)
elsif row[:desc] == InitialDescription::DEFAULT_DESCRIPTION
new_desc = InitialDescription.for(@model, column.name)
if row[:desc] != new_desc
puts " M #{@model}##{column.name} description updated"
row[:desc] = new_desc
end
end
else
puts " A #{@model}##{column.name} [#{type_str(column)}]"
@attrs << {
:name => column.name,
:type => type_str(column),
:desc => InitialDescription.for(@model, column.name)
}
end
end
# find columns that no more exist in db
orphans = @attrs.map{|x| x[:name]} - @model.columns.map(&:name)
unless orphans.empty?
orphans.each do |orphan|
puts " D #{@model}##{orphan}"
@attrs = @attrs.select {|x| x[:name] != orphan}
end
end
@attrs
end
|
[
"def",
"update!",
"@model",
".",
"columns",
".",
"each",
"do",
"|",
"column",
"|",
"if",
"row",
"=",
"@attrs",
".",
"find",
"{",
"|",
"x",
"|",
"x",
"[",
":name",
"]",
"==",
"column",
".",
"name",
"}",
"if",
"row",
"[",
":type",
"]",
"!=",
"type_str",
"(",
"column",
")",
"puts",
"\" M #{@model}##{column.name} [#{row[:type]} -> #{type_str(column)}]\"",
"row",
"[",
":type",
"]",
"=",
"type_str",
"(",
"column",
")",
"elsif",
"row",
"[",
":desc",
"]",
"==",
"InitialDescription",
"::",
"DEFAULT_DESCRIPTION",
"new_desc",
"=",
"InitialDescription",
".",
"for",
"(",
"@model",
",",
"column",
".",
"name",
")",
"if",
"row",
"[",
":desc",
"]",
"!=",
"new_desc",
"puts",
"\" M #{@model}##{column.name} description updated\"",
"row",
"[",
":desc",
"]",
"=",
"new_desc",
"end",
"end",
"else",
"puts",
"\" A #{@model}##{column.name} [#{type_str(column)}]\"",
"@attrs",
"<<",
"{",
":name",
"=>",
"column",
".",
"name",
",",
":type",
"=>",
"type_str",
"(",
"column",
")",
",",
":desc",
"=>",
"InitialDescription",
".",
"for",
"(",
"@model",
",",
"column",
".",
"name",
")",
"}",
"end",
"end",
"# find columns that no more exist in db",
"orphans",
"=",
"@attrs",
".",
"map",
"{",
"|",
"x",
"|",
"x",
"[",
":name",
"]",
"}",
"-",
"@model",
".",
"columns",
".",
"map",
"(",
":name",
")",
"unless",
"orphans",
".",
"empty?",
"orphans",
".",
"each",
"do",
"|",
"orphan",
"|",
"puts",
"\" D #{@model}##{orphan}\"",
"@attrs",
"=",
"@attrs",
".",
"select",
"{",
"|",
"x",
"|",
"x",
"[",
":name",
"]",
"!=",
"orphan",
"}",
"end",
"end",
"@attrs",
"end"
] |
Update attribudes array to the current database state
|
[
"Update",
"attribudes",
"array",
"to",
"the",
"current",
"database",
"state"
] |
ad8f203635633eb3428105be7c39b80694184a2b
|
https://github.com/tech-angels/annotator/blob/ad8f203635633eb3428105be7c39b80694184a2b/lib/annotator/attributes.rb#L34-L67
|
8,887
|
tech-angels/annotator
|
lib/annotator/attributes.rb
|
Annotator.Attributes.parse
|
def parse
@lines.each do |line|
if m = line.match(R_ATTRIBUTE)
@attrs << {:name => m[1].strip, :type => m[2].strip, :desc => m[4].strip}
elsif m = line.match(R_ATTRIBUTE_NEXT_LINE)
@attrs[-1][:desc] += " #{m[1].strip}"
end
end
end
|
ruby
|
def parse
@lines.each do |line|
if m = line.match(R_ATTRIBUTE)
@attrs << {:name => m[1].strip, :type => m[2].strip, :desc => m[4].strip}
elsif m = line.match(R_ATTRIBUTE_NEXT_LINE)
@attrs[-1][:desc] += " #{m[1].strip}"
end
end
end
|
[
"def",
"parse",
"@lines",
".",
"each",
"do",
"|",
"line",
"|",
"if",
"m",
"=",
"line",
".",
"match",
"(",
"R_ATTRIBUTE",
")",
"@attrs",
"<<",
"{",
":name",
"=>",
"m",
"[",
"1",
"]",
".",
"strip",
",",
":type",
"=>",
"m",
"[",
"2",
"]",
".",
"strip",
",",
":desc",
"=>",
"m",
"[",
"4",
"]",
".",
"strip",
"}",
"elsif",
"m",
"=",
"line",
".",
"match",
"(",
"R_ATTRIBUTE_NEXT_LINE",
")",
"@attrs",
"[",
"-",
"1",
"]",
"[",
":desc",
"]",
"+=",
"\" #{m[1].strip}\"",
"end",
"end",
"end"
] |
Convert attributes lines into meaniningful array
|
[
"Convert",
"attributes",
"lines",
"into",
"meaniningful",
"array"
] |
ad8f203635633eb3428105be7c39b80694184a2b
|
https://github.com/tech-angels/annotator/blob/ad8f203635633eb3428105be7c39b80694184a2b/lib/annotator/attributes.rb#L72-L80
|
8,888
|
tech-angels/annotator
|
lib/annotator/attributes.rb
|
Annotator.Attributes.truncate_default
|
def truncate_default(str)
return str unless str.kind_of? String
str.sub!(/^'(.*)'$/m,'\1')
str = "#{str[0..10]}..." if str.size > 10
str.inspect
end
|
ruby
|
def truncate_default(str)
return str unless str.kind_of? String
str.sub!(/^'(.*)'$/m,'\1')
str = "#{str[0..10]}..." if str.size > 10
str.inspect
end
|
[
"def",
"truncate_default",
"(",
"str",
")",
"return",
"str",
"unless",
"str",
".",
"kind_of?",
"String",
"str",
".",
"sub!",
"(",
"/",
"/m",
",",
"'\\1'",
")",
"str",
"=",
"\"#{str[0..10]}...\"",
"if",
"str",
".",
"size",
">",
"10",
"str",
".",
"inspect",
"end"
] |
default value could be a multiple lines string, which would ruin annotations,
so we truncate it and display inspect of that string
|
[
"default",
"value",
"could",
"be",
"a",
"multiple",
"lines",
"string",
"which",
"would",
"ruin",
"annotations",
"so",
"we",
"truncate",
"it",
"and",
"display",
"inspect",
"of",
"that",
"string"
] |
ad8f203635633eb3428105be7c39b80694184a2b
|
https://github.com/tech-angels/annotator/blob/ad8f203635633eb3428105be7c39b80694184a2b/lib/annotator/attributes.rb#L84-L89
|
8,889
|
tech-angels/annotator
|
lib/annotator/attributes.rb
|
Annotator.Attributes.type_str
|
def type_str(c)
ret = c.type.to_s
ret << ", primary" if c.primary
ret << ", default=#{truncate_default(c.default)}" if c.default
ret << ", not null" unless c.null
ret << ", limit=#{c.limit}" if c.limit && (c.limit != 255 && c.type != :string)
ret
end
|
ruby
|
def type_str(c)
ret = c.type.to_s
ret << ", primary" if c.primary
ret << ", default=#{truncate_default(c.default)}" if c.default
ret << ", not null" unless c.null
ret << ", limit=#{c.limit}" if c.limit && (c.limit != 255 && c.type != :string)
ret
end
|
[
"def",
"type_str",
"(",
"c",
")",
"ret",
"=",
"c",
".",
"type",
".",
"to_s",
"ret",
"<<",
"\", primary\"",
"if",
"c",
".",
"primary",
"ret",
"<<",
"\", default=#{truncate_default(c.default)}\"",
"if",
"c",
".",
"default",
"ret",
"<<",
"\", not null\"",
"unless",
"c",
".",
"null",
"ret",
"<<",
"\", limit=#{c.limit}\"",
"if",
"c",
".",
"limit",
"&&",
"(",
"c",
".",
"limit",
"!=",
"255",
"&&",
"c",
".",
"type",
"!=",
":string",
")",
"ret",
"end"
] |
Human readable description of given column type
|
[
"Human",
"readable",
"description",
"of",
"given",
"column",
"type"
] |
ad8f203635633eb3428105be7c39b80694184a2b
|
https://github.com/tech-angels/annotator/blob/ad8f203635633eb3428105be7c39b80694184a2b/lib/annotator/attributes.rb#L92-L99
|
8,890
|
colbell/bitsa
|
lib/bitsa.rb
|
Bitsa.BitsaApp.run
|
def run(global_opts, cmd, search_data)
settings = load_settings(global_opts)
process_cmd(cmd, search_data, settings.login, settings.password,
ContactsCache.new(settings.cache_file_path,
settings.auto_check))
end
|
ruby
|
def run(global_opts, cmd, search_data)
settings = load_settings(global_opts)
process_cmd(cmd, search_data, settings.login, settings.password,
ContactsCache.new(settings.cache_file_path,
settings.auto_check))
end
|
[
"def",
"run",
"(",
"global_opts",
",",
"cmd",
",",
"search_data",
")",
"settings",
"=",
"load_settings",
"(",
"global_opts",
")",
"process_cmd",
"(",
"cmd",
",",
"search_data",
",",
"settings",
".",
"login",
",",
"settings",
".",
"password",
",",
"ContactsCache",
".",
"new",
"(",
"settings",
".",
"cache_file_path",
",",
"settings",
".",
"auto_check",
")",
")",
"end"
] |
Run application.
@example run the application
args = Bitsa::CLI.new
args.parse(ARGV)
app = Bitsa::BitsaApp.new
app.run(args.global_opts, args.cmd, args.search_data)
@param global_opts [Hash] Application arguments
@param cmd [String] The command requested.
@param search_data [String] Data to search for from cmd line.
@return [nil] ignored
|
[
"Run",
"application",
"."
] |
8b73c4988bde1bf8e64d9cb999164c3e5988dba5
|
https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa.rb#L47-L52
|
8,891
|
colbell/bitsa
|
lib/bitsa.rb
|
Bitsa.BitsaApp.load_settings
|
def load_settings(global_opts)
settings = Settings.new
settings.load(ConfigFile.new(global_opts[:config_file]), global_opts)
settings
end
|
ruby
|
def load_settings(global_opts)
settings = Settings.new
settings.load(ConfigFile.new(global_opts[:config_file]), global_opts)
settings
end
|
[
"def",
"load_settings",
"(",
"global_opts",
")",
"settings",
"=",
"Settings",
".",
"new",
"settings",
".",
"load",
"(",
"ConfigFile",
".",
"new",
"(",
"global_opts",
"[",
":config_file",
"]",
")",
",",
"global_opts",
")",
"settings",
"end"
] |
Load settings, combining arguments from cmd lien and the settings file.
@param global_opts [Hash] Application arguments
@return [Settings] Object representing the settings for this run of the
app.
|
[
"Load",
"settings",
"combining",
"arguments",
"from",
"cmd",
"lien",
"and",
"the",
"settings",
"file",
"."
] |
8b73c4988bde1bf8e64d9cb999164c3e5988dba5
|
https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa.rb#L83-L87
|
8,892
|
colbell/bitsa
|
lib/bitsa.rb
|
Bitsa.BitsaApp.search
|
def search(cache, search_data)
puts '' # Force first entry to be displayed in mutt
# Write out as EMAIL <TAB> NAME
cache.search(search_data).each { |k, v| puts "#{k}\t#{v}" }
end
|
ruby
|
def search(cache, search_data)
puts '' # Force first entry to be displayed in mutt
# Write out as EMAIL <TAB> NAME
cache.search(search_data).each { |k, v| puts "#{k}\t#{v}" }
end
|
[
"def",
"search",
"(",
"cache",
",",
"search_data",
")",
"puts",
"''",
"# Force first entry to be displayed in mutt",
"# Write out as EMAIL <TAB> NAME",
"cache",
".",
"search",
"(",
"search_data",
")",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"puts",
"\"#{k}\\t#{v}\"",
"}",
"end"
] |
Search the cache for the requested search_data and write the results to
std output.
@param cache [ContactsCache] Cache of contacts to be searched.
@param search_data [String] Data to search cache for.
|
[
"Search",
"the",
"cache",
"for",
"the",
"requested",
"search_data",
"and",
"write",
"the",
"results",
"to",
"std",
"output",
"."
] |
8b73c4988bde1bf8e64d9cb999164c3e5988dba5
|
https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa.rb#L104-L108
|
8,893
|
NUBIC/aker
|
lib/aker/form/login_form_asset_provider.rb
|
Aker::Form.LoginFormAssetProvider.asset_root
|
def asset_root
File.expand_path(File.join(File.dirname(__FILE__),
%w(.. .. ..),
%w(assets aker form)))
end
|
ruby
|
def asset_root
File.expand_path(File.join(File.dirname(__FILE__),
%w(.. .. ..),
%w(assets aker form)))
end
|
[
"def",
"asset_root",
"File",
".",
"expand_path",
"(",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
",",
"%w(",
"..",
"..",
"..",
")",
",",
"%w(",
"assets",
"aker",
"form",
")",
")",
")",
"end"
] |
Where to look for HTML and CSS assets.
This is currently hardcoded as `(aker gem root)/assets/aker/form`.
@return [String] a directory path
|
[
"Where",
"to",
"look",
"for",
"HTML",
"and",
"CSS",
"assets",
"."
] |
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
|
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/form/login_form_asset_provider.rb#L20-L24
|
8,894
|
NUBIC/aker
|
lib/aker/form/login_form_asset_provider.rb
|
Aker::Form.LoginFormAssetProvider.login_html
|
def login_html(env, options = {})
login_base = env['SCRIPT_NAME'] + login_path(env)
template = File.read(File.join(asset_root, 'login.html.erb'))
ERB.new(template).result(binding)
end
|
ruby
|
def login_html(env, options = {})
login_base = env['SCRIPT_NAME'] + login_path(env)
template = File.read(File.join(asset_root, 'login.html.erb'))
ERB.new(template).result(binding)
end
|
[
"def",
"login_html",
"(",
"env",
",",
"options",
"=",
"{",
"}",
")",
"login_base",
"=",
"env",
"[",
"'SCRIPT_NAME'",
"]",
"+",
"login_path",
"(",
"env",
")",
"template",
"=",
"File",
".",
"read",
"(",
"File",
".",
"join",
"(",
"asset_root",
",",
"'login.html.erb'",
")",
")",
"ERB",
".",
"new",
"(",
"template",
")",
".",
"result",
"(",
"binding",
")",
"end"
] |
Provides the HTML for the login form.
This method expects to find a `login.html.erb` ERB template in
{#asset_root}. The ERB template is evaluated in an environment where
a local variable named `script_name` is bound to the value of the
`SCRIPT_NAME` Rack environment variable, which is useful for CSS and
form action URL generation.
@param env [Rack environment] a Rack environment
@param [Hash] options rendering options
@option options [Boolean] :login_failed If true, will render a failure message
@option options [Boolean] :logged_out If true, will render a logout notification
@option options [String] :username Text for the username field
@option options [String] :url A URL to redirect to upon successful login
@return [String] HTML data
|
[
"Provides",
"the",
"HTML",
"for",
"the",
"login",
"form",
"."
] |
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
|
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/form/login_form_asset_provider.rb#L42-L46
|
8,895
|
GeoffWilliams/puppetbox
|
lib/puppetbox/result.rb
|
PuppetBox.Result.passed?
|
def passed?
passed = nil
@report.each { |r|
if passed == nil
passed = (r[:status] == PS_OK)
else
passed &= (r[:status] == PS_OK)
end
}
passed
end
|
ruby
|
def passed?
passed = nil
@report.each { |r|
if passed == nil
passed = (r[:status] == PS_OK)
else
passed &= (r[:status] == PS_OK)
end
}
passed
end
|
[
"def",
"passed?",
"passed",
"=",
"nil",
"@report",
".",
"each",
"{",
"|",
"r",
"|",
"if",
"passed",
"==",
"nil",
"passed",
"=",
"(",
"r",
"[",
":status",
"]",
"==",
"PS_OK",
")",
"else",
"passed",
"&=",
"(",
"r",
"[",
":status",
"]",
"==",
"PS_OK",
")",
"end",
"}",
"passed",
"end"
] |
Test whether this set of results passed or not
@return true if tests were executed and passed, nil if no tests were
executed, false if tests were exectued and there were failures
|
[
"Test",
"whether",
"this",
"set",
"of",
"results",
"passed",
"or",
"not"
] |
8ace050aa46e8908c1b266b9307f01929e222e53
|
https://github.com/GeoffWilliams/puppetbox/blob/8ace050aa46e8908c1b266b9307f01929e222e53/lib/puppetbox/result.rb#L52-L63
|
8,896
|
pvijayror/rails_exception_logger
|
app/controllers/rails_exception_logger/logged_exceptions_controller.rb
|
RailsExceptionLogger.LoggedExceptionsController.get_auth_data
|
def get_auth_data
auth_key = @@http_auth_headers.detect { |h| request.env.has_key?(h) }
auth_data = request.env[auth_key].to_s.split unless auth_key.blank?
return auth_data && auth_data[0] == 'Basic' ? Base64.decode64(auth_data[1]).split(':')[0..1] : [nil, nil]
end
|
ruby
|
def get_auth_data
auth_key = @@http_auth_headers.detect { |h| request.env.has_key?(h) }
auth_data = request.env[auth_key].to_s.split unless auth_key.blank?
return auth_data && auth_data[0] == 'Basic' ? Base64.decode64(auth_data[1]).split(':')[0..1] : [nil, nil]
end
|
[
"def",
"get_auth_data",
"auth_key",
"=",
"@@http_auth_headers",
".",
"detect",
"{",
"|",
"h",
"|",
"request",
".",
"env",
".",
"has_key?",
"(",
"h",
")",
"}",
"auth_data",
"=",
"request",
".",
"env",
"[",
"auth_key",
"]",
".",
"to_s",
".",
"split",
"unless",
"auth_key",
".",
"blank?",
"return",
"auth_data",
"&&",
"auth_data",
"[",
"0",
"]",
"==",
"'Basic'",
"?",
"Base64",
".",
"decode64",
"(",
"auth_data",
"[",
"1",
"]",
")",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"..",
"1",
"]",
":",
"[",
"nil",
",",
"nil",
"]",
"end"
] |
gets BASIC auth info
|
[
"gets",
"BASIC",
"auth",
"info"
] |
aa58eb0a018ad6318002b87a333b71d04373116a
|
https://github.com/pvijayror/rails_exception_logger/blob/aa58eb0a018ad6318002b87a333b71d04373116a/app/controllers/rails_exception_logger/logged_exceptions_controller.rb#L99-L103
|
8,897
|
marcboeker/mongolicious
|
lib/mongolicious/backup.rb
|
Mongolicious.Backup.parse_jobfile
|
def parse_jobfile(jobfile)
YAML.load(File.read(jobfile))
rescue Errno::ENOENT
Mongolicious.logger.error("Could not find job file at #{ARGV[0]}")
exit
rescue ArgumentError => e
Mongolicious.logger.error("Could not parse job file #{ARGV[0]} - #{e}")
exit
end
|
ruby
|
def parse_jobfile(jobfile)
YAML.load(File.read(jobfile))
rescue Errno::ENOENT
Mongolicious.logger.error("Could not find job file at #{ARGV[0]}")
exit
rescue ArgumentError => e
Mongolicious.logger.error("Could not parse job file #{ARGV[0]} - #{e}")
exit
end
|
[
"def",
"parse_jobfile",
"(",
"jobfile",
")",
"YAML",
".",
"load",
"(",
"File",
".",
"read",
"(",
"jobfile",
")",
")",
"rescue",
"Errno",
"::",
"ENOENT",
"Mongolicious",
".",
"logger",
".",
"error",
"(",
"\"Could not find job file at #{ARGV[0]}\"",
")",
"exit",
"rescue",
"ArgumentError",
"=>",
"e",
"Mongolicious",
".",
"logger",
".",
"error",
"(",
"\"Could not parse job file #{ARGV[0]} - #{e}\"",
")",
"exit",
"end"
] |
Parse YAML job configuration.
@param [String] jobfile the path of the job configuration file.
@return [Hash]
|
[
"Parse",
"YAML",
"job",
"configuration",
"."
] |
bc1553188df97d3df825de6d826b34ab7185a431
|
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/backup.rb#L26-L34
|
8,898
|
marcboeker/mongolicious
|
lib/mongolicious/backup.rb
|
Mongolicious.Backup.schedule_jobs
|
def schedule_jobs(jobs)
scheduler = Rufus::Scheduler.start_new
jobs.each do |job|
if job['cron']
Mongolicious.logger.info("Scheduled new job for #{job['db'].split('/').last} with cron: #{job['cron']}")
scheduler.cron job['cron'] do
backup(job)
end
else
scheduler.every job['interval'] do
Mongolicious.logger.info("Scheduled new job for #{job['db'].split('/').last} with interval: #{job['interval']}")
backup(job)
end
end
end
scheduler.join
end
|
ruby
|
def schedule_jobs(jobs)
scheduler = Rufus::Scheduler.start_new
jobs.each do |job|
if job['cron']
Mongolicious.logger.info("Scheduled new job for #{job['db'].split('/').last} with cron: #{job['cron']}")
scheduler.cron job['cron'] do
backup(job)
end
else
scheduler.every job['interval'] do
Mongolicious.logger.info("Scheduled new job for #{job['db'].split('/').last} with interval: #{job['interval']}")
backup(job)
end
end
end
scheduler.join
end
|
[
"def",
"schedule_jobs",
"(",
"jobs",
")",
"scheduler",
"=",
"Rufus",
"::",
"Scheduler",
".",
"start_new",
"jobs",
".",
"each",
"do",
"|",
"job",
"|",
"if",
"job",
"[",
"'cron'",
"]",
"Mongolicious",
".",
"logger",
".",
"info",
"(",
"\"Scheduled new job for #{job['db'].split('/').last} with cron: #{job['cron']}\"",
")",
"scheduler",
".",
"cron",
"job",
"[",
"'cron'",
"]",
"do",
"backup",
"(",
"job",
")",
"end",
"else",
"scheduler",
".",
"every",
"job",
"[",
"'interval'",
"]",
"do",
"Mongolicious",
".",
"logger",
".",
"info",
"(",
"\"Scheduled new job for #{job['db'].split('/').last} with interval: #{job['interval']}\"",
")",
"backup",
"(",
"job",
")",
"end",
"end",
"end",
"scheduler",
".",
"join",
"end"
] |
Schedule the jobs to be executed in the given interval.
This method will block and keep running until it gets interrupted.
@param [Array] jobs the list of jobs to be scheduled.
@return [nil]
|
[
"Schedule",
"the",
"jobs",
"to",
"be",
"executed",
"in",
"the",
"given",
"interval",
"."
] |
bc1553188df97d3df825de6d826b34ab7185a431
|
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/backup.rb#L43-L61
|
8,899
|
kamui/kanpachi
|
lib/kanpachi/resource_list.rb
|
Kanpachi.ResourceList.add
|
def add(resource)
if @list.key? resource.route
raise DuplicateResource, "A resource accessible via #{resource.http_verb} #{resource.url} already exists"
end
@list[resource.route] = resource
end
|
ruby
|
def add(resource)
if @list.key? resource.route
raise DuplicateResource, "A resource accessible via #{resource.http_verb} #{resource.url} already exists"
end
@list[resource.route] = resource
end
|
[
"def",
"add",
"(",
"resource",
")",
"if",
"@list",
".",
"key?",
"resource",
".",
"route",
"raise",
"DuplicateResource",
",",
"\"A resource accessible via #{resource.http_verb} #{resource.url} already exists\"",
"end",
"@list",
"[",
"resource",
".",
"route",
"]",
"=",
"resource",
"end"
] |
Add a resource to the list
@param [Kanpachi::Resource] The resource to add.
@return [Hash<Kanpachi::Resource>] All the added resources.
@raise DuplicateResource If a resource is being duplicated.
@api public
|
[
"Add",
"a",
"resource",
"to",
"the",
"list"
] |
dbd09646bd8779ab874e1578b57a13f5747b0da7
|
https://github.com/kamui/kanpachi/blob/dbd09646bd8779ab874e1578b57a13f5747b0da7/lib/kanpachi/resource_list.rb#L35-L40
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.