repo
stringlengths 5
67
| sha
stringlengths 40
40
| path
stringlengths 4
234
| url
stringlengths 85
339
| language
stringclasses 6
values | split
stringclasses 3
values | doc
stringlengths 3
51.2k
| sign
stringlengths 5
8.01k
| problem
stringlengths 13
51.2k
| output
stringlengths 0
3.87M
|
---|---|---|---|---|---|---|---|---|---|
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | grid.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/grid.go#L289-L293 | go | train | // func (g *GridType) SetXExtent(dataLf, paperLf, dataRt, paperRt float64) {
// g.xm, g.xb = linear(dataLf, paperLf, dataRt, paperRt)
// }
// func (g *GridType) SetYExtent(dataTp, paperTp, dataBt, paperBt float64) {
// g.ym, g.yb = linear(dataTp, paperTp, dataBt, paperBt)
// } | func lineAttr(pdf *Fpdf, clr RGBAType, lineWd float64) | // func (g *GridType) SetXExtent(dataLf, paperLf, dataRt, paperRt float64) {
// g.xm, g.xb = linear(dataLf, paperLf, dataRt, paperRt)
// }
// func (g *GridType) SetYExtent(dataTp, paperTp, dataBt, paperBt float64) {
// g.ym, g.yb = linear(dataTp, paperTp, dataBt, paperBt)
// }
func lineAttr(pdf *Fpdf, clr RGBAType, lineWd float64) | {
pdf.SetLineWidth(lineWd)
pdf.SetAlpha(clr.Alpha, "Normal")
pdf.SetDrawColor(clr.R, clr.G, clr.B)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | grid.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/grid.go#L296-L422 | go | train | // Grid generates a graph-paperlike set of grid lines on the current page. | func (g GridType) Grid(pdf *Fpdf) | // Grid generates a graph-paperlike set of grid lines on the current page.
func (g GridType) Grid(pdf *Fpdf) | {
var st StateType
var yLen, xLen int
var textSz, halfTextSz, yMin, yMax, xMin, xMax, yDiv, xDiv float64
var str string
var strOfs, strWd, tp, bt, lf, rt, drawX, drawY float64
xLen = len(g.xTicks)
yLen = len(g.yTicks)
if xLen > 1 && yLen > 1 {
st = StateGet(pdf)
line := func(x1, y1, x2, y2 float64, heavy bool) {
if heavy {
lineAttr(pdf, g.ClrMain, g.WdMain)
} else {
lineAttr(pdf, g.ClrSub, g.WdSub)
}
pdf.Line(x1, y1, x2, y2)
}
textSz = pdf.PointToUnitConvert(g.TextSize)
halfTextSz = textSz / 2
pdf.SetAutoPageBreak(false, 0)
pdf.SetFontUnitSize(textSz)
strOfs = pdf.GetStringWidth("0")
pdf.SetFillColor(255, 255, 255)
pdf.SetCellMargin(0)
xMin = g.xTicks[0]
xMax = g.xTicks[xLen-1]
yMin = g.yTicks[0]
yMax = g.yTicks[yLen-1]
lf = g.X(xMin)
rt = g.X(xMax)
bt = g.Y(yMin)
tp = g.Y(yMax)
// Verticals along X axis
xDiv = g.xTicks[1] - g.xTicks[0]
if g.XDiv > 0 {
xDiv = xDiv / float64(g.XDiv)
}
xDiv = g.Wd(xDiv)
for j, x := range g.xTicks {
drawX = g.X(x)
line(drawX, tp, drawX, bt, true)
if j < xLen-1 {
for k := 1; k < g.XDiv; k++ {
drawX += xDiv
line(drawX, tp, drawX, bt, false)
}
}
}
// Horizontals along Y axis
yDiv = g.yTicks[1] - g.yTicks[0]
if g.YDiv > 0 {
yDiv = yDiv / float64(g.YDiv)
}
yDiv = g.Ht(yDiv)
for j, y := range g.yTicks {
drawY = g.Y(y)
line(lf, drawY, rt, drawY, true)
if j < yLen-1 {
for k := 1; k < g.YDiv; k++ {
drawY += yDiv
line(lf, drawY, rt, drawY, false)
}
}
}
// X labels
if g.XTickStr != nil {
drawY = bt
for _, x := range g.xTicks {
str = g.XTickStr(x, g.xPrecision)
strWd = pdf.GetStringWidth(str)
drawX = g.X(x)
if g.XLabelRotate {
pdf.TransformBegin()
pdf.TransformRotate(90, drawX, drawY)
if g.XLabelIn {
pdf.SetXY(drawX+strOfs, drawY-halfTextSz)
} else {
pdf.SetXY(drawX-strOfs-strWd, drawY-halfTextSz)
}
pdf.CellFormat(strWd, textSz, str, "", 0, "L", true, 0, "")
pdf.TransformEnd()
} else {
drawX -= strWd / 2.0
if g.XLabelIn {
pdf.SetXY(drawX, drawY-textSz-strOfs)
} else {
pdf.SetXY(drawX, drawY+strOfs)
}
pdf.CellFormat(strWd, textSz, str, "", 0, "L", true, 0, "")
}
}
}
// Y labels
if g.YTickStr != nil {
drawX = lf
for _, y := range g.yTicks {
// str = strconv.FormatFloat(y, 'f', g.yPrecision, 64)
str = g.YTickStr(y, g.yPrecision)
strWd = pdf.GetStringWidth(str)
if g.YLabelIn {
pdf.SetXY(drawX+strOfs, g.Y(y)-halfTextSz)
} else {
pdf.SetXY(lf-strOfs-strWd, g.Y(y)-halfTextSz)
}
pdf.CellFormat(strWd, textSz, str, "", 0, "L", true, 0, "")
}
}
// Restore drawing attributes
st.Put(pdf)
}
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | grid.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/grid.go#L427-L446 | go | train | // Plot plots a series of count line segments from xMin to xMax. It repeatedly
// calls fnc(x) to retrieve the y value associate with x. The currently
// selected line drawing attributes are used. | func (g GridType) Plot(pdf *Fpdf, xMin, xMax float64, count int, fnc func(x float64) (y float64)) | // Plot plots a series of count line segments from xMin to xMax. It repeatedly
// calls fnc(x) to retrieve the y value associate with x. The currently
// selected line drawing attributes are used.
func (g GridType) Plot(pdf *Fpdf, xMin, xMax float64, count int, fnc func(x float64) (y float64)) | {
if count > 0 {
var x, delta, drawX0, drawY0, drawX1, drawY1 float64
delta = (xMax - xMin) / float64(count)
x = xMin
for j := 0; j <= count; j++ {
if j == 0 {
drawX1 = g.X(x)
drawY1 = g.Y(fnc(x))
} else {
pdf.Line(drawX0, drawY0, drawX1, drawY1)
}
x += delta
drawX0 = drawX1
drawY0 = drawY1
drawX1 = g.X(x)
drawY1 = g.Y(fnc(x))
}
}
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | htmlbasic.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/htmlbasic.go#L35-L92 | go | train | // HTMLBasicTokenize returns a list of HTML tags and literal elements. This is
// done with regular expressions, so the result is only marginally better than
// useless. | func HTMLBasicTokenize(htmlStr string) (list []HTMLBasicSegmentType) | // HTMLBasicTokenize returns a list of HTML tags and literal elements. This is
// done with regular expressions, so the result is only marginally better than
// useless.
func HTMLBasicTokenize(htmlStr string) (list []HTMLBasicSegmentType) | {
// This routine is adapted from http://www.fpdf.org/
list = make([]HTMLBasicSegmentType, 0, 16)
htmlStr = strings.Replace(htmlStr, "\n", " ", -1)
htmlStr = strings.Replace(htmlStr, "\r", "", -1)
tagRe, _ := regexp.Compile(`(?U)<.*>`)
attrRe, _ := regexp.Compile(`([^=]+)=["']?([^"']+)`)
capList := tagRe.FindAllStringIndex(htmlStr, -1)
if capList != nil {
var seg HTMLBasicSegmentType
var parts []string
pos := 0
for _, cap := range capList {
if pos < cap[0] {
seg.Cat = 'T'
seg.Str = htmlStr[pos:cap[0]]
seg.Attr = nil
list = append(list, seg)
}
if htmlStr[cap[0]+1] == '/' {
seg.Cat = 'C'
seg.Str = strings.ToLower(htmlStr[cap[0]+2 : cap[1]-1])
seg.Attr = nil
list = append(list, seg)
} else {
// Extract attributes
parts = strings.Split(htmlStr[cap[0]+1:cap[1]-1], " ")
if len(parts) > 0 {
for j, part := range parts {
if j == 0 {
seg.Cat = 'O'
seg.Str = strings.ToLower(parts[0])
seg.Attr = make(map[string]string)
} else {
attrList := attrRe.FindAllStringSubmatch(part, -1)
if attrList != nil {
for _, attr := range attrList {
seg.Attr[strings.ToLower(attr[1])] = attr[2]
}
}
}
}
list = append(list, seg)
}
}
pos = cap[1]
}
if len(htmlStr) > pos {
seg.Cat = 'T'
seg.Str = htmlStr[pos:]
seg.Attr = nil
list = append(list, seg)
}
} else {
list = append(list, HTMLBasicSegmentType{Cat: 'T', Str: htmlStr, Attr: nil})
}
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | htmlbasic.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/htmlbasic.go#L109-L114 | go | train | // HTMLBasicNew returns an instance that facilitates writing basic HTML in the
// specified PDF file. | func (f *Fpdf) HTMLBasicNew() (html HTMLBasicType) | // HTMLBasicNew returns an instance that facilitates writing basic HTML in the
// specified PDF file.
func (f *Fpdf) HTMLBasicNew() (html HTMLBasicType) | {
html.pdf = f
html.Link.ClrR, html.Link.ClrG, html.Link.ClrB = 0, 0, 128
html.Link.Bold, html.Link.Italic, html.Link.Underscore = false, false, true
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | htmlbasic.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/htmlbasic.go#L125-L220 | go | train | // Write prints text from the current position using the currently selected
// font. See HTMLBasicNew() to create a receiver that is associated with the
// PDF document instance. The text can be encoded with a basic subset of HTML
// that includes hyperlinks and tags for italic (I), bold (B), underscore
// (U) and center (CENTER) attributes. When the right margin is reached a line
// break occurs and text continues from the left margin. Upon method exit, the
// current position is left at the end of the text.
//
// lineHt indicates the line height in the unit of measure specified in New(). | func (html *HTMLBasicType) Write(lineHt float64, htmlStr string) | // Write prints text from the current position using the currently selected
// font. See HTMLBasicNew() to create a receiver that is associated with the
// PDF document instance. The text can be encoded with a basic subset of HTML
// that includes hyperlinks and tags for italic (I), bold (B), underscore
// (U) and center (CENTER) attributes. When the right margin is reached a line
// break occurs and text continues from the left margin. Upon method exit, the
// current position is left at the end of the text.
//
// lineHt indicates the line height in the unit of measure specified in New().
func (html *HTMLBasicType) Write(lineHt float64, htmlStr string) | {
var boldLvl, italicLvl, underscoreLvl, linkBold, linkItalic, linkUnderscore int
var textR, textG, textB = html.pdf.GetTextColor()
var hrefStr string
if html.Link.Bold {
linkBold = 1
}
if html.Link.Italic {
linkItalic = 1
}
if html.Link.Underscore {
linkUnderscore = 1
}
setStyle := func(boldAdj, italicAdj, underscoreAdj int) {
styleStr := ""
boldLvl += boldAdj
if boldLvl > 0 {
styleStr += "B"
}
italicLvl += italicAdj
if italicLvl > 0 {
styleStr += "I"
}
underscoreLvl += underscoreAdj
if underscoreLvl > 0 {
styleStr += "U"
}
html.pdf.SetFont("", styleStr, 0)
}
putLink := func(urlStr, txtStr string) {
// Put a hyperlink
html.pdf.SetTextColor(html.Link.ClrR, html.Link.ClrG, html.Link.ClrB)
setStyle(linkBold, linkItalic, linkUnderscore)
html.pdf.WriteLinkString(lineHt, txtStr, urlStr)
setStyle(-linkBold, -linkItalic, -linkUnderscore)
html.pdf.SetTextColor(textR, textG, textB)
}
list := HTMLBasicTokenize(htmlStr)
var ok bool
alignStr := "L"
for _, el := range list {
switch el.Cat {
case 'T':
if len(hrefStr) > 0 {
putLink(hrefStr, el.Str)
hrefStr = ""
} else {
if alignStr == "C" || alignStr == "R" {
html.pdf.WriteAligned(0, lineHt, el.Str, alignStr)
} else {
html.pdf.Write(lineHt, el.Str)
}
}
case 'O':
switch el.Str {
case "b":
setStyle(1, 0, 0)
case "i":
setStyle(0, 1, 0)
case "u":
setStyle(0, 0, 1)
case "br":
html.pdf.Ln(lineHt)
case "center":
html.pdf.Ln(lineHt)
alignStr = "C"
case "right":
html.pdf.Ln(lineHt)
alignStr = "R"
case "left":
html.pdf.Ln(lineHt)
alignStr = "L"
case "a":
hrefStr, ok = el.Attr["href"]
if !ok {
hrefStr = ""
}
}
case 'C':
switch el.Str {
case "b":
setStyle(-1, 0, 0)
case "i":
setStyle(0, -1, 0)
case "u":
setStyle(0, 0, -1)
case "center":
html.pdf.Ln(lineHt)
alignStr = "L"
case "right":
html.pdf.Ln(lineHt)
alignStr = "L"
}
}
}
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | font.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/font.go#L85-L138 | go | train | // getInfoFromTrueType returns information from a TrueType font | func getInfoFromTrueType(fileStr string, msgWriter io.Writer, embed bool, encList encListType) (info fontInfoType, err error) | // getInfoFromTrueType returns information from a TrueType font
func getInfoFromTrueType(fileStr string, msgWriter io.Writer, embed bool, encList encListType) (info fontInfoType, err error) | {
var ttf TtfType
ttf, err = TtfParse(fileStr)
if err != nil {
return
}
if embed {
if !ttf.Embeddable {
err = fmt.Errorf("font license does not allow embedding")
return
}
info.Data, err = ioutil.ReadFile(fileStr)
if err != nil {
return
}
info.OriginalSize = len(info.Data)
}
k := 1000.0 / float64(ttf.UnitsPerEm)
info.FontName = ttf.PostScriptName
info.Bold = ttf.Bold
info.Desc.ItalicAngle = int(ttf.ItalicAngle)
info.IsFixedPitch = ttf.IsFixedPitch
info.Desc.Ascent = round(k * float64(ttf.TypoAscender))
info.Desc.Descent = round(k * float64(ttf.TypoDescender))
info.UnderlineThickness = round(k * float64(ttf.UnderlineThickness))
info.UnderlinePosition = round(k * float64(ttf.UnderlinePosition))
info.Desc.FontBBox = fontBoxType{
round(k * float64(ttf.Xmin)),
round(k * float64(ttf.Ymin)),
round(k * float64(ttf.Xmax)),
round(k * float64(ttf.Ymax)),
}
// printf("FontBBox\n")
// dump(info.Desc.FontBBox)
info.Desc.CapHeight = round(k * float64(ttf.CapHeight))
info.Desc.MissingWidth = round(k * float64(ttf.Widths[0]))
var wd int
for j := 0; j < len(info.Widths); j++ {
wd = info.Desc.MissingWidth
if encList[j].name != ".notdef" {
uv := encList[j].uv
pos, ok := ttf.Chars[uint16(uv)]
if ok {
wd = round(k * float64(ttf.Widths[pos]))
} else {
fmt.Fprintf(msgWriter, "Character %s is missing\n", encList[j].name)
}
}
info.Widths[j] = wd
}
// printf("getInfoFromTrueType/FontBBox\n")
// dump(info.Desc.FontBBox)
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | font.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/font.go#L170-L289 | go | train | // -rw-r--r-- 1 root root 9532 2010-04-22 11:27 /usr/share/fonts/type1/mathml/Symbol.afm
// -rw-r--r-- 1 root root 37744 2010-04-22 11:27 /usr/share/fonts/type1/mathml/Symbol.pfb
// getInfoFromType1 return information from a Type1 font | func getInfoFromType1(fileStr string, msgWriter io.Writer, embed bool, encList encListType) (info fontInfoType, err error) | // -rw-r--r-- 1 root root 9532 2010-04-22 11:27 /usr/share/fonts/type1/mathml/Symbol.afm
// -rw-r--r-- 1 root root 37744 2010-04-22 11:27 /usr/share/fonts/type1/mathml/Symbol.pfb
// getInfoFromType1 return information from a Type1 font
func getInfoFromType1(fileStr string, msgWriter io.Writer, embed bool, encList encListType) (info fontInfoType, err error) | {
if embed {
var f *os.File
f, err = os.Open(fileStr)
if err != nil {
return
}
defer f.Close()
// Read first segment
var s1, s2 segmentType
s1, err = segmentRead(f)
if err != nil {
return
}
s2, err = segmentRead(f)
if err != nil {
return
}
info.Data = s1.data
info.Data = append(info.Data, s2.data...)
info.Size1 = s1.size
info.Size2 = s2.size
}
afmFileStr := fileStr[0:len(fileStr)-3] + "afm"
size, ok := fileSize(afmFileStr)
if !ok {
err = fmt.Errorf("font file (ATM) %s not found", afmFileStr)
return
} else if size == 0 {
err = fmt.Errorf("font file (AFM) %s empty or not readable", afmFileStr)
return
}
var f *os.File
f, err = os.Open(afmFileStr)
if err != nil {
return
}
defer f.Close()
scanner := bufio.NewScanner(f)
var fields []string
var wd int
var wt, name string
wdMap := make(map[string]int)
for scanner.Scan() {
fields = strings.Fields(strings.TrimSpace(scanner.Text()))
// Comment Generated by FontForge 20080203
// FontName Symbol
// C 32 ; WX 250 ; N space ; B 0 0 0 0 ;
if len(fields) >= 2 {
switch fields[0] {
case "C":
if wd, err = strconv.Atoi(fields[4]); err == nil {
name = fields[7]
wdMap[name] = wd
}
case "FontName":
info.FontName = fields[1]
case "Weight":
wt = strings.ToLower(fields[1])
case "ItalicAngle":
info.Desc.ItalicAngle, err = strconv.Atoi(fields[1])
case "Ascender":
info.Desc.Ascent, err = strconv.Atoi(fields[1])
case "Descender":
info.Desc.Descent, err = strconv.Atoi(fields[1])
case "UnderlineThickness":
info.UnderlineThickness, err = strconv.Atoi(fields[1])
case "UnderlinePosition":
info.UnderlinePosition, err = strconv.Atoi(fields[1])
case "IsFixedPitch":
info.IsFixedPitch = fields[1] == "true"
case "FontBBox":
if info.Desc.FontBBox.Xmin, err = strconv.Atoi(fields[1]); err == nil {
if info.Desc.FontBBox.Ymin, err = strconv.Atoi(fields[2]); err == nil {
if info.Desc.FontBBox.Xmax, err = strconv.Atoi(fields[3]); err == nil {
info.Desc.FontBBox.Ymax, err = strconv.Atoi(fields[4])
}
}
}
case "CapHeight":
info.Desc.CapHeight, err = strconv.Atoi(fields[1])
case "StdVW":
info.Desc.StemV, err = strconv.Atoi(fields[1])
}
}
if err != nil {
return
}
}
if err = scanner.Err(); err != nil {
return
}
if info.FontName == "" {
err = fmt.Errorf("the field FontName missing in AFM file %s", afmFileStr)
return
}
info.Bold = wt == "bold" || wt == "black"
var missingWd int
missingWd, ok = wdMap[".notdef"]
if ok {
info.Desc.MissingWidth = missingWd
}
for j := 0; j < len(info.Widths); j++ {
info.Widths[j] = info.Desc.MissingWidth
}
for j := 0; j < len(info.Widths); j++ {
name = encList[j].name
if name != ".notdef" {
wd, ok = wdMap[name]
if ok {
info.Widths[j] = wd
} else {
fmt.Fprintf(msgWriter, "Character %s is missing\n", name)
}
}
}
// printf("getInfoFromType1/FontBBox\n")
// dump(info.Desc.FontBBox)
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | font.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/font.go#L314-L332 | go | train | // makeFontEncoding builds differences from reference encoding | func makeFontEncoding(encList encListType, refEncFileStr string) (diffStr string, err error) | // makeFontEncoding builds differences from reference encoding
func makeFontEncoding(encList encListType, refEncFileStr string) (diffStr string, err error) | {
var refList encListType
if refList, err = loadMap(refEncFileStr); err != nil {
return
}
var buf fmtBuffer
last := 0
for j := 32; j < 256; j++ {
if encList[j].name != refList[j].name {
if j != last+1 {
buf.printf("%d ", j)
}
last = j
buf.printf("/%s ", encList[j].name)
}
}
diffStr = strings.TrimSpace(buf.String())
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | font.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/font.go#L404-L472 | go | train | // MakeFont generates a font definition file in JSON format. A definition file
// of this type is required to use non-core fonts in the PDF documents that
// gofpdf generates. See the makefont utility in the gofpdf package for a
// command line interface to this function.
//
// fontFileStr is the name of the TrueType file (extension .ttf), OpenType file
// (extension .otf) or binary Type1 file (extension .pfb) from which to
// generate a definition file. If an OpenType file is specified, it must be one
// that is based on TrueType outlines, not PostScript outlines; this cannot be
// determined from the file extension alone. If a Type1 file is specified, a
// metric file with the same pathname except with the extension .afm must be
// present.
//
// encodingFileStr is the name of the encoding file that corresponds to the
// font.
//
// dstDirStr is the name of the directory in which to save the definition file
// and, if embed is true, the compressed font file.
//
// msgWriter is the writer that is called to display messages throughout the
// process. Use nil to turn off messages.
//
// embed is true if the font is to be embedded in the PDF files. | func MakeFont(fontFileStr, encodingFileStr, dstDirStr string, msgWriter io.Writer, embed bool) error | // MakeFont generates a font definition file in JSON format. A definition file
// of this type is required to use non-core fonts in the PDF documents that
// gofpdf generates. See the makefont utility in the gofpdf package for a
// command line interface to this function.
//
// fontFileStr is the name of the TrueType file (extension .ttf), OpenType file
// (extension .otf) or binary Type1 file (extension .pfb) from which to
// generate a definition file. If an OpenType file is specified, it must be one
// that is based on TrueType outlines, not PostScript outlines; this cannot be
// determined from the file extension alone. If a Type1 file is specified, a
// metric file with the same pathname except with the extension .afm must be
// present.
//
// encodingFileStr is the name of the encoding file that corresponds to the
// font.
//
// dstDirStr is the name of the directory in which to save the definition file
// and, if embed is true, the compressed font file.
//
// msgWriter is the writer that is called to display messages throughout the
// process. Use nil to turn off messages.
//
// embed is true if the font is to be embedded in the PDF files.
func MakeFont(fontFileStr, encodingFileStr, dstDirStr string, msgWriter io.Writer, embed bool) error | {
if msgWriter == nil {
msgWriter = ioutil.Discard
}
if !fileExist(fontFileStr) {
return fmt.Errorf("font file not found: %s", fontFileStr)
}
extStr := strings.ToLower(fontFileStr[len(fontFileStr)-3:])
// printf("Font file extension [%s]\n", extStr)
var tpStr string
switch extStr {
case "ttf":
fallthrough
case "otf":
tpStr = "TrueType"
case "pfb":
tpStr = "Type1"
default:
return fmt.Errorf("unrecognized font file extension: %s", extStr)
}
var info fontInfoType
encList, err := loadMap(encodingFileStr)
if err != nil {
return err
}
// printf("Encoding table\n")
// dump(encList)
if tpStr == "TrueType" {
info, err = getInfoFromTrueType(fontFileStr, msgWriter, embed, encList)
if err != nil {
return err
}
} else {
info, err = getInfoFromType1(fontFileStr, msgWriter, embed, encList)
if err != nil {
return err
}
}
baseStr := baseNoExt(fontFileStr)
// fmt.Printf("Base [%s]\n", baseStr)
if embed {
var f *os.File
info.File = baseStr + ".z"
zFileStr := filepath.Join(dstDirStr, info.File)
f, err = os.Create(zFileStr)
if err != nil {
return err
}
defer f.Close()
cmp := zlib.NewWriter(f)
_, err = cmp.Write(info.Data)
if err != nil {
return err
}
err = cmp.Close()
if err != nil {
return err
}
fmt.Fprintf(msgWriter, "Font file compressed: %s\n", zFileStr)
}
defFileStr := filepath.Join(dstDirStr, baseStr+".json")
err = makeDefinitionFile(defFileStr, tpStr, encodingFileStr, embed, encList, info)
if err != nil {
return err
}
fmt.Fprintf(msgWriter, "Font definition file successfully generated: %s\n", defFileStr)
return nil
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | svgbasic.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/svgbasic.go#L172-L201 | go | train | // SVGBasicParse parses a simple scalable vector graphics (SVG) buffer into a
// descriptor. Only a small subset of the SVG standard, in particular the path
// information generated by jSignature, is supported. The returned path data
// includes only the commands 'M' (absolute moveto: x, y), 'L' (absolute
// lineto: x, y), 'C' (absolute cubic Bézier curve: cx0, cy0, cx1, cy1,
// x1,y1) and 'Z' (closepath). | func SVGBasicParse(buf []byte) (sig SVGBasicType, err error) | // SVGBasicParse parses a simple scalable vector graphics (SVG) buffer into a
// descriptor. Only a small subset of the SVG standard, in particular the path
// information generated by jSignature, is supported. The returned path data
// includes only the commands 'M' (absolute moveto: x, y), 'L' (absolute
// lineto: x, y), 'C' (absolute cubic Bézier curve: cx0, cy0, cx1, cy1,
// x1,y1) and 'Z' (closepath).
func SVGBasicParse(buf []byte) (sig SVGBasicType, err error) | {
type pathType struct {
D string `xml:"d,attr"`
}
type srcType struct {
Wd float64 `xml:"width,attr"`
Ht float64 `xml:"height,attr"`
Paths []pathType `xml:"path"`
}
var src srcType
err = xml.Unmarshal(buf, &src)
if err == nil {
if src.Wd > 0 && src.Ht > 0 {
sig.Wd, sig.Ht = src.Wd, src.Ht
var segs []SVGBasicSegmentType
for _, path := range src.Paths {
if err == nil {
segs, err = pathParse(path.D)
if err == nil {
sig.Segments = append(sig.Segments, segs)
}
}
}
} else {
err = fmt.Errorf("unacceptable values for basic SVG extent: %.2f x %.2f",
sig.Wd, sig.Ht)
}
}
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | svgbasic.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/svgbasic.go#L205-L212 | go | train | // SVGBasicFileParse parses a simple scalable vector graphics (SVG) file into a
// basic descriptor. The SVGBasicWrite() example demonstrates this method. | func SVGBasicFileParse(svgFileStr string) (sig SVGBasicType, err error) | // SVGBasicFileParse parses a simple scalable vector graphics (SVG) file into a
// basic descriptor. The SVGBasicWrite() example demonstrates this method.
func SVGBasicFileParse(svgFileStr string) (sig SVGBasicType, err error) | {
var buf []byte
buf, err = ioutil.ReadFile(svgFileStr)
if err == nil {
sig, err = SVGBasicParse(buf)
}
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | template_impl.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/template_impl.go#L29-L54 | go | train | /*
* Copyright (c) 2015 Kurt Jung (Gmail: kurt.w.jung),
* Marcus Downing, Jan Slabon (Setasign)
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// newTpl creates a template, copying graphics settings from a template if one is given | func newTpl(corner PointType, size SizeType, orientationStr, unitStr, fontDirStr string, fn func(*Tpl), copyFrom *Fpdf) Template | /*
* Copyright (c) 2015 Kurt Jung (Gmail: kurt.w.jung),
* Marcus Downing, Jan Slabon (Setasign)
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// newTpl creates a template, copying graphics settings from a template if one is given
func newTpl(corner PointType, size SizeType, orientationStr, unitStr, fontDirStr string, fn func(*Tpl), copyFrom *Fpdf) Template | {
sizeStr := ""
fpdf := fpdfNew(orientationStr, unitStr, sizeStr, fontDirStr, size)
tpl := Tpl{*fpdf}
if copyFrom != nil {
tpl.loadParamsFromFpdf(copyFrom)
}
tpl.Fpdf.AddPage()
fn(&tpl)
bytes := make([][]byte, len(tpl.Fpdf.pages))
// skip the first page as it will always be empty
for x := 1; x < len(bytes); x++ {
bytes[x] = tpl.Fpdf.pages[x].Bytes()
}
templates := make([]Template, 0, len(tpl.Fpdf.templates))
for _, key := range templateKeyList(tpl.Fpdf.templates, true) {
templates = append(templates, tpl.Fpdf.templates[key])
}
images := tpl.Fpdf.images
template := FpdfTpl{corner, size, bytes, images, templates, tpl.Fpdf.page}
return &template
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | template_impl.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/template_impl.go#L67-L69 | go | train | // ID returns the global template identifier | func (t *FpdfTpl) ID() string | // ID returns the global template identifier
func (t *FpdfTpl) ID() string | {
return fmt.Sprintf("%x", sha1.Sum(t.Bytes()))
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | template_impl.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/template_impl.go#L72-L74 | go | train | // Size gives the bounding dimensions of this template | func (t *FpdfTpl) Size() (corner PointType, size SizeType) | // Size gives the bounding dimensions of this template
func (t *FpdfTpl) Size() (corner PointType, size SizeType) | {
return t.corner, t.size
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | template_impl.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/template_impl.go#L82-L100 | go | train | // FromPage creates a new template from a specific Page | func (t *FpdfTpl) FromPage(page int) (Template, error) | // FromPage creates a new template from a specific Page
func (t *FpdfTpl) FromPage(page int) (Template, error) | {
// pages start at 1
if page == 0 {
return nil, errors.New("Pages start at 1 No template will have a page 0")
}
if page > t.NumPages() {
return nil, fmt.Errorf("The template does not have a page %d", page)
}
// if it is already pointing to the correct page
// there is no need to create a new template
if t.page == page {
return t, nil
}
t2 := *t
t2.page = page
return &t2, nil
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | template_impl.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/template_impl.go#L103-L113 | go | train | // FromPages creates a template slice with all the pages within a template. | func (t *FpdfTpl) FromPages() []Template | // FromPages creates a template slice with all the pages within a template.
func (t *FpdfTpl) FromPages() []Template | {
p := make([]Template, t.NumPages())
for x := 1; x <= t.NumPages(); x++ {
// the only error is when accessing a
// non existing template... that can't happen
// here
p[x-1], _ = t.FromPage(x)
}
return p
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | template_impl.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/template_impl.go#L133-L139 | go | train | // Serialize turns a template into a byte string for later deserialization | func (t *FpdfTpl) Serialize() ([]byte, error) | // Serialize turns a template into a byte string for later deserialization
func (t *FpdfTpl) Serialize() ([]byte, error) | {
b := new(bytes.Buffer)
enc := gob.NewEncoder(b)
err := enc.Encode(t)
return b.Bytes(), err
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | template_impl.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/template_impl.go#L143-L148 | go | train | // DeserializeTemplate creaties a template from a previously serialized
// template | func DeserializeTemplate(b []byte) (Template, error) | // DeserializeTemplate creaties a template from a previously serialized
// template
func DeserializeTemplate(b []byte) (Template, error) | {
tpl := new(FpdfTpl)
dec := gob.NewDecoder(bytes.NewBuffer(b))
err := dec.Decode(tpl)
return tpl, err
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | template_impl.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/template_impl.go#L153-L165 | go | train | // childrenImages returns the next layer of children images, it doesn't dig into
// children of children. Applies template namespace to keys to ensure
// no collisions. See UseTemplateScaled | func (t *FpdfTpl) childrenImages() map[string]*ImageInfoType | // childrenImages returns the next layer of children images, it doesn't dig into
// children of children. Applies template namespace to keys to ensure
// no collisions. See UseTemplateScaled
func (t *FpdfTpl) childrenImages() map[string]*ImageInfoType | {
childrenImgs := make(map[string]*ImageInfoType)
for x := 0; x < len(t.templates); x++ {
imgs := t.templates[x].Images()
for key, val := range imgs {
name := sprintf("t%s-%s", t.templates[x].ID(), key)
childrenImgs[name] = val
}
}
return childrenImgs
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | template_impl.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/template_impl.go#L169-L178 | go | train | // childrensTemplates returns the next layer of children templates, it doesn't dig into
// children of children. | func (t *FpdfTpl) childrensTemplates() []Template | // childrensTemplates returns the next layer of children templates, it doesn't dig into
// children of children.
func (t *FpdfTpl) childrensTemplates() []Template | {
childrenTmpls := make([]Template, 0)
for x := 0; x < len(t.templates); x++ {
tmpls := t.templates[x].Templates()
childrenTmpls = append(childrenTmpls, tmpls...)
}
return childrenTmpls
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | template_impl.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/template_impl.go#L182-L227 | go | train | // GobEncode encodes the receiving template into a byte buffer. Use GobDecode
// to decode the byte buffer back to a template. | func (t *FpdfTpl) GobEncode() ([]byte, error) | // GobEncode encodes the receiving template into a byte buffer. Use GobDecode
// to decode the byte buffer back to a template.
func (t *FpdfTpl) GobEncode() ([]byte, error) | {
w := new(bytes.Buffer)
encoder := gob.NewEncoder(w)
childrensTemplates := t.childrensTemplates()
firstClassTemplates := make([]Template, 0)
found_continue:
for x := 0; x < len(t.templates); x++ {
for y := 0; y < len(childrensTemplates); y++ {
if childrensTemplates[y].ID() == t.templates[x].ID() {
continue found_continue
}
}
firstClassTemplates = append(firstClassTemplates, t.templates[x])
}
err := encoder.Encode(firstClassTemplates)
childrenImgs := t.childrenImages()
firstClassImgs := make(map[string]*ImageInfoType)
for key, img := range t.images {
if _, ok := childrenImgs[key]; !ok {
firstClassImgs[key] = img
}
}
if err == nil {
err = encoder.Encode(firstClassImgs)
}
if err == nil {
err = encoder.Encode(t.corner)
}
if err == nil {
err = encoder.Encode(t.size)
}
if err == nil {
err = encoder.Encode(t.bytes)
}
if err == nil {
err = encoder.Encode(t.page)
}
return w.Bytes(), err
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | template_impl.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/template_impl.go#L230-L269 | go | train | // GobDecode decodes the specified byte buffer into the receiving template. | func (t *FpdfTpl) GobDecode(buf []byte) error | // GobDecode decodes the specified byte buffer into the receiving template.
func (t *FpdfTpl) GobDecode(buf []byte) error | {
r := bytes.NewBuffer(buf)
decoder := gob.NewDecoder(r)
firstClassTemplates := make([]*FpdfTpl, 0)
err := decoder.Decode(&firstClassTemplates)
t.templates = make([]Template, len(firstClassTemplates))
for x := 0; x < len(t.templates); x++ {
t.templates[x] = Template(firstClassTemplates[x])
}
firstClassImages := t.childrenImages()
t.templates = append(t.childrensTemplates(), t.templates...)
t.images = make(map[string]*ImageInfoType)
if err == nil {
err = decoder.Decode(&t.images)
}
for k, v := range firstClassImages {
t.images[k] = v
}
if err == nil {
err = decoder.Decode(&t.corner)
}
if err == nil {
err = decoder.Decode(&t.size)
}
if err == nil {
err = decoder.Decode(&t.bytes)
}
if err == nil {
err = decoder.Decode(&t.page)
}
return err
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | internal/example/example.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/internal/example/example.go#L41-L52 | go | train | // setRoot assigns the relative path to the gofpdfDir directory based on current working
// directory | func setRoot() | // setRoot assigns the relative path to the gofpdfDir directory based on current working
// directory
func setRoot() | {
wdStr, err := os.Getwd()
if err == nil {
gofpdfDir = ""
list := strings.Split(filepath.ToSlash(wdStr), "/")
for j := len(list) - 1; j >= 0 && list[j] != "gofpdf"; j-- {
gofpdfDir = filepath.Join(gofpdfDir, "..")
}
} else {
panic(err)
}
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | internal/example/example.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/internal/example/example.go#L100-L110 | go | train | // referenceCompare compares the specified file with the file's reference copy
// located in the 'reference' subdirectory. All bytes of the two files are
// compared except for the value of the /CreationDate field in the PDF. This
// function succeeds if both files are equivalent except for their
// /CreationDate values or if the reference file does not exist. | func referenceCompare(fileStr string) (err error) | // referenceCompare compares the specified file with the file's reference copy
// located in the 'reference' subdirectory. All bytes of the two files are
// compared except for the value of the /CreationDate field in the PDF. This
// function succeeds if both files are equivalent except for their
// /CreationDate values or if the reference file does not exist.
func referenceCompare(fileStr string) (err error) | {
var refFileStr, refDirStr, dirStr, baseFileStr string
dirStr, baseFileStr = filepath.Split(fileStr)
refDirStr = filepath.Join(dirStr, "reference")
err = os.MkdirAll(refDirStr, 0755)
if err == nil {
refFileStr = filepath.Join(refDirStr, baseFileStr)
err = gofpdf.ComparePDFFiles(fileStr, refFileStr, false)
}
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | internal/example/example.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/internal/example/example.go#L116-L123 | go | train | // Summary generates a predictable report for use by test examples. If the
// specified error is nil, the filename delimiters are normalized and the
// filename printed to standard output with a success message. If the specified
// error is not nil, its String() value is printed to standard output. | func Summary(err error, fileStr string) | // Summary generates a predictable report for use by test examples. If the
// specified error is nil, the filename delimiters are normalized and the
// filename printed to standard output with a success message. If the specified
// error is not nil, its String() value is printed to standard output.
func Summary(err error, fileStr string) | {
if err == nil {
fileStr = filepath.ToSlash(fileStr)
fmt.Printf("Successfully generated %s\n", fileStr)
} else {
fmt.Println(err)
}
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | internal/example/example.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/internal/example/example.go#L132-L142 | go | train | // SummaryCompare generates a predictable report for use by test examples. If
// the specified error is nil, the generated file is compared with a reference
// copy for byte-for-byte equality. If the files match, then the filename
// delimiters are normalized and the filename printed to standard output with a
// success message. If the files do not match, this condition is reported on
// standard output. If the specified error is not nil, its String() value is
// printed to standard output. | func SummaryCompare(err error, fileStr string) | // SummaryCompare generates a predictable report for use by test examples. If
// the specified error is nil, the generated file is compared with a reference
// copy for byte-for-byte equality. If the files match, then the filename
// delimiters are normalized and the filename printed to standard output with a
// success message. If the files do not match, this condition is reported on
// standard output. If the specified error is not nil, its String() value is
// printed to standard output.
func SummaryCompare(err error, fileStr string) | {
if err == nil {
err = referenceCompare(fileStr)
}
if err == nil {
fileStr = filepath.ToSlash(fileStr)
fmt.Printf("Successfully generated %s\n", fileStr)
} else {
fmt.Println(err)
}
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | compare.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/compare.go#L89-L113 | go | train | // CompareBytes compares the bytes referred to by sl1 with those referred to by
// sl2. Nil is returned if the buffers are equal, otherwise an error. | func CompareBytes(sl1, sl2 []byte, printDiff bool) (err error) | // CompareBytes compares the bytes referred to by sl1 with those referred to by
// sl2. Nil is returned if the buffers are equal, otherwise an error.
func CompareBytes(sl1, sl2 []byte, printDiff bool) (err error) | {
var posStart, posEnd, len1, len2, length int
var diffs bool
len1 = len(sl1)
len2 = len(sl2)
length = len1
if length > len2 {
length = len2
}
for posStart < length-1 {
posEnd = posStart + 16
if posEnd > length {
posEnd = length
}
if !checkBytes(posStart, sl1[posStart:posEnd], sl2[posStart:posEnd], printDiff) {
diffs = true
}
posStart = posEnd
}
if diffs {
err = fmt.Errorf("documents are different")
}
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | compare.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/compare.go#L118-L128 | go | train | // ComparePDFs reads and compares the full contents of the two specified
// readers byte-for-byte. Nil is returned if the buffers are equal, otherwise
// an error. | func ComparePDFs(rdr1, rdr2 io.Reader, printDiff bool) (err error) | // ComparePDFs reads and compares the full contents of the two specified
// readers byte-for-byte. Nil is returned if the buffers are equal, otherwise
// an error.
func ComparePDFs(rdr1, rdr2 io.Reader, printDiff bool) (err error) | {
var b1, b2 *bytes.Buffer
_, err = b1.ReadFrom(rdr1)
if err == nil {
_, err = b2.ReadFrom(rdr2)
if err == nil {
err = CompareBytes(b1.Bytes(), b2.Bytes(), printDiff)
}
}
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | compare.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/compare.go#L133-L146 | go | train | // ComparePDFFiles reads and compares the full contents of the two specified
// files byte-for-byte. Nil is returned if the file contents are equal, or if
// the second file is missing, otherwise an error. | func ComparePDFFiles(file1Str, file2Str string, printDiff bool) (err error) | // ComparePDFFiles reads and compares the full contents of the two specified
// files byte-for-byte. Nil is returned if the file contents are equal, or if
// the second file is missing, otherwise an error.
func ComparePDFFiles(file1Str, file2Str string, printDiff bool) (err error) | {
var sl1, sl2 []byte
sl1, err = ioutil.ReadFile(file1Str)
if err == nil {
sl2, err = ioutil.ReadFile(file2Str)
if err == nil {
err = CompareBytes(sl1, sl2, printDiff)
} else {
// Second file is missing; treat this as success
err = nil
}
}
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | def.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/def.go#L190-L202 | go | train | // GobEncode encodes the receiving image to a byte slice. | func (info *ImageInfoType) GobEncode() (buf []byte, err error) | // GobEncode encodes the receiving image to a byte slice.
func (info *ImageInfoType) GobEncode() (buf []byte, err error) | {
fields := []interface{}{info.data, info.smask, info.n, info.w, info.h, info.cs,
info.pal, info.bpc, info.f, info.dp, info.trns, info.scale, info.dpi}
w := new(bytes.Buffer)
encoder := gob.NewEncoder(w)
for j := 0; j < len(fields) && err == nil; j++ {
err = encoder.Encode(fields[j])
}
if err == nil {
buf = w.Bytes()
}
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | def.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/def.go#L206-L217 | go | train | // GobDecode decodes the specified byte buffer (generated by GobEncode) into
// the receiving image. | func (info *ImageInfoType) GobDecode(buf []byte) (err error) | // GobDecode decodes the specified byte buffer (generated by GobEncode) into
// the receiving image.
func (info *ImageInfoType) GobDecode(buf []byte) (err error) | {
fields := []interface{}{&info.data, &info.smask, &info.n, &info.w, &info.h,
&info.cs, &info.pal, &info.bpc, &info.f, &info.dp, &info.trns, &info.scale, &info.dpi}
r := bytes.NewBuffer(buf)
decoder := gob.NewDecoder(r)
for j := 0; j < len(fields) && err == nil; j++ {
err = decoder.Decode(fields[j])
}
info.i, err = generateImageID(info)
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | def.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/def.go#L223-L225 | go | train | // PointConvert returns the value of pt, expressed in points (1/72 inch), as a
// value expressed in the unit of measure specified in New(). Since font
// management in Fpdf uses points, this method can help with line height
// calculations and other methods that require user units. | func (f *Fpdf) PointConvert(pt float64) (u float64) | // PointConvert returns the value of pt, expressed in points (1/72 inch), as a
// value expressed in the unit of measure specified in New(). Since font
// management in Fpdf uses points, this method can help with line height
// calculations and other methods that require user units.
func (f *Fpdf) PointConvert(pt float64) (u float64) | {
return pt / f.k
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | def.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/def.go#L228-L230 | go | train | // PointToUnitConvert is an alias for PointConvert. | func (f *Fpdf) PointToUnitConvert(pt float64) (u float64) | // PointToUnitConvert is an alias for PointConvert.
func (f *Fpdf) PointToUnitConvert(pt float64) (u float64) | {
return pt / f.k
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | def.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/def.go#L236-L238 | go | train | // UnitToPointConvert returns the value of u, expressed in the unit of measure
// specified in New(), as a value expressed in points (1/72 inch). Since font
// management in Fpdf uses points, this method can help with setting font sizes
// based on the sizes of other non-font page elements. | func (f *Fpdf) UnitToPointConvert(u float64) (pt float64) | // UnitToPointConvert returns the value of u, expressed in the unit of measure
// specified in New(), as a value expressed in points (1/72 inch). Since font
// management in Fpdf uses points, this method can help with setting font sizes
// based on the sizes of other non-font page elements.
func (f *Fpdf) UnitToPointConvert(u float64) (pt float64) | {
return u * f.k
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | def.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/def.go#L242-L244 | go | train | // Extent returns the width and height of the image in the units of the Fpdf
// object. | func (info *ImageInfoType) Extent() (wd, ht float64) | // Extent returns the width and height of the image in the units of the Fpdf
// object.
func (info *ImageInfoType) Extent() (wd, ht float64) | {
return info.Width(), info.Height()
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | def.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/def.go#L247-L249 | go | train | // Width returns the width of the image in the units of the Fpdf object. | func (info *ImageInfoType) Width() float64 | // Width returns the width of the image in the units of the Fpdf object.
func (info *ImageInfoType) Width() float64 | {
return info.w / (info.scale * info.dpi / 72)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | def.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/def.go#L252-L254 | go | train | // Height returns the height of the image in the units of the Fpdf object. | func (info *ImageInfoType) Height() float64 | // Height returns the height of the image in the units of the Fpdf object.
func (info *ImageInfoType) Height() float64 | {
return info.h / (info.scale * info.dpi / 72)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | def.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/def.go#L703-L708 | go | train | // generateFontID generates a font Id from the font definition | func generateFontID(fdt fontDefType) (string, error) | // generateFontID generates a font Id from the font definition
func generateFontID(fdt fontDefType) (string, error) | {
// file can be different if generated in different instance
fdt.File = ""
b, err := json.Marshal(&fdt)
return fmt.Sprintf("%x", sha1.Sum(b)), err
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L32-L34 | go | train | // TransformScaleX scales the width of the following text, drawings and images.
// scaleWd is the percentage scaling factor. (x, y) is center of scaling.
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformScaleX(scaleWd, x, y float64) | // TransformScaleX scales the width of the following text, drawings and images.
// scaleWd is the percentage scaling factor. (x, y) is center of scaling.
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformScaleX(scaleWd, x, y float64) | {
f.TransformScale(scaleWd, 100, x, y)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L41-L43 | go | train | // TransformScaleY scales the height of the following text, drawings and
// images. scaleHt is the percentage scaling factor. (x, y) is center of
// scaling.
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformScaleY(scaleHt, x, y float64) | // TransformScaleY scales the height of the following text, drawings and
// images. scaleHt is the percentage scaling factor. (x, y) is center of
// scaling.
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformScaleY(scaleHt, x, y float64) | {
f.TransformScale(100, scaleHt, x, y)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L50-L52 | go | train | // TransformScaleXY uniformly scales the width and height of the following
// text, drawings and images. s is the percentage scaling factor for both width
// and height. (x, y) is center of scaling.
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformScaleXY(s, x, y float64) | // TransformScaleXY uniformly scales the width and height of the following
// text, drawings and images. s is the percentage scaling factor for both width
// and height. (x, y) is center of scaling.
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformScaleXY(s, x, y float64) | {
f.TransformScale(s, s, x, y)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L59-L70 | go | train | // TransformScale generally scales the following text, drawings and images.
// scaleWd and scaleHt are the percentage scaling factors for width and height.
// (x, y) is center of scaling.
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformScale(scaleWd, scaleHt, x, y float64) | // TransformScale generally scales the following text, drawings and images.
// scaleWd and scaleHt are the percentage scaling factors for width and height.
// (x, y) is center of scaling.
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformScale(scaleWd, scaleHt, x, y float64) | {
if scaleWd == 0 || scaleHt == 0 {
f.err = fmt.Errorf("scale factor cannot be zero")
return
}
y = (f.h - y) * f.k
x *= f.k
scaleWd /= 100
scaleHt /= 100
f.Transform(TransformMatrix{scaleWd, 0, 0,
scaleHt, x * (1 - scaleWd), y * (1 - scaleHt)})
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L76-L78 | go | train | // TransformMirrorHorizontal horizontally mirrors the following text, drawings
// and images. x is the axis of reflection.
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformMirrorHorizontal(x float64) | // TransformMirrorHorizontal horizontally mirrors the following text, drawings
// and images. x is the axis of reflection.
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformMirrorHorizontal(x float64) | {
f.TransformScale(-100, 100, x, f.y)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L84-L86 | go | train | // TransformMirrorVertical vertically mirrors the following text, drawings and
// images. y is the axis of reflection.
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformMirrorVertical(y float64) | // TransformMirrorVertical vertically mirrors the following text, drawings and
// images. y is the axis of reflection.
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformMirrorVertical(y float64) | {
f.TransformScale(100, -100, f.x, y)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L92-L94 | go | train | // TransformMirrorPoint symmetrically mirrors the following text, drawings and
// images on the point specified by (x, y).
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformMirrorPoint(x, y float64) | // TransformMirrorPoint symmetrically mirrors the following text, drawings and
// images on the point specified by (x, y).
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformMirrorPoint(x, y float64) | {
f.TransformScale(-100, -100, x, y)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L102-L105 | go | train | // TransformMirrorLine symmetrically mirrors the following text, drawings and
// images on the line defined by angle and the point (x, y). angles is
// specified in degrees and measured counter-clockwise from the 3 o'clock
// position.
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformMirrorLine(angle, x, y float64) | // TransformMirrorLine symmetrically mirrors the following text, drawings and
// images on the line defined by angle and the point (x, y). angles is
// specified in degrees and measured counter-clockwise from the 3 o'clock
// position.
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformMirrorLine(angle, x, y float64) | {
f.TransformScale(-100, 100, x, y)
f.TransformRotate(-2*(angle-90), x, y)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L127-L129 | go | train | // TransformTranslate moves the following text, drawings and images
// horizontally and vertically by the amounts specified by tx and ty.
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformTranslate(tx, ty float64) | // TransformTranslate moves the following text, drawings and images
// horizontally and vertically by the amounts specified by tx and ty.
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformTranslate(tx, ty float64) | {
f.Transform(TransformMatrix{1, 0, 0, 1, tx * f.k, -ty * f.k})
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L136-L148 | go | train | // TransformRotate rotates the following text, drawings and images around the
// center point (x, y). angle is specified in degrees and measured
// counter-clockwise from the 3 o'clock position.
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformRotate(angle, x, y float64) | // TransformRotate rotates the following text, drawings and images around the
// center point (x, y). angle is specified in degrees and measured
// counter-clockwise from the 3 o'clock position.
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformRotate(angle, x, y float64) | {
y = (f.h - y) * f.k
x *= f.k
angle = angle * math.Pi / 180
var tm TransformMatrix
tm.A = math.Cos(angle)
tm.B = math.Sin(angle)
tm.C = -tm.B
tm.D = tm.A
tm.E = x + tm.B*y - tm.A*x
tm.F = y - tm.A*y - tm.B*x
f.Transform(tm)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L155-L157 | go | train | // TransformSkewX horizontally skews the following text, drawings and images
// keeping the point (x, y) stationary. angleX ranges from -90 degrees (skew to
// the left) to 90 degrees (skew to the right).
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformSkewX(angleX, x, y float64) | // TransformSkewX horizontally skews the following text, drawings and images
// keeping the point (x, y) stationary. angleX ranges from -90 degrees (skew to
// the left) to 90 degrees (skew to the right).
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformSkewX(angleX, x, y float64) | {
f.TransformSkew(angleX, 0, x, y)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L164-L166 | go | train | // TransformSkewY vertically skews the following text, drawings and images
// keeping the point (x, y) stationary. angleY ranges from -90 degrees (skew to
// the bottom) to 90 degrees (skew to the top).
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformSkewY(angleY, x, y float64) | // TransformSkewY vertically skews the following text, drawings and images
// keeping the point (x, y) stationary. angleY ranges from -90 degrees (skew to
// the bottom) to 90 degrees (skew to the top).
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformSkewY(angleY, x, y float64) | {
f.TransformSkew(0, angleY, x, y)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L174-L189 | go | train | // TransformSkew generally skews the following text, drawings and images
// keeping the point (x, y) stationary. angleX ranges from -90 degrees (skew to
// the left) to 90 degrees (skew to the right). angleY ranges from -90 degrees
// (skew to the bottom) to 90 degrees (skew to the top).
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformSkew(angleX, angleY, x, y float64) | // TransformSkew generally skews the following text, drawings and images
// keeping the point (x, y) stationary. angleX ranges from -90 degrees (skew to
// the left) to 90 degrees (skew to the right). angleY ranges from -90 degrees
// (skew to the bottom) to 90 degrees (skew to the top).
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformSkew(angleX, angleY, x, y float64) | {
if angleX <= -90 || angleX >= 90 || angleY <= -90 || angleY >= 90 {
f.err = fmt.Errorf("skew values must be between -90° and 90°")
return
}
x *= f.k
y = (f.h - y) * f.k
var tm TransformMatrix
tm.A = 1
tm.B = math.Tan(angleY * math.Pi / 180)
tm.C = math.Tan(angleX * math.Pi / 180)
tm.D = 1
tm.E = -tm.C * y
tm.F = -tm.B * x
f.Transform(tm)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L194-L201 | go | train | // Transform generally transforms the following text, drawings and images
// according to the specified matrix. It is typically easier to use the various
// methods such as TransformRotate() and TransformMirrorVertical() instead. | func (f *Fpdf) Transform(tm TransformMatrix) | // Transform generally transforms the following text, drawings and images
// according to the specified matrix. It is typically easier to use the various
// methods such as TransformRotate() and TransformMirrorVertical() instead.
func (f *Fpdf) Transform(tm TransformMatrix) | {
if f.transformNest > 0 {
f.outf("%.5f %.5f %.5f %.5f %.5f %.5f cm",
tm.A, tm.B, tm.C, tm.D, tm.E, tm.F)
} else if f.err == nil {
f.err = fmt.Errorf("transformation context is not active")
}
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | fpdftrans.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdftrans.go#L206-L213 | go | train | // TransformEnd applies a transformation that was begun with a call to TransformBegin().
//
// The TransformBegin() example demonstrates this method. | func (f *Fpdf) TransformEnd() | // TransformEnd applies a transformation that was begun with a call to TransformBegin().
//
// The TransformBegin() example demonstrates this method.
func (f *Fpdf) TransformEnd() | {
if f.transformNest > 0 {
f.transformNest--
f.out("Q")
} else {
f.err = fmt.Errorf("error attempting to end transformation operation out of sequence")
}
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | ttfparser.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/ttfparser.go#L60-L99 | go | train | // TtfParse extracts various metrics from a TrueType font file. | func TtfParse(fileStr string) (TtfRec TtfType, err error) | // TtfParse extracts various metrics from a TrueType font file.
func TtfParse(fileStr string) (TtfRec TtfType, err error) | {
var t ttfParser
t.f, err = os.Open(fileStr)
if err != nil {
return
}
version, err := t.ReadStr(4)
if err != nil {
return
}
if version == "OTTO" {
err = fmt.Errorf("fonts based on PostScript outlines are not supported")
return
}
if version != "\x00\x01\x00\x00" {
err = fmt.Errorf("unrecognized file format")
return
}
numTables := int(t.ReadUShort())
t.Skip(3 * 2) // searchRange, entrySelector, rangeShift
t.tables = make(map[string]uint32)
var tag string
for j := 0; j < numTables; j++ {
tag, err = t.ReadStr(4)
if err != nil {
return
}
t.Skip(4) // checkSum
offset := t.ReadULong()
t.Skip(4) // length
t.tables[tag] = offset
}
err = t.ParseComponents()
if err != nil {
return
}
t.f.Close()
TtfRec = t.rec
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | contrib/httpimg/httpimg.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/contrib/httpimg/httpimg.go#L22-L43 | go | train | // Register registers a HTTP image. Downloading the image from the provided URL
// and adding it to the PDF but not adding it to the page. Use Image() with the
// same URL to add the image to the page. | func Register(f httpimgPdf, urlStr, tp string) (info *gofpdf.ImageInfoType) | // Register registers a HTTP image. Downloading the image from the provided URL
// and adding it to the PDF but not adding it to the page. Use Image() with the
// same URL to add the image to the page.
func Register(f httpimgPdf, urlStr, tp string) (info *gofpdf.ImageInfoType) | {
info = f.GetImageInfo(urlStr)
if info != nil {
return
}
resp, err := http.Get(urlStr)
if err != nil {
f.SetError(err)
return
}
defer resp.Body.Close()
if tp == "" {
tp = f.ImageTypeFromMime(resp.Header["Content-Type"][0])
}
return f.RegisterImageReader(urlStr, tp, resp.Body)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | contrib/tiff/tiff.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/contrib/tiff/tiff.go#L39-L61 | go | train | // RegisterReader registers a TIFF image, adding it to the PDF file but not
// adding it to the page. imgName specifies the name that will be used in the
// call to Image() that actually places the image in the document. options
// specifies various image properties; in this case, the ImageType property
// should be set to "tiff". The TIFF image is a reader from the reader
// specified by r. | func RegisterReader(fpdf *gofpdf.Fpdf, imgName string, options gofpdf.ImageOptions, r io.Reader) (info *gofpdf.ImageInfoType) | // RegisterReader registers a TIFF image, adding it to the PDF file but not
// adding it to the page. imgName specifies the name that will be used in the
// call to Image() that actually places the image in the document. options
// specifies various image properties; in this case, the ImageType property
// should be set to "tiff". The TIFF image is a reader from the reader
// specified by r.
func RegisterReader(fpdf *gofpdf.Fpdf, imgName string, options gofpdf.ImageOptions, r io.Reader) (info *gofpdf.ImageInfoType) | {
var err error
var img image.Image
var buf bytes.Buffer
if fpdf.Ok() {
if options.ImageType == "tiff" || options.ImageType == "tif" {
img, err = tiff.Decode(r)
if err == nil {
err = png.Encode(&buf, img)
if err == nil {
options.ImageType = "png"
info = fpdf.RegisterImageOptionsReader(imgName, options, &buf)
}
}
} else {
err = fmt.Errorf("expecting \"tiff\" or \"tif\" as image type, got \"%s\"", options.ImageType)
}
if err != nil {
fpdf.SetError(err)
}
}
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | contrib/tiff/tiff.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/contrib/tiff/tiff.go#L69-L83 | go | train | // RegisterFile registers a TIFF image, adding it to the PDF file but not
// adding it to the page. imgName specifies the name that will be used in the
// call to Image() that actually places the image in the document. options
// specifies various image properties; in this case, the ImageType property
// should be set to "tiff". The TIFF image is read from the file specified by
// tiffFileStr. | func RegisterFile(fpdf *gofpdf.Fpdf, imgName string, options gofpdf.ImageOptions, tiffFileStr string) (info *gofpdf.ImageInfoType) | // RegisterFile registers a TIFF image, adding it to the PDF file but not
// adding it to the page. imgName specifies the name that will be used in the
// call to Image() that actually places the image in the document. options
// specifies various image properties; in this case, the ImageType property
// should be set to "tiff". The TIFF image is read from the file specified by
// tiffFileStr.
func RegisterFile(fpdf *gofpdf.Fpdf, imgName string, options gofpdf.ImageOptions, tiffFileStr string) (info *gofpdf.ImageInfoType) | {
var f *os.File
var err error
if fpdf.Ok() {
f, err = os.Open(tiffFileStr)
if err == nil {
info = RegisterReader(fpdf, imgName, options, f)
f.Close()
} else {
fpdf.SetError(err)
}
}
return
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | label.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/label.go#L30-L59 | go | train | // niceNum returns a "nice" number approximately equal to x. The number is
// rounded if round is true, converted to its ceiling otherwise. | func niceNum(val float64, round bool) float64 | // niceNum returns a "nice" number approximately equal to x. The number is
// rounded if round is true, converted to its ceiling otherwise.
func niceNum(val float64, round bool) float64 | {
var nf float64
exp := int(math.Floor(math.Log10(val)))
f := val / math.Pow10(exp)
if round {
switch {
case f < 1.5:
nf = 1
case f < 3.0:
nf = 2
case f < 7.0:
nf = 5
default:
nf = 10
}
} else {
switch {
case f <= 1:
nf = 1
case f <= 2.0:
nf = 2
case f <= 5.0:
nf = 5
default:
nf = 10
}
}
return nf * math.Pow10(exp)
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | label.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/label.go#L63-L65 | go | train | // TickmarkPrecision returns an appropriate precision value for label
// formatting. | func TickmarkPrecision(div float64) int | // TickmarkPrecision returns an appropriate precision value for label
// formatting.
func TickmarkPrecision(div float64) int | {
return int(math.Max(-math.Floor(math.Log10(div)), 0))
} |
jung-kurt/gofpdf | 8b09ffb30d9a8716107d250631b3c580aa54ba04 | label.go | https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/label.go#L70-L82 | go | train | // Tickmarks returns a slice of tickmarks appropriate for a chart axis and an
// appropriate precision for formatting purposes. The values min and max will
// be contained within the tickmark range. | func Tickmarks(min, max float64) (list []float64, precision int) | // Tickmarks returns a slice of tickmarks appropriate for a chart axis and an
// appropriate precision for formatting purposes. The values min and max will
// be contained within the tickmark range.
func Tickmarks(min, max float64) (list []float64, precision int) | {
if max > min {
spread := niceNum(max-min, false)
d := niceNum((spread / 4), true)
graphMin := math.Floor(min/d) * d
graphMax := math.Ceil(max/d) * d
precision = TickmarkPrecision(d)
for x := graphMin; x < graphMax+0.5*d; x += d {
list = append(list, x)
}
}
return
} |
fvbock/endless | 447134032cb6a86814f570257390a379982dfc61 | endless.go | https://github.com/fvbock/endless/blob/447134032cb6a86814f570257390a379982dfc61/endless.go#L89-L144 | go | train | /*
NewServer returns an intialized endlessServer Object. Calling Serve on it will
actually "start" the server.
*/ | func NewServer(addr string, handler http.Handler) (srv *endlessServer) | /*
NewServer returns an intialized endlessServer Object. Calling Serve on it will
actually "start" the server.
*/
func NewServer(addr string, handler http.Handler) (srv *endlessServer) | {
runningServerReg.Lock()
defer runningServerReg.Unlock()
socketOrder = os.Getenv("ENDLESS_SOCKET_ORDER")
isChild = os.Getenv("ENDLESS_CONTINUE") != ""
if len(socketOrder) > 0 {
for i, addr := range strings.Split(socketOrder, ",") {
socketPtrOffsetMap[addr] = uint(i)
}
} else {
socketPtrOffsetMap[addr] = uint(len(runningServersOrder))
}
srv = &endlessServer{
wg: sync.WaitGroup{},
sigChan: make(chan os.Signal),
isChild: isChild,
SignalHooks: map[int]map[os.Signal][]func(){
PRE_SIGNAL: map[os.Signal][]func(){
syscall.SIGHUP: []func(){},
syscall.SIGUSR1: []func(){},
syscall.SIGUSR2: []func(){},
syscall.SIGINT: []func(){},
syscall.SIGTERM: []func(){},
syscall.SIGTSTP: []func(){},
},
POST_SIGNAL: map[os.Signal][]func(){
syscall.SIGHUP: []func(){},
syscall.SIGUSR1: []func(){},
syscall.SIGUSR2: []func(){},
syscall.SIGINT: []func(){},
syscall.SIGTERM: []func(){},
syscall.SIGTSTP: []func(){},
},
},
state: STATE_INIT,
lock: &sync.RWMutex{},
}
srv.Server.Addr = addr
srv.Server.ReadTimeout = DefaultReadTimeOut
srv.Server.WriteTimeout = DefaultWriteTimeOut
srv.Server.MaxHeaderBytes = DefaultMaxHeaderBytes
srv.Server.Handler = handler
srv.BeforeBegin = func(addr string) {
log.Println(syscall.Getpid(), addr)
}
runningServersOrder = append(runningServersOrder, addr)
runningServers[addr] = srv
return
} |
fvbock/endless | 447134032cb6a86814f570257390a379982dfc61 | endless.go | https://github.com/fvbock/endless/blob/447134032cb6a86814f570257390a379982dfc61/endless.go#L151-L154 | go | train | /*
ListenAndServe listens on the TCP network address addr and then calls Serve
with handler to handle requests on incoming connections. Handler is typically
nil, in which case the DefaultServeMux is used.
*/ | func ListenAndServe(addr string, handler http.Handler) error | /*
ListenAndServe listens on the TCP network address addr and then calls Serve
with handler to handle requests on incoming connections. Handler is typically
nil, in which case the DefaultServeMux is used.
*/
func ListenAndServe(addr string, handler http.Handler) error | {
server := NewServer(addr, handler)
return server.ListenAndServe()
} |
fvbock/endless | 447134032cb6a86814f570257390a379982dfc61 | endless.go | https://github.com/fvbock/endless/blob/447134032cb6a86814f570257390a379982dfc61/endless.go#L163-L166 | go | train | /*
ListenAndServeTLS acts identically to ListenAndServe, except that it expects
HTTPS connections. Additionally, files containing a certificate and matching
private key for the server must be provided. If the certificate is signed by a
certificate authority, the certFile should be the concatenation of the server's
certificate followed by the CA's certificate.
*/ | func ListenAndServeTLS(addr string, certFile string, keyFile string, handler http.Handler) error | /*
ListenAndServeTLS acts identically to ListenAndServe, except that it expects
HTTPS connections. Additionally, files containing a certificate and matching
private key for the server must be provided. If the certificate is signed by a
certificate authority, the certFile should be the concatenation of the server's
certificate followed by the CA's certificate.
*/
func ListenAndServeTLS(addr string, certFile string, keyFile string, handler http.Handler) error | {
server := NewServer(addr, handler)
return server.ListenAndServeTLS(certFile, keyFile)
} |
fvbock/endless | 447134032cb6a86814f570257390a379982dfc61 | endless.go | https://github.com/fvbock/endless/blob/447134032cb6a86814f570257390a379982dfc61/endless.go#L192-L200 | go | train | /*
Serve accepts incoming HTTP connections on the listener l, creating a new
service goroutine for each. The service goroutines read requests and then call
handler to reply to them. Handler is typically nil, in which case the
DefaultServeMux is used.
In addition to the stl Serve behaviour each connection is added to a
sync.Waitgroup so that all outstanding connections can be served before shutting
down the server.
*/ | func (srv *endlessServer) Serve() (err error) | /*
Serve accepts incoming HTTP connections on the listener l, creating a new
service goroutine for each. The service goroutines read requests and then call
handler to reply to them. Handler is typically nil, in which case the
DefaultServeMux is used.
In addition to the stl Serve behaviour each connection is added to a
sync.Waitgroup so that all outstanding connections can be served before shutting
down the server.
*/
func (srv *endlessServer) Serve() (err error) | {
defer log.Println(syscall.Getpid(), "Serve() returning...")
srv.setState(STATE_RUNNING)
err = srv.Server.Serve(srv.EndlessListener)
log.Println(syscall.Getpid(), "Waiting for connections to finish...")
srv.wg.Wait()
srv.setState(STATE_TERMINATE)
return
} |
fvbock/endless | 447134032cb6a86814f570257390a379982dfc61 | endless.go | https://github.com/fvbock/endless/blob/447134032cb6a86814f570257390a379982dfc61/endless.go#L207-L230 | go | train | /*
ListenAndServe listens on the TCP network address srv.Addr and then calls Serve
to handle requests on incoming connections. If srv.Addr is blank, ":http" is
used.
*/ | func (srv *endlessServer) ListenAndServe() (err error) | /*
ListenAndServe listens on the TCP network address srv.Addr and then calls Serve
to handle requests on incoming connections. If srv.Addr is blank, ":http" is
used.
*/
func (srv *endlessServer) ListenAndServe() (err error) | {
addr := srv.Addr
if addr == "" {
addr = ":http"
}
go srv.handleSignals()
l, err := srv.getListener(addr)
if err != nil {
log.Println(err)
return
}
srv.EndlessListener = newEndlessListener(l, srv)
if srv.isChild {
syscall.Kill(syscall.Getppid(), syscall.SIGTERM)
}
srv.BeforeBegin(srv.Addr)
return srv.Serve()
} |
fvbock/endless | 447134032cb6a86814f570257390a379982dfc61 | endless.go | https://github.com/fvbock/endless/blob/447134032cb6a86814f570257390a379982dfc61/endless.go#L243-L280 | go | train | /*
ListenAndServeTLS listens on the TCP network address srv.Addr and then calls
Serve to handle requests on incoming TLS connections.
Filenames containing a certificate and matching private key for the server must
be provided. If the certificate is signed by a certificate authority, the
certFile should be the concatenation of the server's certificate followed by the
CA's certificate.
If srv.Addr is blank, ":https" is used.
*/ | func (srv *endlessServer) ListenAndServeTLS(certFile, keyFile string) (err error) | /*
ListenAndServeTLS listens on the TCP network address srv.Addr and then calls
Serve to handle requests on incoming TLS connections.
Filenames containing a certificate and matching private key for the server must
be provided. If the certificate is signed by a certificate authority, the
certFile should be the concatenation of the server's certificate followed by the
CA's certificate.
If srv.Addr is blank, ":https" is used.
*/
func (srv *endlessServer) ListenAndServeTLS(certFile, keyFile string) (err error) | {
addr := srv.Addr
if addr == "" {
addr = ":https"
}
config := &tls.Config{}
if srv.TLSConfig != nil {
*config = *srv.TLSConfig
}
if config.NextProtos == nil {
config.NextProtos = []string{"http/1.1"}
}
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return
}
go srv.handleSignals()
l, err := srv.getListener(addr)
if err != nil {
log.Println(err)
return
}
srv.tlsInnerListener = newEndlessListener(l, srv)
srv.EndlessListener = tls.NewListener(srv.tlsInnerListener, config)
if srv.isChild {
syscall.Kill(syscall.Getppid(), syscall.SIGTERM)
}
log.Println(syscall.Getpid(), srv.Addr)
return srv.Serve()
} |
fvbock/endless | 447134032cb6a86814f570257390a379982dfc61 | endless.go | https://github.com/fvbock/endless/blob/447134032cb6a86814f570257390a379982dfc61/endless.go#L286-L310 | go | train | /*
getListener either opens a new socket to listen on, or takes the acceptor socket
it got passed when restarted.
*/ | func (srv *endlessServer) getListener(laddr string) (l net.Listener, err error) | /*
getListener either opens a new socket to listen on, or takes the acceptor socket
it got passed when restarted.
*/
func (srv *endlessServer) getListener(laddr string) (l net.Listener, err error) | {
if srv.isChild {
var ptrOffset uint = 0
runningServerReg.RLock()
defer runningServerReg.RUnlock()
if len(socketPtrOffsetMap) > 0 {
ptrOffset = socketPtrOffsetMap[laddr]
// log.Println("laddr", laddr, "ptr offset", socketPtrOffsetMap[laddr])
}
f := os.NewFile(uintptr(3+ptrOffset), "")
l, err = net.FileListener(f)
if err != nil {
err = fmt.Errorf("net.FileListener error: %v", err)
return
}
} else {
l, err = net.Listen("tcp", laddr)
if err != nil {
err = fmt.Errorf("net.Listen error: %v", err)
return
}
}
return
} |
fvbock/endless | 447134032cb6a86814f570257390a379982dfc61 | endless.go | https://github.com/fvbock/endless/blob/447134032cb6a86814f570257390a379982dfc61/endless.go#L316-L353 | go | train | /*
handleSignals listens for os Signals and calls any hooked in function that the
user had registered with the signal.
*/ | func (srv *endlessServer) handleSignals() | /*
handleSignals listens for os Signals and calls any hooked in function that the
user had registered with the signal.
*/
func (srv *endlessServer) handleSignals() | {
var sig os.Signal
signal.Notify(
srv.sigChan,
hookableSignals...,
)
pid := syscall.Getpid()
for {
sig = <-srv.sigChan
srv.signalHooks(PRE_SIGNAL, sig)
switch sig {
case syscall.SIGHUP:
log.Println(pid, "Received SIGHUP. forking.")
err := srv.fork()
if err != nil {
log.Println("Fork err:", err)
}
case syscall.SIGUSR1:
log.Println(pid, "Received SIGUSR1.")
case syscall.SIGUSR2:
log.Println(pid, "Received SIGUSR2.")
srv.hammerTime(0 * time.Second)
case syscall.SIGINT:
log.Println(pid, "Received SIGINT.")
srv.shutdown()
case syscall.SIGTERM:
log.Println(pid, "Received SIGTERM.")
srv.shutdown()
case syscall.SIGTSTP:
log.Println(pid, "Received SIGTSTP.")
default:
log.Printf("Received %v: nothing i care about...\n", sig)
}
srv.signalHooks(POST_SIGNAL, sig)
}
} |
fvbock/endless | 447134032cb6a86814f570257390a379982dfc61 | endless.go | https://github.com/fvbock/endless/blob/447134032cb6a86814f570257390a379982dfc61/endless.go#L370-L387 | go | train | /*
shutdown closes the listener so that no new connections are accepted. it also
starts a goroutine that will hammer (stop all running requests) the server
after DefaultHammerTime.
*/ | func (srv *endlessServer) shutdown() | /*
shutdown closes the listener so that no new connections are accepted. it also
starts a goroutine that will hammer (stop all running requests) the server
after DefaultHammerTime.
*/
func (srv *endlessServer) shutdown() | {
if srv.getState() != STATE_RUNNING {
return
}
srv.setState(STATE_SHUTTING_DOWN)
if DefaultHammerTime >= 0 {
go srv.hammerTime(DefaultHammerTime)
}
// disable keep-alives on existing connections
srv.SetKeepAlivesEnabled(false)
err := srv.EndlessListener.Close()
if err != nil {
log.Println(syscall.Getpid(), "Listener.Close() error:", err)
} else {
log.Println(syscall.Getpid(), srv.EndlessListener.Addr(), "Listener closed.")
}
} |
fvbock/endless | 447134032cb6a86814f570257390a379982dfc61 | endless.go | https://github.com/fvbock/endless/blob/447134032cb6a86814f570257390a379982dfc61/endless.go#L398-L419 | go | train | /*
hammerTime forces the server to shutdown in a given timeout - whether it
finished outstanding requests or not. if Read/WriteTimeout are not set or the
max header size is very big a connection could hang...
srv.Serve() will not return until all connections are served. this will
unblock the srv.wg.Wait() in Serve() thus causing ListenAndServe(TLS) to
return.
*/ | func (srv *endlessServer) hammerTime(d time.Duration) | /*
hammerTime forces the server to shutdown in a given timeout - whether it
finished outstanding requests or not. if Read/WriteTimeout are not set or the
max header size is very big a connection could hang...
srv.Serve() will not return until all connections are served. this will
unblock the srv.wg.Wait() in Serve() thus causing ListenAndServe(TLS) to
return.
*/
func (srv *endlessServer) hammerTime(d time.Duration) | {
defer func() {
// we are calling srv.wg.Done() until it panics which means we called
// Done() when the counter was already at 0 and we're done.
// (and thus Serve() will return and the parent will exit)
if r := recover(); r != nil {
log.Println("WaitGroup at 0", r)
}
}()
if srv.getState() != STATE_SHUTTING_DOWN {
return
}
time.Sleep(d)
log.Println("[STOP - Hammer Time] Forcefully shutting down parent")
for {
if srv.getState() == STATE_TERMINATE {
break
}
srv.wg.Done()
runtime.Gosched()
}
} |
fvbock/endless | 447134032cb6a86814f570257390a379982dfc61 | endless.go | https://github.com/fvbock/endless/blob/447134032cb6a86814f570257390a379982dfc61/endless.go#L550-L563 | go | train | /*
RegisterSignalHook registers a function to be run PRE_SIGNAL or POST_SIGNAL for
a given signal. PRE or POST in this case means before or after the signal
related code endless itself runs
*/ | func (srv *endlessServer) RegisterSignalHook(prePost int, sig os.Signal, f func()) (err error) | /*
RegisterSignalHook registers a function to be run PRE_SIGNAL or POST_SIGNAL for
a given signal. PRE or POST in this case means before or after the signal
related code endless itself runs
*/
func (srv *endlessServer) RegisterSignalHook(prePost int, sig os.Signal, f func()) (err error) | {
if prePost != PRE_SIGNAL && prePost != POST_SIGNAL {
err = fmt.Errorf("Cannot use %v for prePost arg. Must be endless.PRE_SIGNAL or endless.POST_SIGNAL.", sig)
return
}
for _, s := range hookableSignals {
if s == sig {
srv.SignalHooks[prePost][sig] = append(srv.SignalHooks[prePost][sig], f)
return
}
}
err = fmt.Errorf("Signal %v is not supported.", sig)
return
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | sample/concurrent/mock/concurrent_mock.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/concurrent/mock/concurrent_mock.go#L24-L28 | go | train | // NewMockMath creates a new mock instance | func NewMockMath(ctrl *gomock.Controller) *MockMath | // NewMockMath creates a new mock instance
func NewMockMath(ctrl *gomock.Controller) *MockMath | {
mock := &MockMath{ctrl: ctrl}
mock.recorder = &MockMathMockRecorder{mock}
return mock
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | sample/concurrent/mock/concurrent_mock.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/concurrent/mock/concurrent_mock.go#L36-L41 | go | train | // Sum mocks base method | func (m *MockMath) Sum(arg0, arg1 int) int | // Sum mocks base method
func (m *MockMath) Sum(arg0, arg1 int) int | {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Sum", arg0, arg1)
ret0, _ := ret[0].(int)
return ret0
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | sample/concurrent/mock/concurrent_mock.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/concurrent/mock/concurrent_mock.go#L44-L47 | go | train | // Sum indicates an expected call of Sum | func (mr *MockMathMockRecorder) Sum(arg0, arg1 interface{}) *gomock.Call | // Sum indicates an expected call of Sum
func (mr *MockMathMockRecorder) Sum(arg0, arg1 interface{}) *gomock.Call | {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sum", reflect.TypeOf((*MockMath)(nil).Sum), arg0, arg1)
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | mockgen/reflect.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/reflect.go#L54-L90 | go | train | // run the given program and parse the output as a model.Package. | func run(program string) (*model.Package, error) | // run the given program and parse the output as a model.Package.
func run(program string) (*model.Package, error) | {
f, err := ioutil.TempFile("", "")
if err != nil {
return nil, err
}
filename := f.Name()
defer os.Remove(filename)
if err := f.Close(); err != nil {
return nil, err
}
// Run the program.
cmd := exec.Command(program, "-output", filename)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return nil, err
}
f, err = os.Open(filename)
if err != nil {
return nil, err
}
// Process output.
var pkg model.Package
if err := gob.NewDecoder(f).Decode(&pkg); err != nil {
return nil, err
}
if err := f.Close(); err != nil {
return nil, err
}
return &pkg, nil
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | mockgen/reflect.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/reflect.go#L94-L132 | go | train | // runInDir writes the given program into the given dir, runs it there, and
// parses the output as a model.Package. | func runInDir(program []byte, dir string) (*model.Package, error) | // runInDir writes the given program into the given dir, runs it there, and
// parses the output as a model.Package.
func runInDir(program []byte, dir string) (*model.Package, error) | {
// We use TempDir instead of TempFile so we can control the filename.
tmpDir, err := ioutil.TempDir(dir, "gomock_reflect_")
if err != nil {
return nil, err
}
defer func() {
if err := os.RemoveAll(tmpDir); err != nil {
log.Printf("failed to remove temp directory: %s", err)
}
}()
const progSource = "prog.go"
var progBinary = "prog.bin"
if runtime.GOOS == "windows" {
// Windows won't execute a program unless it has a ".exe" suffix.
progBinary += ".exe"
}
if err := ioutil.WriteFile(filepath.Join(tmpDir, progSource), program, 0600); err != nil {
return nil, err
}
cmdArgs := []string{}
cmdArgs = append(cmdArgs, "build")
if *buildFlags != "" {
cmdArgs = append(cmdArgs, *buildFlags)
}
cmdArgs = append(cmdArgs, "-o", progBinary, progSource)
// Build the program.
cmd := exec.Command("go", cmdArgs...)
cmd.Dir = tmpDir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return nil, err
}
return run(filepath.Join(tmpDir, progBinary))
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | sample/user.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/user.go#L95-L108 | go | train | // A function that we will test that uses the above interface.
// It takes a list of keys and values, and puts them in the index. | func Remember(index Index, keys []string, values []interface{}) | // A function that we will test that uses the above interface.
// It takes a list of keys and values, and puts them in the index.
func Remember(index Index, keys []string, values []interface{}) | {
for i, k := range keys {
index.Put(k, values[i])
}
err := index.NillableRet()
if err != nil {
log.Fatalf("Woah! %v", err)
}
if len(keys) > 0 && keys[0] == "a" {
index.Ellip("%d", 0, 1, 1, 2, 3)
index.Ellip("%d", 1, 3, 6, 10, 15)
index.EllipOnly("arg")
}
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L49-L77 | go | train | // newCall creates a *Call. It requires the method type in order to support
// unexported methods. | func newCall(t TestHelper, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call | // newCall creates a *Call. It requires the method type in order to support
// unexported methods.
func newCall(t TestHelper, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call | {
t.Helper()
// TODO: check arity, types.
margs := make([]Matcher, len(args))
for i, arg := range args {
if m, ok := arg.(Matcher); ok {
margs[i] = m
} else if arg == nil {
// Handle nil specially so that passing a nil interface value
// will match the typed nils of concrete args.
margs[i] = Nil()
} else {
margs[i] = Eq(arg)
}
}
origin := callerInfo(3)
actions := []func([]interface{}) []interface{}{func([]interface{}) []interface{} {
// Synthesize the zero value for each of the return args' types.
rets := make([]interface{}, methodType.NumOut())
for i := 0; i < methodType.NumOut(); i++ {
rets[i] = reflect.Zero(methodType.Out(i)).Interface()
}
return rets
}}
return &Call{t: t, receiver: receiver, method: method, methodType: methodType,
args: margs, origin: origin, minCalls: 1, maxCalls: 1, actions: actions}
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L87-L93 | go | train | // MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called, MinTimes also
// sets the maximum number of calls to infinity. | func (c *Call) MinTimes(n int) *Call | // MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called, MinTimes also
// sets the maximum number of calls to infinity.
func (c *Call) MinTimes(n int) *Call | {
c.minCalls = n
if c.maxCalls == 1 {
c.maxCalls = 1e8
}
return c
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L97-L103 | go | train | // MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called, MaxTimes also
// sets the minimum number of calls to 0. | func (c *Call) MaxTimes(n int) *Call | // MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called, MaxTimes also
// sets the minimum number of calls to 0.
func (c *Call) MaxTimes(n int) *Call | {
c.maxCalls = n
if c.minCalls == 1 {
c.minCalls = 0
}
return c
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L108-L131 | go | train | // DoAndReturn declares the action to run when the call is matched.
// The return values from this function are returned by the mocked function.
// It takes an interface{} argument to support n-arity functions. | func (c *Call) DoAndReturn(f interface{}) *Call | // DoAndReturn declares the action to run when the call is matched.
// The return values from this function are returned by the mocked function.
// It takes an interface{} argument to support n-arity functions.
func (c *Call) DoAndReturn(f interface{}) *Call | {
// TODO: Check arity and types here, rather than dying badly elsewhere.
v := reflect.ValueOf(f)
c.addAction(func(args []interface{}) []interface{} {
vargs := make([]reflect.Value, len(args))
ft := v.Type()
for i := 0; i < len(args); i++ {
if args[i] != nil {
vargs[i] = reflect.ValueOf(args[i])
} else {
// Use the zero value for the arg.
vargs[i] = reflect.Zero(ft.In(i))
}
}
vrets := v.Call(vargs)
rets := make([]interface{}, len(vrets))
for i, ret := range vrets {
rets[i] = ret.Interface()
}
return rets
})
return c
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L137-L156 | go | train | // Do declares the action to run when the call is matched. The function's
// return values are ignored to retain backward compatibility. To use the
// return values call DoAndReturn.
// It takes an interface{} argument to support n-arity functions. | func (c *Call) Do(f interface{}) *Call | // Do declares the action to run when the call is matched. The function's
// return values are ignored to retain backward compatibility. To use the
// return values call DoAndReturn.
// It takes an interface{} argument to support n-arity functions.
func (c *Call) Do(f interface{}) *Call | {
// TODO: Check arity and types here, rather than dying badly elsewhere.
v := reflect.ValueOf(f)
c.addAction(func(args []interface{}) []interface{} {
vargs := make([]reflect.Value, len(args))
ft := v.Type()
for i := 0; i < len(args); i++ {
if args[i] != nil {
vargs[i] = reflect.ValueOf(args[i])
} else {
// Use the zero value for the arg.
vargs[i] = reflect.Zero(ft.In(i))
}
}
v.Call(vargs)
return nil
})
return c
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L159-L196 | go | train | // Return declares the values to be returned by the mocked function call. | func (c *Call) Return(rets ...interface{}) *Call | // Return declares the values to be returned by the mocked function call.
func (c *Call) Return(rets ...interface{}) *Call | {
c.t.Helper()
mt := c.methodType
if len(rets) != mt.NumOut() {
c.t.Fatalf("wrong number of arguments to Return for %T.%v: got %d, want %d [%s]",
c.receiver, c.method, len(rets), mt.NumOut(), c.origin)
}
for i, ret := range rets {
if got, want := reflect.TypeOf(ret), mt.Out(i); got == want {
// Identical types; nothing to do.
} else if got == nil {
// Nil needs special handling.
switch want.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
// ok
default:
c.t.Fatalf("argument %d to Return for %T.%v is nil, but %v is not nillable [%s]",
i, c.receiver, c.method, want, c.origin)
}
} else if got.AssignableTo(want) {
// Assignable type relation. Make the assignment now so that the generated code
// can return the values with a type assertion.
v := reflect.New(want).Elem()
v.Set(reflect.ValueOf(ret))
rets[i] = v.Interface()
} else {
c.t.Fatalf("wrong type of argument %d to Return for %T.%v: %v is not assignable to %v [%s]",
i, c.receiver, c.method, got, want, c.origin)
}
}
c.addAction(func([]interface{}) []interface{} {
return rets
})
return c
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L199-L202 | go | train | // Times declares the exact number of times a function call is expected to be executed. | func (c *Call) Times(n int) *Call | // Times declares the exact number of times a function call is expected to be executed.
func (c *Call) Times(n int) *Call | {
c.minCalls, c.maxCalls = n, n
return c
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L207-L247 | go | train | // SetArg declares an action that will set the nth argument's value,
// indirected through a pointer. Or, in the case of a slice, SetArg
// will copy value's elements into the nth argument. | func (c *Call) SetArg(n int, value interface{}) *Call | // SetArg declares an action that will set the nth argument's value,
// indirected through a pointer. Or, in the case of a slice, SetArg
// will copy value's elements into the nth argument.
func (c *Call) SetArg(n int, value interface{}) *Call | {
c.t.Helper()
mt := c.methodType
// TODO: This will break on variadic methods.
// We will need to check those at invocation time.
if n < 0 || n >= mt.NumIn() {
c.t.Fatalf("SetArg(%d, ...) called for a method with %d args [%s]",
n, mt.NumIn(), c.origin)
}
// Permit setting argument through an interface.
// In the interface case, we don't (nay, can't) check the type here.
at := mt.In(n)
switch at.Kind() {
case reflect.Ptr:
dt := at.Elem()
if vt := reflect.TypeOf(value); !vt.AssignableTo(dt) {
c.t.Fatalf("SetArg(%d, ...) argument is a %v, not assignable to %v [%s]",
n, vt, dt, c.origin)
}
case reflect.Interface:
// nothing to do
case reflect.Slice:
// nothing to do
default:
c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice type %v [%s]",
n, at, c.origin)
}
c.addAction(func(args []interface{}) []interface{} {
v := reflect.ValueOf(value)
switch reflect.TypeOf(args[n]).Kind() {
case reflect.Slice:
setSlice(args[n], v)
default:
reflect.ValueOf(args[n]).Elem().Set(v)
}
return nil
})
return c
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L250-L257 | go | train | // isPreReq returns true if other is a direct or indirect prerequisite to c. | func (c *Call) isPreReq(other *Call) bool | // isPreReq returns true if other is a direct or indirect prerequisite to c.
func (c *Call) isPreReq(other *Call) bool | {
for _, preReq := range c.preReqs {
if other == preReq || preReq.isPreReq(other) {
return true
}
}
return false
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L260-L272 | go | train | // After declares that the call may only match after preReq has been exhausted. | func (c *Call) After(preReq *Call) *Call | // After declares that the call may only match after preReq has been exhausted.
func (c *Call) After(preReq *Call) *Call | {
c.t.Helper()
if c == preReq {
c.t.Fatalf("A call isn't allowed to be its own prerequisite")
}
if preReq.isPreReq(c) {
c.t.Fatalf("Loop in call order: %v is a prerequisite to %v (possibly indirectly).", c, preReq)
}
c.preReqs = append(c.preReqs, preReq)
return c
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L295-L389 | go | train | // Tests if the given call matches the expected call.
// If yes, returns nil. If no, returns error with message explaining why it does not match. | func (c *Call) matches(args []interface{}) error | // Tests if the given call matches the expected call.
// If yes, returns nil. If no, returns error with message explaining why it does not match.
func (c *Call) matches(args []interface{}) error | {
if !c.methodType.IsVariadic() {
if len(args) != len(c.args) {
return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
c.origin, len(args), len(c.args))
}
for i, m := range c.args {
if !m.Matches(args[i]) {
return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
c.origin, strconv.Itoa(i), args[i], m)
}
}
} else {
if len(c.args) < c.methodType.NumIn()-1 {
return fmt.Errorf("Expected call at %s has the wrong number of matchers. Got: %d, want: %d",
c.origin, len(c.args), c.methodType.NumIn()-1)
}
if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) {
return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
c.origin, len(args), len(c.args))
}
if len(args) < len(c.args)-1 {
return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d",
c.origin, len(args), len(c.args)-1)
}
for i, m := range c.args {
if i < c.methodType.NumIn()-1 {
// Non-variadic args
if !m.Matches(args[i]) {
return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
c.origin, strconv.Itoa(i), args[i], m)
}
continue
}
// The last arg has a possibility of a variadic argument, so let it branch
// sample: Foo(a int, b int, c ...int)
if i < len(c.args) && i < len(args) {
if m.Matches(args[i]) {
// Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any())
// Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher)
// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC)
// Got Foo(a, b) want Foo(matcherA, matcherB)
// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD)
continue
}
}
// The number of actual args don't match the number of matchers,
// or the last matcher is a slice and the last arg is not.
// If this function still matches it is because the last matcher
// matches all the remaining arguments or the lack of any.
// Convert the remaining arguments, if any, into a slice of the
// expected type.
vargsType := c.methodType.In(c.methodType.NumIn() - 1)
vargs := reflect.MakeSlice(vargsType, 0, len(args)-i)
for _, arg := range args[i:] {
vargs = reflect.Append(vargs, reflect.ValueOf(arg))
}
if m.Matches(vargs.Interface()) {
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any())
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher)
// Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any())
// Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher)
break
}
// Wrong number of matchers or not match. Fail.
// Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD)
// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD)
// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE)
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD)
// Got Foo(a, b, c) want Foo(matcherA, matcherB)
return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
c.origin, strconv.Itoa(i), args[i:], c.args[i])
}
}
// Check that all prerequisite calls have been satisfied.
for _, preReqCall := range c.preReqs {
if !preReqCall.satisfied() {
return fmt.Errorf("Expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v",
c.origin, preReqCall, c)
}
}
// Check that the call is not exhausted.
if c.exhausted() {
return fmt.Errorf("Expected call at %s has already been called the max number of times.", c.origin)
}
return nil
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L393-L397 | go | train | // dropPrereqs tells the expected Call to not re-check prerequisite calls any
// longer, and to return its current set. | func (c *Call) dropPrereqs() (preReqs []*Call) | // dropPrereqs tells the expected Call to not re-check prerequisite calls any
// longer, and to return its current set.
func (c *Call) dropPrereqs() (preReqs []*Call) | {
preReqs = c.preReqs
c.preReqs = nil
return
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/call.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/call.go#L405-L409 | go | train | // InOrder declares that the given calls should occur in order. | func InOrder(calls ...*Call) | // InOrder declares that the given calls should occur in order.
func InOrder(calls ...*Call) | {
for i := 1; i < len(calls); i++ {
calls[i].After(calls[i-1])
}
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | mockgen/mockgen.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/mockgen.go#L215-L235 | go | train | // sanitize cleans up a string to make a suitable package name. | func sanitize(s string) string | // sanitize cleans up a string to make a suitable package name.
func sanitize(s string) string | {
t := ""
for _, r := range s {
if t == "" {
if unicode.IsLetter(r) || r == '_' {
t += string(r)
continue
}
} else {
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
t += string(r)
continue
}
}
t += "_"
}
if t == "_" {
t = "x"
}
return t
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | mockgen/mockgen.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/mockgen.go#L330-L336 | go | train | // The name of the mock type to use for the given interface identifier. | func (g *generator) mockName(typeName string) string | // The name of the mock type to use for the given interface identifier.
func (g *generator) mockName(typeName string) string | {
if mockName, ok := g.mockNames[typeName]; ok {
return mockName
}
return "Mock" + typeName
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | mockgen/mockgen.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/mockgen.go#L411-L474 | go | train | // GenerateMockMethod generates a mock method implementation.
// If non-empty, pkgOverride is the package in which unqualified types reside. | func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOverride string) error | // GenerateMockMethod generates a mock method implementation.
// If non-empty, pkgOverride is the package in which unqualified types reside.
func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOverride string) error | {
argNames := g.getArgNames(m)
argTypes := g.getArgTypes(m, pkgOverride)
argString := makeArgString(argNames, argTypes)
rets := make([]string, len(m.Out))
for i, p := range m.Out {
rets[i] = p.Type.String(g.packageMap, pkgOverride)
}
retString := strings.Join(rets, ", ")
if len(rets) > 1 {
retString = "(" + retString + ")"
}
if retString != "" {
retString = " " + retString
}
ia := newIdentifierAllocator(argNames)
idRecv := ia.allocateIdentifier("m")
g.p("// %v mocks base method", m.Name)
g.p("func (%v *%v) %v(%v)%v {", idRecv, mockType, m.Name, argString, retString)
g.in()
g.p("%s.ctrl.T.Helper()", idRecv)
var callArgs string
if m.Variadic == nil {
if len(argNames) > 0 {
callArgs = ", " + strings.Join(argNames, ", ")
}
} else {
// Non-trivial. The generated code must build a []interface{},
// but the variadic argument may be any type.
idVarArgs := ia.allocateIdentifier("varargs")
idVArg := ia.allocateIdentifier("a")
g.p("%s := []interface{}{%s}", idVarArgs, strings.Join(argNames[:len(argNames)-1], ", "))
g.p("for _, %s := range %s {", idVArg, argNames[len(argNames)-1])
g.in()
g.p("%s = append(%s, %s)", idVarArgs, idVarArgs, idVArg)
g.out()
g.p("}")
callArgs = ", " + idVarArgs + "..."
}
if len(m.Out) == 0 {
g.p(`%v.ctrl.Call(%v, %q%v)`, idRecv, idRecv, m.Name, callArgs)
} else {
idRet := ia.allocateIdentifier("ret")
g.p(`%v := %v.ctrl.Call(%v, %q%v)`, idRet, idRecv, idRecv, m.Name, callArgs)
// Go does not allow "naked" type assertions on nil values, so we use the two-value form here.
// The value of that is either (x.(T), true) or (Z, false), where Z is the zero value for T.
// Happily, this coincides with the semantics we want here.
retNames := make([]string, len(rets))
for i, t := range rets {
retNames[i] = ia.allocateIdentifier(fmt.Sprintf("ret%d", i))
g.p("%s, _ := %s[%d].(%s)", retNames[i], idRet, i, t)
}
g.p("return " + strings.Join(retNames, ", "))
}
g.out()
g.p("}")
return nil
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | mockgen/mockgen.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/mockgen/mockgen.go#L582-L588 | go | train | // Output returns the generator's output, formatted in the standard Go style. | func (g *generator) Output() []byte | // Output returns the generator's output, formatted in the standard Go style.
func (g *generator) Output() []byte | {
src, err := format.Source(g.buf.Bytes())
if err != nil {
log.Fatalf("Failed to format generated source code: %s\n%s", err, g.buf.String())
}
return src
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/callset.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/callset.go#L42-L49 | go | train | // Add adds a new expected call. | func (cs callSet) Add(call *Call) | // Add adds a new expected call.
func (cs callSet) Add(call *Call) | {
key := callSetKey{call.receiver, call.method}
m := cs.expected
if call.exhausted() {
m = cs.exhausted
}
m[key] = append(m[key], call)
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/callset.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/callset.go#L52-L63 | go | train | // Remove removes an expected call. | func (cs callSet) Remove(call *Call) | // Remove removes an expected call.
func (cs callSet) Remove(call *Call) | {
key := callSetKey{call.receiver, call.method}
calls := cs.expected[key]
for i, c := range calls {
if c == call {
// maintain order for remaining calls
cs.expected[key] = append(calls[:i], calls[i+1:]...)
cs.exhausted[key] = append(cs.exhausted[key], call)
break
}
}
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/callset.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/callset.go#L66-L95 | go | train | // FindMatch searches for a matching call. Returns error with explanation message if no call matched. | func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) (*Call, error) | // FindMatch searches for a matching call. Returns error with explanation message if no call matched.
func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) (*Call, error) | {
key := callSetKey{receiver, method}
// Search through the expected calls.
expected := cs.expected[key]
var callsErrors bytes.Buffer
for _, call := range expected {
err := call.matches(args)
if err != nil {
fmt.Fprintf(&callsErrors, "\n%v", err)
} else {
return call, nil
}
}
// If we haven't found a match then search through the exhausted calls so we
// get useful error messages.
exhausted := cs.exhausted[key]
for _, call := range exhausted {
if err := call.matches(args); err != nil {
fmt.Fprintf(&callsErrors, "\n%v", err)
}
}
if len(expected)+len(exhausted) == 0 {
fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method)
}
return nil, fmt.Errorf(callsErrors.String())
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | gomock/callset.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/gomock/callset.go#L98-L108 | go | train | // Failures returns the calls that are not satisfied. | func (cs callSet) Failures() []*Call | // Failures returns the calls that are not satisfied.
func (cs callSet) Failures() []*Call | {
failures := make([]*Call, 0, len(cs.expected))
for _, calls := range cs.expected {
for _, call := range calls {
if !call.satisfied() {
failures = append(failures, call)
}
}
}
return failures
} |
golang/mock | 937870445b8bddd7f05ea90e81c58ebe83681534 | sample/mock_user/mock_user.go | https://github.com/golang/mock/blob/937870445b8bddd7f05ea90e81c58ebe83681534/sample/mock_user/mock_user.go#L35-L39 | go | train | // NewMockIndex creates a new mock instance | func NewMockIndex(ctrl *gomock.Controller) *MockIndex | // NewMockIndex creates a new mock instance
func NewMockIndex(ctrl *gomock.Controller) *MockIndex | {
mock := &MockIndex{ctrl: ctrl}
mock.recorder = &MockIndexMockRecorder{mock}
return mock
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.