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
|
---|---|---|---|---|---|---|---|---|---|---|---|
21,600 |
zed-0xff/zpng
|
lib/zpng/image.rb
|
ZPNG.Image.save
|
def save fname, options={}
File.open(fname,"wb"){ |f| f << export(options) }
end
|
ruby
|
def save fname, options={}
File.open(fname,"wb"){ |f| f << export(options) }
end
|
[
"def",
"save",
"fname",
",",
"options",
"=",
"{",
"}",
"File",
".",
"open",
"(",
"fname",
",",
"\"wb\"",
")",
"{",
"|",
"f",
"|",
"f",
"<<",
"export",
"(",
"options",
")",
"}",
"end"
] |
save image to file
|
[
"save",
"image",
"to",
"file"
] |
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
|
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/image.rb#L80-L82
|
21,601 |
zed-0xff/zpng
|
lib/zpng/image.rb
|
ZPNG.Image._safe_inflate
|
def _safe_inflate data
zi = Zlib::Inflate.new
pos = 0; r = ''
begin
# save some memory by not using String#[] when not necessary
r << zi.inflate(pos==0 ? data : data[pos..-1])
if zi.total_in < data.size
@extradata << data[zi.total_in..-1]
puts "[?] #{@extradata.last.size} bytes of extra data after zlib stream".red if @verbose >= 1
end
# decompress OK
rescue Zlib::BufError
# tried to decompress, but got EOF - need more data
puts "[!] #{$!.inspect}".red if @verbose >= -1
# collect any remaining data in decompress buffer
r << zi.flush_next_out
rescue Zlib::DataError
puts "[!] #{$!.inspect}".red if @verbose >= -1
#p [pos, zi.total_in, zi.total_out, data.size, r.size]
r << zi.flush_next_out
# XXX TODO try to skip error and continue
# printf "[d] pos=%d/%d t_in=%d t_out=%d bytes_ok=%d\n".gray, pos, data.size,
# zi.total_in, zi.total_out, r.size
# if pos < zi.total_in
# pos = zi.total_in
# else
# pos += 1
# end
# pos = 0
# retry if pos < data.size
rescue Zlib::NeedDict
puts "[!] #{$!.inspect}".red if @verbose >= -1
# collect any remaining data in decompress buffer
r << zi.flush_next_out
end
r == "" ? nil : r
ensure
zi.close if zi && !zi.closed?
end
|
ruby
|
def _safe_inflate data
zi = Zlib::Inflate.new
pos = 0; r = ''
begin
# save some memory by not using String#[] when not necessary
r << zi.inflate(pos==0 ? data : data[pos..-1])
if zi.total_in < data.size
@extradata << data[zi.total_in..-1]
puts "[?] #{@extradata.last.size} bytes of extra data after zlib stream".red if @verbose >= 1
end
# decompress OK
rescue Zlib::BufError
# tried to decompress, but got EOF - need more data
puts "[!] #{$!.inspect}".red if @verbose >= -1
# collect any remaining data in decompress buffer
r << zi.flush_next_out
rescue Zlib::DataError
puts "[!] #{$!.inspect}".red if @verbose >= -1
#p [pos, zi.total_in, zi.total_out, data.size, r.size]
r << zi.flush_next_out
# XXX TODO try to skip error and continue
# printf "[d] pos=%d/%d t_in=%d t_out=%d bytes_ok=%d\n".gray, pos, data.size,
# zi.total_in, zi.total_out, r.size
# if pos < zi.total_in
# pos = zi.total_in
# else
# pos += 1
# end
# pos = 0
# retry if pos < data.size
rescue Zlib::NeedDict
puts "[!] #{$!.inspect}".red if @verbose >= -1
# collect any remaining data in decompress buffer
r << zi.flush_next_out
end
r == "" ? nil : r
ensure
zi.close if zi && !zi.closed?
end
|
[
"def",
"_safe_inflate",
"data",
"zi",
"=",
"Zlib",
"::",
"Inflate",
".",
"new",
"pos",
"=",
"0",
";",
"r",
"=",
"''",
"begin",
"# save some memory by not using String#[] when not necessary",
"r",
"<<",
"zi",
".",
"inflate",
"(",
"pos",
"==",
"0",
"?",
"data",
":",
"data",
"[",
"pos",
"..",
"-",
"1",
"]",
")",
"if",
"zi",
".",
"total_in",
"<",
"data",
".",
"size",
"@extradata",
"<<",
"data",
"[",
"zi",
".",
"total_in",
"..",
"-",
"1",
"]",
"puts",
"\"[?] #{@extradata.last.size} bytes of extra data after zlib stream\"",
".",
"red",
"if",
"@verbose",
">=",
"1",
"end",
"# decompress OK",
"rescue",
"Zlib",
"::",
"BufError",
"# tried to decompress, but got EOF - need more data",
"puts",
"\"[!] #{$!.inspect}\"",
".",
"red",
"if",
"@verbose",
">=",
"-",
"1",
"# collect any remaining data in decompress buffer",
"r",
"<<",
"zi",
".",
"flush_next_out",
"rescue",
"Zlib",
"::",
"DataError",
"puts",
"\"[!] #{$!.inspect}\"",
".",
"red",
"if",
"@verbose",
">=",
"-",
"1",
"#p [pos, zi.total_in, zi.total_out, data.size, r.size]",
"r",
"<<",
"zi",
".",
"flush_next_out",
"# XXX TODO try to skip error and continue",
"# printf \"[d] pos=%d/%d t_in=%d t_out=%d bytes_ok=%d\\n\".gray, pos, data.size,",
"# zi.total_in, zi.total_out, r.size",
"# if pos < zi.total_in",
"# pos = zi.total_in",
"# else",
"# pos += 1",
"# end",
"# pos = 0",
"# retry if pos < data.size",
"rescue",
"Zlib",
"::",
"NeedDict",
"puts",
"\"[!] #{$!.inspect}\"",
".",
"red",
"if",
"@verbose",
">=",
"-",
"1",
"# collect any remaining data in decompress buffer",
"r",
"<<",
"zi",
".",
"flush_next_out",
"end",
"r",
"==",
"\"\"",
"?",
"nil",
":",
"r",
"ensure",
"zi",
".",
"close",
"if",
"zi",
"&&",
"!",
"zi",
".",
"closed?",
"end"
] |
unpack zlib,
on errors keep going and try to return maximum possible data
|
[
"unpack",
"zlib",
"on",
"errors",
"keep",
"going",
"and",
"try",
"to",
"return",
"maximum",
"possible",
"data"
] |
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
|
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/image.rb#L245-L284
|
21,602 |
zed-0xff/zpng
|
lib/zpng/image.rb
|
ZPNG.Image.crop!
|
def crop! params
decode_all_scanlines
x,y,h,w = (params[:x]||0), (params[:y]||0), params[:height], params[:width]
raise ArgumentError, "negative params not allowed" if [x,y,h,w].any?{ |x| x < 0 }
# adjust crop sizes if they greater than image sizes
h = self.height-y if (y+h) > self.height
w = self.width-x if (x+w) > self.width
raise ArgumentError, "negative params not allowed (p2)" if [x,y,h,w].any?{ |x| x < 0 }
# delete excess scanlines at tail
scanlines[(y+h)..-1] = [] if (y+h) < scanlines.size
# delete excess scanlines at head
scanlines[0,y] = [] if y > 0
# crop remaining scanlines
scanlines.each{ |l| l.crop!(x,w) }
# modify header
hdr.height, hdr.width = h, w
# return self
self
end
|
ruby
|
def crop! params
decode_all_scanlines
x,y,h,w = (params[:x]||0), (params[:y]||0), params[:height], params[:width]
raise ArgumentError, "negative params not allowed" if [x,y,h,w].any?{ |x| x < 0 }
# adjust crop sizes if they greater than image sizes
h = self.height-y if (y+h) > self.height
w = self.width-x if (x+w) > self.width
raise ArgumentError, "negative params not allowed (p2)" if [x,y,h,w].any?{ |x| x < 0 }
# delete excess scanlines at tail
scanlines[(y+h)..-1] = [] if (y+h) < scanlines.size
# delete excess scanlines at head
scanlines[0,y] = [] if y > 0
# crop remaining scanlines
scanlines.each{ |l| l.crop!(x,w) }
# modify header
hdr.height, hdr.width = h, w
# return self
self
end
|
[
"def",
"crop!",
"params",
"decode_all_scanlines",
"x",
",",
"y",
",",
"h",
",",
"w",
"=",
"(",
"params",
"[",
":x",
"]",
"||",
"0",
")",
",",
"(",
"params",
"[",
":y",
"]",
"||",
"0",
")",
",",
"params",
"[",
":height",
"]",
",",
"params",
"[",
":width",
"]",
"raise",
"ArgumentError",
",",
"\"negative params not allowed\"",
"if",
"[",
"x",
",",
"y",
",",
"h",
",",
"w",
"]",
".",
"any?",
"{",
"|",
"x",
"|",
"x",
"<",
"0",
"}",
"# adjust crop sizes if they greater than image sizes",
"h",
"=",
"self",
".",
"height",
"-",
"y",
"if",
"(",
"y",
"+",
"h",
")",
">",
"self",
".",
"height",
"w",
"=",
"self",
".",
"width",
"-",
"x",
"if",
"(",
"x",
"+",
"w",
")",
">",
"self",
".",
"width",
"raise",
"ArgumentError",
",",
"\"negative params not allowed (p2)\"",
"if",
"[",
"x",
",",
"y",
",",
"h",
",",
"w",
"]",
".",
"any?",
"{",
"|",
"x",
"|",
"x",
"<",
"0",
"}",
"# delete excess scanlines at tail",
"scanlines",
"[",
"(",
"y",
"+",
"h",
")",
"..",
"-",
"1",
"]",
"=",
"[",
"]",
"if",
"(",
"y",
"+",
"h",
")",
"<",
"scanlines",
".",
"size",
"# delete excess scanlines at head",
"scanlines",
"[",
"0",
",",
"y",
"]",
"=",
"[",
"]",
"if",
"y",
">",
"0",
"# crop remaining scanlines",
"scanlines",
".",
"each",
"{",
"|",
"l",
"|",
"l",
".",
"crop!",
"(",
"x",
",",
"w",
")",
"}",
"# modify header",
"hdr",
".",
"height",
",",
"hdr",
".",
"width",
"=",
"h",
",",
"w",
"# return self",
"self",
"end"
] |
modifies this image
|
[
"modifies",
"this",
"image"
] |
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
|
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/image.rb#L430-L455
|
21,603 |
zed-0xff/zpng
|
lib/zpng/image.rb
|
ZPNG.Image.deinterlace
|
def deinterlace
return self unless interlaced?
# copy all but 'interlace' header params
h = Hash[*%w'width height depth color compression filter'.map{ |k| [k.to_sym, hdr.send(k)] }.flatten]
# don't auto-add palette chunk
h[:palette] = nil
# create new img
new_img = self.class.new h
# copy all but hdr/imagedata/end chunks
chunks.each do |chunk|
next if chunk.is_a?(Chunk::IHDR)
next if chunk.is_a?(Chunk::IDAT)
next if chunk.is_a?(Chunk::IEND)
new_img.chunks << chunk.deep_copy
end
# pixel-by-pixel copy
each_pixel do |c,x,y|
new_img[x,y] = c
end
new_img
end
|
ruby
|
def deinterlace
return self unless interlaced?
# copy all but 'interlace' header params
h = Hash[*%w'width height depth color compression filter'.map{ |k| [k.to_sym, hdr.send(k)] }.flatten]
# don't auto-add palette chunk
h[:palette] = nil
# create new img
new_img = self.class.new h
# copy all but hdr/imagedata/end chunks
chunks.each do |chunk|
next if chunk.is_a?(Chunk::IHDR)
next if chunk.is_a?(Chunk::IDAT)
next if chunk.is_a?(Chunk::IEND)
new_img.chunks << chunk.deep_copy
end
# pixel-by-pixel copy
each_pixel do |c,x,y|
new_img[x,y] = c
end
new_img
end
|
[
"def",
"deinterlace",
"return",
"self",
"unless",
"interlaced?",
"# copy all but 'interlace' header params",
"h",
"=",
"Hash",
"[",
"%w'",
"width",
"height",
"depth",
"color",
"compression",
"filter",
"'",
".",
"map",
"{",
"|",
"k",
"|",
"[",
"k",
".",
"to_sym",
",",
"hdr",
".",
"send",
"(",
"k",
")",
"]",
"}",
".",
"flatten",
"]",
"# don't auto-add palette chunk",
"h",
"[",
":palette",
"]",
"=",
"nil",
"# create new img",
"new_img",
"=",
"self",
".",
"class",
".",
"new",
"h",
"# copy all but hdr/imagedata/end chunks",
"chunks",
".",
"each",
"do",
"|",
"chunk",
"|",
"next",
"if",
"chunk",
".",
"is_a?",
"(",
"Chunk",
"::",
"IHDR",
")",
"next",
"if",
"chunk",
".",
"is_a?",
"(",
"Chunk",
"::",
"IDAT",
")",
"next",
"if",
"chunk",
".",
"is_a?",
"(",
"Chunk",
"::",
"IEND",
")",
"new_img",
".",
"chunks",
"<<",
"chunk",
".",
"deep_copy",
"end",
"# pixel-by-pixel copy",
"each_pixel",
"do",
"|",
"c",
",",
"x",
",",
"y",
"|",
"new_img",
"[",
"x",
",",
"y",
"]",
"=",
"c",
"end",
"new_img",
"end"
] |
returns new deinterlaced image if deinterlaced
OR returns self if no need to deinterlace
|
[
"returns",
"new",
"deinterlaced",
"image",
"if",
"deinterlaced",
"OR",
"returns",
"self",
"if",
"no",
"need",
"to",
"deinterlace"
] |
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
|
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/image.rb#L488-L514
|
21,604 |
zed-0xff/zpng
|
lib/zpng/color.rb
|
ZPNG.Color.to_ansi
|
def to_ansi
return to_depth(8).to_ansi if depth != 8
a = ANSI_COLORS.map{|c| self.class.const_get(c.to_s.upcase) }
a.map!{ |c| self.euclidian(c) }
ANSI_COLORS[a.index(a.min)]
end
|
ruby
|
def to_ansi
return to_depth(8).to_ansi if depth != 8
a = ANSI_COLORS.map{|c| self.class.const_get(c.to_s.upcase) }
a.map!{ |c| self.euclidian(c) }
ANSI_COLORS[a.index(a.min)]
end
|
[
"def",
"to_ansi",
"return",
"to_depth",
"(",
"8",
")",
".",
"to_ansi",
"if",
"depth",
"!=",
"8",
"a",
"=",
"ANSI_COLORS",
".",
"map",
"{",
"|",
"c",
"|",
"self",
".",
"class",
".",
"const_get",
"(",
"c",
".",
"to_s",
".",
"upcase",
")",
"}",
"a",
".",
"map!",
"{",
"|",
"c",
"|",
"self",
".",
"euclidian",
"(",
"c",
")",
"}",
"ANSI_COLORS",
"[",
"a",
".",
"index",
"(",
"a",
".",
"min",
")",
"]",
"end"
] |
convert to ANSI color name
|
[
"convert",
"to",
"ANSI",
"color",
"name"
] |
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
|
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/color.rb#L142-L147
|
21,605 |
zed-0xff/zpng
|
lib/zpng/color.rb
|
ZPNG.Color.to_depth
|
def to_depth new_depth
return self if depth == new_depth
color = Color.new :depth => new_depth
if new_depth > self.depth
%w'r g b a'.each do |part|
color.send("#{part}=", (2**new_depth-1)/(2**depth-1)*self.send(part))
end
else
# new_depth < self.depth
%w'r g b a'.each do |part|
color.send("#{part}=", self.send(part)>>(self.depth-new_depth))
end
end
color
end
|
ruby
|
def to_depth new_depth
return self if depth == new_depth
color = Color.new :depth => new_depth
if new_depth > self.depth
%w'r g b a'.each do |part|
color.send("#{part}=", (2**new_depth-1)/(2**depth-1)*self.send(part))
end
else
# new_depth < self.depth
%w'r g b a'.each do |part|
color.send("#{part}=", self.send(part)>>(self.depth-new_depth))
end
end
color
end
|
[
"def",
"to_depth",
"new_depth",
"return",
"self",
"if",
"depth",
"==",
"new_depth",
"color",
"=",
"Color",
".",
"new",
":depth",
"=>",
"new_depth",
"if",
"new_depth",
">",
"self",
".",
"depth",
"%w'",
"r",
"g",
"b",
"a",
"'",
".",
"each",
"do",
"|",
"part",
"|",
"color",
".",
"send",
"(",
"\"#{part}=\"",
",",
"(",
"2",
"**",
"new_depth",
"-",
"1",
")",
"/",
"(",
"2",
"**",
"depth",
"-",
"1",
")",
"*",
"self",
".",
"send",
"(",
"part",
")",
")",
"end",
"else",
"# new_depth < self.depth",
"%w'",
"r",
"g",
"b",
"a",
"'",
".",
"each",
"do",
"|",
"part",
"|",
"color",
".",
"send",
"(",
"\"#{part}=\"",
",",
"self",
".",
"send",
"(",
"part",
")",
">>",
"(",
"self",
".",
"depth",
"-",
"new_depth",
")",
")",
"end",
"end",
"color",
"end"
] |
change bit depth, return new Color
|
[
"change",
"bit",
"depth",
"return",
"new",
"Color"
] |
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
|
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/color.rb#L159-L174
|
21,606 |
zed-0xff/zpng
|
lib/zpng/color.rb
|
ZPNG.Color.op
|
def op op, c=nil
# XXX what to do with alpha?
max = 2**depth-1
if c
c = c.to_depth(depth)
Color.new(
@r.send(op, c.r) & max,
@g.send(op, c.g) & max,
@b.send(op, c.b) & max,
:depth => self.depth
)
else
Color.new(
@r.send(op) & max,
@g.send(op) & max,
@b.send(op) & max,
:depth => self.depth
)
end
end
|
ruby
|
def op op, c=nil
# XXX what to do with alpha?
max = 2**depth-1
if c
c = c.to_depth(depth)
Color.new(
@r.send(op, c.r) & max,
@g.send(op, c.g) & max,
@b.send(op, c.b) & max,
:depth => self.depth
)
else
Color.new(
@r.send(op) & max,
@g.send(op) & max,
@b.send(op) & max,
:depth => self.depth
)
end
end
|
[
"def",
"op",
"op",
",",
"c",
"=",
"nil",
"# XXX what to do with alpha?",
"max",
"=",
"2",
"**",
"depth",
"-",
"1",
"if",
"c",
"c",
"=",
"c",
".",
"to_depth",
"(",
"depth",
")",
"Color",
".",
"new",
"(",
"@r",
".",
"send",
"(",
"op",
",",
"c",
".",
"r",
")",
"&",
"max",
",",
"@g",
".",
"send",
"(",
"op",
",",
"c",
".",
"g",
")",
"&",
"max",
",",
"@b",
".",
"send",
"(",
"op",
",",
"c",
".",
"b",
")",
"&",
"max",
",",
":depth",
"=>",
"self",
".",
"depth",
")",
"else",
"Color",
".",
"new",
"(",
"@r",
".",
"send",
"(",
"op",
")",
"&",
"max",
",",
"@g",
".",
"send",
"(",
"op",
")",
"&",
"max",
",",
"@b",
".",
"send",
"(",
"op",
")",
"&",
"max",
",",
":depth",
"=>",
"self",
".",
"depth",
")",
"end",
"end"
] |
Op! op! op! Op!! Oppan Gangnam Style!!
|
[
"Op!",
"op!",
"op!",
"Op!!",
"Oppan",
"Gangnam",
"Style!!"
] |
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
|
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/color.rb#L245-L264
|
21,607 |
socrata/soda-ruby
|
lib/soda/client.rb
|
SODA.Client.handle_response
|
def handle_response(response)
# Check our response code
check_response_fail(response)
return nil if blank?(response.body)
# Return a bunch of mashes as the body if we're JSON
begin
response.body = JSON.parse(response.body, max_nesting: false)
response.body = if response.body.is_a? Array
response.body.map { |r| Hashie::Mash.new(r) }
else
Hashie::Mash.new(response.body)
end
rescue => exception
raise "JSON parsing failed. Error details: #{exception}"
ensure
return response
end
end
|
ruby
|
def handle_response(response)
# Check our response code
check_response_fail(response)
return nil if blank?(response.body)
# Return a bunch of mashes as the body if we're JSON
begin
response.body = JSON.parse(response.body, max_nesting: false)
response.body = if response.body.is_a? Array
response.body.map { |r| Hashie::Mash.new(r) }
else
Hashie::Mash.new(response.body)
end
rescue => exception
raise "JSON parsing failed. Error details: #{exception}"
ensure
return response
end
end
|
[
"def",
"handle_response",
"(",
"response",
")",
"# Check our response code",
"check_response_fail",
"(",
"response",
")",
"return",
"nil",
"if",
"blank?",
"(",
"response",
".",
"body",
")",
"# Return a bunch of mashes as the body if we're JSON",
"begin",
"response",
".",
"body",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
",",
"max_nesting",
":",
"false",
")",
"response",
".",
"body",
"=",
"if",
"response",
".",
"body",
".",
"is_a?",
"Array",
"response",
".",
"body",
".",
"map",
"{",
"|",
"r",
"|",
"Hashie",
"::",
"Mash",
".",
"new",
"(",
"r",
")",
"}",
"else",
"Hashie",
"::",
"Mash",
".",
"new",
"(",
"response",
".",
"body",
")",
"end",
"rescue",
"=>",
"exception",
"raise",
"\"JSON parsing failed. Error details: #{exception}\"",
"ensure",
"return",
"response",
"end",
"end"
] |
Returns a response with a parsed body
|
[
"Returns",
"a",
"response",
"with",
"a",
"parsed",
"body"
] |
7d3174b78fc6723ed30561a30e682d14bf6d62af
|
https://github.com/socrata/soda-ruby/blob/7d3174b78fc6723ed30561a30e682d14bf6d62af/lib/soda/client.rb#L186-L204
|
21,608 |
jpablobr/active_paypal_adaptive_payment
|
lib/active_merchant/billing/gateways/paypal_adaptive_payments/ext.rb
|
Hashie.Rash.underscore_string
|
def underscore_string(str)
str.to_s.strip.
gsub(' ', '_').
gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
squeeze("_").
downcase
end
|
ruby
|
def underscore_string(str)
str.to_s.strip.
gsub(' ', '_').
gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
squeeze("_").
downcase
end
|
[
"def",
"underscore_string",
"(",
"str",
")",
"str",
".",
"to_s",
".",
"strip",
".",
"gsub",
"(",
"' '",
",",
"'_'",
")",
".",
"gsub",
"(",
"/",
"/",
",",
"'/'",
")",
".",
"gsub",
"(",
"/",
"/",
",",
"'\\1_\\2'",
")",
".",
"gsub",
"(",
"/",
"\\d",
"/",
",",
"'\\1_\\2'",
")",
".",
"tr",
"(",
"\"-\"",
",",
"\"_\"",
")",
".",
"squeeze",
"(",
"\"_\"",
")",
".",
"downcase",
"end"
] |
converts a camel_cased string to a underscore string
subs spaces with underscores, strips whitespace
Same way ActiveSupport does string.underscore
|
[
"converts",
"a",
"camel_cased",
"string",
"to",
"a",
"underscore",
"string",
"subs",
"spaces",
"with",
"underscores",
"strips",
"whitespace",
"Same",
"way",
"ActiveSupport",
"does",
"string",
".",
"underscore"
] |
e2b215fda00d9430c4b2433c592718b128da92e6
|
https://github.com/jpablobr/active_paypal_adaptive_payment/blob/e2b215fda00d9430c4b2433c592718b128da92e6/lib/active_merchant/billing/gateways/paypal_adaptive_payments/ext.rb#L18-L27
|
21,609 |
hexdigest/ruby-nfc
|
lib/ruby-nfc/reader.rb
|
NFC.Reader.discover
|
def discover(*card_types)
# TODO: по правильному здесь надо делать низкоуровневый
card_types.inject([]) do |tags, card_type|
raise NFC::Error.new('Wrong card type') unless card_type.respond_to? :discover
tags += card_type.discover(connect)
end
end
|
ruby
|
def discover(*card_types)
# TODO: по правильному здесь надо делать низкоуровневый
card_types.inject([]) do |tags, card_type|
raise NFC::Error.new('Wrong card type') unless card_type.respond_to? :discover
tags += card_type.discover(connect)
end
end
|
[
"def",
"discover",
"(",
"*",
"card_types",
")",
"# TODO: по правильному здесь надо делать низкоуровневый",
"card_types",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"tags",
",",
"card_type",
"|",
"raise",
"NFC",
"::",
"Error",
".",
"new",
"(",
"'Wrong card type'",
")",
"unless",
"card_type",
".",
"respond_to?",
":discover",
"tags",
"+=",
"card_type",
".",
"discover",
"(",
"connect",
")",
"end",
"end"
] |
Returns list of tags applied to reader
|
[
"Returns",
"list",
"of",
"tags",
"applied",
"to",
"reader"
] |
fa53d263ae37d565a41a0fbb238601b85bd53a59
|
https://github.com/hexdigest/ruby-nfc/blob/fa53d263ae37d565a41a0fbb238601b85bd53a59/lib/ruby-nfc/reader.rb#L21-L27
|
21,610 |
ncgr/quorum
|
app/controllers/quorum/jobs_controller.rb
|
Quorum.JobsController.search
|
def search
data = Job.search(params)
# Respond with :json, :txt (tab delimited Blast results), or GFF3.
respond_with data.flatten!(1) do |format|
format.json {
render :json => Quorum::JobSerializer.as_json(data)
}
format.gff {
render :text => Quorum::JobSerializer.as_gff(data)
}
format.txt {
render :text => Quorum::JobSerializer.as_txt(data)
}
end
end
|
ruby
|
def search
data = Job.search(params)
# Respond with :json, :txt (tab delimited Blast results), or GFF3.
respond_with data.flatten!(1) do |format|
format.json {
render :json => Quorum::JobSerializer.as_json(data)
}
format.gff {
render :text => Quorum::JobSerializer.as_gff(data)
}
format.txt {
render :text => Quorum::JobSerializer.as_txt(data)
}
end
end
|
[
"def",
"search",
"data",
"=",
"Job",
".",
"search",
"(",
"params",
")",
"# Respond with :json, :txt (tab delimited Blast results), or GFF3.",
"respond_with",
"data",
".",
"flatten!",
"(",
"1",
")",
"do",
"|",
"format",
"|",
"format",
".",
"json",
"{",
"render",
":json",
"=>",
"Quorum",
"::",
"JobSerializer",
".",
"as_json",
"(",
"data",
")",
"}",
"format",
".",
"gff",
"{",
"render",
":text",
"=>",
"Quorum",
"::",
"JobSerializer",
".",
"as_gff",
"(",
"data",
")",
"}",
"format",
".",
"txt",
"{",
"render",
":text",
"=>",
"Quorum",
"::",
"JobSerializer",
".",
"as_txt",
"(",
"data",
")",
"}",
"end",
"end"
] |
Returns Quorum's search results.
This method should be used to gather Resque worker results, or user
supplied query params.
|
[
"Returns",
"Quorum",
"s",
"search",
"results",
"."
] |
0309cbdf38aab64ff4c002dec34e01fd10e0c823
|
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/app/controllers/quorum/jobs_controller.rb#L43-L58
|
21,611 |
ncgr/quorum
|
app/controllers/quorum/jobs_controller.rb
|
Quorum.JobsController.build_blast_jobs
|
def build_blast_jobs
@job ||= Job.new
@job.build_blastn_job if @job.blastn_job.nil?
@job.build_blastx_job if @job.blastx_job.nil?
@job.build_tblastn_job if @job.tblastn_job.nil?
@job.build_blastp_job if @job.blastp_job.nil?
end
|
ruby
|
def build_blast_jobs
@job ||= Job.new
@job.build_blastn_job if @job.blastn_job.nil?
@job.build_blastx_job if @job.blastx_job.nil?
@job.build_tblastn_job if @job.tblastn_job.nil?
@job.build_blastp_job if @job.blastp_job.nil?
end
|
[
"def",
"build_blast_jobs",
"@job",
"||=",
"Job",
".",
"new",
"@job",
".",
"build_blastn_job",
"if",
"@job",
".",
"blastn_job",
".",
"nil?",
"@job",
".",
"build_blastx_job",
"if",
"@job",
".",
"blastx_job",
".",
"nil?",
"@job",
".",
"build_tblastn_job",
"if",
"@job",
".",
"tblastn_job",
".",
"nil?",
"@job",
".",
"build_blastp_job",
"if",
"@job",
".",
"blastp_job",
".",
"nil?",
"end"
] |
Create new Job and build associations.
|
[
"Create",
"new",
"Job",
"and",
"build",
"associations",
"."
] |
0309cbdf38aab64ff4c002dec34e01fd10e0c823
|
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/app/controllers/quorum/jobs_controller.rb#L86-L92
|
21,612 |
ncgr/quorum
|
lib/tasks/blastdb/build_blast_db.rb
|
Quorum.BuildBlastDB.create_file_name
|
def create_file_name(file, base_dir)
file_name = file.split("/").delete_if { |f| f.include?(".") }.first
unless File.exists?(File.join(base_dir, file_name))
Dir.mkdir(File.join(base_dir, file_name))
end
file_name
end
|
ruby
|
def create_file_name(file, base_dir)
file_name = file.split("/").delete_if { |f| f.include?(".") }.first
unless File.exists?(File.join(base_dir, file_name))
Dir.mkdir(File.join(base_dir, file_name))
end
file_name
end
|
[
"def",
"create_file_name",
"(",
"file",
",",
"base_dir",
")",
"file_name",
"=",
"file",
".",
"split",
"(",
"\"/\"",
")",
".",
"delete_if",
"{",
"|",
"f",
"|",
"f",
".",
"include?",
"(",
"\".\"",
")",
"}",
".",
"first",
"unless",
"File",
".",
"exists?",
"(",
"File",
".",
"join",
"(",
"base_dir",
",",
"file_name",
")",
")",
"Dir",
".",
"mkdir",
"(",
"File",
".",
"join",
"(",
"base_dir",
",",
"file_name",
")",
")",
"end",
"file_name",
"end"
] |
Create directories per tarball and return tarball file name
minus the file extension.
|
[
"Create",
"directories",
"per",
"tarball",
"and",
"return",
"tarball",
"file",
"name",
"minus",
"the",
"file",
"extension",
"."
] |
0309cbdf38aab64ff4c002dec34e01fd10e0c823
|
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/tasks/blastdb/build_blast_db.rb#L69-L75
|
21,613 |
ncgr/quorum
|
lib/tasks/blastdb/build_blast_db.rb
|
Quorum.BuildBlastDB.extract_files
|
def extract_files(src, file, flag, path)
extract_data_error = File.join(@log_dir, "extract_data_error.log")
cmd = "tar -x#{flag}Of #{src} #{file} >> #{path} 2>> " <<
"#{extract_data_error}"
system(cmd)
if $?.exitstatus > 0
raise "Data extraction error. " <<
"See #{extract_data_error} for details."
end
end
|
ruby
|
def extract_files(src, file, flag, path)
extract_data_error = File.join(@log_dir, "extract_data_error.log")
cmd = "tar -x#{flag}Of #{src} #{file} >> #{path} 2>> " <<
"#{extract_data_error}"
system(cmd)
if $?.exitstatus > 0
raise "Data extraction error. " <<
"See #{extract_data_error} for details."
end
end
|
[
"def",
"extract_files",
"(",
"src",
",",
"file",
",",
"flag",
",",
"path",
")",
"extract_data_error",
"=",
"File",
".",
"join",
"(",
"@log_dir",
",",
"\"extract_data_error.log\"",
")",
"cmd",
"=",
"\"tar -x#{flag}Of #{src} #{file} >> #{path} 2>> \"",
"<<",
"\"#{extract_data_error}\"",
"system",
"(",
"cmd",
")",
"if",
"$?",
".",
"exitstatus",
">",
"0",
"raise",
"\"Data extraction error. \"",
"<<",
"\"See #{extract_data_error} for details.\"",
"end",
"end"
] |
Extracts and concatenates files from tarballs.
|
[
"Extracts",
"and",
"concatenates",
"files",
"from",
"tarballs",
"."
] |
0309cbdf38aab64ff4c002dec34e01fd10e0c823
|
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/tasks/blastdb/build_blast_db.rb#L80-L90
|
21,614 |
ncgr/quorum
|
lib/tasks/blastdb/build_blast_db.rb
|
Quorum.BuildBlastDB.execute_makeblastdb
|
def execute_makeblastdb(type, title, input)
@output.puts "Executing makeblastdb for #{title} dbtype #{type}..."
makeblast_log = File.join(@log_dir, "makeblastdb.log")
output = File.dirname(input)
cmd = "makeblastdb " <<
"-dbtype #{type} " <<
"-title #{title} " <<
"-in #{input} " <<
"-out #{output} " <<
"-hash_index >> #{makeblast_log}"
system(cmd)
if $?.exitstatus > 0
raise "makeblastdb error. " <<
"See #{makeblast_log} for details."
end
end
|
ruby
|
def execute_makeblastdb(type, title, input)
@output.puts "Executing makeblastdb for #{title} dbtype #{type}..."
makeblast_log = File.join(@log_dir, "makeblastdb.log")
output = File.dirname(input)
cmd = "makeblastdb " <<
"-dbtype #{type} " <<
"-title #{title} " <<
"-in #{input} " <<
"-out #{output} " <<
"-hash_index >> #{makeblast_log}"
system(cmd)
if $?.exitstatus > 0
raise "makeblastdb error. " <<
"See #{makeblast_log} for details."
end
end
|
[
"def",
"execute_makeblastdb",
"(",
"type",
",",
"title",
",",
"input",
")",
"@output",
".",
"puts",
"\"Executing makeblastdb for #{title} dbtype #{type}...\"",
"makeblast_log",
"=",
"File",
".",
"join",
"(",
"@log_dir",
",",
"\"makeblastdb.log\"",
")",
"output",
"=",
"File",
".",
"dirname",
"(",
"input",
")",
"cmd",
"=",
"\"makeblastdb \"",
"<<",
"\"-dbtype #{type} \"",
"<<",
"\"-title #{title} \"",
"<<",
"\"-in #{input} \"",
"<<",
"\"-out #{output} \"",
"<<",
"\"-hash_index >> #{makeblast_log}\"",
"system",
"(",
"cmd",
")",
"if",
"$?",
".",
"exitstatus",
">",
"0",
"raise",
"\"makeblastdb error. \"",
"<<",
"\"See #{makeblast_log} for details.\"",
"end",
"end"
] |
Execute makeblastdb on an extracted dataset.
|
[
"Execute",
"makeblastdb",
"on",
"an",
"extracted",
"dataset",
"."
] |
0309cbdf38aab64ff4c002dec34e01fd10e0c823
|
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/tasks/blastdb/build_blast_db.rb#L95-L112
|
21,615 |
ncgr/quorum
|
lib/tasks/blastdb/build_blast_db.rb
|
Quorum.BuildBlastDB.build_blast_db
|
def build_blast_db(blastdb)
Dir.glob(File.expand_path(blastdb) + "/*").each do |d|
if File.directory?(d)
contigs = File.join(d, "contigs.fa")
peptides = File.join(d, "peptides.fa")
found = false
if File.exists?(contigs) && File.readable?(contigs)
execute_makeblastdb("nucl", d, contigs)
found = true
end
if File.exists?(peptides) && File.readable?(peptides)
execute_makeblastdb("prot", d, peptides)
found = true
end
unless found
raise "Extracted data not found for #{contigs} or #{peptides}. " <<
"Make sure you supplied the correct data directory and file names."
end
end
end
end
|
ruby
|
def build_blast_db(blastdb)
Dir.glob(File.expand_path(blastdb) + "/*").each do |d|
if File.directory?(d)
contigs = File.join(d, "contigs.fa")
peptides = File.join(d, "peptides.fa")
found = false
if File.exists?(contigs) && File.readable?(contigs)
execute_makeblastdb("nucl", d, contigs)
found = true
end
if File.exists?(peptides) && File.readable?(peptides)
execute_makeblastdb("prot", d, peptides)
found = true
end
unless found
raise "Extracted data not found for #{contigs} or #{peptides}. " <<
"Make sure you supplied the correct data directory and file names."
end
end
end
end
|
[
"def",
"build_blast_db",
"(",
"blastdb",
")",
"Dir",
".",
"glob",
"(",
"File",
".",
"expand_path",
"(",
"blastdb",
")",
"+",
"\"/*\"",
")",
".",
"each",
"do",
"|",
"d",
"|",
"if",
"File",
".",
"directory?",
"(",
"d",
")",
"contigs",
"=",
"File",
".",
"join",
"(",
"d",
",",
"\"contigs.fa\"",
")",
"peptides",
"=",
"File",
".",
"join",
"(",
"d",
",",
"\"peptides.fa\"",
")",
"found",
"=",
"false",
"if",
"File",
".",
"exists?",
"(",
"contigs",
")",
"&&",
"File",
".",
"readable?",
"(",
"contigs",
")",
"execute_makeblastdb",
"(",
"\"nucl\"",
",",
"d",
",",
"contigs",
")",
"found",
"=",
"true",
"end",
"if",
"File",
".",
"exists?",
"(",
"peptides",
")",
"&&",
"File",
".",
"readable?",
"(",
"peptides",
")",
"execute_makeblastdb",
"(",
"\"prot\"",
",",
"d",
",",
"peptides",
")",
"found",
"=",
"true",
"end",
"unless",
"found",
"raise",
"\"Extracted data not found for #{contigs} or #{peptides}. \"",
"<<",
"\"Make sure you supplied the correct data directory and file names.\"",
"end",
"end",
"end",
"end"
] |
Builds a Blast database from parse_blast_db_data.
|
[
"Builds",
"a",
"Blast",
"database",
"from",
"parse_blast_db_data",
"."
] |
0309cbdf38aab64ff4c002dec34e01fd10e0c823
|
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/tasks/blastdb/build_blast_db.rb#L117-L140
|
21,616 |
ncgr/quorum
|
lib/generators/templates/logger.rb
|
Quorum.Logger.log
|
def log(program, message, exit_status = nil, files = nil)
File.open(File.join(@log_directory, @log_file), "a") do |log|
log.puts ""
log.puts Time.now.to_s + " " + program
log.puts message
log.puts ""
end
if exit_status
remove_files(files) unless files.nil?
exit exit_status.to_i
end
end
|
ruby
|
def log(program, message, exit_status = nil, files = nil)
File.open(File.join(@log_directory, @log_file), "a") do |log|
log.puts ""
log.puts Time.now.to_s + " " + program
log.puts message
log.puts ""
end
if exit_status
remove_files(files) unless files.nil?
exit exit_status.to_i
end
end
|
[
"def",
"log",
"(",
"program",
",",
"message",
",",
"exit_status",
"=",
"nil",
",",
"files",
"=",
"nil",
")",
"File",
".",
"open",
"(",
"File",
".",
"join",
"(",
"@log_directory",
",",
"@log_file",
")",
",",
"\"a\"",
")",
"do",
"|",
"log",
"|",
"log",
".",
"puts",
"\"\"",
"log",
".",
"puts",
"Time",
".",
"now",
".",
"to_s",
"+",
"\" \"",
"+",
"program",
"log",
".",
"puts",
"message",
"log",
".",
"puts",
"\"\"",
"end",
"if",
"exit_status",
"remove_files",
"(",
"files",
")",
"unless",
"files",
".",
"nil?",
"exit",
"exit_status",
".",
"to_i",
"end",
"end"
] |
Write to log file and exit if exit_status is present.
|
[
"Write",
"to",
"log",
"file",
"and",
"exit",
"if",
"exit_status",
"is",
"present",
"."
] |
0309cbdf38aab64ff4c002dec34e01fd10e0c823
|
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/generators/templates/logger.rb#L12-L24
|
21,617 |
ncgr/quorum
|
app/models/quorum/job.rb
|
Quorum.Job.algorithm_selected
|
def algorithm_selected
in_queue = false
if (self.blastn_job && self.blastn_job.queue) ||
(self.blastx_job && self.blastx_job.queue) ||
(self.tblastn_job && self.tblastn_job.queue) ||
(self.blastp_job && self.blastp_job.queue)
in_queue = true
end
unless in_queue
errors.add(
:algorithm,
" - Please select at least one algorithm to continue."
)
end
end
|
ruby
|
def algorithm_selected
in_queue = false
if (self.blastn_job && self.blastn_job.queue) ||
(self.blastx_job && self.blastx_job.queue) ||
(self.tblastn_job && self.tblastn_job.queue) ||
(self.blastp_job && self.blastp_job.queue)
in_queue = true
end
unless in_queue
errors.add(
:algorithm,
" - Please select at least one algorithm to continue."
)
end
end
|
[
"def",
"algorithm_selected",
"in_queue",
"=",
"false",
"if",
"(",
"self",
".",
"blastn_job",
"&&",
"self",
".",
"blastn_job",
".",
"queue",
")",
"||",
"(",
"self",
".",
"blastx_job",
"&&",
"self",
".",
"blastx_job",
".",
"queue",
")",
"||",
"(",
"self",
".",
"tblastn_job",
"&&",
"self",
".",
"tblastn_job",
".",
"queue",
")",
"||",
"(",
"self",
".",
"blastp_job",
"&&",
"self",
".",
"blastp_job",
".",
"queue",
")",
"in_queue",
"=",
"true",
"end",
"unless",
"in_queue",
"errors",
".",
"add",
"(",
":algorithm",
",",
"\" - Please select at least one algorithm to continue.\"",
")",
"end",
"end"
] |
Make sure an algorithm is selected.
|
[
"Make",
"sure",
"an",
"algorithm",
"is",
"selected",
"."
] |
0309cbdf38aab64ff4c002dec34e01fd10e0c823
|
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/app/models/quorum/job.rb#L173-L187
|
21,618 |
pivotal-legacy/saucelabs-adapter
|
lib/saucelabs_adapter/utilities.rb
|
SaucelabsAdapter.Utilities.start_mongrel
|
def start_mongrel(suite_name = {})
pid_file = File.join(RAILS_ROOT, "tmp", "pids", "mongrel_selenium.pid")
port = suite_name[:port] rescue @selenium_config.application_port
say "Starting mongrel at #{pid_file}, port #{port}"
system "mongrel_rails start -d --chdir='#{RAILS_ROOT}' --port=#{port} --environment=test --pid #{pid_file} %"
end
|
ruby
|
def start_mongrel(suite_name = {})
pid_file = File.join(RAILS_ROOT, "tmp", "pids", "mongrel_selenium.pid")
port = suite_name[:port] rescue @selenium_config.application_port
say "Starting mongrel at #{pid_file}, port #{port}"
system "mongrel_rails start -d --chdir='#{RAILS_ROOT}' --port=#{port} --environment=test --pid #{pid_file} %"
end
|
[
"def",
"start_mongrel",
"(",
"suite_name",
"=",
"{",
"}",
")",
"pid_file",
"=",
"File",
".",
"join",
"(",
"RAILS_ROOT",
",",
"\"tmp\"",
",",
"\"pids\"",
",",
"\"mongrel_selenium.pid\"",
")",
"port",
"=",
"suite_name",
"[",
":port",
"]",
"rescue",
"@selenium_config",
".",
"application_port",
"say",
"\"Starting mongrel at #{pid_file}, port #{port}\"",
"system",
"\"mongrel_rails start -d --chdir='#{RAILS_ROOT}' --port=#{port} --environment=test --pid #{pid_file} %\"",
"end"
] |
parameters required when invoked by test_unit
|
[
"parameters",
"required",
"when",
"invoked",
"by",
"test_unit"
] |
b9b66094aba315af164f9d57e3743534006cec9f
|
https://github.com/pivotal-legacy/saucelabs-adapter/blob/b9b66094aba315af164f9d57e3743534006cec9f/lib/saucelabs_adapter/utilities.rb#L39-L44
|
21,619 |
ncgr/quorum
|
lib/quorum/sequence.rb
|
Quorum.Sequence.create_hash
|
def create_hash(sequence)
Digest::MD5.hexdigest(sequence).to_s + "-" + Time.now.to_f.to_s
end
|
ruby
|
def create_hash(sequence)
Digest::MD5.hexdigest(sequence).to_s + "-" + Time.now.to_f.to_s
end
|
[
"def",
"create_hash",
"(",
"sequence",
")",
"Digest",
"::",
"MD5",
".",
"hexdigest",
"(",
"sequence",
")",
".",
"to_s",
"+",
"\"-\"",
"+",
"Time",
".",
"now",
".",
"to_f",
".",
"to_s",
"end"
] |
Create a unique hash plus timestamp.
|
[
"Create",
"a",
"unique",
"hash",
"plus",
"timestamp",
"."
] |
0309cbdf38aab64ff4c002dec34e01fd10e0c823
|
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/quorum/sequence.rb#L7-L9
|
21,620 |
ncgr/quorum
|
lib/quorum/sequence.rb
|
Quorum.Sequence.write_input_sequence_to_file
|
def write_input_sequence_to_file(tmp_dir, hash, sequence)
seq = File.join(tmp_dir, hash + ".seq")
File.open(seq, "w") do |f|
f << sequence
end
fasta = File.join(tmp_dir, hash + ".fa")
# Force FASTA format.
cmd = "seqret -filter -sformat pearson -osformat fasta < #{seq} " <<
"> #{fasta} 2> /dev/null"
system(cmd)
if $?.exitstatus > 0
raise " - Please enter your sequence(s) in Plain Text as " <<
"FASTA."
end
end
|
ruby
|
def write_input_sequence_to_file(tmp_dir, hash, sequence)
seq = File.join(tmp_dir, hash + ".seq")
File.open(seq, "w") do |f|
f << sequence
end
fasta = File.join(tmp_dir, hash + ".fa")
# Force FASTA format.
cmd = "seqret -filter -sformat pearson -osformat fasta < #{seq} " <<
"> #{fasta} 2> /dev/null"
system(cmd)
if $?.exitstatus > 0
raise " - Please enter your sequence(s) in Plain Text as " <<
"FASTA."
end
end
|
[
"def",
"write_input_sequence_to_file",
"(",
"tmp_dir",
",",
"hash",
",",
"sequence",
")",
"seq",
"=",
"File",
".",
"join",
"(",
"tmp_dir",
",",
"hash",
"+",
"\".seq\"",
")",
"File",
".",
"open",
"(",
"seq",
",",
"\"w\"",
")",
"do",
"|",
"f",
"|",
"f",
"<<",
"sequence",
"end",
"fasta",
"=",
"File",
".",
"join",
"(",
"tmp_dir",
",",
"hash",
"+",
"\".fa\"",
")",
"# Force FASTA format.",
"cmd",
"=",
"\"seqret -filter -sformat pearson -osformat fasta < #{seq} \"",
"<<",
"\"> #{fasta} 2> /dev/null\"",
"system",
"(",
"cmd",
")",
"if",
"$?",
".",
"exitstatus",
">",
"0",
"raise",
"\" - Please enter your sequence(s) in Plain Text as \"",
"<<",
"\"FASTA.\"",
"end",
"end"
] |
Write input sequence to file. Pass the raw input data through seqret
to ensure FASTA format.
|
[
"Write",
"input",
"sequence",
"to",
"file",
".",
"Pass",
"the",
"raw",
"input",
"data",
"through",
"seqret",
"to",
"ensure",
"FASTA",
"format",
"."
] |
0309cbdf38aab64ff4c002dec34e01fd10e0c823
|
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/quorum/sequence.rb#L15-L31
|
21,621 |
ncgr/quorum
|
lib/quorum/helpers.rb
|
Quorum.Helpers.set_flash_message
|
def set_flash_message(key, kind, options = {})
options[:scope] = "quorum.#{controller_name}"
options[:scope] << ".errors" if key.to_s == "error"
options[:scope] << ".notices" if key.to_s == "notice"
options[:scope] << ".alerts" if key.to_s == "alert"
message = I18n.t("#{kind}", options)
flash[key] = message if message.present?
end
|
ruby
|
def set_flash_message(key, kind, options = {})
options[:scope] = "quorum.#{controller_name}"
options[:scope] << ".errors" if key.to_s == "error"
options[:scope] << ".notices" if key.to_s == "notice"
options[:scope] << ".alerts" if key.to_s == "alert"
message = I18n.t("#{kind}", options)
flash[key] = message if message.present?
end
|
[
"def",
"set_flash_message",
"(",
"key",
",",
"kind",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":scope",
"]",
"=",
"\"quorum.#{controller_name}\"",
"options",
"[",
":scope",
"]",
"<<",
"\".errors\"",
"if",
"key",
".",
"to_s",
"==",
"\"error\"",
"options",
"[",
":scope",
"]",
"<<",
"\".notices\"",
"if",
"key",
".",
"to_s",
"==",
"\"notice\"",
"options",
"[",
":scope",
"]",
"<<",
"\".alerts\"",
"if",
"key",
".",
"to_s",
"==",
"\"alert\"",
"message",
"=",
"I18n",
".",
"t",
"(",
"\"#{kind}\"",
",",
"options",
")",
"flash",
"[",
"key",
"]",
"=",
"message",
"if",
"message",
".",
"present?",
"end"
] |
I18n flash helper. Set flash message based on key.
|
[
"I18n",
"flash",
"helper",
".",
"Set",
"flash",
"message",
"based",
"on",
"key",
"."
] |
0309cbdf38aab64ff4c002dec34e01fd10e0c823
|
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/quorum/helpers.rb#L7-L14
|
21,622 |
ncgr/quorum
|
app/models/quorum/blastx_job.rb
|
Quorum.BlastxJob.gap_opening_extension=
|
def gap_opening_extension=(value)
v = value.split(',')
self.gap_opening_penalty = v.first
self.gap_extension_penalty = v.last
end
|
ruby
|
def gap_opening_extension=(value)
v = value.split(',')
self.gap_opening_penalty = v.first
self.gap_extension_penalty = v.last
end
|
[
"def",
"gap_opening_extension",
"=",
"(",
"value",
")",
"v",
"=",
"value",
".",
"split",
"(",
"','",
")",
"self",
".",
"gap_opening_penalty",
"=",
"v",
".",
"first",
"self",
".",
"gap_extension_penalty",
"=",
"v",
".",
"last",
"end"
] |
Virtual attribute setter.
|
[
"Virtual",
"attribute",
"setter",
"."
] |
0309cbdf38aab64ff4c002dec34e01fd10e0c823
|
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/app/models/quorum/blastx_job.rb#L75-L79
|
21,623 |
zokioki/fitbit_api
|
lib/fitbit_api/helpers/utils.rb
|
FitbitAPI.Client.deep_transform_keys!
|
def deep_transform_keys!(object, &block)
case object
when Hash
object.keys.each do |key|
value = object.delete(key)
object[yield(key)] = deep_transform_keys!(value) { |key| yield(key) }
end
object
when Array
object.map! { |e| deep_transform_keys!(e) { |key| yield(key) } }
else
object
end
end
|
ruby
|
def deep_transform_keys!(object, &block)
case object
when Hash
object.keys.each do |key|
value = object.delete(key)
object[yield(key)] = deep_transform_keys!(value) { |key| yield(key) }
end
object
when Array
object.map! { |e| deep_transform_keys!(e) { |key| yield(key) } }
else
object
end
end
|
[
"def",
"deep_transform_keys!",
"(",
"object",
",",
"&",
"block",
")",
"case",
"object",
"when",
"Hash",
"object",
".",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"value",
"=",
"object",
".",
"delete",
"(",
"key",
")",
"object",
"[",
"yield",
"(",
"key",
")",
"]",
"=",
"deep_transform_keys!",
"(",
"value",
")",
"{",
"|",
"key",
"|",
"yield",
"(",
"key",
")",
"}",
"end",
"object",
"when",
"Array",
"object",
".",
"map!",
"{",
"|",
"e",
"|",
"deep_transform_keys!",
"(",
"e",
")",
"{",
"|",
"key",
"|",
"yield",
"(",
"key",
")",
"}",
"}",
"else",
"object",
"end",
"end"
] |
Inspired by ActiveSupport's implementation
|
[
"Inspired",
"by",
"ActiveSupport",
"s",
"implementation"
] |
13c8cf99fbab2327e3429d590a71ccfc4b633045
|
https://github.com/zokioki/fitbit_api/blob/13c8cf99fbab2327e3429d590a71ccfc4b633045/lib/fitbit_api/helpers/utils.rb#L51-L64
|
21,624 |
crate/crate_ruby
|
lib/crate_ruby/client.rb
|
CrateRuby.Client.execute
|
def execute(sql, args = nil, bulk_args = nil, http_options = {})
@logger.debug sql
req = Net::HTTP::Post.new('/_sql', headers)
body = { 'stmt' => sql }
body['args'] = args if args
body['bulk_args'] = bulk_args if bulk_args
req.body = body.to_json
response = request(req, http_options)
@logger.debug response.body
case response.code
when /^2\d{2}/
ResultSet.new response.body
else
@logger.info(response.body)
raise CrateRuby::CrateError, response.body
end
end
|
ruby
|
def execute(sql, args = nil, bulk_args = nil, http_options = {})
@logger.debug sql
req = Net::HTTP::Post.new('/_sql', headers)
body = { 'stmt' => sql }
body['args'] = args if args
body['bulk_args'] = bulk_args if bulk_args
req.body = body.to_json
response = request(req, http_options)
@logger.debug response.body
case response.code
when /^2\d{2}/
ResultSet.new response.body
else
@logger.info(response.body)
raise CrateRuby::CrateError, response.body
end
end
|
[
"def",
"execute",
"(",
"sql",
",",
"args",
"=",
"nil",
",",
"bulk_args",
"=",
"nil",
",",
"http_options",
"=",
"{",
"}",
")",
"@logger",
".",
"debug",
"sql",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"'/_sql'",
",",
"headers",
")",
"body",
"=",
"{",
"'stmt'",
"=>",
"sql",
"}",
"body",
"[",
"'args'",
"]",
"=",
"args",
"if",
"args",
"body",
"[",
"'bulk_args'",
"]",
"=",
"bulk_args",
"if",
"bulk_args",
"req",
".",
"body",
"=",
"body",
".",
"to_json",
"response",
"=",
"request",
"(",
"req",
",",
"http_options",
")",
"@logger",
".",
"debug",
"response",
".",
"body",
"case",
"response",
".",
"code",
"when",
"/",
"\\d",
"/",
"ResultSet",
".",
"new",
"response",
".",
"body",
"else",
"@logger",
".",
"info",
"(",
"response",
".",
"body",
")",
"raise",
"CrateRuby",
"::",
"CrateError",
",",
"response",
".",
"body",
"end",
"end"
] |
Executes a SQL statement against the Crate HTTP REST endpoint.
@param [String] sql statement to execute
@param [Array] args Array of values used for parameter substitution
@param [Array] bulk_args List of lists containing records to be processed
@param [Hash] http_options Net::HTTP options (open_timeout, read_timeout)
@return [ResultSet]
|
[
"Executes",
"a",
"SQL",
"statement",
"against",
"the",
"Crate",
"HTTP",
"REST",
"endpoint",
"."
] |
64015c0ad2ae7914329f8107eae6b689e45a48af
|
https://github.com/crate/crate_ruby/blob/64015c0ad2ae7914329f8107eae6b689e45a48af/lib/crate_ruby/client.rb#L115-L132
|
21,625 |
crate/crate_ruby
|
lib/crate_ruby/client.rb
|
CrateRuby.Client.blob_put
|
def blob_put(table, digest, data)
uri = blob_path(table, digest)
@logger.debug("BLOB PUT #{uri}")
req = Net::HTTP::Put.new(blob_path(table, digest), headers)
req.body = data
response = request(req)
case response.code
when '201'
true
else
@logger.info("Response #{response.code}: " + response.body)
false
end
end
|
ruby
|
def blob_put(table, digest, data)
uri = blob_path(table, digest)
@logger.debug("BLOB PUT #{uri}")
req = Net::HTTP::Put.new(blob_path(table, digest), headers)
req.body = data
response = request(req)
case response.code
when '201'
true
else
@logger.info("Response #{response.code}: " + response.body)
false
end
end
|
[
"def",
"blob_put",
"(",
"table",
",",
"digest",
",",
"data",
")",
"uri",
"=",
"blob_path",
"(",
"table",
",",
"digest",
")",
"@logger",
".",
"debug",
"(",
"\"BLOB PUT #{uri}\"",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Put",
".",
"new",
"(",
"blob_path",
"(",
"table",
",",
"digest",
")",
",",
"headers",
")",
"req",
".",
"body",
"=",
"data",
"response",
"=",
"request",
"(",
"req",
")",
"case",
"response",
".",
"code",
"when",
"'201'",
"true",
"else",
"@logger",
".",
"info",
"(",
"\"Response #{response.code}: \"",
"+",
"response",
".",
"body",
")",
"false",
"end",
"end"
] |
Upload a File to a blob table
@param [String] table
@param [String] digest SHA1 hexdigest
@param [Boolean] data Can be any payload object that can be sent via HTTP, e.g. STRING, FILE
|
[
"Upload",
"a",
"File",
"to",
"a",
"blob",
"table"
] |
64015c0ad2ae7914329f8107eae6b689e45a48af
|
https://github.com/crate/crate_ruby/blob/64015c0ad2ae7914329f8107eae6b689e45a48af/lib/crate_ruby/client.rb#L138-L151
|
21,626 |
dazzl-tv/ruby-rabbitmq-janus
|
lib/rrj/admin.rb
|
RubyRabbitmqJanus.RRJAdmin.start_transaction_admin
|
def start_transaction_admin(options = {})
transaction = Janus::Transactions::Admin.new(options)
transaction.connect { yield(transaction) }
rescue
raise Errors::RRJAdmin::StartTransactionAdmin, options
end
|
ruby
|
def start_transaction_admin(options = {})
transaction = Janus::Transactions::Admin.new(options)
transaction.connect { yield(transaction) }
rescue
raise Errors::RRJAdmin::StartTransactionAdmin, options
end
|
[
"def",
"start_transaction_admin",
"(",
"options",
"=",
"{",
"}",
")",
"transaction",
"=",
"Janus",
"::",
"Transactions",
"::",
"Admin",
".",
"new",
"(",
"options",
")",
"transaction",
".",
"connect",
"{",
"yield",
"(",
"transaction",
")",
"}",
"rescue",
"raise",
"Errors",
"::",
"RRJAdmin",
"::",
"StartTransactionAdmin",
",",
"options",
"end"
] |
Create a transaction between apps and Janus for request without handle
@param [Hash] options
Give a session number for use another session in Janus
@example Get Janus session
@rrj.start_transaction_admin do |transaction|
response = transaction.publish_message('admin:sessions').sessions
end
@since 2.0.0
|
[
"Create",
"a",
"transaction",
"between",
"apps",
"and",
"Janus",
"for",
"request",
"without",
"handle"
] |
680fca9260b10191ca8dfbcac83d315dce895206
|
https://github.com/dazzl-tv/ruby-rabbitmq-janus/blob/680fca9260b10191ca8dfbcac83d315dce895206/lib/rrj/admin.rb#L28-L33
|
21,627 |
wycats/rake-pipeline-web-filters
|
lib/rake-pipeline-web-filters/coffee_script_filter.rb
|
Rake::Pipeline::Web::Filters.CoffeeScriptFilter.generate_output
|
def generate_output(inputs, output)
inputs.each do |input|
begin
output.write CoffeeScript.compile(input, options)
rescue ExecJS::Error => error
raise error, "Error compiling #{input.path}. #{error.message}"
end
end
end
|
ruby
|
def generate_output(inputs, output)
inputs.each do |input|
begin
output.write CoffeeScript.compile(input, options)
rescue ExecJS::Error => error
raise error, "Error compiling #{input.path}. #{error.message}"
end
end
end
|
[
"def",
"generate_output",
"(",
"inputs",
",",
"output",
")",
"inputs",
".",
"each",
"do",
"|",
"input",
"|",
"begin",
"output",
".",
"write",
"CoffeeScript",
".",
"compile",
"(",
"input",
",",
"options",
")",
"rescue",
"ExecJS",
"::",
"Error",
"=>",
"error",
"raise",
"error",
",",
"\"Error compiling #{input.path}. #{error.message}\"",
"end",
"end",
"end"
] |
By default, the CoffeeScriptFilter converts inputs
with the extension +.coffee+ to +.js+.
@param [Hash] options options to pass to the CoffeeScript
compiler.
@param [Proc] block the output name generator block
The body of the filter. Compile each input file into
a CoffeeScript compiled output file.
@param [Array] inputs an Array of FileWrapper objects.
@param [FileWrapper] output a FileWrapper object
|
[
"By",
"default",
"the",
"CoffeeScriptFilter",
"converts",
"inputs",
"with",
"the",
"extension",
"+",
".",
"coffee",
"+",
"to",
"+",
".",
"js",
"+",
"."
] |
7bd283aac83d7c46a8908f089033a6087d7cd68f
|
https://github.com/wycats/rake-pipeline-web-filters/blob/7bd283aac83d7c46a8908f089033a6087d7cd68f/lib/rake-pipeline-web-filters/coffee_script_filter.rb#L27-L35
|
21,628 |
dazzl-tv/ruby-rabbitmq-janus
|
lib/rrj/init.rb
|
RubyRabbitmqJanus.RRJ.start_transaction
|
def start_transaction(exclusive = true, options = {})
session = @option.use_current_session?(options)
transaction = Janus::Transactions::Session.new(exclusive, session)
transaction.connect { yield(transaction) }
rescue
raise Errors::RRJ::StartTransaction.new(exclusive, options)
end
|
ruby
|
def start_transaction(exclusive = true, options = {})
session = @option.use_current_session?(options)
transaction = Janus::Transactions::Session.new(exclusive, session)
transaction.connect { yield(transaction) }
rescue
raise Errors::RRJ::StartTransaction.new(exclusive, options)
end
|
[
"def",
"start_transaction",
"(",
"exclusive",
"=",
"true",
",",
"options",
"=",
"{",
"}",
")",
"session",
"=",
"@option",
".",
"use_current_session?",
"(",
"options",
")",
"transaction",
"=",
"Janus",
"::",
"Transactions",
"::",
"Session",
".",
"new",
"(",
"exclusive",
",",
"session",
")",
"transaction",
".",
"connect",
"{",
"yield",
"(",
"transaction",
")",
"}",
"rescue",
"raise",
"Errors",
"::",
"RRJ",
"::",
"StartTransaction",
".",
"new",
"(",
"exclusive",
",",
"options",
")",
"end"
] |
Return a new instance of RubyRabbitmqJanus.
@example Create a instance to this gem
@rrj = RubyRabbitmqJanus::RRJ.new
=> #<RubyRabbitmqJanus::RRJ:0x007 @session=123>
Start a transaction with Janus. Request use session_id information.
@param [Boolean] exclusive Choose if message is storage in exclusive queue
@param [Hash] options
Give a session number for use another session in Janus
@example Get Janus information
@rrj.start_transaction do |transaction|
response = transaction.publish_message('base::info').to_hash
end
@since 2.0.0
|
[
"Return",
"a",
"new",
"instance",
"of",
"RubyRabbitmqJanus",
"."
] |
680fca9260b10191ca8dfbcac83d315dce895206
|
https://github.com/dazzl-tv/ruby-rabbitmq-janus/blob/680fca9260b10191ca8dfbcac83d315dce895206/lib/rrj/init.rb#L58-L64
|
21,629 |
wycats/rake-pipeline-web-filters
|
lib/rake-pipeline-web-filters/es6_module_filter.rb
|
Rake::Pipeline::Web::Filters.ES6ModuleFilter.generate_output
|
def generate_output(inputs, output)
inputs.each do |input|
begin
body = input.read if input.respond_to?(:read)
local_opts = {}
if @module_id_generator
local_opts[:moduleName] = @module_id_generator.call(input)
end
opts = @options.merge(local_opts)
opts.delete(:module_id_generator)
output.write RubyES6ModuleTranspiler.transpile(body, opts)
rescue ExecJS::Error => error
raise error, "Error compiling #{input.path}. #{error.message}"
end
end
end
|
ruby
|
def generate_output(inputs, output)
inputs.each do |input|
begin
body = input.read if input.respond_to?(:read)
local_opts = {}
if @module_id_generator
local_opts[:moduleName] = @module_id_generator.call(input)
end
opts = @options.merge(local_opts)
opts.delete(:module_id_generator)
output.write RubyES6ModuleTranspiler.transpile(body, opts)
rescue ExecJS::Error => error
raise error, "Error compiling #{input.path}. #{error.message}"
end
end
end
|
[
"def",
"generate_output",
"(",
"inputs",
",",
"output",
")",
"inputs",
".",
"each",
"do",
"|",
"input",
"|",
"begin",
"body",
"=",
"input",
".",
"read",
"if",
"input",
".",
"respond_to?",
"(",
":read",
")",
"local_opts",
"=",
"{",
"}",
"if",
"@module_id_generator",
"local_opts",
"[",
":moduleName",
"]",
"=",
"@module_id_generator",
".",
"call",
"(",
"input",
")",
"end",
"opts",
"=",
"@options",
".",
"merge",
"(",
"local_opts",
")",
"opts",
".",
"delete",
"(",
":module_id_generator",
")",
"output",
".",
"write",
"RubyES6ModuleTranspiler",
".",
"transpile",
"(",
"body",
",",
"opts",
")",
"rescue",
"ExecJS",
"::",
"Error",
"=>",
"error",
"raise",
"error",
",",
"\"Error compiling #{input.path}. #{error.message}\"",
"end",
"end",
"end"
] |
Create an instance of this filter.
Possible options:
module_id_generator: provide a Proc to convert an input to a
module identifier (AMD only)
Other options are passed along to the RubyES6ModuleTranspiler and then to
the node transpiler. See https://github.com/square/es6-module-transpiler
for more info.
@param [Hash] options options (see above)
@param [Proc] block the output name generator block
The body of the filter. Compile each input file into
a ES6 Module Transpiled output file.
@param [Array] inputs an Array of FileWrapper objects.
@param [FileWrapper] output a FileWrapper object
|
[
"Create",
"an",
"instance",
"of",
"this",
"filter",
"."
] |
7bd283aac83d7c46a8908f089033a6087d7cd68f
|
https://github.com/wycats/rake-pipeline-web-filters/blob/7bd283aac83d7c46a8908f089033a6087d7cd68f/lib/rake-pipeline-web-filters/es6_module_filter.rb#L31-L46
|
21,630 |
dazzl-tv/ruby-rabbitmq-janus
|
lib/rrj/task.rb
|
RubyRabbitmqJanus.RRJTask.start_transaction_handle
|
def start_transaction_handle(exclusive = true, options = {})
janus = session_instance(options)
handle = 0 # Create always a new handle
transaction = Janus::Transactions::Handle.new(exclusive,
janus.session,
handle,
janus.instance)
transaction.connect { yield(transaction) }
rescue
raise Errors::RRJTask::StartTransactionHandle.new(exclusive, options)
end
|
ruby
|
def start_transaction_handle(exclusive = true, options = {})
janus = session_instance(options)
handle = 0 # Create always a new handle
transaction = Janus::Transactions::Handle.new(exclusive,
janus.session,
handle,
janus.instance)
transaction.connect { yield(transaction) }
rescue
raise Errors::RRJTask::StartTransactionHandle.new(exclusive, options)
end
|
[
"def",
"start_transaction_handle",
"(",
"exclusive",
"=",
"true",
",",
"options",
"=",
"{",
"}",
")",
"janus",
"=",
"session_instance",
"(",
"options",
")",
"handle",
"=",
"0",
"# Create always a new handle",
"transaction",
"=",
"Janus",
"::",
"Transactions",
"::",
"Handle",
".",
"new",
"(",
"exclusive",
",",
"janus",
".",
"session",
",",
"handle",
",",
"janus",
".",
"instance",
")",
"transaction",
".",
"connect",
"{",
"yield",
"(",
"transaction",
")",
"}",
"rescue",
"raise",
"Errors",
"::",
"RRJTask",
"::",
"StartTransactionHandle",
".",
"new",
"(",
"exclusive",
",",
"options",
")",
"end"
] |
Create a transaction between apps and janus with a handle
@since 2.1.0
|
[
"Create",
"a",
"transaction",
"between",
"apps",
"and",
"janus",
"with",
"a",
"handle"
] |
680fca9260b10191ca8dfbcac83d315dce895206
|
https://github.com/dazzl-tv/ruby-rabbitmq-janus/blob/680fca9260b10191ca8dfbcac83d315dce895206/lib/rrj/task.rb#L42-L52
|
21,631 |
dazzl-tv/ruby-rabbitmq-janus
|
lib/generators/ruby_rabbitmq_janus/templates/actions.rb
|
RubyRabbitmqJanus.ActionEvents.actions
|
def actions
lambda do |reason, data|
Rails.logger.debug "Execute block code with reason : #{reason}"
case reason
when event then case_events(data.to_hash)
end
end
end
|
ruby
|
def actions
lambda do |reason, data|
Rails.logger.debug "Execute block code with reason : #{reason}"
case reason
when event then case_events(data.to_hash)
end
end
end
|
[
"def",
"actions",
"lambda",
"do",
"|",
"reason",
",",
"data",
"|",
"Rails",
".",
"logger",
".",
"debug",
"\"Execute block code with reason : #{reason}\"",
"case",
"reason",
"when",
"event",
"then",
"case_events",
"(",
"data",
".",
"to_hash",
")",
"end",
"end",
"end"
] |
Default method using for sending a block of code
|
[
"Default",
"method",
"using",
"for",
"sending",
"a",
"block",
"of",
"code"
] |
680fca9260b10191ca8dfbcac83d315dce895206
|
https://github.com/dazzl-tv/ruby-rabbitmq-janus/blob/680fca9260b10191ca8dfbcac83d315dce895206/lib/generators/ruby_rabbitmq_janus/templates/actions.rb#L7-L14
|
21,632 |
wvk/railsdav
|
lib/railsdav/renderer.rb
|
Railsdav.Renderer.response
|
def response(options = {})
elements = options.slice(:error)
render do
response_for options[:href] do |dav|
elements.each do |name, value|
status_for options[:status]
dav.__send__ name, value
end
end
end
end
|
ruby
|
def response(options = {})
elements = options.slice(:error)
render do
response_for options[:href] do |dav|
elements.each do |name, value|
status_for options[:status]
dav.__send__ name, value
end
end
end
end
|
[
"def",
"response",
"(",
"options",
"=",
"{",
"}",
")",
"elements",
"=",
"options",
".",
"slice",
"(",
":error",
")",
"render",
"do",
"response_for",
"options",
"[",
":href",
"]",
"do",
"|",
"dav",
"|",
"elements",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"status_for",
"options",
"[",
":status",
"]",
"dav",
".",
"__send__",
"name",
",",
"value",
"end",
"end",
"end",
"end"
] |
Render a WebDAV multistatus response with a single "response" element.
This is primarily intended vor responding to single resource errors.
Arguments:
options:
- href: the requested resource URL, usually request.url
- status: the response status, something like :unprocessable_entity or 204.
- error: an Error description, if any.
|
[
"Render",
"a",
"WebDAV",
"multistatus",
"response",
"with",
"a",
"single",
"response",
"element",
".",
"This",
"is",
"primarily",
"intended",
"vor",
"responding",
"to",
"single",
"resource",
"errors",
"."
] |
2a51bf43a726175eaa93bdfe7ba2bed0248d3d87
|
https://github.com/wvk/railsdav/blob/2a51bf43a726175eaa93bdfe7ba2bed0248d3d87/lib/railsdav/renderer.rb#L86-L97
|
21,633 |
simplelogica/nocms-blocks
|
app/models/no_cms/blocks/block.rb
|
NoCms::Blocks.Block.duplicate_self
|
def duplicate_self new_self
new_self.translations = translations.map(&:dup)
new_self.translations.each { |t| t.globalized_model = new_self }
children.each do |child|
new_self.children << child.dup
end
end
|
ruby
|
def duplicate_self new_self
new_self.translations = translations.map(&:dup)
new_self.translations.each { |t| t.globalized_model = new_self }
children.each do |child|
new_self.children << child.dup
end
end
|
[
"def",
"duplicate_self",
"new_self",
"new_self",
".",
"translations",
"=",
"translations",
".",
"map",
"(",
":dup",
")",
"new_self",
".",
"translations",
".",
"each",
"{",
"|",
"t",
"|",
"t",
".",
"globalized_model",
"=",
"new_self",
"}",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"new_self",
".",
"children",
"<<",
"child",
".",
"dup",
"end",
"end"
] |
A block dups all it's children and the translations
|
[
"A",
"block",
"dups",
"all",
"it",
"s",
"children",
"and",
"the",
"translations"
] |
30c69ce0ce0867244604ea59e8252f761d6b508e
|
https://github.com/simplelogica/nocms-blocks/blob/30c69ce0ce0867244604ea59e8252f761d6b508e/app/models/no_cms/blocks/block.rb#L25-L33
|
21,634 |
tuskenraiders/degu
|
lib/degu/has_set.rb
|
Degu.HasSet.has_set_coerce_argument_value
|
def has_set_coerce_argument_value(enum_class, argument_value)
invalid_set_elements = []
set_elements =
if String === argument_value
argument_value.split(',').map(&:strip)
else
Array(argument_value)
end.map do |set_element|
if result = enum_class[set_element]
result
else
invalid_set_elements << set_element
nil
end
end
invalid_set_elements.empty? or
raise ArgumentError, "element #{argument_value.inspect} contains invalid elements: #{invalid_set_elements.inspect}"
set_elements
end
|
ruby
|
def has_set_coerce_argument_value(enum_class, argument_value)
invalid_set_elements = []
set_elements =
if String === argument_value
argument_value.split(',').map(&:strip)
else
Array(argument_value)
end.map do |set_element|
if result = enum_class[set_element]
result
else
invalid_set_elements << set_element
nil
end
end
invalid_set_elements.empty? or
raise ArgumentError, "element #{argument_value.inspect} contains invalid elements: #{invalid_set_elements.inspect}"
set_elements
end
|
[
"def",
"has_set_coerce_argument_value",
"(",
"enum_class",
",",
"argument_value",
")",
"invalid_set_elements",
"=",
"[",
"]",
"set_elements",
"=",
"if",
"String",
"===",
"argument_value",
"argument_value",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
":strip",
")",
"else",
"Array",
"(",
"argument_value",
")",
"end",
".",
"map",
"do",
"|",
"set_element",
"|",
"if",
"result",
"=",
"enum_class",
"[",
"set_element",
"]",
"result",
"else",
"invalid_set_elements",
"<<",
"set_element",
"nil",
"end",
"end",
"invalid_set_elements",
".",
"empty?",
"or",
"raise",
"ArgumentError",
",",
"\"element #{argument_value.inspect} contains invalid elements: #{invalid_set_elements.inspect}\"",
"set_elements",
"end"
] |
Understands the arguments as the list of enum values
The argument value can be
- a `string` of enum values joined by a comma
- an enum constant
- a `symbol` which resolves to the enum constant
- an `integer` as the index of the enum class
If you have just 1 value, you do not need to enclose it in an `Array`
|
[
"Understands",
"the",
"arguments",
"as",
"the",
"list",
"of",
"enum",
"values",
"The",
"argument",
"value",
"can",
"be",
"-",
"a",
"string",
"of",
"enum",
"values",
"joined",
"by",
"a",
"comma",
"-",
"an",
"enum",
"constant",
"-",
"a",
"symbol",
"which",
"resolves",
"to",
"the",
"enum",
"constant",
"-",
"an",
"integer",
"as",
"the",
"index",
"of",
"the",
"enum",
"class",
"If",
"you",
"have",
"just",
"1",
"value",
"you",
"do",
"not",
"need",
"to",
"enclose",
"it",
"in",
"an",
"Array"
] |
b968b5d3c7a995a0650faad32a2d89a394c11364
|
https://github.com/tuskenraiders/degu/blob/b968b5d3c7a995a0650faad32a2d89a394c11364/lib/degu/has_set.rb#L111-L129
|
21,635 |
crystalcommerce/hijacker
|
lib/hijacker/redis_keys.rb
|
Hijacker.RedisKeys.unresponsive_dbhost_count
|
def unresponsive_dbhost_count(db_host)
begin
count = $hijacker_redis.hget( redis_keys(:unresponsive_dbhosts), db_host) unless db_host.nil?
(count or 0).to_i
rescue
0
end
end
|
ruby
|
def unresponsive_dbhost_count(db_host)
begin
count = $hijacker_redis.hget( redis_keys(:unresponsive_dbhosts), db_host) unless db_host.nil?
(count or 0).to_i
rescue
0
end
end
|
[
"def",
"unresponsive_dbhost_count",
"(",
"db_host",
")",
"begin",
"count",
"=",
"$hijacker_redis",
".",
"hget",
"(",
"redis_keys",
"(",
":unresponsive_dbhosts",
")",
",",
"db_host",
")",
"unless",
"db_host",
".",
"nil?",
"(",
"count",
"or",
"0",
")",
".",
"to_i",
"rescue",
"0",
"end",
"end"
] |
Get the current count for the number of times requests were not able to
connect to a given database host
|
[
"Get",
"the",
"current",
"count",
"for",
"the",
"number",
"of",
"times",
"requests",
"were",
"not",
"able",
"to",
"connect",
"to",
"a",
"given",
"database",
"host"
] |
71bb89ff3c1d1bf7517958989ae1fdf529721a6c
|
https://github.com/crystalcommerce/hijacker/blob/71bb89ff3c1d1bf7517958989ae1fdf529721a6c/lib/hijacker/redis_keys.rb#L83-L90
|
21,636 |
blahah/datastructures
|
lib/datastructures/linked_list.rb
|
DataStructures.LinkedList.to_a
|
def to_a
current = @first
array = []
while !current.nil?
array << current.data
current = current.next
end
array
end
|
ruby
|
def to_a
current = @first
array = []
while !current.nil?
array << current.data
current = current.next
end
array
end
|
[
"def",
"to_a",
"current",
"=",
"@first",
"array",
"=",
"[",
"]",
"while",
"!",
"current",
".",
"nil?",
"array",
"<<",
"current",
".",
"data",
"current",
"=",
"current",
".",
"next",
"end",
"array",
"end"
] |
Returns an array containing the data from the nodes in the list
|
[
"Returns",
"an",
"array",
"containing",
"the",
"data",
"from",
"the",
"nodes",
"in",
"the",
"list"
] |
09bcca77118320278f4772ddce53081c446eb7c1
|
https://github.com/blahah/datastructures/blob/09bcca77118320278f4772ddce53081c446eb7c1/lib/datastructures/linked_list.rb#L160-L168
|
21,637 |
osulp/triplestore-adapter
|
lib/triplestore_adapter/providers/blazegraph.rb
|
TriplestoreAdapter::Providers.Blazegraph.delete
|
def delete(statements)
raise(TriplestoreAdapter::TriplestoreException, "delete received invalid array of statements") unless statements.any?
#TODO: Evaluate that all statements are singular, and without bnodes?
writer = RDF::Writer.for(:jsonld)
uri = URI.parse("#{@uri}?delete")
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/ld+json'
request.body = writer.dump(statements)
@http.request(uri, request)
return true
end
|
ruby
|
def delete(statements)
raise(TriplestoreAdapter::TriplestoreException, "delete received invalid array of statements") unless statements.any?
#TODO: Evaluate that all statements are singular, and without bnodes?
writer = RDF::Writer.for(:jsonld)
uri = URI.parse("#{@uri}?delete")
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/ld+json'
request.body = writer.dump(statements)
@http.request(uri, request)
return true
end
|
[
"def",
"delete",
"(",
"statements",
")",
"raise",
"(",
"TriplestoreAdapter",
"::",
"TriplestoreException",
",",
"\"delete received invalid array of statements\"",
")",
"unless",
"statements",
".",
"any?",
"#TODO: Evaluate that all statements are singular, and without bnodes?",
"writer",
"=",
"RDF",
"::",
"Writer",
".",
"for",
"(",
":jsonld",
")",
"uri",
"=",
"URI",
".",
"parse",
"(",
"\"#{@uri}?delete\"",
")",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
")",
"request",
"[",
"'Content-Type'",
"]",
"=",
"'application/ld+json'",
"request",
".",
"body",
"=",
"writer",
".",
"dump",
"(",
"statements",
")",
"@http",
".",
"request",
"(",
"uri",
",",
"request",
")",
"return",
"true",
"end"
] |
Delete the provided statements from the triplestore
@param [RDF::Enumerable] statements to delete from the triplestore
@return [Boolean] true if the delete was successful
|
[
"Delete",
"the",
"provided",
"statements",
"from",
"the",
"triplestore"
] |
597fa5842f846e57cba7574da873f1412ab76ffa
|
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/providers/blazegraph.rb#L39-L50
|
21,638 |
osulp/triplestore-adapter
|
lib/triplestore_adapter/providers/blazegraph.rb
|
TriplestoreAdapter::Providers.Blazegraph.get_statements
|
def get_statements(subject: nil)
raise(TriplestoreAdapter::TriplestoreException, "get_statements received blank subject") if subject.empty?
subject = URI.escape(subject.to_s)
uri = URI.parse(format("%{uri}?GETSTMTS&s=<%{subject}>&includeInferred=false", {uri: @uri, subject: subject}))
request = Net::HTTP::Get.new(uri)
response = @http.request(uri, request)
RDF::Reader.for(:ntriples).new(response.body)
end
|
ruby
|
def get_statements(subject: nil)
raise(TriplestoreAdapter::TriplestoreException, "get_statements received blank subject") if subject.empty?
subject = URI.escape(subject.to_s)
uri = URI.parse(format("%{uri}?GETSTMTS&s=<%{subject}>&includeInferred=false", {uri: @uri, subject: subject}))
request = Net::HTTP::Get.new(uri)
response = @http.request(uri, request)
RDF::Reader.for(:ntriples).new(response.body)
end
|
[
"def",
"get_statements",
"(",
"subject",
":",
"nil",
")",
"raise",
"(",
"TriplestoreAdapter",
"::",
"TriplestoreException",
",",
"\"get_statements received blank subject\"",
")",
"if",
"subject",
".",
"empty?",
"subject",
"=",
"URI",
".",
"escape",
"(",
"subject",
".",
"to_s",
")",
"uri",
"=",
"URI",
".",
"parse",
"(",
"format",
"(",
"\"%{uri}?GETSTMTS&s=<%{subject}>&includeInferred=false\"",
",",
"{",
"uri",
":",
"@uri",
",",
"subject",
":",
"subject",
"}",
")",
")",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
")",
"response",
"=",
"@http",
".",
"request",
"(",
"uri",
",",
"request",
")",
"RDF",
"::",
"Reader",
".",
"for",
"(",
":ntriples",
")",
".",
"new",
"(",
"response",
".",
"body",
")",
"end"
] |
Returns statements matching the subject
@param [String] subject url
@return [RDF::Enumerable] RDF statements
|
[
"Returns",
"statements",
"matching",
"the",
"subject"
] |
597fa5842f846e57cba7574da873f1412ab76ffa
|
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/providers/blazegraph.rb#L56-L63
|
21,639 |
osulp/triplestore-adapter
|
lib/triplestore_adapter/providers/blazegraph.rb
|
TriplestoreAdapter::Providers.Blazegraph.build_namespace
|
def build_namespace(namespace)
raise(TriplestoreAdapter::TriplestoreException, "build_namespace received blank namespace") if namespace.empty?
request = Net::HTTP::Post.new("#{build_url}/blazegraph/namespace")
request['Content-Type'] = 'text/plain'
request.body = "com.bigdata.rdf.sail.namespace=#{namespace}"
@http.request(@uri, request)
"#{build_url}/blazegraph/namespace/#{namespace}/sparql"
end
|
ruby
|
def build_namespace(namespace)
raise(TriplestoreAdapter::TriplestoreException, "build_namespace received blank namespace") if namespace.empty?
request = Net::HTTP::Post.new("#{build_url}/blazegraph/namespace")
request['Content-Type'] = 'text/plain'
request.body = "com.bigdata.rdf.sail.namespace=#{namespace}"
@http.request(@uri, request)
"#{build_url}/blazegraph/namespace/#{namespace}/sparql"
end
|
[
"def",
"build_namespace",
"(",
"namespace",
")",
"raise",
"(",
"TriplestoreAdapter",
"::",
"TriplestoreException",
",",
"\"build_namespace received blank namespace\"",
")",
"if",
"namespace",
".",
"empty?",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"\"#{build_url}/blazegraph/namespace\"",
")",
"request",
"[",
"'Content-Type'",
"]",
"=",
"'text/plain'",
"request",
".",
"body",
"=",
"\"com.bigdata.rdf.sail.namespace=#{namespace}\"",
"@http",
".",
"request",
"(",
"@uri",
",",
"request",
")",
"\"#{build_url}/blazegraph/namespace/#{namespace}/sparql\"",
"end"
] |
Create a new namespace on the triplestore
@param [String] namespace to be built
@return [String] URI for the new namespace
|
[
"Create",
"a",
"new",
"namespace",
"on",
"the",
"triplestore"
] |
597fa5842f846e57cba7574da873f1412ab76ffa
|
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/providers/blazegraph.rb#L79-L86
|
21,640 |
osulp/triplestore-adapter
|
lib/triplestore_adapter/triplestore.rb
|
TriplestoreAdapter.Triplestore.store
|
def store(graph)
begin
statements = graph.each_statement.to_a
@client.insert(statements)
graph
rescue => e
raise TriplestoreAdapter::TriplestoreException, "store graph in triplestore cache failed with exception: #{e.message}"
end
end
|
ruby
|
def store(graph)
begin
statements = graph.each_statement.to_a
@client.insert(statements)
graph
rescue => e
raise TriplestoreAdapter::TriplestoreException, "store graph in triplestore cache failed with exception: #{e.message}"
end
end
|
[
"def",
"store",
"(",
"graph",
")",
"begin",
"statements",
"=",
"graph",
".",
"each_statement",
".",
"to_a",
"@client",
".",
"insert",
"(",
"statements",
")",
"graph",
"rescue",
"=>",
"e",
"raise",
"TriplestoreAdapter",
"::",
"TriplestoreException",
",",
"\"store graph in triplestore cache failed with exception: #{e.message}\"",
"end",
"end"
] |
Store the graph in the triplestore cache
@param [RDF::Graph] graph
@return [RDF::Graph]
@raise [Exception] if client fails to store the graph
|
[
"Store",
"the",
"graph",
"in",
"the",
"triplestore",
"cache"
] |
597fa5842f846e57cba7574da873f1412ab76ffa
|
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/triplestore.rb#L42-L50
|
21,641 |
osulp/triplestore-adapter
|
lib/triplestore_adapter/triplestore.rb
|
TriplestoreAdapter.Triplestore.delete
|
def delete(rdf_url)
begin
graph = fetch_cached_graph(rdf_url)
puts "[INFO] did not delete #{rdf_url}, it doesn't exist in the triplestore cache" if graph.nil?
return true if graph.nil?
statements = graph.each_statement.to_a
@client.delete(statements)
return true
rescue => e
raise TriplestoreAdapter::TriplestoreException, "delete #{rdf_url} from triplestore cache failed with exception: #{e.message}"
end
end
|
ruby
|
def delete(rdf_url)
begin
graph = fetch_cached_graph(rdf_url)
puts "[INFO] did not delete #{rdf_url}, it doesn't exist in the triplestore cache" if graph.nil?
return true if graph.nil?
statements = graph.each_statement.to_a
@client.delete(statements)
return true
rescue => e
raise TriplestoreAdapter::TriplestoreException, "delete #{rdf_url} from triplestore cache failed with exception: #{e.message}"
end
end
|
[
"def",
"delete",
"(",
"rdf_url",
")",
"begin",
"graph",
"=",
"fetch_cached_graph",
"(",
"rdf_url",
")",
"puts",
"\"[INFO] did not delete #{rdf_url}, it doesn't exist in the triplestore cache\"",
"if",
"graph",
".",
"nil?",
"return",
"true",
"if",
"graph",
".",
"nil?",
"statements",
"=",
"graph",
".",
"each_statement",
".",
"to_a",
"@client",
".",
"delete",
"(",
"statements",
")",
"return",
"true",
"rescue",
"=>",
"e",
"raise",
"TriplestoreAdapter",
"::",
"TriplestoreException",
",",
"\"delete #{rdf_url} from triplestore cache failed with exception: #{e.message}\"",
"end",
"end"
] |
Delete the graph from the triplestore cache
@param [String] rdf_url
@return [Boolean]
|
[
"Delete",
"the",
"graph",
"from",
"the",
"triplestore",
"cache"
] |
597fa5842f846e57cba7574da873f1412ab76ffa
|
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/triplestore.rb#L57-L69
|
21,642 |
osulp/triplestore-adapter
|
lib/triplestore_adapter/triplestore.rb
|
TriplestoreAdapter.Triplestore.fetch_cached_graph
|
def fetch_cached_graph(rdf_url)
statements = @client.get_statements(subject: rdf_url.to_s)
if statements.count == 0
puts "[INFO] fetch_cached_graph(#{rdf_url.to_s}) not found in triplestore cache (#{@client.url})"
return nil
end
RDF::Graph.new.insert(*statements)
end
|
ruby
|
def fetch_cached_graph(rdf_url)
statements = @client.get_statements(subject: rdf_url.to_s)
if statements.count == 0
puts "[INFO] fetch_cached_graph(#{rdf_url.to_s}) not found in triplestore cache (#{@client.url})"
return nil
end
RDF::Graph.new.insert(*statements)
end
|
[
"def",
"fetch_cached_graph",
"(",
"rdf_url",
")",
"statements",
"=",
"@client",
".",
"get_statements",
"(",
"subject",
":",
"rdf_url",
".",
"to_s",
")",
"if",
"statements",
".",
"count",
"==",
"0",
"puts",
"\"[INFO] fetch_cached_graph(#{rdf_url.to_s}) not found in triplestore cache (#{@client.url})\"",
"return",
"nil",
"end",
"RDF",
"::",
"Graph",
".",
"new",
".",
"insert",
"(",
"statements",
")",
"end"
] |
Fetch the graph from the triplestore cache
@private
@param [String] url
@return [RDF::Graph] if the graph is found in the cache
@return [nil] if the graph was not in the cache
|
[
"Fetch",
"the",
"graph",
"from",
"the",
"triplestore",
"cache"
] |
597fa5842f846e57cba7574da873f1412ab76ffa
|
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/triplestore.rb#L92-L99
|
21,643 |
osulp/triplestore-adapter
|
lib/triplestore_adapter/triplestore.rb
|
TriplestoreAdapter.Triplestore.fetch_and_cache_graph
|
def fetch_and_cache_graph(rdf_url)
begin
graph = RDF::Graph.load(rdf_url)
store(graph)
graph
rescue TriplestoreAdapter::TriplestoreException => tse
puts "[ERROR] *****\n[ERROR] Unable to store graph in triplestore cache! Returning graph fetched from source.\n[ERROR] *****\n#{tse.message}"
graph
rescue => e
raise TriplestoreAdapter::TriplestoreException, "fetch_and_cache_graph(#{rdf_url}) failed to load the graph with exception: #{e.message}"
end
end
|
ruby
|
def fetch_and_cache_graph(rdf_url)
begin
graph = RDF::Graph.load(rdf_url)
store(graph)
graph
rescue TriplestoreAdapter::TriplestoreException => tse
puts "[ERROR] *****\n[ERROR] Unable to store graph in triplestore cache! Returning graph fetched from source.\n[ERROR] *****\n#{tse.message}"
graph
rescue => e
raise TriplestoreAdapter::TriplestoreException, "fetch_and_cache_graph(#{rdf_url}) failed to load the graph with exception: #{e.message}"
end
end
|
[
"def",
"fetch_and_cache_graph",
"(",
"rdf_url",
")",
"begin",
"graph",
"=",
"RDF",
"::",
"Graph",
".",
"load",
"(",
"rdf_url",
")",
"store",
"(",
"graph",
")",
"graph",
"rescue",
"TriplestoreAdapter",
"::",
"TriplestoreException",
"=>",
"tse",
"puts",
"\"[ERROR] *****\\n[ERROR] Unable to store graph in triplestore cache! Returning graph fetched from source.\\n[ERROR] *****\\n#{tse.message}\"",
"graph",
"rescue",
"=>",
"e",
"raise",
"TriplestoreAdapter",
"::",
"TriplestoreException",
",",
"\"fetch_and_cache_graph(#{rdf_url}) failed to load the graph with exception: #{e.message}\"",
"end",
"end"
] |
Fetch the graph from the source URL, and cache it for future use
@private
@param [String] url
@return [RDF::Graph] if a graph is found
@raise [Exception] if fetching the graph failed
|
[
"Fetch",
"the",
"graph",
"from",
"the",
"source",
"URL",
"and",
"cache",
"it",
"for",
"future",
"use"
] |
597fa5842f846e57cba7574da873f1412ab76ffa
|
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/triplestore.rb#L108-L119
|
21,644 |
osulp/triplestore-adapter
|
lib/triplestore_adapter/client.rb
|
TriplestoreAdapter.Client.get_statements
|
def get_statements(subject: nil)
raise TriplestoreAdapter::TriplestoreException.new("#{@provider.class.name} missing get_statements method.") unless @provider.respond_to?(:get_statements)
@provider.get_statements(subject: subject)
end
|
ruby
|
def get_statements(subject: nil)
raise TriplestoreAdapter::TriplestoreException.new("#{@provider.class.name} missing get_statements method.") unless @provider.respond_to?(:get_statements)
@provider.get_statements(subject: subject)
end
|
[
"def",
"get_statements",
"(",
"subject",
":",
"nil",
")",
"raise",
"TriplestoreAdapter",
"::",
"TriplestoreException",
".",
"new",
"(",
"\"#{@provider.class.name} missing get_statements method.\"",
")",
"unless",
"@provider",
".",
"respond_to?",
"(",
":get_statements",
")",
"@provider",
".",
"get_statements",
"(",
"subject",
":",
"subject",
")",
"end"
] |
Get statements from the server
@param [String] subject url
@raise [TriplestoreAdapter::TriplestoreException] if the provider doesn't implement this method
|
[
"Get",
"statements",
"from",
"the",
"server"
] |
597fa5842f846e57cba7574da873f1412ab76ffa
|
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/client.rb#L41-L44
|
21,645 |
toasterlovin/csv_party
|
lib/csv_party/validations.rb
|
CSVParty.Validations.raise_unless_all_named_parsers_exist!
|
def raise_unless_all_named_parsers_exist!
config.columns_with_named_parsers.each do |name, options|
parser = options[:parser]
next if named_parsers.include? parser
raise UnknownParserError.new(name, parser, named_parsers)
end
end
|
ruby
|
def raise_unless_all_named_parsers_exist!
config.columns_with_named_parsers.each do |name, options|
parser = options[:parser]
next if named_parsers.include? parser
raise UnknownParserError.new(name, parser, named_parsers)
end
end
|
[
"def",
"raise_unless_all_named_parsers_exist!",
"config",
".",
"columns_with_named_parsers",
".",
"each",
"do",
"|",
"name",
",",
"options",
"|",
"parser",
"=",
"options",
"[",
":parser",
"]",
"next",
"if",
"named_parsers",
".",
"include?",
"parser",
"raise",
"UnknownParserError",
".",
"new",
"(",
"name",
",",
"parser",
",",
"named_parsers",
")",
"end",
"end"
] |
This error has to be raised at runtime because, when the class body
is being executed, the parser methods won't be available unless
they are defined above the column definitions in the class body
|
[
"This",
"error",
"has",
"to",
"be",
"raised",
"at",
"runtime",
"because",
"when",
"the",
"class",
"body",
"is",
"being",
"executed",
"the",
"parser",
"methods",
"won",
"t",
"be",
"available",
"unless",
"they",
"are",
"defined",
"above",
"the",
"column",
"definitions",
"in",
"the",
"class",
"body"
] |
4f6ad97cc8d9a93c60cbd44df257ec2253c371b4
|
https://github.com/toasterlovin/csv_party/blob/4f6ad97cc8d9a93c60cbd44df257ec2253c371b4/lib/csv_party/validations.rb#L26-L33
|
21,646 |
piotrmurach/tty-which
|
lib/tty/which.rb
|
TTY.Which.which
|
def which(cmd, paths: search_paths)
if file_with_path?(cmd)
return cmd if executable_file?(cmd)
extensions.each do |ext|
exe = ::File.join(cmd, ext)
return ::File.absolute_path(exe) if executable_file?(exe)
end
return nil
end
paths.each do |path|
if file_with_exec_ext?(cmd)
exe = ::File.join(path, cmd)
return ::File.absolute_path(exe) if executable_file?(exe)
end
extensions.each do |ext|
exe = ::File.join(path, "#{cmd}#{ext}")
return ::File.absolute_path(exe) if executable_file?(exe)
end
end
nil
end
|
ruby
|
def which(cmd, paths: search_paths)
if file_with_path?(cmd)
return cmd if executable_file?(cmd)
extensions.each do |ext|
exe = ::File.join(cmd, ext)
return ::File.absolute_path(exe) if executable_file?(exe)
end
return nil
end
paths.each do |path|
if file_with_exec_ext?(cmd)
exe = ::File.join(path, cmd)
return ::File.absolute_path(exe) if executable_file?(exe)
end
extensions.each do |ext|
exe = ::File.join(path, "#{cmd}#{ext}")
return ::File.absolute_path(exe) if executable_file?(exe)
end
end
nil
end
|
[
"def",
"which",
"(",
"cmd",
",",
"paths",
":",
"search_paths",
")",
"if",
"file_with_path?",
"(",
"cmd",
")",
"return",
"cmd",
"if",
"executable_file?",
"(",
"cmd",
")",
"extensions",
".",
"each",
"do",
"|",
"ext",
"|",
"exe",
"=",
"::",
"File",
".",
"join",
"(",
"cmd",
",",
"ext",
")",
"return",
"::",
"File",
".",
"absolute_path",
"(",
"exe",
")",
"if",
"executable_file?",
"(",
"exe",
")",
"end",
"return",
"nil",
"end",
"paths",
".",
"each",
"do",
"|",
"path",
"|",
"if",
"file_with_exec_ext?",
"(",
"cmd",
")",
"exe",
"=",
"::",
"File",
".",
"join",
"(",
"path",
",",
"cmd",
")",
"return",
"::",
"File",
".",
"absolute_path",
"(",
"exe",
")",
"if",
"executable_file?",
"(",
"exe",
")",
"end",
"extensions",
".",
"each",
"do",
"|",
"ext",
"|",
"exe",
"=",
"::",
"File",
".",
"join",
"(",
"path",
",",
"\"#{cmd}#{ext}\"",
")",
"return",
"::",
"File",
".",
"absolute_path",
"(",
"exe",
")",
"if",
"executable_file?",
"(",
"exe",
")",
"end",
"end",
"nil",
"end"
] |
Find an executable in a platform independent way
@param [String] command
the command to search for
@param [Array[String]] paths
the paths to look through
@example
which('ruby') # => '/usr/local/bin/ruby'
which('/usr/local/bin/ruby') # => '/usr/local/bin/ruby'
which('foo') # => nil
@example
which('ruby', paths: ['/usr/locale/bin', '/usr/bin', '/bin'])
@return [String, nil]
the absolute path to executable if found, `nil` otherwise
@api public
|
[
"Find",
"an",
"executable",
"in",
"a",
"platform",
"independent",
"way"
] |
ae541cb7b4020eb291ebe0aca498ac24f183c8f5
|
https://github.com/piotrmurach/tty-which/blob/ae541cb7b4020eb291ebe0aca498ac24f183c8f5/lib/tty/which.rb#L27-L48
|
21,647 |
piotrmurach/tty-which
|
lib/tty/which.rb
|
TTY.Which.search_paths
|
def search_paths(path = ENV['PATH'])
paths = if path && !path.empty?
path.split(::File::PATH_SEPARATOR)
else
%w(/usr/local/bin /usr/ucb /usr/bin /bin)
end
paths.select(&Dir.method(:exist?))
end
|
ruby
|
def search_paths(path = ENV['PATH'])
paths = if path && !path.empty?
path.split(::File::PATH_SEPARATOR)
else
%w(/usr/local/bin /usr/ucb /usr/bin /bin)
end
paths.select(&Dir.method(:exist?))
end
|
[
"def",
"search_paths",
"(",
"path",
"=",
"ENV",
"[",
"'PATH'",
"]",
")",
"paths",
"=",
"if",
"path",
"&&",
"!",
"path",
".",
"empty?",
"path",
".",
"split",
"(",
"::",
"File",
"::",
"PATH_SEPARATOR",
")",
"else",
"%w(",
"/usr/local/bin",
"/usr/ucb",
"/usr/bin",
"/bin",
")",
"end",
"paths",
".",
"select",
"(",
"Dir",
".",
"method",
"(",
":exist?",
")",
")",
"end"
] |
Find default system paths
@param [String] path
the path to search through
@example
search_paths("/usr/local/bin:/bin")
# => ['/bin']
@return [Array[String]]
the array of paths to search
@api private
|
[
"Find",
"default",
"system",
"paths"
] |
ae541cb7b4020eb291ebe0aca498ac24f183c8f5
|
https://github.com/piotrmurach/tty-which/blob/ae541cb7b4020eb291ebe0aca498ac24f183c8f5/lib/tty/which.rb#L80-L87
|
21,648 |
piotrmurach/tty-which
|
lib/tty/which.rb
|
TTY.Which.extensions
|
def extensions(path_ext = ENV['PATHEXT'])
return [''] unless path_ext
path_ext.split(::File::PATH_SEPARATOR).select { |part| part.include?('.') }
end
|
ruby
|
def extensions(path_ext = ENV['PATHEXT'])
return [''] unless path_ext
path_ext.split(::File::PATH_SEPARATOR).select { |part| part.include?('.') }
end
|
[
"def",
"extensions",
"(",
"path_ext",
"=",
"ENV",
"[",
"'PATHEXT'",
"]",
")",
"return",
"[",
"''",
"]",
"unless",
"path_ext",
"path_ext",
".",
"split",
"(",
"::",
"File",
"::",
"PATH_SEPARATOR",
")",
".",
"select",
"{",
"|",
"part",
"|",
"part",
".",
"include?",
"(",
"'.'",
")",
"}",
"end"
] |
All possible file extensions
@example
extensions('.exe;cmd;.bat')
# => ['.exe','.bat']
@param [String] path_ext
a string of semicolon separated filename extensions
@return [Array[String]]
an array with valid file extensions
@api private
|
[
"All",
"possible",
"file",
"extensions"
] |
ae541cb7b4020eb291ebe0aca498ac24f183c8f5
|
https://github.com/piotrmurach/tty-which/blob/ae541cb7b4020eb291ebe0aca498ac24f183c8f5/lib/tty/which.rb#L103-L106
|
21,649 |
piotrmurach/tty-which
|
lib/tty/which.rb
|
TTY.Which.executable_file?
|
def executable_file?(filename, dir = nil)
path = ::File.join(dir, filename) if dir
path ||= filename
::File.file?(path) && ::File.executable?(path)
end
|
ruby
|
def executable_file?(filename, dir = nil)
path = ::File.join(dir, filename) if dir
path ||= filename
::File.file?(path) && ::File.executable?(path)
end
|
[
"def",
"executable_file?",
"(",
"filename",
",",
"dir",
"=",
"nil",
")",
"path",
"=",
"::",
"File",
".",
"join",
"(",
"dir",
",",
"filename",
")",
"if",
"dir",
"path",
"||=",
"filename",
"::",
"File",
".",
"file?",
"(",
"path",
")",
"&&",
"::",
"File",
".",
"executable?",
"(",
"path",
")",
"end"
] |
Determines if filename is an executable file
@example Basic usage
executable_file?('/usr/bin/less') # => true
@example Executable in directory
executable_file?('less', '/usr/bin') # => true
executable_file?('less', '/usr') # => false
@param [String] filename
the path to file
@param [String] dir
the directory within which to search for filename
@return [Boolean]
@api private
|
[
"Determines",
"if",
"filename",
"is",
"an",
"executable",
"file"
] |
ae541cb7b4020eb291ebe0aca498ac24f183c8f5
|
https://github.com/piotrmurach/tty-which/blob/ae541cb7b4020eb291ebe0aca498ac24f183c8f5/lib/tty/which.rb#L126-L130
|
21,650 |
piotrmurach/tty-which
|
lib/tty/which.rb
|
TTY.Which.file_with_exec_ext?
|
def file_with_exec_ext?(filename)
extension = ::File.extname(filename)
return false if extension.empty?
extensions.any? { |ext| extension.casecmp(ext).zero? }
end
|
ruby
|
def file_with_exec_ext?(filename)
extension = ::File.extname(filename)
return false if extension.empty?
extensions.any? { |ext| extension.casecmp(ext).zero? }
end
|
[
"def",
"file_with_exec_ext?",
"(",
"filename",
")",
"extension",
"=",
"::",
"File",
".",
"extname",
"(",
"filename",
")",
"return",
"false",
"if",
"extension",
".",
"empty?",
"extensions",
".",
"any?",
"{",
"|",
"ext",
"|",
"extension",
".",
"casecmp",
"(",
"ext",
")",
".",
"zero?",
"}",
"end"
] |
Check if command itself has executable extension
@param [String] filename
the path to executable file
@example
file_with_exec_ext?("file.bat")
# => true
@return [Boolean]
@api private
|
[
"Check",
"if",
"command",
"itself",
"has",
"executable",
"extension"
] |
ae541cb7b4020eb291ebe0aca498ac24f183c8f5
|
https://github.com/piotrmurach/tty-which/blob/ae541cb7b4020eb291ebe0aca498ac24f183c8f5/lib/tty/which.rb#L145-L149
|
21,651 |
iainbeeston/nickel
|
lib/nickel/construct_finder.rb
|
Nickel.ConstructFinder.found_now_through_following_dayname
|
def found_now_through_following_dayname
@constructs << DateSpanConstruct.new(start_date: @curdate, end_date: @curdate.this(@day_index), comp_start: @pos, comp_end: @pos += 3, found_in: __method__)
end
|
ruby
|
def found_now_through_following_dayname
@constructs << DateSpanConstruct.new(start_date: @curdate, end_date: @curdate.this(@day_index), comp_start: @pos, comp_end: @pos += 3, found_in: __method__)
end
|
[
"def",
"found_now_through_following_dayname",
"@constructs",
"<<",
"DateSpanConstruct",
".",
"new",
"(",
"start_date",
":",
"@curdate",
",",
"end_date",
":",
"@curdate",
".",
"this",
"(",
"@day_index",
")",
",",
"comp_start",
":",
"@pos",
",",
"comp_end",
":",
"@pos",
"+=",
"3",
",",
"found_in",
":",
"__method__",
")",
"end"
] |
redundant!! preprocess this out of here!
|
[
"redundant!!",
"preprocess",
"this",
"out",
"of",
"here!"
] |
47755277499db945f5eb65a4c0fb27c0e344c90b
|
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/construct_finder.rb#L1067-L1069
|
21,652 |
iainbeeston/nickel
|
lib/nickel/nlp.rb
|
Nickel.NLP.correct_case
|
def correct_case
orig = @query.split
latest = @message.split
orig.each_with_index do |original_word, j|
if i = latest.index(original_word.downcase)
latest[i] = original_word
end
end
@message = latest.join(' ')
end
|
ruby
|
def correct_case
orig = @query.split
latest = @message.split
orig.each_with_index do |original_word, j|
if i = latest.index(original_word.downcase)
latest[i] = original_word
end
end
@message = latest.join(' ')
end
|
[
"def",
"correct_case",
"orig",
"=",
"@query",
".",
"split",
"latest",
"=",
"@message",
".",
"split",
"orig",
".",
"each_with_index",
"do",
"|",
"original_word",
",",
"j",
"|",
"if",
"i",
"=",
"latest",
".",
"index",
"(",
"original_word",
".",
"downcase",
")",
"latest",
"[",
"i",
"]",
"=",
"original_word",
"end",
"end",
"@message",
"=",
"latest",
".",
"join",
"(",
"' '",
")",
"end"
] |
returns any words in the query that appeared as input to their original case
|
[
"returns",
"any",
"words",
"in",
"the",
"query",
"that",
"appeared",
"as",
"input",
"to",
"their",
"original",
"case"
] |
47755277499db945f5eb65a4c0fb27c0e344c90b
|
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/nlp.rb#L83-L92
|
21,653 |
iainbeeston/nickel
|
lib/nickel/zdate.rb
|
Nickel.ZDate.ordinal_dayindex
|
def ordinal_dayindex(num, day_index)
# create a date object at the first occurrence of day_index
first_occ_date = ZDate.new(ZDate.format_date(year_str, month_str)).this(day_index)
# if num is 1 through 4, we can just add (num-1) weeks
if num <= 4
d = first_occ_date.add_weeks(num - 1)
else
# we want the last occurrence of this month
# add 4 weeks to first occurrence, see if we are in the same month, subtract 1 week if we are not
d = first_occ_date.add_weeks(4)
if d.month != month
d = d.sub_weeks(1)
end
end
d
end
|
ruby
|
def ordinal_dayindex(num, day_index)
# create a date object at the first occurrence of day_index
first_occ_date = ZDate.new(ZDate.format_date(year_str, month_str)).this(day_index)
# if num is 1 through 4, we can just add (num-1) weeks
if num <= 4
d = first_occ_date.add_weeks(num - 1)
else
# we want the last occurrence of this month
# add 4 weeks to first occurrence, see if we are in the same month, subtract 1 week if we are not
d = first_occ_date.add_weeks(4)
if d.month != month
d = d.sub_weeks(1)
end
end
d
end
|
[
"def",
"ordinal_dayindex",
"(",
"num",
",",
"day_index",
")",
"# create a date object at the first occurrence of day_index",
"first_occ_date",
"=",
"ZDate",
".",
"new",
"(",
"ZDate",
".",
"format_date",
"(",
"year_str",
",",
"month_str",
")",
")",
".",
"this",
"(",
"day_index",
")",
"# if num is 1 through 4, we can just add (num-1) weeks",
"if",
"num",
"<=",
"4",
"d",
"=",
"first_occ_date",
".",
"add_weeks",
"(",
"num",
"-",
"1",
")",
"else",
"# we want the last occurrence of this month",
"# add 4 weeks to first occurrence, see if we are in the same month, subtract 1 week if we are not",
"d",
"=",
"first_occ_date",
".",
"add_weeks",
"(",
"4",
")",
"if",
"d",
".",
"month",
"!=",
"month",
"d",
"=",
"d",
".",
"sub_weeks",
"(",
"1",
")",
"end",
"end",
"d",
"end"
] |
for example, "1st friday", uses self as the reference month
|
[
"for",
"example",
"1st",
"friday",
"uses",
"self",
"as",
"the",
"reference",
"month"
] |
47755277499db945f5eb65a4c0fb27c0e344c90b
|
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L100-L115
|
21,654 |
iainbeeston/nickel
|
lib/nickel/zdate.rb
|
Nickel.ZDate.x_weeks_from_day
|
def x_weeks_from_day(weeks_away, day2index)
day1index = dayindex
if day1index > day2index
days_away = 7 * (weeks_away + 1) - (day1index - day2index)
elsif day1index < day2index
days_away = (weeks_away * 7) + (day2index - day1index)
elsif day1index == day2index
days_away = 7 * weeks_away
end
add_days(days_away) # returns a new date object
end
|
ruby
|
def x_weeks_from_day(weeks_away, day2index)
day1index = dayindex
if day1index > day2index
days_away = 7 * (weeks_away + 1) - (day1index - day2index)
elsif day1index < day2index
days_away = (weeks_away * 7) + (day2index - day1index)
elsif day1index == day2index
days_away = 7 * weeks_away
end
add_days(days_away) # returns a new date object
end
|
[
"def",
"x_weeks_from_day",
"(",
"weeks_away",
",",
"day2index",
")",
"day1index",
"=",
"dayindex",
"if",
"day1index",
">",
"day2index",
"days_away",
"=",
"7",
"*",
"(",
"weeks_away",
"+",
"1",
")",
"-",
"(",
"day1index",
"-",
"day2index",
")",
"elsif",
"day1index",
"<",
"day2index",
"days_away",
"=",
"(",
"weeks_away",
"*",
"7",
")",
"+",
"(",
"day2index",
"-",
"day1index",
")",
"elsif",
"day1index",
"==",
"day2index",
"days_away",
"=",
"7",
"*",
"weeks_away",
"end",
"add_days",
"(",
"days_away",
")",
"# returns a new date object",
"end"
] |
returns a new date object
|
[
"returns",
"a",
"new",
"date",
"object"
] |
47755277499db945f5eb65a4c0fb27c0e344c90b
|
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L133-L143
|
21,655 |
iainbeeston/nickel
|
lib/nickel/zdate.rb
|
Nickel.ZDate.add_days
|
def add_days(number)
if number < 0
return sub_days(number.abs)
end
o = dup # new ZDate object
# Let's see what month we are going to end in
while number > 0
if o.days_left_in_month >= number
o.date = ZDate.format_date(o.year_str, o.month_str, o.day + number)
number = 0
else
number = number - 1 - o.days_left_in_month # it costs 1 day to increment the month
o.increment_month!
end
end
o
end
|
ruby
|
def add_days(number)
if number < 0
return sub_days(number.abs)
end
o = dup # new ZDate object
# Let's see what month we are going to end in
while number > 0
if o.days_left_in_month >= number
o.date = ZDate.format_date(o.year_str, o.month_str, o.day + number)
number = 0
else
number = number - 1 - o.days_left_in_month # it costs 1 day to increment the month
o.increment_month!
end
end
o
end
|
[
"def",
"add_days",
"(",
"number",
")",
"if",
"number",
"<",
"0",
"return",
"sub_days",
"(",
"number",
".",
"abs",
")",
"end",
"o",
"=",
"dup",
"# new ZDate object",
"# Let's see what month we are going to end in",
"while",
"number",
">",
"0",
"if",
"o",
".",
"days_left_in_month",
">=",
"number",
"o",
".",
"date",
"=",
"ZDate",
".",
"format_date",
"(",
"o",
".",
"year_str",
",",
"o",
".",
"month_str",
",",
"o",
".",
"day",
"+",
"number",
")",
"number",
"=",
"0",
"else",
"number",
"=",
"number",
"-",
"1",
"-",
"o",
".",
"days_left_in_month",
"# it costs 1 day to increment the month",
"o",
".",
"increment_month!",
"end",
"end",
"o",
"end"
] |
add_ methods return new ZDate object, they DO NOT modify self
|
[
"add_",
"methods",
"return",
"new",
"ZDate",
"object",
"they",
"DO",
"NOT",
"modify",
"self"
] |
47755277499db945f5eb65a4c0fb27c0e344c90b
|
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L146-L162
|
21,656 |
iainbeeston/nickel
|
lib/nickel/zdate.rb
|
Nickel.ZDate.sub_days
|
def sub_days(number)
o = dup
while number > 0
if (o.day - 1) >= number
o.date = ZDate.format_date(o.year_str, o.month_str, o.day - number)
number = 0
else
number -= o.day
o.decrement_month!
end
end
o
end
|
ruby
|
def sub_days(number)
o = dup
while number > 0
if (o.day - 1) >= number
o.date = ZDate.format_date(o.year_str, o.month_str, o.day - number)
number = 0
else
number -= o.day
o.decrement_month!
end
end
o
end
|
[
"def",
"sub_days",
"(",
"number",
")",
"o",
"=",
"dup",
"while",
"number",
">",
"0",
"if",
"(",
"o",
".",
"day",
"-",
"1",
")",
">=",
"number",
"o",
".",
"date",
"=",
"ZDate",
".",
"format_date",
"(",
"o",
".",
"year_str",
",",
"o",
".",
"month_str",
",",
"o",
".",
"day",
"-",
"number",
")",
"number",
"=",
"0",
"else",
"number",
"-=",
"o",
".",
"day",
"o",
".",
"decrement_month!",
"end",
"end",
"o",
"end"
] |
sub_ methods return new ZDate object, they do not modify self.
|
[
"sub_",
"methods",
"return",
"new",
"ZDate",
"object",
"they",
"do",
"not",
"modify",
"self",
"."
] |
47755277499db945f5eb65a4c0fb27c0e344c90b
|
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L224-L236
|
21,657 |
iainbeeston/nickel
|
lib/nickel/zdate.rb
|
Nickel.ZDate.diff_in_days
|
def diff_in_days(date_to_compare)
# d1 will be the earlier date, d2 the later
if date_to_compare > self
d1, d2 = dup, date_to_compare.dup
elsif self > date_to_compare
d1, d2 = date_to_compare.dup, dup
else
return 0 # same date
end
total = 0
while d1.year != d2.year
total += d1.days_left_in_year + 1 # need one extra day to push us to jan 1
d1 = ZDate.new(ZDate.format_date(d1.year + 1))
end
total += d2.day_of_year - d1.day_of_year
total
end
|
ruby
|
def diff_in_days(date_to_compare)
# d1 will be the earlier date, d2 the later
if date_to_compare > self
d1, d2 = dup, date_to_compare.dup
elsif self > date_to_compare
d1, d2 = date_to_compare.dup, dup
else
return 0 # same date
end
total = 0
while d1.year != d2.year
total += d1.days_left_in_year + 1 # need one extra day to push us to jan 1
d1 = ZDate.new(ZDate.format_date(d1.year + 1))
end
total += d2.day_of_year - d1.day_of_year
total
end
|
[
"def",
"diff_in_days",
"(",
"date_to_compare",
")",
"# d1 will be the earlier date, d2 the later",
"if",
"date_to_compare",
">",
"self",
"d1",
",",
"d2",
"=",
"dup",
",",
"date_to_compare",
".",
"dup",
"elsif",
"self",
">",
"date_to_compare",
"d1",
",",
"d2",
"=",
"date_to_compare",
".",
"dup",
",",
"dup",
"else",
"return",
"0",
"# same date",
"end",
"total",
"=",
"0",
"while",
"d1",
".",
"year",
"!=",
"d2",
".",
"year",
"total",
"+=",
"d1",
".",
"days_left_in_year",
"+",
"1",
"# need one extra day to push us to jan 1",
"d1",
"=",
"ZDate",
".",
"new",
"(",
"ZDate",
".",
"format_date",
"(",
"d1",
".",
"year",
"+",
"1",
")",
")",
"end",
"total",
"+=",
"d2",
".",
"day_of_year",
"-",
"d1",
".",
"day_of_year",
"total",
"end"
] |
Gets the absolute difference in days between self and date_to_compare, order is not important.
|
[
"Gets",
"the",
"absolute",
"difference",
"in",
"days",
"between",
"self",
"and",
"date_to_compare",
"order",
"is",
"not",
"important",
"."
] |
47755277499db945f5eb65a4c0fb27c0e344c90b
|
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L251-L268
|
21,658 |
iainbeeston/nickel
|
lib/nickel/zdate.rb
|
Nickel.ZDate.diff_in_months
|
def diff_in_months(date2)
if date2 > self
ZDate.diff_in_months(month, year, date2.month, date2.year)
else
ZDate.diff_in_months(date2.month, date2.year, month, year) * -1
end
end
|
ruby
|
def diff_in_months(date2)
if date2 > self
ZDate.diff_in_months(month, year, date2.month, date2.year)
else
ZDate.diff_in_months(date2.month, date2.year, month, year) * -1
end
end
|
[
"def",
"diff_in_months",
"(",
"date2",
")",
"if",
"date2",
">",
"self",
"ZDate",
".",
"diff_in_months",
"(",
"month",
",",
"year",
",",
"date2",
".",
"month",
",",
"date2",
".",
"year",
")",
"else",
"ZDate",
".",
"diff_in_months",
"(",
"date2",
".",
"month",
",",
"date2",
".",
"year",
",",
"month",
",",
"year",
")",
"*",
"-",
"1",
"end",
"end"
] |
difference in months FROM self TO date2, for instance, if self is oct 1 and date2 is nov 14, will return 1
if self is nov 14 and date2 is oct 1, will return -1
|
[
"difference",
"in",
"months",
"FROM",
"self",
"TO",
"date2",
"for",
"instance",
"if",
"self",
"is",
"oct",
"1",
"and",
"date2",
"is",
"nov",
"14",
"will",
"return",
"1",
"if",
"self",
"is",
"nov",
"14",
"and",
"date2",
"is",
"oct",
"1",
"will",
"return",
"-",
"1"
] |
47755277499db945f5eb65a4c0fb27c0e344c90b
|
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L399-L405
|
21,659 |
iainbeeston/nickel
|
lib/nickel/zdate.rb
|
Nickel.ZDate.increment_month!
|
def increment_month!
if month != 12
# just bump up a number
self.date = ZDate.format_date(year_str, month + 1)
else
self.date = ZDate.format_date(year + 1)
end
end
|
ruby
|
def increment_month!
if month != 12
# just bump up a number
self.date = ZDate.format_date(year_str, month + 1)
else
self.date = ZDate.format_date(year + 1)
end
end
|
[
"def",
"increment_month!",
"if",
"month",
"!=",
"12",
"# just bump up a number",
"self",
".",
"date",
"=",
"ZDate",
".",
"format_date",
"(",
"year_str",
",",
"month",
"+",
"1",
")",
"else",
"self",
".",
"date",
"=",
"ZDate",
".",
"format_date",
"(",
"year",
"+",
"1",
")",
"end",
"end"
] |
Modifies self.
bumps self to first day of next month
|
[
"Modifies",
"self",
".",
"bumps",
"self",
"to",
"first",
"day",
"of",
"next",
"month"
] |
47755277499db945f5eb65a4c0fb27c0e344c90b
|
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L538-L545
|
21,660 |
iainbeeston/nickel
|
lib/nickel/ztime.rb
|
Nickel.ZTime.modify_such_that_is_before
|
def modify_such_that_is_before(time2)
fail 'ZTime#modify_such_that_is_before says: trying to modify time that has @firm set' if @firm
fail 'ZTime#modify_such_that_is_before says: time2 does not have @firm set' unless time2.firm
# self cannot have @firm set, so all hours will be between 1 and 12
# time2 is an end time, self could be its current setting, or off by 12 hours
# self to time2 --> self to time2
# 12 to 2am --> 1200 to 0200
# 12 to 12am --> 1200 to 0000
# 1220 to 12am --> 1220 to 0000
# 11 to 2am or 1100 to 0200
if self > time2
if hour == 12 && time2.hour == 0
# do nothing
else
hour == 12 ? change_hour_to(0) : change_hour_to(hour + 12)
end
elsif self < time2
if time2.hour >= 12 && ZTime.new(ZTime.format_time(time2.hour - 12, time2.min_str, time2.sec_str)) > self
# 4 to 5pm or 0400 to 1700
change_hour_to(hour + 12)
else
# 4 to 1pm or 0400 to 1300
# do nothing
end
else
# the times are equal, and self can only be between 0100 and 1200, so move self forward 12 hours, unless hour is 12
hour == 12 ? change_hour_to(0) : change_hour_to(hour + 12)
end
self.firm = true
self
end
|
ruby
|
def modify_such_that_is_before(time2)
fail 'ZTime#modify_such_that_is_before says: trying to modify time that has @firm set' if @firm
fail 'ZTime#modify_such_that_is_before says: time2 does not have @firm set' unless time2.firm
# self cannot have @firm set, so all hours will be between 1 and 12
# time2 is an end time, self could be its current setting, or off by 12 hours
# self to time2 --> self to time2
# 12 to 2am --> 1200 to 0200
# 12 to 12am --> 1200 to 0000
# 1220 to 12am --> 1220 to 0000
# 11 to 2am or 1100 to 0200
if self > time2
if hour == 12 && time2.hour == 0
# do nothing
else
hour == 12 ? change_hour_to(0) : change_hour_to(hour + 12)
end
elsif self < time2
if time2.hour >= 12 && ZTime.new(ZTime.format_time(time2.hour - 12, time2.min_str, time2.sec_str)) > self
# 4 to 5pm or 0400 to 1700
change_hour_to(hour + 12)
else
# 4 to 1pm or 0400 to 1300
# do nothing
end
else
# the times are equal, and self can only be between 0100 and 1200, so move self forward 12 hours, unless hour is 12
hour == 12 ? change_hour_to(0) : change_hour_to(hour + 12)
end
self.firm = true
self
end
|
[
"def",
"modify_such_that_is_before",
"(",
"time2",
")",
"fail",
"'ZTime#modify_such_that_is_before says: trying to modify time that has @firm set'",
"if",
"@firm",
"fail",
"'ZTime#modify_such_that_is_before says: time2 does not have @firm set'",
"unless",
"time2",
".",
"firm",
"# self cannot have @firm set, so all hours will be between 1 and 12",
"# time2 is an end time, self could be its current setting, or off by 12 hours",
"# self to time2 --> self to time2",
"# 12 to 2am --> 1200 to 0200",
"# 12 to 12am --> 1200 to 0000",
"# 1220 to 12am --> 1220 to 0000",
"# 11 to 2am or 1100 to 0200",
"if",
"self",
">",
"time2",
"if",
"hour",
"==",
"12",
"&&",
"time2",
".",
"hour",
"==",
"0",
"# do nothing",
"else",
"hour",
"==",
"12",
"?",
"change_hour_to",
"(",
"0",
")",
":",
"change_hour_to",
"(",
"hour",
"+",
"12",
")",
"end",
"elsif",
"self",
"<",
"time2",
"if",
"time2",
".",
"hour",
">=",
"12",
"&&",
"ZTime",
".",
"new",
"(",
"ZTime",
".",
"format_time",
"(",
"time2",
".",
"hour",
"-",
"12",
",",
"time2",
".",
"min_str",
",",
"time2",
".",
"sec_str",
")",
")",
">",
"self",
"# 4 to 5pm or 0400 to 1700",
"change_hour_to",
"(",
"hour",
"+",
"12",
")",
"else",
"# 4 to 1pm or 0400 to 1300",
"# do nothing",
"end",
"else",
"# the times are equal, and self can only be between 0100 and 1200, so move self forward 12 hours, unless hour is 12",
"hour",
"==",
"12",
"?",
"change_hour_to",
"(",
"0",
")",
":",
"change_hour_to",
"(",
"hour",
"+",
"12",
")",
"end",
"self",
".",
"firm",
"=",
"true",
"self",
"end"
] |
this can very easily be cleaned up
|
[
"this",
"can",
"very",
"easily",
"be",
"cleaned",
"up"
] |
47755277499db945f5eb65a4c0fb27c0e344c90b
|
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/ztime.rb#L269-L300
|
21,661 |
madeindjs/active_storage-send_zip
|
lib/active_storage/send_zip.rb
|
ActiveStorage.SendZip.send_zip
|
def send_zip(active_storages, filename: 'my.zip')
require 'zip'
files = SendZipHelper.save_files_on_server active_storages
zip_data = SendZipHelper.create_temporary_zip_file files
send_data(zip_data, type: 'application/zip', filename: filename)
end
|
ruby
|
def send_zip(active_storages, filename: 'my.zip')
require 'zip'
files = SendZipHelper.save_files_on_server active_storages
zip_data = SendZipHelper.create_temporary_zip_file files
send_data(zip_data, type: 'application/zip', filename: filename)
end
|
[
"def",
"send_zip",
"(",
"active_storages",
",",
"filename",
":",
"'my.zip'",
")",
"require",
"'zip'",
"files",
"=",
"SendZipHelper",
".",
"save_files_on_server",
"active_storages",
"zip_data",
"=",
"SendZipHelper",
".",
"create_temporary_zip_file",
"files",
"send_data",
"(",
"zip_data",
",",
"type",
":",
"'application/zip'",
",",
"filename",
":",
"filename",
")",
"end"
] |
Zip all given files into a zip and send it with `send_data`
@param active_storages [ActiveStorage::Attached::Many] files to save
@param filename [ActiveStorage::Attached::Many] files to save
|
[
"Zip",
"all",
"given",
"files",
"into",
"a",
"zip",
"and",
"send",
"it",
"with",
"send_data"
] |
65921be2a3273aa0a2f84d5aa7780c2086ae05b9
|
https://github.com/madeindjs/active_storage-send_zip/blob/65921be2a3273aa0a2f84d5aa7780c2086ae05b9/lib/active_storage/send_zip.rb#L17-L23
|
21,662 |
jdennes/contribution-checker
|
lib/contribution-checker/checker.rb
|
ContributionChecker.Checker.check
|
def check
@nwo, @sha = parse_commit_url @commit_url
begin
@commit = @client.commit @nwo, @sha
rescue ArgumentError
raise ContributionChecker::InvalidCommitUrlError
rescue Octokit::NotFound
raise ContributionChecker::InvalidCommitUrlError
rescue Octokit::Unauthorized
raise ContributionChecker::InvalidAccessTokenError
end
@repo = @client.repository @nwo
@user = @client.user
@commit_email_is_not_generic = commit_email_is_not_generic?
@commit_in_valid_branch = commit_in_valid_branch?
@repo_not_a_fork = !repository_is_fork?
@commit_email_linked_to_user = commit_email_linked_to_user?
@user_has_starred_repo = user_has_starred_repo?
@user_can_push_to_repo = user_can_push_to_repo?
@user_is_repo_org_member = user_is_repo_org_member?
@user_has_fork_of_repo = user_has_fork_of_repo?
@user_has_opened_issue_or_pr_in_repo = user_has_opened_issue_or_pr_in_repo?
{
:contribution => and_criteria_met? && or_criteria_met?,
:and_criteria => {
:commit_email_is_not_generic => @commit_email_is_not_generic,
:commit_in_valid_branch => @commit_in_valid_branch,
:repo_not_a_fork => @repo_not_a_fork,
:commit_email_linked_to_user => @commit_email_linked_to_user,
:commit_email => @commit[:commit][:author][:email],
:default_branch => @repo[:default_branch],
},
:or_criteria => {
:user_has_starred_repo => @user_has_starred_repo,
:user_can_push_to_repo => @user_can_push_to_repo,
:user_is_repo_org_member => @user_is_repo_org_member,
:user_has_fork_of_repo => @user_has_fork_of_repo,
:user_has_opened_issue_or_pr_in_repo => @user_has_opened_issue_or_pr_in_repo,
}
}
end
|
ruby
|
def check
@nwo, @sha = parse_commit_url @commit_url
begin
@commit = @client.commit @nwo, @sha
rescue ArgumentError
raise ContributionChecker::InvalidCommitUrlError
rescue Octokit::NotFound
raise ContributionChecker::InvalidCommitUrlError
rescue Octokit::Unauthorized
raise ContributionChecker::InvalidAccessTokenError
end
@repo = @client.repository @nwo
@user = @client.user
@commit_email_is_not_generic = commit_email_is_not_generic?
@commit_in_valid_branch = commit_in_valid_branch?
@repo_not_a_fork = !repository_is_fork?
@commit_email_linked_to_user = commit_email_linked_to_user?
@user_has_starred_repo = user_has_starred_repo?
@user_can_push_to_repo = user_can_push_to_repo?
@user_is_repo_org_member = user_is_repo_org_member?
@user_has_fork_of_repo = user_has_fork_of_repo?
@user_has_opened_issue_or_pr_in_repo = user_has_opened_issue_or_pr_in_repo?
{
:contribution => and_criteria_met? && or_criteria_met?,
:and_criteria => {
:commit_email_is_not_generic => @commit_email_is_not_generic,
:commit_in_valid_branch => @commit_in_valid_branch,
:repo_not_a_fork => @repo_not_a_fork,
:commit_email_linked_to_user => @commit_email_linked_to_user,
:commit_email => @commit[:commit][:author][:email],
:default_branch => @repo[:default_branch],
},
:or_criteria => {
:user_has_starred_repo => @user_has_starred_repo,
:user_can_push_to_repo => @user_can_push_to_repo,
:user_is_repo_org_member => @user_is_repo_org_member,
:user_has_fork_of_repo => @user_has_fork_of_repo,
:user_has_opened_issue_or_pr_in_repo => @user_has_opened_issue_or_pr_in_repo,
}
}
end
|
[
"def",
"check",
"@nwo",
",",
"@sha",
"=",
"parse_commit_url",
"@commit_url",
"begin",
"@commit",
"=",
"@client",
".",
"commit",
"@nwo",
",",
"@sha",
"rescue",
"ArgumentError",
"raise",
"ContributionChecker",
"::",
"InvalidCommitUrlError",
"rescue",
"Octokit",
"::",
"NotFound",
"raise",
"ContributionChecker",
"::",
"InvalidCommitUrlError",
"rescue",
"Octokit",
"::",
"Unauthorized",
"raise",
"ContributionChecker",
"::",
"InvalidAccessTokenError",
"end",
"@repo",
"=",
"@client",
".",
"repository",
"@nwo",
"@user",
"=",
"@client",
".",
"user",
"@commit_email_is_not_generic",
"=",
"commit_email_is_not_generic?",
"@commit_in_valid_branch",
"=",
"commit_in_valid_branch?",
"@repo_not_a_fork",
"=",
"!",
"repository_is_fork?",
"@commit_email_linked_to_user",
"=",
"commit_email_linked_to_user?",
"@user_has_starred_repo",
"=",
"user_has_starred_repo?",
"@user_can_push_to_repo",
"=",
"user_can_push_to_repo?",
"@user_is_repo_org_member",
"=",
"user_is_repo_org_member?",
"@user_has_fork_of_repo",
"=",
"user_has_fork_of_repo?",
"@user_has_opened_issue_or_pr_in_repo",
"=",
"user_has_opened_issue_or_pr_in_repo?",
"{",
":contribution",
"=>",
"and_criteria_met?",
"&&",
"or_criteria_met?",
",",
":and_criteria",
"=>",
"{",
":commit_email_is_not_generic",
"=>",
"@commit_email_is_not_generic",
",",
":commit_in_valid_branch",
"=>",
"@commit_in_valid_branch",
",",
":repo_not_a_fork",
"=>",
"@repo_not_a_fork",
",",
":commit_email_linked_to_user",
"=>",
"@commit_email_linked_to_user",
",",
":commit_email",
"=>",
"@commit",
"[",
":commit",
"]",
"[",
":author",
"]",
"[",
":email",
"]",
",",
":default_branch",
"=>",
"@repo",
"[",
":default_branch",
"]",
",",
"}",
",",
":or_criteria",
"=>",
"{",
":user_has_starred_repo",
"=>",
"@user_has_starred_repo",
",",
":user_can_push_to_repo",
"=>",
"@user_can_push_to_repo",
",",
":user_is_repo_org_member",
"=>",
"@user_is_repo_org_member",
",",
":user_has_fork_of_repo",
"=>",
"@user_has_fork_of_repo",
",",
":user_has_opened_issue_or_pr_in_repo",
"=>",
"@user_has_opened_issue_or_pr_in_repo",
",",
"}",
"}",
"end"
] |
Initialise a new Checker instance with an API access token and commit URL.
@param options [Hash] Options which should take the form:
{
:access_token => "<Your 40 char GitHub API token>",
:commit_url => "https://github.com/user/repo/commit/sha"
}
@return [ContributionChecker::Checker] Contribution checker initialised
for an authenticated user and a specific commit
Checks whether the commit is counted as a contribution for the
authenticated user.
@return [Hash] The return value takes the following form:
{
:contribution => true,
:and_criteria => {
:commit_email_is_not_generic => true,
:commit_in_valid_branch => true,
:repo_not_a_fork => true,
:commit_email_linked_to_user => true,
:commit_email => "[email protected]",
:default_branch => "master"
},
:or_criteria => {
:user_has_starred_repo => false,
:user_can_push_to_repo => false,
:user_is_repo_org_member => true,
:user_has_fork_of_repo => false,
:user_has_opened_issue_or_pr_in_repo => false
}
}
|
[
"Initialise",
"a",
"new",
"Checker",
"instance",
"with",
"an",
"API",
"access",
"token",
"and",
"commit",
"URL",
"."
] |
1370314972a404642321b19cc1c5e0d99d54dfc6
|
https://github.com/jdennes/contribution-checker/blob/1370314972a404642321b19cc1c5e0d99d54dfc6/lib/contribution-checker/checker.rb#L51-L93
|
21,663 |
jdennes/contribution-checker
|
lib/contribution-checker/checker.rb
|
ContributionChecker.Checker.parse_commit_url
|
def parse_commit_url(url)
begin
parts = URI.parse(@commit_url).path.split("/")
nwo = "#{parts[1]}/#{parts[2]}"
sha = parts[4]
return nwo, sha
rescue
raise ContributionChecker::InvalidCommitUrlError
end
end
|
ruby
|
def parse_commit_url(url)
begin
parts = URI.parse(@commit_url).path.split("/")
nwo = "#{parts[1]}/#{parts[2]}"
sha = parts[4]
return nwo, sha
rescue
raise ContributionChecker::InvalidCommitUrlError
end
end
|
[
"def",
"parse_commit_url",
"(",
"url",
")",
"begin",
"parts",
"=",
"URI",
".",
"parse",
"(",
"@commit_url",
")",
".",
"path",
".",
"split",
"(",
"\"/\"",
")",
"nwo",
"=",
"\"#{parts[1]}/#{parts[2]}\"",
"sha",
"=",
"parts",
"[",
"4",
"]",
"return",
"nwo",
",",
"sha",
"rescue",
"raise",
"ContributionChecker",
"::",
"InvalidCommitUrlError",
"end",
"end"
] |
Parses the commit URL provided.
@return [Array] URL parts: nwo, sha
|
[
"Parses",
"the",
"commit",
"URL",
"provided",
"."
] |
1370314972a404642321b19cc1c5e0d99d54dfc6
|
https://github.com/jdennes/contribution-checker/blob/1370314972a404642321b19cc1c5e0d99d54dfc6/lib/contribution-checker/checker.rb#L100-L109
|
21,664 |
jdennes/contribution-checker
|
lib/contribution-checker/checker.rb
|
ContributionChecker.Checker.user_has_fork_of_repo?
|
def user_has_fork_of_repo?
# The API doesn't provide a simple means of checking whether a user has
# forked a repository.
# First, if there are no forks for the repository, return false.
return false if @repo[:forks_count] == 0
# Then check whether it's worth getting the list of forks
if @repo[:forks_count] <= 100
repo_forks = @client.forks @repo[:full_name], :per_page => 100
repo_forks.each do |f|
return true if f[:owner][:login] == @user[:login]
end
end
# Then try to directly find a repository with the same name as the
# repository in which the commit exists.
potential_fork_nwo = "#{@user[:login]}/#{@repo[:name]}"
begin
potential_fork = @client.repository potential_fork_nwo
if potential_fork[:fork]
return true if potential_fork[:parent][:full_name] == @repo[:full_name]
end
rescue Octokit::NotFound
# Keep going...
end
# Otherwise, get the user's forks and check the `parent` field of each
# fork to see whether it matches @repo.
@client.auto_paginate = true
@user_repos = @client.repos
@user_forks = @user_repos.select { |r| r[:fork] }
@user_forks.each do |f|
r = @client.repository f[:full_name]
if r[:parent][:full_name] == @repo[:full_name]
@client.auto_paginate = false
return true
end
end
@client.auto_paginate = false
false
end
|
ruby
|
def user_has_fork_of_repo?
# The API doesn't provide a simple means of checking whether a user has
# forked a repository.
# First, if there are no forks for the repository, return false.
return false if @repo[:forks_count] == 0
# Then check whether it's worth getting the list of forks
if @repo[:forks_count] <= 100
repo_forks = @client.forks @repo[:full_name], :per_page => 100
repo_forks.each do |f|
return true if f[:owner][:login] == @user[:login]
end
end
# Then try to directly find a repository with the same name as the
# repository in which the commit exists.
potential_fork_nwo = "#{@user[:login]}/#{@repo[:name]}"
begin
potential_fork = @client.repository potential_fork_nwo
if potential_fork[:fork]
return true if potential_fork[:parent][:full_name] == @repo[:full_name]
end
rescue Octokit::NotFound
# Keep going...
end
# Otherwise, get the user's forks and check the `parent` field of each
# fork to see whether it matches @repo.
@client.auto_paginate = true
@user_repos = @client.repos
@user_forks = @user_repos.select { |r| r[:fork] }
@user_forks.each do |f|
r = @client.repository f[:full_name]
if r[:parent][:full_name] == @repo[:full_name]
@client.auto_paginate = false
return true
end
end
@client.auto_paginate = false
false
end
|
[
"def",
"user_has_fork_of_repo?",
"# The API doesn't provide a simple means of checking whether a user has",
"# forked a repository.",
"# First, if there are no forks for the repository, return false.",
"return",
"false",
"if",
"@repo",
"[",
":forks_count",
"]",
"==",
"0",
"# Then check whether it's worth getting the list of forks",
"if",
"@repo",
"[",
":forks_count",
"]",
"<=",
"100",
"repo_forks",
"=",
"@client",
".",
"forks",
"@repo",
"[",
":full_name",
"]",
",",
":per_page",
"=>",
"100",
"repo_forks",
".",
"each",
"do",
"|",
"f",
"|",
"return",
"true",
"if",
"f",
"[",
":owner",
"]",
"[",
":login",
"]",
"==",
"@user",
"[",
":login",
"]",
"end",
"end",
"# Then try to directly find a repository with the same name as the",
"# repository in which the commit exists.",
"potential_fork_nwo",
"=",
"\"#{@user[:login]}/#{@repo[:name]}\"",
"begin",
"potential_fork",
"=",
"@client",
".",
"repository",
"potential_fork_nwo",
"if",
"potential_fork",
"[",
":fork",
"]",
"return",
"true",
"if",
"potential_fork",
"[",
":parent",
"]",
"[",
":full_name",
"]",
"==",
"@repo",
"[",
":full_name",
"]",
"end",
"rescue",
"Octokit",
"::",
"NotFound",
"# Keep going...",
"end",
"# Otherwise, get the user's forks and check the `parent` field of each",
"# fork to see whether it matches @repo.",
"@client",
".",
"auto_paginate",
"=",
"true",
"@user_repos",
"=",
"@client",
".",
"repos",
"@user_forks",
"=",
"@user_repos",
".",
"select",
"{",
"|",
"r",
"|",
"r",
"[",
":fork",
"]",
"}",
"@user_forks",
".",
"each",
"do",
"|",
"f",
"|",
"r",
"=",
"@client",
".",
"repository",
"f",
"[",
":full_name",
"]",
"if",
"r",
"[",
":parent",
"]",
"[",
":full_name",
"]",
"==",
"@repo",
"[",
":full_name",
"]",
"@client",
".",
"auto_paginate",
"=",
"false",
"return",
"true",
"end",
"end",
"@client",
".",
"auto_paginate",
"=",
"false",
"false",
"end"
] |
Checks whether the authenticated user has forked the repository in which
the commit exists.
@return [Boolean]
|
[
"Checks",
"whether",
"the",
"authenticated",
"user",
"has",
"forked",
"the",
"repository",
"in",
"which",
"the",
"commit",
"exists",
"."
] |
1370314972a404642321b19cc1c5e0d99d54dfc6
|
https://github.com/jdennes/contribution-checker/blob/1370314972a404642321b19cc1c5e0d99d54dfc6/lib/contribution-checker/checker.rb#L202-L243
|
21,665 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/encoder.rb
|
Phidgets.Encoder.on_input_change
|
def on_input_change(obj=nil, &block)
@on_input_change_obj = obj
@on_input_change = Proc.new { |device, obj_ptr, index, state|
yield self, @inputs[index], (state == 0 ? false : true), object_for(obj_ptr)
}
Klass.set_OnInputChange_Handler(@handle, @on_input_change, pointer_for(obj))
end
|
ruby
|
def on_input_change(obj=nil, &block)
@on_input_change_obj = obj
@on_input_change = Proc.new { |device, obj_ptr, index, state|
yield self, @inputs[index], (state == 0 ? false : true), object_for(obj_ptr)
}
Klass.set_OnInputChange_Handler(@handle, @on_input_change, pointer_for(obj))
end
|
[
"def",
"on_input_change",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_input_change_obj",
"=",
"obj",
"@on_input_change",
"=",
"Proc",
".",
"new",
"{",
"|",
"device",
",",
"obj_ptr",
",",
"index",
",",
"state",
"|",
"yield",
"self",
",",
"@inputs",
"[",
"index",
"]",
",",
"(",
"state",
"==",
"0",
"?",
"false",
":",
"true",
")",
",",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Klass",
".",
"set_OnInputChange_Handler",
"(",
"@handle",
",",
"@on_input_change",
",",
"pointer_for",
"(",
"obj",
")",
")",
"end"
] |
Sets an input change handler callback function. This is called when a digital input on the PhidgetEncoder board has changed.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
en.on_input_change do |device, input, state, obj|
print "Digital Input #{input.index}, changed to #{state}\n"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"an",
"input",
"change",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"a",
"digital",
"input",
"on",
"the",
"PhidgetEncoder",
"board",
"has",
"changed",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/encoder.rb#L37-L43
|
21,666 |
elektronaut/dynamic_image
|
lib/dynamic_image/image_sizing.rb
|
DynamicImage.ImageSizing.crop_geometry
|
def crop_geometry(ratio_vector)
# Maximize the crop area to fit the image size
crop_size = ratio_vector.fit(size).round
# Ignore pixels outside the pre-cropped area for now
center = crop_gravity - crop_start
start = center - (crop_size / 2).floor
start = clamp(start, crop_size, size)
[crop_size, (start + crop_start)]
end
|
ruby
|
def crop_geometry(ratio_vector)
# Maximize the crop area to fit the image size
crop_size = ratio_vector.fit(size).round
# Ignore pixels outside the pre-cropped area for now
center = crop_gravity - crop_start
start = center - (crop_size / 2).floor
start = clamp(start, crop_size, size)
[crop_size, (start + crop_start)]
end
|
[
"def",
"crop_geometry",
"(",
"ratio_vector",
")",
"# Maximize the crop area to fit the image size",
"crop_size",
"=",
"ratio_vector",
".",
"fit",
"(",
"size",
")",
".",
"round",
"# Ignore pixels outside the pre-cropped area for now",
"center",
"=",
"crop_gravity",
"-",
"crop_start",
"start",
"=",
"center",
"-",
"(",
"crop_size",
"/",
"2",
")",
".",
"floor",
"start",
"=",
"clamp",
"(",
"start",
",",
"crop_size",
",",
"size",
")",
"[",
"crop_size",
",",
"(",
"start",
"+",
"crop_start",
")",
"]",
"end"
] |
Calculates crop geometry. The given vector is scaled
to match the image size, since DynamicImage performs
cropping before resizing.
==== Example
image = Image.find(params[:id]) # 320x200 image
sizing = DynamicImage::ImageSizing.new(image)
sizing.crop_geometry(Vector2d(100, 100))
# => [Vector2d(200, 200), Vector2d(60, 0)]
Returns a tuple with crop size and crop start vectors.
|
[
"Calculates",
"crop",
"geometry",
".",
"The",
"given",
"vector",
"is",
"scaled",
"to",
"match",
"the",
"image",
"size",
"since",
"DynamicImage",
"performs",
"cropping",
"before",
"resizing",
"."
] |
d711f8f5d8385fb36d7ff9a6012f3fd123005c18
|
https://github.com/elektronaut/dynamic_image/blob/d711f8f5d8385fb36d7ff9a6012f3fd123005c18/lib/dynamic_image/image_sizing.rb#L26-L37
|
21,667 |
elektronaut/dynamic_image
|
lib/dynamic_image/image_sizing.rb
|
DynamicImage.ImageSizing.fit
|
def fit(fit_size, options = {})
fit_size = parse_vector(fit_size)
require_dimensions!(fit_size) if options[:crop]
fit_size = size.fit(fit_size) unless options[:crop]
fit_size = size.contain(fit_size) unless options[:upscale]
fit_size
end
|
ruby
|
def fit(fit_size, options = {})
fit_size = parse_vector(fit_size)
require_dimensions!(fit_size) if options[:crop]
fit_size = size.fit(fit_size) unless options[:crop]
fit_size = size.contain(fit_size) unless options[:upscale]
fit_size
end
|
[
"def",
"fit",
"(",
"fit_size",
",",
"options",
"=",
"{",
"}",
")",
"fit_size",
"=",
"parse_vector",
"(",
"fit_size",
")",
"require_dimensions!",
"(",
"fit_size",
")",
"if",
"options",
"[",
":crop",
"]",
"fit_size",
"=",
"size",
".",
"fit",
"(",
"fit_size",
")",
"unless",
"options",
"[",
":crop",
"]",
"fit_size",
"=",
"size",
".",
"contain",
"(",
"fit_size",
")",
"unless",
"options",
"[",
":upscale",
"]",
"fit_size",
"end"
] |
Adjusts +fit_size+ to fit the image dimensions.
Any dimension set to zero will be ignored.
==== Options
* <tt>:crop</tt> - Don't keep aspect ratio. This will allow
the image to be cropped to the requested size.
* <tt>:upscale</tt> - Don't limit to the size of the image.
Images smaller than the given size will be scaled up.
==== Examples
image = Image.find(params[:id]) # 320x200 image
sizing = DynamicImage::ImageSizing.new(image)
sizing.fit(Vector2d(0, 100))
# => Vector2d(160.0, 100.0)
sizing.fit(Vector2d(500, 500))
# => Vector2d(320.0, 200.0)
sizing.fit(Vector2d(500, 500), crop: true)
# => Vector2d(200.0, 200.0)
sizing.fit(Vector2d(500, 500), upscale: true)
# => Vector2d(500.0, 312.5)
|
[
"Adjusts",
"+",
"fit_size",
"+",
"to",
"fit",
"the",
"image",
"dimensions",
".",
"Any",
"dimension",
"set",
"to",
"zero",
"will",
"be",
"ignored",
"."
] |
d711f8f5d8385fb36d7ff9a6012f3fd123005c18
|
https://github.com/elektronaut/dynamic_image/blob/d711f8f5d8385fb36d7ff9a6012f3fd123005c18/lib/dynamic_image/image_sizing.rb#L79-L85
|
21,668 |
elektronaut/dynamic_image
|
lib/dynamic_image/image_sizing.rb
|
DynamicImage.ImageSizing.clamp
|
def clamp(start, size, max_size)
start += shift_vector(start)
start -= shift_vector(max_size - (start + size))
start
end
|
ruby
|
def clamp(start, size, max_size)
start += shift_vector(start)
start -= shift_vector(max_size - (start + size))
start
end
|
[
"def",
"clamp",
"(",
"start",
",",
"size",
",",
"max_size",
")",
"start",
"+=",
"shift_vector",
"(",
"start",
")",
"start",
"-=",
"shift_vector",
"(",
"max_size",
"-",
"(",
"start",
"+",
"size",
")",
")",
"start",
"end"
] |
Clamps the rectangle defined by +start+ and +size+
to fit inside 0, 0 and +max_size+. It is assumed
that +size+ will always be smaller than +max_size+.
Returns the start vector.
|
[
"Clamps",
"the",
"rectangle",
"defined",
"by",
"+",
"start",
"+",
"and",
"+",
"size",
"+",
"to",
"fit",
"inside",
"0",
"0",
"and",
"+",
"max_size",
"+",
".",
"It",
"is",
"assumed",
"that",
"+",
"size",
"+",
"will",
"always",
"be",
"smaller",
"than",
"+",
"max_size",
"+",
"."
] |
d711f8f5d8385fb36d7ff9a6012f3fd123005c18
|
https://github.com/elektronaut/dynamic_image/blob/d711f8f5d8385fb36d7ff9a6012f3fd123005c18/lib/dynamic_image/image_sizing.rb#L118-L122
|
21,669 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/frequency_counter.rb
|
Phidgets.FrequencyCounter.on_count
|
def on_count(obj=nil, &block)
@on_count_obj = obj
@on_count = Proc.new { |device, obj_ptr, index, time, counts|
yield self, @inputs[index], time, counts, object_for(obj_ptr)
}
Klass.set_OnCount_Handler(@handle, @on_count, pointer_for(obj))
end
|
ruby
|
def on_count(obj=nil, &block)
@on_count_obj = obj
@on_count = Proc.new { |device, obj_ptr, index, time, counts|
yield self, @inputs[index], time, counts, object_for(obj_ptr)
}
Klass.set_OnCount_Handler(@handle, @on_count, pointer_for(obj))
end
|
[
"def",
"on_count",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_count_obj",
"=",
"obj",
"@on_count",
"=",
"Proc",
".",
"new",
"{",
"|",
"device",
",",
"obj_ptr",
",",
"index",
",",
"time",
",",
"counts",
"|",
"yield",
"self",
",",
"@inputs",
"[",
"index",
"]",
",",
"time",
",",
"counts",
",",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Klass",
".",
"set_OnCount_Handler",
"(",
"@handle",
",",
"@on_count",
",",
"pointer_for",
"(",
"obj",
")",
")",
"end"
] |
Sets an count handler callback function. This is called when ticks are counted on an frequency counter input, or when the timeout expires
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
fc.on_count do |device, input, time, count, obj|
puts "Channel #{input.index}: #{count} pulses in #{time} microseconds"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"an",
"count",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"ticks",
"are",
"counted",
"on",
"an",
"frequency",
"counter",
"input",
"or",
"when",
"the",
"timeout",
"expires"
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/frequency_counter.rb#L32-L38
|
21,670 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/common.rb
|
Phidgets.Common.create
|
def create
ptr = ::FFI::MemoryPointer.new(:pointer, 1)
self.class::Klass.create(ptr)
@handle = ptr.get_pointer(0)
true
end
|
ruby
|
def create
ptr = ::FFI::MemoryPointer.new(:pointer, 1)
self.class::Klass.create(ptr)
@handle = ptr.get_pointer(0)
true
end
|
[
"def",
"create",
"ptr",
"=",
"::",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":pointer",
",",
"1",
")",
"self",
".",
"class",
"::",
"Klass",
".",
"create",
"(",
"ptr",
")",
"@handle",
"=",
"ptr",
".",
"get_pointer",
"(",
"0",
")",
"true",
"end"
] |
Create a pointer for this Device handle .. must be called before open or anything else.
Called automatically when objects are instantiated in block form.
|
[
"Create",
"a",
"pointer",
"for",
"this",
"Device",
"handle",
"..",
"must",
"be",
"called",
"before",
"open",
"or",
"anything",
"else",
".",
"Called",
"automatically",
"when",
"objects",
"are",
"instantiated",
"in",
"block",
"form",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/common.rb#L185-L190
|
21,671 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/common.rb
|
Phidgets.Common.close
|
def close
remove_common_event_handlers
remove_specific_event_handlers
sleep 0.2
Phidgets::FFI::Common.close(@handle)
delete
true
end
|
ruby
|
def close
remove_common_event_handlers
remove_specific_event_handlers
sleep 0.2
Phidgets::FFI::Common.close(@handle)
delete
true
end
|
[
"def",
"close",
"remove_common_event_handlers",
"remove_specific_event_handlers",
"sleep",
"0.2",
"Phidgets",
"::",
"FFI",
"::",
"Common",
".",
"close",
"(",
"@handle",
")",
"delete",
"true",
"end"
] |
Closes and frees a Phidget. This should be called before closing your application or things may not shut down cleanly.
@return [Boolean] returns true or raises an error
|
[
"Closes",
"and",
"frees",
"a",
"Phidget",
".",
"This",
"should",
"be",
"called",
"before",
"closing",
"your",
"application",
"or",
"things",
"may",
"not",
"shut",
"down",
"cleanly",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/common.rb#L253-L260
|
21,672 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/common.rb
|
Phidgets.Common.on_attach
|
def on_attach(obj=nil, &block)
@on_attach_obj = obj
@on_attach = Proc.new { |handle, obj_ptr|
load_device_attributes
yield self, object_for(obj_ptr)
}
Phidgets::FFI::Common.set_OnAttach_Handler(@handle, @on_attach, pointer_for(obj))
true
end
|
ruby
|
def on_attach(obj=nil, &block)
@on_attach_obj = obj
@on_attach = Proc.new { |handle, obj_ptr|
load_device_attributes
yield self, object_for(obj_ptr)
}
Phidgets::FFI::Common.set_OnAttach_Handler(@handle, @on_attach, pointer_for(obj))
true
end
|
[
"def",
"on_attach",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_attach_obj",
"=",
"obj",
"@on_attach",
"=",
"Proc",
".",
"new",
"{",
"|",
"handle",
",",
"obj_ptr",
"|",
"load_device_attributes",
"yield",
"self",
",",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Phidgets",
"::",
"FFI",
"::",
"Common",
".",
"set_OnAttach_Handler",
"(",
"@handle",
",",
"@on_attach",
",",
"pointer_for",
"(",
"obj",
")",
")",
"true",
"end"
] |
Sets an attach handler callback function. This is called when the Phidget is plugged into the system, and is ready for use.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
ifkit.on_attach do |device, obj|
puts "InterfaceKit attached #{device.attributes.inspect}"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"an",
"attach",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"the",
"Phidget",
"is",
"plugged",
"into",
"the",
"system",
"and",
"is",
"ready",
"for",
"use",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/common.rb#L364-L372
|
21,673 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/common.rb
|
Phidgets.Common.on_detach
|
def on_detach(obj=nil, &block)
@on_detach_obj = obj
@on_detach = Proc.new { |handle, obj_ptr|
yield self, object_for(obj_ptr)
}
Phidgets::FFI::Common.set_OnDetach_Handler(@handle, @on_detach, pointer_for(obj))
true
end
|
ruby
|
def on_detach(obj=nil, &block)
@on_detach_obj = obj
@on_detach = Proc.new { |handle, obj_ptr|
yield self, object_for(obj_ptr)
}
Phidgets::FFI::Common.set_OnDetach_Handler(@handle, @on_detach, pointer_for(obj))
true
end
|
[
"def",
"on_detach",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_detach_obj",
"=",
"obj",
"@on_detach",
"=",
"Proc",
".",
"new",
"{",
"|",
"handle",
",",
"obj_ptr",
"|",
"yield",
"self",
",",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Phidgets",
"::",
"FFI",
"::",
"Common",
".",
"set_OnDetach_Handler",
"(",
"@handle",
",",
"@on_detach",
",",
"pointer_for",
"(",
"obj",
")",
")",
"true",
"end"
] |
Sets a detach handler callback function. This is called when the Phidget is physically detached from the system, and is no longer available.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
ifkit.on_detach do |device, obj|
puts "InterfaceKit detached #{device.attributes.inspect}"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"a",
"detach",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"the",
"Phidget",
"is",
"physically",
"detached",
"from",
"the",
"system",
"and",
"is",
"no",
"longer",
"available",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/common.rb#L384-L391
|
21,674 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/common.rb
|
Phidgets.Common.on_error
|
def on_error(obj=nil, &block)
@on_error_obj = obj
@on_error = Proc.new { |handle, obj_ptr, code, description|
yield self, object_for(obj_ptr), code, description
}
Phidgets::FFI::Common.set_OnError_Handler(@handle, @on_error, pointer_for(obj))
true
end
|
ruby
|
def on_error(obj=nil, &block)
@on_error_obj = obj
@on_error = Proc.new { |handle, obj_ptr, code, description|
yield self, object_for(obj_ptr), code, description
}
Phidgets::FFI::Common.set_OnError_Handler(@handle, @on_error, pointer_for(obj))
true
end
|
[
"def",
"on_error",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_error_obj",
"=",
"obj",
"@on_error",
"=",
"Proc",
".",
"new",
"{",
"|",
"handle",
",",
"obj_ptr",
",",
"code",
",",
"description",
"|",
"yield",
"self",
",",
"object_for",
"(",
"obj_ptr",
")",
",",
"code",
",",
"description",
"}",
"Phidgets",
"::",
"FFI",
"::",
"Common",
".",
"set_OnError_Handler",
"(",
"@handle",
",",
"@on_error",
",",
"pointer_for",
"(",
"obj",
")",
")",
"true",
"end"
] |
Sets an error handler callback function. This is called when an asynchronous error occurs. This is generally used for network errors, and device hardware error messages.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
ifkit.on_error do |device, obj, code, description|
puts "Error - code #{code}, description #{description}"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"an",
"error",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"an",
"asynchronous",
"error",
"occurs",
".",
"This",
"is",
"generally",
"used",
"for",
"network",
"errors",
"and",
"device",
"hardware",
"error",
"messages",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/common.rb#L403-L410
|
21,675 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/common.rb
|
Phidgets.Common.on_server_connect
|
def on_server_connect(obj=nil, &block)
@on_server_connect_obj = obj
@on_server_connect = Proc.new { |handle, obj_ptr|
yield self, object_for(obj_ptr)
}
Phidgets::FFI::Common.set_OnServerConnect_Handler(@handle, @on_server_connect, pointer_for(obj))
true
end
|
ruby
|
def on_server_connect(obj=nil, &block)
@on_server_connect_obj = obj
@on_server_connect = Proc.new { |handle, obj_ptr|
yield self, object_for(obj_ptr)
}
Phidgets::FFI::Common.set_OnServerConnect_Handler(@handle, @on_server_connect, pointer_for(obj))
true
end
|
[
"def",
"on_server_connect",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_server_connect_obj",
"=",
"obj",
"@on_server_connect",
"=",
"Proc",
".",
"new",
"{",
"|",
"handle",
",",
"obj_ptr",
"|",
"yield",
"self",
",",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Phidgets",
"::",
"FFI",
"::",
"Common",
".",
"set_OnServerConnect_Handler",
"(",
"@handle",
",",
"@on_server_connect",
",",
"pointer_for",
"(",
"obj",
")",
")",
"true",
"end"
] |
Sets a server connect handler callback function. This is called for network opened Phidgets when a connection to the PhidgetWebService has been established.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
ifkit.on_server_connect do |device, obj|
puts "Server connect #{device.attributes.inspect}"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"a",
"server",
"connect",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"for",
"network",
"opened",
"Phidgets",
"when",
"a",
"connection",
"to",
"the",
"PhidgetWebService",
"has",
"been",
"established",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/common.rb#L422-L429
|
21,676 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/common.rb
|
Phidgets.Common.on_sleep
|
def on_sleep(obj=nil, &block)
@on_sleep_obj = obj
@on_sleep = Proc.new { |obj_ptr|
yield object_for(obj_ptr)
}
Phidgets::FFI::Common.set_OnWillSleep_Handler(@on_sleep, pointer_for(obj))
true
end
|
ruby
|
def on_sleep(obj=nil, &block)
@on_sleep_obj = obj
@on_sleep = Proc.new { |obj_ptr|
yield object_for(obj_ptr)
}
Phidgets::FFI::Common.set_OnWillSleep_Handler(@on_sleep, pointer_for(obj))
true
end
|
[
"def",
"on_sleep",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_sleep_obj",
"=",
"obj",
"@on_sleep",
"=",
"Proc",
".",
"new",
"{",
"|",
"obj_ptr",
"|",
"yield",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Phidgets",
"::",
"FFI",
"::",
"Common",
".",
"set_OnWillSleep_Handler",
"(",
"@on_sleep",
",",
"pointer_for",
"(",
"obj",
")",
")",
"true",
"end"
] |
Sets a sleep handler callback function. This is called when the MacOS X is entering sleep mode.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
ifkit.on_sleep do |obj|
puts "System sleeping"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
@note Used only in Mac OS X
|
[
"Sets",
"a",
"sleep",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"the",
"MacOS",
"X",
"is",
"entering",
"sleep",
"mode",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/common.rb#L461-L469
|
21,677 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/common.rb
|
Phidgets.Common.on_wake
|
def on_wake(obj=nil, &block)
@on_wake_obj = obj
@on_wake = Proc.new { |obj_ptr|
yield object_for(obj_ptr)
}
Phidgets::FFI::Common.set_OnWakeup_Handler(@on_wake, pointer_for(obj))
true
end
|
ruby
|
def on_wake(obj=nil, &block)
@on_wake_obj = obj
@on_wake = Proc.new { |obj_ptr|
yield object_for(obj_ptr)
}
Phidgets::FFI::Common.set_OnWakeup_Handler(@on_wake, pointer_for(obj))
true
end
|
[
"def",
"on_wake",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_wake_obj",
"=",
"obj",
"@on_wake",
"=",
"Proc",
".",
"new",
"{",
"|",
"obj_ptr",
"|",
"yield",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Phidgets",
"::",
"FFI",
"::",
"Common",
".",
"set_OnWakeup_Handler",
"(",
"@on_wake",
",",
"pointer_for",
"(",
"obj",
")",
")",
"true",
"end"
] |
Sets a wake callback function. This is called when the MacOS X is waking up from sleep mode.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
ifkit.on_wake do |obj|
puts "System waking up"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
@note Used only in Mac OS X
|
[
"Sets",
"a",
"wake",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"the",
"MacOS",
"X",
"is",
"waking",
"up",
"from",
"sleep",
"mode",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/common.rb#L482-L489
|
21,678 |
elektronaut/dynamic_image
|
lib/dynamic_image/routing.rb
|
DynamicImage.Routing.image_resources
|
def image_resources(resource_name, options = {})
options = {
path: "#{resource_name}/:digest(/:size)",
constraints: { size: /\d+x\d+/ },
only: [:show]
}.merge(options)
resources resource_name, options do
get :uncropped, on: :member
get :original, on: :member
get :download, on: :member
end
end
|
ruby
|
def image_resources(resource_name, options = {})
options = {
path: "#{resource_name}/:digest(/:size)",
constraints: { size: /\d+x\d+/ },
only: [:show]
}.merge(options)
resources resource_name, options do
get :uncropped, on: :member
get :original, on: :member
get :download, on: :member
end
end
|
[
"def",
"image_resources",
"(",
"resource_name",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"path",
":",
"\"#{resource_name}/:digest(/:size)\"",
",",
"constraints",
":",
"{",
"size",
":",
"/",
"\\d",
"\\d",
"/",
"}",
",",
"only",
":",
"[",
":show",
"]",
"}",
".",
"merge",
"(",
"options",
")",
"resources",
"resource_name",
",",
"options",
"do",
"get",
":uncropped",
",",
"on",
":",
":member",
"get",
":original",
",",
"on",
":",
":member",
"get",
":download",
",",
"on",
":",
":member",
"end",
"end"
] |
Declares an image resource.
image_resources :avatars
|
[
"Declares",
"an",
"image",
"resource",
"."
] |
d711f8f5d8385fb36d7ff9a6012f3fd123005c18
|
https://github.com/elektronaut/dynamic_image/blob/d711f8f5d8385fb36d7ff9a6012f3fd123005c18/lib/dynamic_image/routing.rb#L12-L23
|
21,679 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/manager.rb
|
Phidgets.Manager.on_attach
|
def on_attach(obj=nil, &block)
@on_attach_obj = obj
@on_attach = Proc.new { |handle, obj_ptr|
yield handle, object_for(obj_ptr)
}
Klass.set_OnAttach_Handler(@handle, @on_attach, pointer_for(obj))
end
|
ruby
|
def on_attach(obj=nil, &block)
@on_attach_obj = obj
@on_attach = Proc.new { |handle, obj_ptr|
yield handle, object_for(obj_ptr)
}
Klass.set_OnAttach_Handler(@handle, @on_attach, pointer_for(obj))
end
|
[
"def",
"on_attach",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_attach_obj",
"=",
"obj",
"@on_attach",
"=",
"Proc",
".",
"new",
"{",
"|",
"handle",
",",
"obj_ptr",
"|",
"yield",
"handle",
",",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Klass",
".",
"set_OnAttach_Handler",
"(",
"@handle",
",",
"@on_attach",
",",
"pointer_for",
"(",
"obj",
")",
")",
"end"
] |
Sets an attach handler callback function. This is called when a Phidget is plugged into the system.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
manager.on_attach do |device_ptr, obj|
puts "Attaching #{Phidgets::Common.name(device_ptr)}"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"an",
"attach",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"a",
"Phidget",
"is",
"plugged",
"into",
"the",
"system",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/manager.rb#L137-L143
|
21,680 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/manager.rb
|
Phidgets.Manager.on_detach
|
def on_detach(obj=nil, &block)
@on_detach_obj = obj
@on_detach = Proc.new { |handle, obj_ptr|
yield handle, object_for(obj_ptr)
}
Klass.set_OnDetach_Handler(@handle, @on_detach, pointer_for(obj))
end
|
ruby
|
def on_detach(obj=nil, &block)
@on_detach_obj = obj
@on_detach = Proc.new { |handle, obj_ptr|
yield handle, object_for(obj_ptr)
}
Klass.set_OnDetach_Handler(@handle, @on_detach, pointer_for(obj))
end
|
[
"def",
"on_detach",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_detach_obj",
"=",
"obj",
"@on_detach",
"=",
"Proc",
".",
"new",
"{",
"|",
"handle",
",",
"obj_ptr",
"|",
"yield",
"handle",
",",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Klass",
".",
"set_OnDetach_Handler",
"(",
"@handle",
",",
"@on_detach",
",",
"pointer_for",
"(",
"obj",
")",
")",
"end"
] |
Sets a detach handler callback function. This is called when a Phidget is unplugged from the system.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
manager.on_detach do |device_ptr, obj|
puts "Detaching #{Phidgets::Common.name(device_ptr)}"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"a",
"detach",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"a",
"Phidget",
"is",
"unplugged",
"from",
"the",
"system",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/manager.rb#L155-L161
|
21,681 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/manager.rb
|
Phidgets.Manager.on_server_connect
|
def on_server_connect(obj=nil, &block)
@on_server_connect_obj = obj
@on_server_connect = Proc.new { |handle, obj_ptr|
yield self, object_for(obj_pointer)
}
Klass.set_OnServerConnect_Handler(@handle, @on_server_connect, pointer_for(obj))
end
|
ruby
|
def on_server_connect(obj=nil, &block)
@on_server_connect_obj = obj
@on_server_connect = Proc.new { |handle, obj_ptr|
yield self, object_for(obj_pointer)
}
Klass.set_OnServerConnect_Handler(@handle, @on_server_connect, pointer_for(obj))
end
|
[
"def",
"on_server_connect",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_server_connect_obj",
"=",
"obj",
"@on_server_connect",
"=",
"Proc",
".",
"new",
"{",
"|",
"handle",
",",
"obj_ptr",
"|",
"yield",
"self",
",",
"object_for",
"(",
"obj_pointer",
")",
"}",
"Klass",
".",
"set_OnServerConnect_Handler",
"(",
"@handle",
",",
"@on_server_connect",
",",
"pointer_for",
"(",
"obj",
")",
")",
"end"
] |
Sets a server connect handler callback function. This is used for opening the PhidgetManager remotely, and is called when a connection to the server has been made.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
manager.on_server_connect do |obj|
puts 'Connected'
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"a",
"server",
"connect",
"handler",
"callback",
"function",
".",
"This",
"is",
"used",
"for",
"opening",
"the",
"PhidgetManager",
"remotely",
"and",
"is",
"called",
"when",
"a",
"connection",
"to",
"the",
"server",
"has",
"been",
"made",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/manager.rb#L173-L179
|
21,682 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/manager.rb
|
Phidgets.Manager.on_server_disconnect
|
def on_server_disconnect(obj=nil, &block)
@on_server_disconnect_obj = obj
@on_server_disconnect = Proc.new { |handle, obj_ptr|
yield self, object_for(obj_ptr)
}
Klass.set_OnServerDisconnect_Handler(@handle, @on_server_disconnect, pointer_for(obj))
end
|
ruby
|
def on_server_disconnect(obj=nil, &block)
@on_server_disconnect_obj = obj
@on_server_disconnect = Proc.new { |handle, obj_ptr|
yield self, object_for(obj_ptr)
}
Klass.set_OnServerDisconnect_Handler(@handle, @on_server_disconnect, pointer_for(obj))
end
|
[
"def",
"on_server_disconnect",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_server_disconnect_obj",
"=",
"obj",
"@on_server_disconnect",
"=",
"Proc",
".",
"new",
"{",
"|",
"handle",
",",
"obj_ptr",
"|",
"yield",
"self",
",",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Klass",
".",
"set_OnServerDisconnect_Handler",
"(",
"@handle",
",",
"@on_server_disconnect",
",",
"pointer_for",
"(",
"obj",
")",
")",
"end"
] |
Sets a server disconnect handler callback function. This is used for opening the PhidgetManager remotely, and is called when a connection to the server has been lost
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
manager.on_server_disconnect do |obj|
puts 'Disconnected'
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"a",
"server",
"disconnect",
"handler",
"callback",
"function",
".",
"This",
"is",
"used",
"for",
"opening",
"the",
"PhidgetManager",
"remotely",
"and",
"is",
"called",
"when",
"a",
"connection",
"to",
"the",
"server",
"has",
"been",
"lost"
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/manager.rb#L191-L197
|
21,683 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/manager.rb
|
Phidgets.Manager.on_error
|
def on_error(obj=nil, &block)
@on_error_obj = obj
@on_error = Proc.new { |handle, obj_ptr, code, description|
yield self, object_for(obj_ptr), code, description
}
Klass.set_OnError_Handler(@handle, @on_error, pointer_for(obj))
end
|
ruby
|
def on_error(obj=nil, &block)
@on_error_obj = obj
@on_error = Proc.new { |handle, obj_ptr, code, description|
yield self, object_for(obj_ptr), code, description
}
Klass.set_OnError_Handler(@handle, @on_error, pointer_for(obj))
end
|
[
"def",
"on_error",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_error_obj",
"=",
"obj",
"@on_error",
"=",
"Proc",
".",
"new",
"{",
"|",
"handle",
",",
"obj_ptr",
",",
"code",
",",
"description",
"|",
"yield",
"self",
",",
"object_for",
"(",
"obj_ptr",
")",
",",
"code",
",",
"description",
"}",
"Klass",
".",
"set_OnError_Handler",
"(",
"@handle",
",",
"@on_error",
",",
"pointer_for",
"(",
"obj",
")",
")",
"end"
] |
Sets a error handler callback function. This is called when an asynchronous error occurs.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
manager.on_error do |obj|
puts "Error (#{code}): #{reason}"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"a",
"error",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"an",
"asynchronous",
"error",
"occurs",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/manager.rb#L209-L215
|
21,684 |
activenetwork-automation/vcoworkflows
|
lib/vcoworkflows/runner.rb
|
VcoWorkflows.Runner.execute!
|
def execute!
exit_code = begin
# Thor accesses these streams directly rather than letting them be
# injected, so we replace them...
$stderr = @stderr
$stdin = @stdin
$stdout = @stdout
VcoWorkflows::CLI.start(@argv)
# Thor::Base#start does not have a return value, assume success if no
# exception is raised.
0
rescue StandardError => e
# The ruby interpreter would pipe this to STDERR and exit 1 in the
# case of an unhandled exception
b = e.backtrace
b.unshift("#{b.shift}: #{e.message} (#{e.class})")
@stderr.puts(b.map { |s| "\tfrom #{s}" }.join("\n"))
1
ensure
# put them back.
$stderr = STDERR
$stdin = STDIN
$stdout = STDOUT
end
# Proxy exit code back to the injected kernel.
@kernel.exit(exit_code)
end
|
ruby
|
def execute!
exit_code = begin
# Thor accesses these streams directly rather than letting them be
# injected, so we replace them...
$stderr = @stderr
$stdin = @stdin
$stdout = @stdout
VcoWorkflows::CLI.start(@argv)
# Thor::Base#start does not have a return value, assume success if no
# exception is raised.
0
rescue StandardError => e
# The ruby interpreter would pipe this to STDERR and exit 1 in the
# case of an unhandled exception
b = e.backtrace
b.unshift("#{b.shift}: #{e.message} (#{e.class})")
@stderr.puts(b.map { |s| "\tfrom #{s}" }.join("\n"))
1
ensure
# put them back.
$stderr = STDERR
$stdin = STDIN
$stdout = STDOUT
end
# Proxy exit code back to the injected kernel.
@kernel.exit(exit_code)
end
|
[
"def",
"execute!",
"exit_code",
"=",
"begin",
"# Thor accesses these streams directly rather than letting them be",
"# injected, so we replace them...",
"$stderr",
"=",
"@stderr",
"$stdin",
"=",
"@stdin",
"$stdout",
"=",
"@stdout",
"VcoWorkflows",
"::",
"CLI",
".",
"start",
"(",
"@argv",
")",
"# Thor::Base#start does not have a return value, assume success if no",
"# exception is raised.",
"0",
"rescue",
"StandardError",
"=>",
"e",
"# The ruby interpreter would pipe this to STDERR and exit 1 in the",
"# case of an unhandled exception",
"b",
"=",
"e",
".",
"backtrace",
"b",
".",
"unshift",
"(",
"\"#{b.shift}: #{e.message} (#{e.class})\"",
")",
"@stderr",
".",
"puts",
"(",
"b",
".",
"map",
"{",
"|",
"s",
"|",
"\"\\tfrom #{s}\"",
"}",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"1",
"ensure",
"# put them back.",
"$stderr",
"=",
"STDERR",
"$stdin",
"=",
"STDIN",
"$stdout",
"=",
"STDOUT",
"end",
"# Proxy exit code back to the injected kernel.",
"@kernel",
".",
"exit",
"(",
"exit_code",
")",
"end"
] |
Allow everything fun to be injected from the outside while defaulting to normal implementations.
Do the things!
|
[
"Allow",
"everything",
"fun",
"to",
"be",
"injected",
"from",
"the",
"outside",
"while",
"defaulting",
"to",
"normal",
"implementations",
".",
"Do",
"the",
"things!"
] |
01db57318c14e572dc47261f55c8d08341306642
|
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/runner.rb#L13-L41
|
21,685 |
activenetwork-automation/vcoworkflows
|
lib/vcoworkflows/workflowservice.rb
|
VcoWorkflows.WorkflowService.get_workflow_for_name
|
def get_workflow_for_name(name)
path = "/workflows?conditions=name=#{url_encode(name)}"
response = JSON.parse(@session.get(path).body)
# barf if we got anything other than a single workflow
fail(IOError, ERR[:too_many_workflows]) if response['total'] > 1
fail(IOError, ERR[:no_workflow_found]) if response['total'] == 0
# yank out the workflow id and name from the result attributes
workflow_id = nil
response['link'][0]['attributes'].each do |a|
workflow_id = a['value'] if a['name'].eql?('id')
end
# Get the workflow by GUID
get_workflow_for_id(workflow_id)
end
|
ruby
|
def get_workflow_for_name(name)
path = "/workflows?conditions=name=#{url_encode(name)}"
response = JSON.parse(@session.get(path).body)
# barf if we got anything other than a single workflow
fail(IOError, ERR[:too_many_workflows]) if response['total'] > 1
fail(IOError, ERR[:no_workflow_found]) if response['total'] == 0
# yank out the workflow id and name from the result attributes
workflow_id = nil
response['link'][0]['attributes'].each do |a|
workflow_id = a['value'] if a['name'].eql?('id')
end
# Get the workflow by GUID
get_workflow_for_id(workflow_id)
end
|
[
"def",
"get_workflow_for_name",
"(",
"name",
")",
"path",
"=",
"\"/workflows?conditions=name=#{url_encode(name)}\"",
"response",
"=",
"JSON",
".",
"parse",
"(",
"@session",
".",
"get",
"(",
"path",
")",
".",
"body",
")",
"# barf if we got anything other than a single workflow",
"fail",
"(",
"IOError",
",",
"ERR",
"[",
":too_many_workflows",
"]",
")",
"if",
"response",
"[",
"'total'",
"]",
">",
"1",
"fail",
"(",
"IOError",
",",
"ERR",
"[",
":no_workflow_found",
"]",
")",
"if",
"response",
"[",
"'total'",
"]",
"==",
"0",
"# yank out the workflow id and name from the result attributes",
"workflow_id",
"=",
"nil",
"response",
"[",
"'link'",
"]",
"[",
"0",
"]",
"[",
"'attributes'",
"]",
".",
"each",
"do",
"|",
"a",
"|",
"workflow_id",
"=",
"a",
"[",
"'value'",
"]",
"if",
"a",
"[",
"'name'",
"]",
".",
"eql?",
"(",
"'id'",
")",
"end",
"# Get the workflow by GUID",
"get_workflow_for_id",
"(",
"workflow_id",
")",
"end"
] |
Get one workflow with a specified name.
@param [String] name Name of the workflow
@return [String] the JSON document of the requested workflow
|
[
"Get",
"one",
"workflow",
"with",
"a",
"specified",
"name",
"."
] |
01db57318c14e572dc47261f55c8d08341306642
|
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/workflowservice.rb#L43-L59
|
21,686 |
activenetwork-automation/vcoworkflows
|
lib/vcoworkflows/workflowservice.rb
|
VcoWorkflows.WorkflowService.get_execution_list
|
def get_execution_list(workflow_id)
path = "/workflows/#{workflow_id}/executions/"
relations = JSON.parse(@session.get(path).body)['relations']
# The first two elements of the relations['link'] array are URLS,
# so scrap them. Everything else is an execution.
executions = {}
relations['link'].each do |link|
next unless link.key?('attributes')
attributes = {}
link['attributes'].each { |a| attributes[a['name']] = a['value'] }
executions[attributes['id']] = attributes
end
executions
end
|
ruby
|
def get_execution_list(workflow_id)
path = "/workflows/#{workflow_id}/executions/"
relations = JSON.parse(@session.get(path).body)['relations']
# The first two elements of the relations['link'] array are URLS,
# so scrap them. Everything else is an execution.
executions = {}
relations['link'].each do |link|
next unless link.key?('attributes')
attributes = {}
link['attributes'].each { |a| attributes[a['name']] = a['value'] }
executions[attributes['id']] = attributes
end
executions
end
|
[
"def",
"get_execution_list",
"(",
"workflow_id",
")",
"path",
"=",
"\"/workflows/#{workflow_id}/executions/\"",
"relations",
"=",
"JSON",
".",
"parse",
"(",
"@session",
".",
"get",
"(",
"path",
")",
".",
"body",
")",
"[",
"'relations'",
"]",
"# The first two elements of the relations['link'] array are URLS,",
"# so scrap them. Everything else is an execution.",
"executions",
"=",
"{",
"}",
"relations",
"[",
"'link'",
"]",
".",
"each",
"do",
"|",
"link",
"|",
"next",
"unless",
"link",
".",
"key?",
"(",
"'attributes'",
")",
"attributes",
"=",
"{",
"}",
"link",
"[",
"'attributes'",
"]",
".",
"each",
"{",
"|",
"a",
"|",
"attributes",
"[",
"a",
"[",
"'name'",
"]",
"]",
"=",
"a",
"[",
"'value'",
"]",
"}",
"executions",
"[",
"attributes",
"[",
"'id'",
"]",
"]",
"=",
"attributes",
"end",
"executions",
"end"
] |
Get a list of executions for the given workflow GUID
@param [String] workflow_id Workflow GUID
@return [Hash] workflow executions, keyed by execution ID
|
[
"Get",
"a",
"list",
"of",
"executions",
"for",
"the",
"given",
"workflow",
"GUID"
] |
01db57318c14e572dc47261f55c8d08341306642
|
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/workflowservice.rb#L73-L86
|
21,687 |
activenetwork-automation/vcoworkflows
|
lib/vcoworkflows/workflowservice.rb
|
VcoWorkflows.WorkflowService.execute_workflow
|
def execute_workflow(id, parameter_json)
path = "/workflows/#{id}/executions/"
response = @session.post(path, parameter_json)
# Execution ID is the final component in the Location header URL, so
# chop off the front, then pull off any trailing /
response.headers[:location].gsub(%r{^.*/executions/}, '').gsub(%r{\/$}, '')
end
|
ruby
|
def execute_workflow(id, parameter_json)
path = "/workflows/#{id}/executions/"
response = @session.post(path, parameter_json)
# Execution ID is the final component in the Location header URL, so
# chop off the front, then pull off any trailing /
response.headers[:location].gsub(%r{^.*/executions/}, '').gsub(%r{\/$}, '')
end
|
[
"def",
"execute_workflow",
"(",
"id",
",",
"parameter_json",
")",
"path",
"=",
"\"/workflows/#{id}/executions/\"",
"response",
"=",
"@session",
".",
"post",
"(",
"path",
",",
"parameter_json",
")",
"# Execution ID is the final component in the Location header URL, so",
"# chop off the front, then pull off any trailing /",
"response",
".",
"headers",
"[",
":location",
"]",
".",
"gsub",
"(",
"%r{",
"}",
",",
"''",
")",
".",
"gsub",
"(",
"%r{",
"\\/",
"}",
",",
"''",
")",
"end"
] |
Submit the given workflow for execution
@param [String] id Workflow GUID for the workflow we want to execute
@param [String] parameter_json JSON document of input parameters
@return [String] Execution ID
|
[
"Submit",
"the",
"given",
"workflow",
"for",
"execution"
] |
01db57318c14e572dc47261f55c8d08341306642
|
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/workflowservice.rb#L101-L107
|
21,688 |
nwjsmith/thumbtack
|
lib/thumbtack/specification.rb
|
Thumbtack.Specification.parameters
|
def parameters(arguments)
Hash[
arguments.map do |name, value|
type_handler = @type_handlers.fetch(name)
type_handler.validate(value)
[name, type_handler.serialize(value)]
end
]
end
|
ruby
|
def parameters(arguments)
Hash[
arguments.map do |name, value|
type_handler = @type_handlers.fetch(name)
type_handler.validate(value)
[name, type_handler.serialize(value)]
end
]
end
|
[
"def",
"parameters",
"(",
"arguments",
")",
"Hash",
"[",
"arguments",
".",
"map",
"do",
"|",
"name",
",",
"value",
"|",
"type_handler",
"=",
"@type_handlers",
".",
"fetch",
"(",
"name",
")",
"type_handler",
".",
"validate",
"(",
"value",
")",
"[",
"name",
",",
"type_handler",
".",
"serialize",
"(",
"value",
")",
"]",
"end",
"]",
"end"
] |
Initialize a Specification
@param [Hash{Symbol => Type}] type_handlers
a map of parameter names to their type handlers
Validate and translate client parameters to their Pinboard values
@param [Hash{Symbol => Object}] arguments
parameter names associated with their values
@return [Hash{Symbol => Object}]
parameter names associated with translations to their Pinboard values
|
[
"Initialize",
"a",
"Specification"
] |
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
|
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/specification.rb#L24-L32
|
21,689 |
activenetwork-automation/vcoworkflows
|
lib/vcoworkflows/workflowexecutionlog.rb
|
VcoWorkflows.WorkflowExecutionLog.to_s
|
def to_s
message = ''
@messages.keys.sort.each do |timestamp|
message << "#{Time.at(timestamp / 1000)}"
message << " #{@messages[timestamp]['severity']}: #{@messages[timestamp]['user']}:"
message << " #{@messages[timestamp]['short-description']}"
unless @messages[timestamp]['short-description'].eql?(@messages[timestamp]['long-description'])
message << "; #{@messages[timestamp]['long-description']}"
end
message << "\n"
end
message
end
|
ruby
|
def to_s
message = ''
@messages.keys.sort.each do |timestamp|
message << "#{Time.at(timestamp / 1000)}"
message << " #{@messages[timestamp]['severity']}: #{@messages[timestamp]['user']}:"
message << " #{@messages[timestamp]['short-description']}"
unless @messages[timestamp]['short-description'].eql?(@messages[timestamp]['long-description'])
message << "; #{@messages[timestamp]['long-description']}"
end
message << "\n"
end
message
end
|
[
"def",
"to_s",
"message",
"=",
"''",
"@messages",
".",
"keys",
".",
"sort",
".",
"each",
"do",
"|",
"timestamp",
"|",
"message",
"<<",
"\"#{Time.at(timestamp / 1000)}\"",
"message",
"<<",
"\" #{@messages[timestamp]['severity']}: #{@messages[timestamp]['user']}:\"",
"message",
"<<",
"\" #{@messages[timestamp]['short-description']}\"",
"unless",
"@messages",
"[",
"timestamp",
"]",
"[",
"'short-description'",
"]",
".",
"eql?",
"(",
"@messages",
"[",
"timestamp",
"]",
"[",
"'long-description'",
"]",
")",
"message",
"<<",
"\"; #{@messages[timestamp]['long-description']}\"",
"end",
"message",
"<<",
"\"\\n\"",
"end",
"message",
"end"
] |
Create an execution log object
@param [String] log_json JSON document as string
@return [VcoWorkflows::WorkflowExecutionLog]
rubocop:disable MethodLength, LineLength
Stringify the log
@return [String]
|
[
"Create",
"an",
"execution",
"log",
"object"
] |
01db57318c14e572dc47261f55c8d08341306642
|
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/workflowexecutionlog.rb#L27-L39
|
21,690 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/led.rb
|
Phidgets.LED.current_limit=
|
def current_limit=(new_current_limit)
ptr = ::FFI::MemoryPointer.new(:int)
Klass.setCurrentLimit(@handle, Phidgets::FFI::LEDCurrentLimit[new_current_limit])
new_current_limit
end
|
ruby
|
def current_limit=(new_current_limit)
ptr = ::FFI::MemoryPointer.new(:int)
Klass.setCurrentLimit(@handle, Phidgets::FFI::LEDCurrentLimit[new_current_limit])
new_current_limit
end
|
[
"def",
"current_limit",
"=",
"(",
"new_current_limit",
")",
"ptr",
"=",
"::",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":int",
")",
"Klass",
".",
"setCurrentLimit",
"(",
"@handle",
",",
"Phidgets",
"::",
"FFI",
"::",
"LEDCurrentLimit",
"[",
"new_current_limit",
"]",
")",
"new_current_limit",
"end"
] |
Sets the board current limit for all LEDs, or raises an error. Not supported on all PhidgetLEDs.
@param [Phidgets::FFI::LEDCurrentLimit] new_current_limit new current limit
@return [Phidgets::FFI::LEDCurrentLimit] returns the board current limit, or raises an error.
|
[
"Sets",
"the",
"board",
"current",
"limit",
"for",
"all",
"LEDs",
"or",
"raises",
"an",
"error",
".",
"Not",
"supported",
"on",
"all",
"PhidgetLEDs",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/led.rb#L32-L36
|
21,691 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/led.rb
|
Phidgets.LED.voltage=
|
def voltage=(new_voltage)
ptr = ::FFI::MemoryPointer.new(:int)
Klass.setVoltage(@handle, Phidgets::FFI::LEDVoltage[new_voltage])
new_voltage
end
|
ruby
|
def voltage=(new_voltage)
ptr = ::FFI::MemoryPointer.new(:int)
Klass.setVoltage(@handle, Phidgets::FFI::LEDVoltage[new_voltage])
new_voltage
end
|
[
"def",
"voltage",
"=",
"(",
"new_voltage",
")",
"ptr",
"=",
"::",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":int",
")",
"Klass",
".",
"setVoltage",
"(",
"@handle",
",",
"Phidgets",
"::",
"FFI",
"::",
"LEDVoltage",
"[",
"new_voltage",
"]",
")",
"new_voltage",
"end"
] |
Sets the voltage level for all LEDs, or raises an error. Not supported on all PhidgetLEDs.
@param [Phidgets::FFI::LEDVoltage] new_voltage new voltage
@return [Phidgets::FFI::LEDVoltage] returns the voltage level, or raises an error.
|
[
"Sets",
"the",
"voltage",
"level",
"for",
"all",
"LEDs",
"or",
"raises",
"an",
"error",
".",
"Not",
"supported",
"on",
"all",
"PhidgetLEDs",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/led.rb#L48-L52
|
21,692 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/stepper.rb
|
Phidgets.Stepper.on_velocity_change
|
def on_velocity_change(obj=nil, &block)
@on_velocity_change_obj = obj
@on_velocity_change = Proc.new { |device, obj_ptr, index, velocity|
yield self, @steppers[index], velocity, object_for(obj_ptr)
}
Klass.set_OnVelocityChange_Handler(@handle, @on_velocity_change, pointer_for(obj))
end
|
ruby
|
def on_velocity_change(obj=nil, &block)
@on_velocity_change_obj = obj
@on_velocity_change = Proc.new { |device, obj_ptr, index, velocity|
yield self, @steppers[index], velocity, object_for(obj_ptr)
}
Klass.set_OnVelocityChange_Handler(@handle, @on_velocity_change, pointer_for(obj))
end
|
[
"def",
"on_velocity_change",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_velocity_change_obj",
"=",
"obj",
"@on_velocity_change",
"=",
"Proc",
".",
"new",
"{",
"|",
"device",
",",
"obj_ptr",
",",
"index",
",",
"velocity",
"|",
"yield",
"self",
",",
"@steppers",
"[",
"index",
"]",
",",
"velocity",
",",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Klass",
".",
"set_OnVelocityChange_Handler",
"(",
"@handle",
",",
"@on_velocity_change",
",",
"pointer_for",
"(",
"obj",
")",
")",
"end"
] |
Sets a velocity change handler callback function. This is called when a stepper velocity changes.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
st.on_velocity_change do |device, stepper, velocity, obj|
puts "Stepper #{stepper.index}'s velocity has changed to #{velocity}"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"a",
"velocity",
"change",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"a",
"stepper",
"velocity",
"changes",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/stepper.rb#L55-L61
|
21,693 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/accelerometer.rb
|
Phidgets.Accelerometer.on_acceleration_change
|
def on_acceleration_change(obj=nil, &block)
@on_acceleration_change_obj = obj
@on_acceleration_change = Proc.new { |device, obj_ptr, ind, acc|
yield self, axes[ind], acc, object_for(obj_ptr)
}
Klass.set_OnAccelerationChange_Handler(@handle, @on_acceleration_change, pointer_for(obj))
end
|
ruby
|
def on_acceleration_change(obj=nil, &block)
@on_acceleration_change_obj = obj
@on_acceleration_change = Proc.new { |device, obj_ptr, ind, acc|
yield self, axes[ind], acc, object_for(obj_ptr)
}
Klass.set_OnAccelerationChange_Handler(@handle, @on_acceleration_change, pointer_for(obj))
end
|
[
"def",
"on_acceleration_change",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_acceleration_change_obj",
"=",
"obj",
"@on_acceleration_change",
"=",
"Proc",
".",
"new",
"{",
"|",
"device",
",",
"obj_ptr",
",",
"ind",
",",
"acc",
"|",
"yield",
"self",
",",
"axes",
"[",
"ind",
"]",
",",
"acc",
",",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Klass",
".",
"set_OnAccelerationChange_Handler",
"(",
"@handle",
",",
"@on_acceleration_change",
",",
"pointer_for",
"(",
"obj",
")",
")",
"end"
] |
Sets an acceleration change handler callback function. This is called when the acceleration of an axis changes by more than the set sensitivity.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
acc.on_acceleration_change do |device, axis, acceleration, obj|
puts "Axis #{axis.index}'s acceleration changed to #{acceleration}"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"an",
"acceleration",
"change",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"the",
"acceleration",
"of",
"an",
"axis",
"changes",
"by",
"more",
"than",
"the",
"set",
"sensitivity",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/accelerometer.rb#L32-L38
|
21,694 |
elektronaut/dynamic_image
|
lib/dynamic_image/processed_image.rb
|
DynamicImage.ProcessedImage.cropped_and_resized
|
def cropped_and_resized(size)
normalized do |image|
if record.cropped? || size != record.size
image.crop(image_sizing.crop_geometry_string(size))
image.resize(size)
end
end
end
|
ruby
|
def cropped_and_resized(size)
normalized do |image|
if record.cropped? || size != record.size
image.crop(image_sizing.crop_geometry_string(size))
image.resize(size)
end
end
end
|
[
"def",
"cropped_and_resized",
"(",
"size",
")",
"normalized",
"do",
"|",
"image",
"|",
"if",
"record",
".",
"cropped?",
"||",
"size",
"!=",
"record",
".",
"size",
"image",
".",
"crop",
"(",
"image_sizing",
".",
"crop_geometry_string",
"(",
"size",
")",
")",
"image",
".",
"resize",
"(",
"size",
")",
"end",
"end",
"end"
] |
Crops and resizes the image. Normalization is performed as well.
==== Example
processed = DynamicImage::ProcessedImage.new(image)
image_data = processed.cropped_and_resized(Vector2d.new(200, 200))
Returns a binary string.
|
[
"Crops",
"and",
"resizes",
"the",
"image",
".",
"Normalization",
"is",
"performed",
"as",
"well",
"."
] |
d711f8f5d8385fb36d7ff9a6012f3fd123005c18
|
https://github.com/elektronaut/dynamic_image/blob/d711f8f5d8385fb36d7ff9a6012f3fd123005c18/lib/dynamic_image/processed_image.rb#L37-L44
|
21,695 |
elektronaut/dynamic_image
|
lib/dynamic_image/processed_image.rb
|
DynamicImage.ProcessedImage.normalized
|
def normalized
require_valid_image!
process_data do |image|
image.combine_options do |combined|
combined.auto_orient
combined.colorspace("sRGB") if needs_colorspace_conversion?
yield(combined) if block_given?
optimize(combined)
end
image.format(format) if needs_format_conversion?
end
end
|
ruby
|
def normalized
require_valid_image!
process_data do |image|
image.combine_options do |combined|
combined.auto_orient
combined.colorspace("sRGB") if needs_colorspace_conversion?
yield(combined) if block_given?
optimize(combined)
end
image.format(format) if needs_format_conversion?
end
end
|
[
"def",
"normalized",
"require_valid_image!",
"process_data",
"do",
"|",
"image",
"|",
"image",
".",
"combine_options",
"do",
"|",
"combined",
"|",
"combined",
".",
"auto_orient",
"combined",
".",
"colorspace",
"(",
"\"sRGB\"",
")",
"if",
"needs_colorspace_conversion?",
"yield",
"(",
"combined",
")",
"if",
"block_given?",
"optimize",
"(",
"combined",
")",
"end",
"image",
".",
"format",
"(",
"format",
")",
"if",
"needs_format_conversion?",
"end",
"end"
] |
Normalizes the image.
* Applies EXIF rotation
* CMYK images are converted to sRGB
* Strips metadata
* Optimizes GIFs
* Performs format conversion if the requested format is different
==== Example
processed = DynamicImage::ProcessedImage.new(image, :jpeg)
jpg_data = processed.normalized
Returns a binary string.
|
[
"Normalizes",
"the",
"image",
"."
] |
d711f8f5d8385fb36d7ff9a6012f3fd123005c18
|
https://github.com/elektronaut/dynamic_image/blob/d711f8f5d8385fb36d7ff9a6012f3fd123005c18/lib/dynamic_image/processed_image.rb#L60-L71
|
21,696 |
axsh/isono
|
lib/isono/manifest.rb
|
Isono.Manifest.load_config
|
def load_config(path)
return unless File.exist?(path)
buf = File.read(path)
eval("#{buf}", binding, path)
end
|
ruby
|
def load_config(path)
return unless File.exist?(path)
buf = File.read(path)
eval("#{buf}", binding, path)
end
|
[
"def",
"load_config",
"(",
"path",
")",
"return",
"unless",
"File",
".",
"exist?",
"(",
"path",
")",
"buf",
"=",
"File",
".",
"read",
"(",
"path",
")",
"eval",
"(",
"\"#{buf}\"",
",",
"binding",
",",
"path",
")",
"end"
] |
load config file and merge up with the config tree.
it will not work when the config_path is nil or the file is missed
|
[
"load",
"config",
"file",
"and",
"merge",
"up",
"with",
"the",
"config",
"tree",
".",
"it",
"will",
"not",
"work",
"when",
"the",
"config_path",
"is",
"nil",
"or",
"the",
"file",
"is",
"missed"
] |
0325eb1a46538b8eea63e80745a9161e2532b7cf
|
https://github.com/axsh/isono/blob/0325eb1a46538b8eea63e80745a9161e2532b7cf/lib/isono/manifest.rb#L86-L90
|
21,697 |
manojmj92/fulfil-ruby
|
lib/fulfil/base.rb
|
Fulfil.Base.method_missing
|
def method_missing(method)
method = method.to_s
raise NoMethodError, "No such method: #{method}" unless @args.keys.include? method
@args[method]
end
|
ruby
|
def method_missing(method)
method = method.to_s
raise NoMethodError, "No such method: #{method}" unless @args.keys.include? method
@args[method]
end
|
[
"def",
"method_missing",
"(",
"method",
")",
"method",
"=",
"method",
".",
"to_s",
"raise",
"NoMethodError",
",",
"\"No such method: #{method}\"",
"unless",
"@args",
".",
"keys",
".",
"include?",
"method",
"@args",
"[",
"method",
"]",
"end"
] |
This will return arguments as object methods.
|
[
"This",
"will",
"return",
"arguments",
"as",
"object",
"methods",
"."
] |
f47832eeb4137c8cc531fab4c1f9a181e6be5652
|
https://github.com/manojmj92/fulfil-ruby/blob/f47832eeb4137c8cc531fab4c1f9a181e6be5652/lib/fulfil/base.rb#L38-L42
|
21,698 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/motor_control.rb
|
Phidgets.MotorControl.attributes
|
def attributes
super.merge({
:motors => motors.size,
:encoders => encoders.size,
:inputs => inputs.size,
:sensors => sensors.size,
:ratiometric => ratiometric
})
end
|
ruby
|
def attributes
super.merge({
:motors => motors.size,
:encoders => encoders.size,
:inputs => inputs.size,
:sensors => sensors.size,
:ratiometric => ratiometric
})
end
|
[
"def",
"attributes",
"super",
".",
"merge",
"(",
"{",
":motors",
"=>",
"motors",
".",
"size",
",",
":encoders",
"=>",
"encoders",
".",
"size",
",",
":inputs",
"=>",
"inputs",
".",
"size",
",",
":sensors",
"=>",
"sensors",
".",
"size",
",",
":ratiometric",
"=>",
"ratiometric",
"}",
")",
"end"
] |
The attributes of a PhidgetMotorControl
|
[
"The",
"attributes",
"of",
"a",
"PhidgetMotorControl"
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/motor_control.rb#L28-L36
|
21,699 |
kreynolds/phidgets-ffi
|
lib/phidgets-ffi/motor_control.rb
|
Phidgets.MotorControl.on_current_change
|
def on_current_change(obj=nil, &block)
@on_current_change_obj = obj
@on_current_change = Proc.new { |device, obj_ptr, motor, current|
yield self, @motors[motor], current, object_for(obj_ptr)
}
Klass.set_OnCurrentChange_Handler(@handle, @on_current_change, pointer_for(obj))
end
|
ruby
|
def on_current_change(obj=nil, &block)
@on_current_change_obj = obj
@on_current_change = Proc.new { |device, obj_ptr, motor, current|
yield self, @motors[motor], current, object_for(obj_ptr)
}
Klass.set_OnCurrentChange_Handler(@handle, @on_current_change, pointer_for(obj))
end
|
[
"def",
"on_current_change",
"(",
"obj",
"=",
"nil",
",",
"&",
"block",
")",
"@on_current_change_obj",
"=",
"obj",
"@on_current_change",
"=",
"Proc",
".",
"new",
"{",
"|",
"device",
",",
"obj_ptr",
",",
"motor",
",",
"current",
"|",
"yield",
"self",
",",
"@motors",
"[",
"motor",
"]",
",",
"current",
",",
"object_for",
"(",
"obj_ptr",
")",
"}",
"Klass",
".",
"set_OnCurrentChange_Handler",
"(",
"@handle",
",",
"@on_current_change",
",",
"pointer_for",
"(",
"obj",
")",
")",
"end"
] |
Sets a current change handler callback function. This is called when the current consumed by a motor changes.
@param [String] obj Object to pass to the callback function. This is optional.
@param [Proc] Block When the callback is executed, the device and object are yielded to this block.
@example
mc.on_current_change do |device, motor, current|
puts "Motor #{motor.index}'s current changed to #{current}"
end
As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more.
@return [Boolean] returns true or raises an error
|
[
"Sets",
"a",
"current",
"change",
"handler",
"callback",
"function",
".",
"This",
"is",
"called",
"when",
"the",
"current",
"consumed",
"by",
"a",
"motor",
"changes",
"."
] |
5c22e206804dc47e8ad37173baf952c874845973
|
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/motor_control.rb#L68-L76
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.