id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
17,500
haifengl/smile
math/src/main/java/smile/math/matrix/JMatrix.java
JMatrix.eltran
private static void eltran(DenseMatrix A, DenseMatrix V, int[] perm) { int n = A.nrows(); for (int mp = n - 2; mp > 0; mp--) { for (int k = mp + 1; k < n; k++) { V.set(k, mp, A.get(k, mp - 1)); } int i = perm[mp]; if (i != mp) { for (int j = mp; j < n; j++) { V.set(mp, j, V.get(i, j)); V.set(i, j, 0.0); } V.set(i, mp, 1.0); } } }
java
private static void eltran(DenseMatrix A, DenseMatrix V, int[] perm) { int n = A.nrows(); for (int mp = n - 2; mp > 0; mp--) { for (int k = mp + 1; k < n; k++) { V.set(k, mp, A.get(k, mp - 1)); } int i = perm[mp]; if (i != mp) { for (int j = mp; j < n; j++) { V.set(mp, j, V.get(i, j)); V.set(i, j, 0.0); } V.set(i, mp, 1.0); } } }
[ "private", "static", "void", "eltran", "(", "DenseMatrix", "A", ",", "DenseMatrix", "V", ",", "int", "[", "]", "perm", ")", "{", "int", "n", "=", "A", ".", "nrows", "(", ")", ";", "for", "(", "int", "mp", "=", "n", "-", "2", ";", "mp", ">", "0", ";", "mp", "--", ")", "{", "for", "(", "int", "k", "=", "mp", "+", "1", ";", "k", "<", "n", ";", "k", "++", ")", "{", "V", ".", "set", "(", "k", ",", "mp", ",", "A", ".", "get", "(", "k", ",", "mp", "-", "1", ")", ")", ";", "}", "int", "i", "=", "perm", "[", "mp", "]", ";", "if", "(", "i", "!=", "mp", ")", "{", "for", "(", "int", "j", "=", "mp", ";", "j", "<", "n", ";", "j", "++", ")", "{", "V", ".", "set", "(", "mp", ",", "j", ",", "V", ".", "get", "(", "i", ",", "j", ")", ")", ";", "V", ".", "set", "(", "i", ",", "j", ",", "0.0", ")", ";", "}", "V", ".", "set", "(", "i", ",", "mp", ",", "1.0", ")", ";", "}", "}", "}" ]
Accumulate the stabilized elementary similarity transformations used in the reduction of a real nonsymmetric matrix to upper Hessenberg form by elmhes.
[ "Accumulate", "the", "stabilized", "elementary", "similarity", "transformations", "used", "in", "the", "reduction", "of", "a", "real", "nonsymmetric", "matrix", "to", "upper", "Hessenberg", "form", "by", "elmhes", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/JMatrix.java#L1933-L1948
17,501
haifengl/smile
math/src/main/java/smile/math/matrix/JMatrix.java
JMatrix.cdiv
private static Complex cdiv(double xr, double xi, double yr, double yi) { double cdivr, cdivi; double r, d; if (Math.abs(yr) > Math.abs(yi)) { r = yi / yr; d = yr + r * yi; cdivr = (xr + r * xi) / d; cdivi = (xi - r * xr) / d; } else { r = yr / yi; d = yi + r * yr; cdivr = (r * xr + xi) / d; cdivi = (r * xi - xr) / d; } return new Complex(cdivr, cdivi); }
java
private static Complex cdiv(double xr, double xi, double yr, double yi) { double cdivr, cdivi; double r, d; if (Math.abs(yr) > Math.abs(yi)) { r = yi / yr; d = yr + r * yi; cdivr = (xr + r * xi) / d; cdivi = (xi - r * xr) / d; } else { r = yr / yi; d = yi + r * yr; cdivr = (r * xr + xi) / d; cdivi = (r * xi - xr) / d; } return new Complex(cdivr, cdivi); }
[ "private", "static", "Complex", "cdiv", "(", "double", "xr", ",", "double", "xi", ",", "double", "yr", ",", "double", "yi", ")", "{", "double", "cdivr", ",", "cdivi", ";", "double", "r", ",", "d", ";", "if", "(", "Math", ".", "abs", "(", "yr", ")", ">", "Math", ".", "abs", "(", "yi", ")", ")", "{", "r", "=", "yi", "/", "yr", ";", "d", "=", "yr", "+", "r", "*", "yi", ";", "cdivr", "=", "(", "xr", "+", "r", "*", "xi", ")", "/", "d", ";", "cdivi", "=", "(", "xi", "-", "r", "*", "xr", ")", "/", "d", ";", "}", "else", "{", "r", "=", "yr", "/", "yi", ";", "d", "=", "yi", "+", "r", "*", "yr", ";", "cdivr", "=", "(", "r", "*", "xr", "+", "xi", ")", "/", "d", ";", "cdivi", "=", "(", "r", "*", "xi", "-", "xr", ")", "/", "d", ";", "}", "return", "new", "Complex", "(", "cdivr", ",", "cdivi", ")", ";", "}" ]
Complex scalar division.
[ "Complex", "scalar", "division", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/JMatrix.java#L2409-L2425
17,502
haifengl/smile
math/src/main/java/smile/math/matrix/JMatrix.java
JMatrix.sort
protected static void sort(double[] d, double[] e) { int i = 0; int n = d.length; for (int j = 1; j < n; j++) { double real = d[j]; double img = e[j]; for (i = j - 1; i >= 0; i--) { if (d[i] >= d[j]) { break; } d[i + 1] = d[i]; e[i + 1] = e[i]; } d[i + 1] = real; e[i + 1] = img; } }
java
protected static void sort(double[] d, double[] e) { int i = 0; int n = d.length; for (int j = 1; j < n; j++) { double real = d[j]; double img = e[j]; for (i = j - 1; i >= 0; i--) { if (d[i] >= d[j]) { break; } d[i + 1] = d[i]; e[i + 1] = e[i]; } d[i + 1] = real; e[i + 1] = img; } }
[ "protected", "static", "void", "sort", "(", "double", "[", "]", "d", ",", "double", "[", "]", "e", ")", "{", "int", "i", "=", "0", ";", "int", "n", "=", "d", ".", "length", ";", "for", "(", "int", "j", "=", "1", ";", "j", "<", "n", ";", "j", "++", ")", "{", "double", "real", "=", "d", "[", "j", "]", ";", "double", "img", "=", "e", "[", "j", "]", ";", "for", "(", "i", "=", "j", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "d", "[", "i", "]", ">=", "d", "[", "j", "]", ")", "{", "break", ";", "}", "d", "[", "i", "+", "1", "]", "=", "d", "[", "i", "]", ";", "e", "[", "i", "+", "1", "]", "=", "e", "[", "i", "]", ";", "}", "d", "[", "i", "+", "1", "]", "=", "real", ";", "e", "[", "i", "+", "1", "]", "=", "img", ";", "}", "}" ]
Sort eigenvalues.
[ "Sort", "eigenvalues", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/JMatrix.java#L2430-L2446
17,503
haifengl/smile
math/src/main/java/smile/math/matrix/JMatrix.java
JMatrix.sort
protected static void sort(double[] d, double[] e, DenseMatrix V) { int i = 0; int n = d.length; double[] temp = new double[n]; for (int j = 1; j < n; j++) { double real = d[j]; double img = e[j]; for (int k = 0; k < n; k++) { temp[k] = V.get(k, j); } for (i = j - 1; i >= 0; i--) { if (d[i] >= d[j]) { break; } d[i + 1] = d[i]; e[i + 1] = e[i]; for (int k = 0; k < n; k++) { V.set(k, i + 1, V.get(k, i)); } } d[i + 1] = real; e[i + 1] = img; for (int k = 0; k < n; k++) { V.set(k, i + 1, temp[k]); } } }
java
protected static void sort(double[] d, double[] e, DenseMatrix V) { int i = 0; int n = d.length; double[] temp = new double[n]; for (int j = 1; j < n; j++) { double real = d[j]; double img = e[j]; for (int k = 0; k < n; k++) { temp[k] = V.get(k, j); } for (i = j - 1; i >= 0; i--) { if (d[i] >= d[j]) { break; } d[i + 1] = d[i]; e[i + 1] = e[i]; for (int k = 0; k < n; k++) { V.set(k, i + 1, V.get(k, i)); } } d[i + 1] = real; e[i + 1] = img; for (int k = 0; k < n; k++) { V.set(k, i + 1, temp[k]); } } }
[ "protected", "static", "void", "sort", "(", "double", "[", "]", "d", ",", "double", "[", "]", "e", ",", "DenseMatrix", "V", ")", "{", "int", "i", "=", "0", ";", "int", "n", "=", "d", ".", "length", ";", "double", "[", "]", "temp", "=", "new", "double", "[", "n", "]", ";", "for", "(", "int", "j", "=", "1", ";", "j", "<", "n", ";", "j", "++", ")", "{", "double", "real", "=", "d", "[", "j", "]", ";", "double", "img", "=", "e", "[", "j", "]", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "n", ";", "k", "++", ")", "{", "temp", "[", "k", "]", "=", "V", ".", "get", "(", "k", ",", "j", ")", ";", "}", "for", "(", "i", "=", "j", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "d", "[", "i", "]", ">=", "d", "[", "j", "]", ")", "{", "break", ";", "}", "d", "[", "i", "+", "1", "]", "=", "d", "[", "i", "]", ";", "e", "[", "i", "+", "1", "]", "=", "e", "[", "i", "]", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "n", ";", "k", "++", ")", "{", "V", ".", "set", "(", "k", ",", "i", "+", "1", ",", "V", ".", "get", "(", "k", ",", "i", ")", ")", ";", "}", "}", "d", "[", "i", "+", "1", "]", "=", "real", ";", "e", "[", "i", "+", "1", "]", "=", "img", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "n", ";", "k", "++", ")", "{", "V", ".", "set", "(", "k", ",", "i", "+", "1", ",", "temp", "[", "k", "]", ")", ";", "}", "}", "}" ]
Sort eigenvalues and eigenvectors.
[ "Sort", "eigenvalues", "and", "eigenvectors", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/JMatrix.java#L2451-L2477
17,504
haifengl/smile
math/src/main/java/smile/stat/distribution/GammaDistribution.java
GammaDistribution.rand
@Override public double rand() { if (k - Math.floor(k) != 0.0) { throw new IllegalArgumentException("Gamma random number generator support only integer shape parameter."); } double r = 0.0; for (int i = 0; i < k; i++) { r += Math.log(Math.random()); } r *= -theta; return r; }
java
@Override public double rand() { if (k - Math.floor(k) != 0.0) { throw new IllegalArgumentException("Gamma random number generator support only integer shape parameter."); } double r = 0.0; for (int i = 0; i < k; i++) { r += Math.log(Math.random()); } r *= -theta; return r; }
[ "@", "Override", "public", "double", "rand", "(", ")", "{", "if", "(", "k", "-", "Math", ".", "floor", "(", "k", ")", "!=", "0.0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Gamma random number generator support only integer shape parameter.\"", ")", ";", "}", "double", "r", "=", "0.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "k", ";", "i", "++", ")", "{", "r", "+=", "Math", ".", "log", "(", "Math", ".", "random", "(", ")", ")", ";", "}", "r", "*=", "-", "theta", ";", "return", "r", ";", "}" ]
Only support shape parameter k of integer.
[ "Only", "support", "shape", "parameter", "k", "of", "integer", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/stat/distribution/GammaDistribution.java#L160-L175
17,505
haifengl/smile
plot/src/main/java/smile/plot/PlotCanvas.java
PlotCanvas.initCanvas
private void initCanvas() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); if (ge.isHeadless()) { setPreferredSize(new Dimension(1600,1200)); } setLayout(new BorderLayout()); canvas = new MathCanvas(); add(canvas, BorderLayout.CENTER); initContextMenauAndToolBar(); // set a new dismiss delay to a really big value, default is 4 sec. //ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE); }
java
private void initCanvas() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); if (ge.isHeadless()) { setPreferredSize(new Dimension(1600,1200)); } setLayout(new BorderLayout()); canvas = new MathCanvas(); add(canvas, BorderLayout.CENTER); initContextMenauAndToolBar(); // set a new dismiss delay to a really big value, default is 4 sec. //ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE); }
[ "private", "void", "initCanvas", "(", ")", "{", "GraphicsEnvironment", "ge", "=", "GraphicsEnvironment", ".", "getLocalGraphicsEnvironment", "(", ")", ";", "if", "(", "ge", ".", "isHeadless", "(", ")", ")", "{", "setPreferredSize", "(", "new", "Dimension", "(", "1600", ",", "1200", ")", ")", ";", "}", "setLayout", "(", "new", "BorderLayout", "(", ")", ")", ";", "canvas", "=", "new", "MathCanvas", "(", ")", ";", "add", "(", "canvas", ",", "BorderLayout", ".", "CENTER", ")", ";", "initContextMenauAndToolBar", "(", ")", ";", "// set a new dismiss delay to a really big value, default is 4 sec.", "//ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE);", "}" ]
Initialize the canvas.
[ "Initialize", "the", "canvas", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/PlotCanvas.java#L565-L581
17,506
haifengl/smile
plot/src/main/java/smile/plot/PlotCanvas.java
PlotCanvas.save
public void save(File file) throws IOException { BufferedImage bi = new BufferedImage(canvas.getWidth(), canvas.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = bi.createGraphics(); canvas.print(g2d); ImageIO.write(bi, FileChooser.getExtension(file), file); }
java
public void save(File file) throws IOException { BufferedImage bi = new BufferedImage(canvas.getWidth(), canvas.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = bi.createGraphics(); canvas.print(g2d); ImageIO.write(bi, FileChooser.getExtension(file), file); }
[ "public", "void", "save", "(", "File", "file", ")", "throws", "IOException", "{", "BufferedImage", "bi", "=", "new", "BufferedImage", "(", "canvas", ".", "getWidth", "(", ")", ",", "canvas", ".", "getHeight", "(", ")", ",", "BufferedImage", ".", "TYPE_INT_ARGB", ")", ";", "Graphics2D", "g2d", "=", "bi", ".", "createGraphics", "(", ")", ";", "canvas", ".", "print", "(", "g2d", ")", ";", "ImageIO", ".", "write", "(", "bi", ",", "FileChooser", ".", "getExtension", "(", "file", ")", ",", "file", ")", ";", "}" ]
Exports the plot to an image file. @param file the destination file. @throws IOException if an error occurs during writing.
[ "Exports", "the", "plot", "to", "an", "image", "file", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/PlotCanvas.java#L1068-L1074
17,507
haifengl/smile
plot/src/main/java/smile/plot/PlotCanvas.java
PlotCanvas.reset
public void reset() { base.reset(); graphics.projection.reset(); baseGrid.setBase(base); if (graphics.projection instanceof Projection3D) { ((Projection3D) graphics.projection).setDefaultView(); } canvas.repaint(); }
java
public void reset() { base.reset(); graphics.projection.reset(); baseGrid.setBase(base); if (graphics.projection instanceof Projection3D) { ((Projection3D) graphics.projection).setDefaultView(); } canvas.repaint(); }
[ "public", "void", "reset", "(", ")", "{", "base", ".", "reset", "(", ")", ";", "graphics", ".", "projection", ".", "reset", "(", ")", ";", "baseGrid", ".", "setBase", "(", "base", ")", ";", "if", "(", "graphics", ".", "projection", "instanceof", "Projection3D", ")", "{", "(", "(", "Projection3D", ")", "graphics", ".", "projection", ")", ".", "setDefaultView", "(", ")", ";", "}", "canvas", ".", "repaint", "(", ")", ";", "}" ]
Resets the plot.
[ "Resets", "the", "plot", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/PlotCanvas.java#L1110-L1120
17,508
haifengl/smile
plot/src/main/java/smile/plot/PlotCanvas.java
PlotCanvas.initBase
private void initBase(double[] lowerBound, double[] upperBound, boolean extendBound) { base = new Base(lowerBound, upperBound, extendBound); backupBase = base; baseGrid = new BaseGrid(base); }
java
private void initBase(double[] lowerBound, double[] upperBound, boolean extendBound) { base = new Base(lowerBound, upperBound, extendBound); backupBase = base; baseGrid = new BaseGrid(base); }
[ "private", "void", "initBase", "(", "double", "[", "]", "lowerBound", ",", "double", "[", "]", "upperBound", ",", "boolean", "extendBound", ")", "{", "base", "=", "new", "Base", "(", "lowerBound", ",", "upperBound", ",", "extendBound", ")", ";", "backupBase", "=", "base", ";", "baseGrid", "=", "new", "BaseGrid", "(", "base", ")", ";", "}" ]
Initialize a coordinate base.
[ "Initialize", "a", "coordinate", "base", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/PlotCanvas.java#L1145-L1149
17,509
haifengl/smile
plot/src/main/java/smile/plot/PlotCanvas.java
PlotCanvas.add
public void add(Plot p) { shapes.add(p); JComponent[] tb = p.getToolBar(); if (tb != null) { toolbar.addSeparator(); for (JComponent comp : tb) { toolbar.add(comp); } } repaint(); }
java
public void add(Plot p) { shapes.add(p); JComponent[] tb = p.getToolBar(); if (tb != null) { toolbar.addSeparator(); for (JComponent comp : tb) { toolbar.add(comp); } } repaint(); }
[ "public", "void", "add", "(", "Plot", "p", ")", "{", "shapes", ".", "add", "(", "p", ")", ";", "JComponent", "[", "]", "tb", "=", "p", ".", "getToolBar", "(", ")", ";", "if", "(", "tb", "!=", "null", ")", "{", "toolbar", ".", "addSeparator", "(", ")", ";", "for", "(", "JComponent", "comp", ":", "tb", ")", "{", "toolbar", ".", "add", "(", "comp", ")", ";", "}", "}", "repaint", "(", ")", ";", "}" ]
Add a graphical shape to the canvas.
[ "Add", "a", "graphical", "shape", "to", "the", "canvas", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/PlotCanvas.java#L1319-L1331
17,510
haifengl/smile
plot/src/main/java/smile/plot/PlotCanvas.java
PlotCanvas.remove
public void remove(Plot p) { shapes.remove(p); JComponent[] tb = p.getToolBar(); if (tb != null) { for (JComponent comp : tb) { toolbar.remove(comp); } } repaint(); }
java
public void remove(Plot p) { shapes.remove(p); JComponent[] tb = p.getToolBar(); if (tb != null) { for (JComponent comp : tb) { toolbar.remove(comp); } } repaint(); }
[ "public", "void", "remove", "(", "Plot", "p", ")", "{", "shapes", ".", "remove", "(", "p", ")", ";", "JComponent", "[", "]", "tb", "=", "p", ".", "getToolBar", "(", ")", ";", "if", "(", "tb", "!=", "null", ")", "{", "for", "(", "JComponent", "comp", ":", "tb", ")", "{", "toolbar", ".", "remove", "(", "comp", ")", ";", "}", "}", "repaint", "(", ")", ";", "}" ]
Remove a graphical shape from the canvas.
[ "Remove", "a", "graphical", "shape", "from", "the", "canvas", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/PlotCanvas.java#L1336-L1347
17,511
haifengl/smile
plot/src/main/java/smile/plot/PlotCanvas.java
PlotCanvas.point
public void point(char legend, Color color, double... coord) { add(new Point(legend, color, coord)); }
java
public void point(char legend, Color color, double... coord) { add(new Point(legend, color, coord)); }
[ "public", "void", "point", "(", "char", "legend", ",", "Color", "color", ",", "double", "...", "coord", ")", "{", "add", "(", "new", "Point", "(", "legend", ",", "color", ",", "coord", ")", ")", ";", "}" ]
Adds a point to this canvas.
[ "Adds", "a", "point", "to", "this", "canvas", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/PlotCanvas.java#L1457-L1459
17,512
haifengl/smile
plot/src/main/java/smile/plot/PlotCanvas.java
PlotCanvas.line
public LinePlot line(double[] y, Line.Style style) { return line(null, y, style); }
java
public LinePlot line(double[] y, Line.Style style) { return line(null, y, style); }
[ "public", "LinePlot", "line", "(", "double", "[", "]", "y", ",", "Line", ".", "Style", "style", ")", "{", "return", "line", "(", "null", ",", "y", ",", "style", ")", ";", "}" ]
Add a poly line plot of given data into the current canvas. @param y a data vector that describes y coordinates of points. The x coordinates will be [0, n), where n is the length of y. @param style the stroke style of line.
[ "Add", "a", "poly", "line", "plot", "of", "given", "data", "into", "the", "current", "canvas", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/PlotCanvas.java#L1776-L1778
17,513
haifengl/smile
plot/src/main/java/smile/plot/PlotCanvas.java
PlotCanvas.staircase
public StaircasePlot staircase(String id, double[][] data, Color color) { if (data[0].length != 2 && data[0].length != 3) { throw new IllegalArgumentException("Invalid data dimension: " + data[0].length); } StaircasePlot plot = new StaircasePlot(data); plot.setID(id); plot.setColor(color); add(plot); return plot; }
java
public StaircasePlot staircase(String id, double[][] data, Color color) { if (data[0].length != 2 && data[0].length != 3) { throw new IllegalArgumentException("Invalid data dimension: " + data[0].length); } StaircasePlot plot = new StaircasePlot(data); plot.setID(id); plot.setColor(color); add(plot); return plot; }
[ "public", "StaircasePlot", "staircase", "(", "String", "id", ",", "double", "[", "]", "[", "]", "data", ",", "Color", "color", ")", "{", "if", "(", "data", "[", "0", "]", ".", "length", "!=", "2", "&&", "data", "[", "0", "]", ".", "length", "!=", "3", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid data dimension: \"", "+", "data", "[", "0", "]", ".", "length", ")", ";", "}", "StaircasePlot", "plot", "=", "new", "StaircasePlot", "(", "data", ")", ";", "plot", ".", "setID", "(", "id", ")", ";", "plot", ".", "setColor", "(", "color", ")", ";", "add", "(", "plot", ")", ";", "return", "plot", ";", "}" ]
Adds a staircase line plot to this canvas. @param id the id of the plot. @param data a n x 2 or n x 3 matrix that describes coordinates of points. @param color the color of line.
[ "Adds", "a", "staircase", "line", "plot", "to", "this", "canvas", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/PlotCanvas.java#L1985-L1995
17,514
haifengl/smile
plot/src/main/java/smile/plot/PlotCanvas.java
PlotCanvas.grid
public Grid grid(double[][][] data) { if (base.dimension != 2) { throw new IllegalArgumentException("Grid can be only painted in a 2D canvas. Try surface() for 3D grid."); } Grid grid = new Grid(data); add(grid); return grid; }
java
public Grid grid(double[][][] data) { if (base.dimension != 2) { throw new IllegalArgumentException("Grid can be only painted in a 2D canvas. Try surface() for 3D grid."); } Grid grid = new Grid(data); add(grid); return grid; }
[ "public", "Grid", "grid", "(", "double", "[", "]", "[", "]", "[", "]", "data", ")", "{", "if", "(", "base", ".", "dimension", "!=", "2", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Grid can be only painted in a 2D canvas. Try surface() for 3D grid.\"", ")", ";", "}", "Grid", "grid", "=", "new", "Grid", "(", "data", ")", ";", "add", "(", "grid", ")", ";", "return", "grid", ";", "}" ]
Adds a 2D grid plot to the canvas. @param data an m x n x 2 array which are coordinates of m x n grid.
[ "Adds", "a", "2D", "grid", "plot", "to", "the", "canvas", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/PlotCanvas.java#L2235-L2243
17,515
haifengl/smile
plot/src/main/java/smile/plot/PlotCanvas.java
PlotCanvas.screeplot
public static PlotCanvas screeplot(PCA pca) { int n = pca.getVarianceProportion().length; double[] lowerBound = {0, 0.0}; double[] upperBound = {n + 1, 1.0}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound, false); canvas.setAxisLabels("Principal Component", "Proportion of Variance"); String[] labels = new String[n]; double[] x = new double[n]; double[][] data = new double[n][2]; double[][] data2 = new double[n][2]; for (int i = 0; i < n; i++) { labels[i] = "PC" + (i + 1); x[i] = i + 1; data[i][0] = x[i]; data[i][1] = pca.getVarianceProportion()[i]; data2[i][0] = x[i]; data2[i][1] = pca.getCumulativeVarianceProportion()[i]; } LinePlot plot = new LinePlot(data); plot.setID("Variance"); plot.setColor(Color.RED); plot.setLegend('@'); canvas.add(plot); canvas.getAxis(0).addLabel(labels, x); LinePlot plot2 = new LinePlot(data2); plot2.setID("Cumulative Variance"); plot2.setColor(Color.BLUE); plot2.setLegend('@'); canvas.add(plot2); return canvas; }
java
public static PlotCanvas screeplot(PCA pca) { int n = pca.getVarianceProportion().length; double[] lowerBound = {0, 0.0}; double[] upperBound = {n + 1, 1.0}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound, false); canvas.setAxisLabels("Principal Component", "Proportion of Variance"); String[] labels = new String[n]; double[] x = new double[n]; double[][] data = new double[n][2]; double[][] data2 = new double[n][2]; for (int i = 0; i < n; i++) { labels[i] = "PC" + (i + 1); x[i] = i + 1; data[i][0] = x[i]; data[i][1] = pca.getVarianceProportion()[i]; data2[i][0] = x[i]; data2[i][1] = pca.getCumulativeVarianceProportion()[i]; } LinePlot plot = new LinePlot(data); plot.setID("Variance"); plot.setColor(Color.RED); plot.setLegend('@'); canvas.add(plot); canvas.getAxis(0).addLabel(labels, x); LinePlot plot2 = new LinePlot(data2); plot2.setID("Cumulative Variance"); plot2.setColor(Color.BLUE); plot2.setLegend('@'); canvas.add(plot2); return canvas; }
[ "public", "static", "PlotCanvas", "screeplot", "(", "PCA", "pca", ")", "{", "int", "n", "=", "pca", ".", "getVarianceProportion", "(", ")", ".", "length", ";", "double", "[", "]", "lowerBound", "=", "{", "0", ",", "0.0", "}", ";", "double", "[", "]", "upperBound", "=", "{", "n", "+", "1", ",", "1.0", "}", ";", "PlotCanvas", "canvas", "=", "new", "PlotCanvas", "(", "lowerBound", ",", "upperBound", ",", "false", ")", ";", "canvas", ".", "setAxisLabels", "(", "\"Principal Component\"", ",", "\"Proportion of Variance\"", ")", ";", "String", "[", "]", "labels", "=", "new", "String", "[", "n", "]", ";", "double", "[", "]", "x", "=", "new", "double", "[", "n", "]", ";", "double", "[", "]", "[", "]", "data", "=", "new", "double", "[", "n", "]", "[", "2", "]", ";", "double", "[", "]", "[", "]", "data2", "=", "new", "double", "[", "n", "]", "[", "2", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "labels", "[", "i", "]", "=", "\"PC\"", "+", "(", "i", "+", "1", ")", ";", "x", "[", "i", "]", "=", "i", "+", "1", ";", "data", "[", "i", "]", "[", "0", "]", "=", "x", "[", "i", "]", ";", "data", "[", "i", "]", "[", "1", "]", "=", "pca", ".", "getVarianceProportion", "(", ")", "[", "i", "]", ";", "data2", "[", "i", "]", "[", "0", "]", "=", "x", "[", "i", "]", ";", "data2", "[", "i", "]", "[", "1", "]", "=", "pca", ".", "getCumulativeVarianceProportion", "(", ")", "[", "i", "]", ";", "}", "LinePlot", "plot", "=", "new", "LinePlot", "(", "data", ")", ";", "plot", ".", "setID", "(", "\"Variance\"", ")", ";", "plot", ".", "setColor", "(", "Color", ".", "RED", ")", ";", "plot", ".", "setLegend", "(", "'", "'", ")", ";", "canvas", ".", "add", "(", "plot", ")", ";", "canvas", ".", "getAxis", "(", "0", ")", ".", "addLabel", "(", "labels", ",", "x", ")", ";", "LinePlot", "plot2", "=", "new", "LinePlot", "(", "data2", ")", ";", "plot2", ".", "setID", "(", "\"Cumulative Variance\"", ")", ";", "plot2", ".", "setColor", "(", "Color", ".", "BLUE", ")", ";", "plot2", ".", "setLegend", "(", "'", "'", ")", ";", "canvas", ".", "add", "(", "plot2", ")", ";", "return", "canvas", ";", "}" ]
Create a scree plot for PCA. @param pca principal component analysis object.
[ "Create", "a", "scree", "plot", "for", "PCA", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/PlotCanvas.java#L2249-L2285
17,516
haifengl/smile
data/src/main/java/smile/data/Dataset.java
Dataset.response
public AttributeVector response() { double[] y = new double[data.size()]; for (int i = 0; i < y.length; i++) { y[i] = data.get(i).y; } return new AttributeVector(response, y); }
java
public AttributeVector response() { double[] y = new double[data.size()]; for (int i = 0; i < y.length; i++) { y[i] = data.get(i).y; } return new AttributeVector(response, y); }
[ "public", "AttributeVector", "response", "(", ")", "{", "double", "[", "]", "y", "=", "new", "double", "[", "data", ".", "size", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "y", ".", "length", ";", "i", "++", ")", "{", "y", "[", "i", "]", "=", "data", ".", "get", "(", "i", ")", ".", "y", ";", "}", "return", "new", "AttributeVector", "(", "response", ",", "y", ")", ";", "}" ]
Returns the response attribute vector. null means no response variable in this dataset. @return the response attribute vector. null means no response variable in this dataset.
[ "Returns", "the", "response", "attribute", "vector", ".", "null", "means", "no", "response", "variable", "in", "this", "dataset", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/Dataset.java#L128-L134
17,517
haifengl/smile
math/src/main/java/smile/math/kernel/PearsonKernel.java
PearsonKernel.setOmega
public void setOmega(double omega) { this.omega = omega; this.constant = 2 * Math.sqrt(Math.pow(2, (1 / omega)) - 1) / sigma; }
java
public void setOmega(double omega) { this.omega = omega; this.constant = 2 * Math.sqrt(Math.pow(2, (1 / omega)) - 1) / sigma; }
[ "public", "void", "setOmega", "(", "double", "omega", ")", "{", "this", ".", "omega", "=", "omega", ";", "this", ".", "constant", "=", "2", "*", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "2", ",", "(", "1", "/", "omega", ")", ")", "-", "1", ")", "/", "sigma", ";", "}" ]
Set the omega parameter. @param omega Omega parameter.
[ "Set", "the", "omega", "parameter", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/kernel/PearsonKernel.java#L45-L48
17,518
haifengl/smile
math/src/main/java/smile/math/kernel/PearsonKernel.java
PearsonKernel.setSigma
public void setSigma(double sigma) { this.sigma = sigma; this.constant = 2 * Math.sqrt(Math.pow(2, (1 / omega)) - 1) / sigma; }
java
public void setSigma(double sigma) { this.sigma = sigma; this.constant = 2 * Math.sqrt(Math.pow(2, (1 / omega)) - 1) / sigma; }
[ "public", "void", "setSigma", "(", "double", "sigma", ")", "{", "this", ".", "sigma", "=", "sigma", ";", "this", ".", "constant", "=", "2", "*", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "2", ",", "(", "1", "/", "omega", ")", ")", "-", "1", ")", "/", "sigma", ";", "}" ]
Set the sigma parameter. @param sigma Sigma parameter.
[ "Set", "the", "sigma", "parameter", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/kernel/PearsonKernel.java#L62-L65
17,519
haifengl/smile
demo/src/main/java/smile/demo/classification/ClassificationDemo.java
ClassificationDemo.paintOnCanvas
protected PlotCanvas paintOnCanvas(double[][] data, int[] label) { PlotCanvas canvas = ScatterPlot.plot(data, pointLegend); for (int i = 0; i < data.length; i++) { canvas.point(pointLegend, Palette.COLORS[label[i]], data[i]); } return canvas; }
java
protected PlotCanvas paintOnCanvas(double[][] data, int[] label) { PlotCanvas canvas = ScatterPlot.plot(data, pointLegend); for (int i = 0; i < data.length; i++) { canvas.point(pointLegend, Palette.COLORS[label[i]], data[i]); } return canvas; }
[ "protected", "PlotCanvas", "paintOnCanvas", "(", "double", "[", "]", "[", "]", "data", ",", "int", "[", "]", "label", ")", "{", "PlotCanvas", "canvas", "=", "ScatterPlot", ".", "plot", "(", "data", ",", "pointLegend", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "canvas", ".", "point", "(", "pointLegend", ",", "Palette", ".", "COLORS", "[", "label", "[", "i", "]", "]", ",", "data", "[", "i", "]", ")", ";", "}", "return", "canvas", ";", "}" ]
paint given data with label on canvas @param data the data point(s) to paint, only support 2D or 3D features @param label the data label for classification
[ "paint", "given", "data", "with", "label", "on", "canvas" ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/demo/src/main/java/smile/demo/classification/ClassificationDemo.java#L123-L129
17,520
haifengl/smile
demo/src/main/java/smile/demo/classification/ClassificationDemo.java
ClassificationDemo.error
double error(int[] x, int[] y) { int e = 0; for (int i = 0; i < x.length; i++) { if (x[i] != y[i]) { e++; } } return (double) e / x.length; }
java
double error(int[] x, int[] y) { int e = 0; for (int i = 0; i < x.length; i++) { if (x[i] != y[i]) { e++; } } return (double) e / x.length; }
[ "double", "error", "(", "int", "[", "]", "x", ",", "int", "[", "]", "y", ")", "{", "int", "e", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "x", ".", "length", ";", "i", "++", ")", "{", "if", "(", "x", "[", "i", "]", "!=", "y", "[", "i", "]", ")", "{", "e", "++", ";", "}", "}", "return", "(", "double", ")", "e", "/", "x", ".", "length", ";", "}" ]
Returns the error rate.
[ "Returns", "the", "error", "rate", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/demo/src/main/java/smile/demo/classification/ClassificationDemo.java#L142-L152
17,521
haifengl/smile
core/src/main/java/smile/feature/Bag.java
Bag.feature
@Override public double[] feature(T[] x) { double[] bag = new double[features.size()]; if (binary) { for (T word : x) { Integer f = features.get(word); if (f != null) { bag[f] = 1.0; } } } else { for (T word : x) { Integer f = features.get(word); if (f != null) { bag[f]++; } } } return bag; }
java
@Override public double[] feature(T[] x) { double[] bag = new double[features.size()]; if (binary) { for (T word : x) { Integer f = features.get(word); if (f != null) { bag[f] = 1.0; } } } else { for (T word : x) { Integer f = features.get(word); if (f != null) { bag[f]++; } } } return bag; }
[ "@", "Override", "public", "double", "[", "]", "feature", "(", "T", "[", "]", "x", ")", "{", "double", "[", "]", "bag", "=", "new", "double", "[", "features", ".", "size", "(", ")", "]", ";", "if", "(", "binary", ")", "{", "for", "(", "T", "word", ":", "x", ")", "{", "Integer", "f", "=", "features", ".", "get", "(", "word", ")", ";", "if", "(", "f", "!=", "null", ")", "{", "bag", "[", "f", "]", "=", "1.0", ";", "}", "}", "}", "else", "{", "for", "(", "T", "word", ":", "x", ")", "{", "Integer", "f", "=", "features", ".", "get", "(", "word", ")", ";", "if", "(", "f", "!=", "null", ")", "{", "bag", "[", "f", "]", "++", ";", "}", "}", "}", "return", "bag", ";", "}" ]
Returns the bag-of-words features of a document. The features are real-valued in convenience of most learning algorithms although they take only integer or binary values.
[ "Returns", "the", "bag", "-", "of", "-", "words", "features", "of", "a", "document", ".", "The", "features", "are", "real", "-", "valued", "in", "convenience", "of", "most", "learning", "algorithms", "although", "they", "take", "only", "integer", "or", "binary", "values", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/feature/Bag.java#L95-L116
17,522
haifengl/smile
math/src/main/java/smile/math/distance/DynamicTimeWarping.java
DynamicTimeWarping.d
public static double d(int[] x1, int[] x2) { int n1 = x1.length; int n2 = x2.length; double[][] table = new double[2][n2 + 1]; table[0][0] = 0; for (int i = 1; i <= n2; i++) { table[0][i] = Double.POSITIVE_INFINITY; } for (int i = 1; i <= n1; i++) { table[1][0] = Double.POSITIVE_INFINITY; for (int j = 1; j <= n2; j++) { double cost = Math.abs(x1[i-1] - x2[j-1]); double min = table[0][j - 1]; if (min > table[0][j]) { min = table[0][j]; } if (min > table[1][j - 1]) { min = table[1][j - 1]; } table[1][j] = cost + min; } double[] swap = table[0]; table[0] = table[1]; table[1] = swap; } return table[0][n2]; }
java
public static double d(int[] x1, int[] x2) { int n1 = x1.length; int n2 = x2.length; double[][] table = new double[2][n2 + 1]; table[0][0] = 0; for (int i = 1; i <= n2; i++) { table[0][i] = Double.POSITIVE_INFINITY; } for (int i = 1; i <= n1; i++) { table[1][0] = Double.POSITIVE_INFINITY; for (int j = 1; j <= n2; j++) { double cost = Math.abs(x1[i-1] - x2[j-1]); double min = table[0][j - 1]; if (min > table[0][j]) { min = table[0][j]; } if (min > table[1][j - 1]) { min = table[1][j - 1]; } table[1][j] = cost + min; } double[] swap = table[0]; table[0] = table[1]; table[1] = swap; } return table[0][n2]; }
[ "public", "static", "double", "d", "(", "int", "[", "]", "x1", ",", "int", "[", "]", "x2", ")", "{", "int", "n1", "=", "x1", ".", "length", ";", "int", "n2", "=", "x2", ".", "length", ";", "double", "[", "]", "[", "]", "table", "=", "new", "double", "[", "2", "]", "[", "n2", "+", "1", "]", ";", "table", "[", "0", "]", "[", "0", "]", "=", "0", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "n2", ";", "i", "++", ")", "{", "table", "[", "0", "]", "[", "i", "]", "=", "Double", ".", "POSITIVE_INFINITY", ";", "}", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "n1", ";", "i", "++", ")", "{", "table", "[", "1", "]", "[", "0", "]", "=", "Double", ".", "POSITIVE_INFINITY", ";", "for", "(", "int", "j", "=", "1", ";", "j", "<=", "n2", ";", "j", "++", ")", "{", "double", "cost", "=", "Math", ".", "abs", "(", "x1", "[", "i", "-", "1", "]", "-", "x2", "[", "j", "-", "1", "]", ")", ";", "double", "min", "=", "table", "[", "0", "]", "[", "j", "-", "1", "]", ";", "if", "(", "min", ">", "table", "[", "0", "]", "[", "j", "]", ")", "{", "min", "=", "table", "[", "0", "]", "[", "j", "]", ";", "}", "if", "(", "min", ">", "table", "[", "1", "]", "[", "j", "-", "1", "]", ")", "{", "min", "=", "table", "[", "1", "]", "[", "j", "-", "1", "]", ";", "}", "table", "[", "1", "]", "[", "j", "]", "=", "cost", "+", "min", ";", "}", "double", "[", "]", "swap", "=", "table", "[", "0", "]", ";", "table", "[", "0", "]", "=", "table", "[", "1", "]", ";", "table", "[", "1", "]", "=", "swap", ";", "}", "return", "table", "[", "0", "]", "[", "n2", "]", ";", "}" ]
Dynamic time warping without path constraints.
[ "Dynamic", "time", "warping", "without", "path", "constraints", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/distance/DynamicTimeWarping.java#L134-L170
17,523
haifengl/smile
math/src/main/java/smile/stat/distribution/MultivariateGaussianDistribution.java
MultivariateGaussianDistribution.rand
public double[] rand() { double[] spt = new double[mu.length]; for (int i = 0; i < mu.length; i++) { double u, v, q; do { u = Math.random(); v = 1.7156 * (Math.random() - 0.5); double x = u - 0.449871; double y = Math.abs(v) + 0.386595; q = x * x + y * (0.19600 * y - 0.25472 * x); } while (q > 0.27597 && (q > 0.27846 || v * v > -4 * Math.log(u) * u * u)); spt[i] = v / u; } double[] pt = new double[sigmaL.nrows()]; // pt = sigmaL * spt for (int i = 0; i < pt.length; i++) { for (int j = 0; j <= i; j++) { pt[i] += sigmaL.get(i, j) * spt[j]; } } Math.plus(pt, mu); return pt; }
java
public double[] rand() { double[] spt = new double[mu.length]; for (int i = 0; i < mu.length; i++) { double u, v, q; do { u = Math.random(); v = 1.7156 * (Math.random() - 0.5); double x = u - 0.449871; double y = Math.abs(v) + 0.386595; q = x * x + y * (0.19600 * y - 0.25472 * x); } while (q > 0.27597 && (q > 0.27846 || v * v > -4 * Math.log(u) * u * u)); spt[i] = v / u; } double[] pt = new double[sigmaL.nrows()]; // pt = sigmaL * spt for (int i = 0; i < pt.length; i++) { for (int j = 0; j <= i; j++) { pt[i] += sigmaL.get(i, j) * spt[j]; } } Math.plus(pt, mu); return pt; }
[ "public", "double", "[", "]", "rand", "(", ")", "{", "double", "[", "]", "spt", "=", "new", "double", "[", "mu", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "mu", ".", "length", ";", "i", "++", ")", "{", "double", "u", ",", "v", ",", "q", ";", "do", "{", "u", "=", "Math", ".", "random", "(", ")", ";", "v", "=", "1.7156", "*", "(", "Math", ".", "random", "(", ")", "-", "0.5", ")", ";", "double", "x", "=", "u", "-", "0.449871", ";", "double", "y", "=", "Math", ".", "abs", "(", "v", ")", "+", "0.386595", ";", "q", "=", "x", "*", "x", "+", "y", "*", "(", "0.19600", "*", "y", "-", "0.25472", "*", "x", ")", ";", "}", "while", "(", "q", ">", "0.27597", "&&", "(", "q", ">", "0.27846", "||", "v", "*", "v", ">", "-", "4", "*", "Math", ".", "log", "(", "u", ")", "*", "u", "*", "u", ")", ")", ";", "spt", "[", "i", "]", "=", "v", "/", "u", ";", "}", "double", "[", "]", "pt", "=", "new", "double", "[", "sigmaL", ".", "nrows", "(", ")", "]", ";", "// pt = sigmaL * spt", "for", "(", "int", "i", "=", "0", ";", "i", "<", "pt", ".", "length", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<=", "i", ";", "j", "++", ")", "{", "pt", "[", "i", "]", "+=", "sigmaL", ".", "get", "(", "i", ",", "j", ")", "*", "spt", "[", "j", "]", ";", "}", "}", "Math", ".", "plus", "(", "pt", ",", "mu", ")", ";", "return", "pt", ";", "}" ]
Generate a random multivariate Gaussian sample.
[ "Generate", "a", "random", "multivariate", "Gaussian", "sample", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/stat/distribution/MultivariateGaussianDistribution.java#L281-L309
17,524
haifengl/smile
data/src/main/java/smile/data/parser/microarray/RESParser.java
RESParser.parse
public AttributeDataset parse(String name, InputStream stream) throws IOException, ParseException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line = reader.readLine(); if (line == null) { throw new IOException("Empty data source."); } String[] tokens = line.split("\t", -1); int p = (tokens.length - 2) / 2; line = reader.readLine(); if (line == null) { throw new IOException("Premature end of file."); } String[] samples = line.split("\t", -1); if (samples.length != tokens.length-1) { throw new IOException("Invalid sample description header."); } Attribute[] attributes = new Attribute[p]; for (int i = 0; i < p; i++) { attributes[i] = new NumericAttribute(tokens[2*i+2], samples[2*i+1]); } line = reader.readLine(); if (line == null) { throw new IOException("Premature end of file."); } int n = Integer.parseInt(line); if (n <= 0) { throw new IOException("Invalid number of rows: " + n); } AttributeDataset data = new AttributeDataset(name, attributes); for (int i = 0; i < n; i++) { line = reader.readLine(); if (line == null) { throw new IOException("Premature end of file."); } tokens = line.split("\t", -1); if (tokens.length != samples.length+1) { throw new IOException(String.format("Invalid number of elements of line %d: %d", i+4, tokens.length)); } double[] x = new double[p]; for (int j = 0; j < p; j++) { x[j] = Double.valueOf(tokens[2*j+2]); } AttributeDataset.Row datum = data.add(x); datum.name = tokens[1]; datum.description = tokens[0]; } reader.close(); return data; }
java
public AttributeDataset parse(String name, InputStream stream) throws IOException, ParseException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line = reader.readLine(); if (line == null) { throw new IOException("Empty data source."); } String[] tokens = line.split("\t", -1); int p = (tokens.length - 2) / 2; line = reader.readLine(); if (line == null) { throw new IOException("Premature end of file."); } String[] samples = line.split("\t", -1); if (samples.length != tokens.length-1) { throw new IOException("Invalid sample description header."); } Attribute[] attributes = new Attribute[p]; for (int i = 0; i < p; i++) { attributes[i] = new NumericAttribute(tokens[2*i+2], samples[2*i+1]); } line = reader.readLine(); if (line == null) { throw new IOException("Premature end of file."); } int n = Integer.parseInt(line); if (n <= 0) { throw new IOException("Invalid number of rows: " + n); } AttributeDataset data = new AttributeDataset(name, attributes); for (int i = 0; i < n; i++) { line = reader.readLine(); if (line == null) { throw new IOException("Premature end of file."); } tokens = line.split("\t", -1); if (tokens.length != samples.length+1) { throw new IOException(String.format("Invalid number of elements of line %d: %d", i+4, tokens.length)); } double[] x = new double[p]; for (int j = 0; j < p; j++) { x[j] = Double.valueOf(tokens[2*j+2]); } AttributeDataset.Row datum = data.add(x); datum.name = tokens[1]; datum.description = tokens[0]; } reader.close(); return data; }
[ "public", "AttributeDataset", "parse", "(", "String", "name", ",", "InputStream", "stream", ")", "throws", "IOException", ",", "ParseException", "{", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "stream", ")", ")", ";", "String", "line", "=", "reader", ".", "readLine", "(", ")", ";", "if", "(", "line", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"Empty data source.\"", ")", ";", "}", "String", "[", "]", "tokens", "=", "line", ".", "split", "(", "\"\\t\"", ",", "-", "1", ")", ";", "int", "p", "=", "(", "tokens", ".", "length", "-", "2", ")", "/", "2", ";", "line", "=", "reader", ".", "readLine", "(", ")", ";", "if", "(", "line", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"Premature end of file.\"", ")", ";", "}", "String", "[", "]", "samples", "=", "line", ".", "split", "(", "\"\\t\"", ",", "-", "1", ")", ";", "if", "(", "samples", ".", "length", "!=", "tokens", ".", "length", "-", "1", ")", "{", "throw", "new", "IOException", "(", "\"Invalid sample description header.\"", ")", ";", "}", "Attribute", "[", "]", "attributes", "=", "new", "Attribute", "[", "p", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "p", ";", "i", "++", ")", "{", "attributes", "[", "i", "]", "=", "new", "NumericAttribute", "(", "tokens", "[", "2", "*", "i", "+", "2", "]", ",", "samples", "[", "2", "*", "i", "+", "1", "]", ")", ";", "}", "line", "=", "reader", ".", "readLine", "(", ")", ";", "if", "(", "line", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"Premature end of file.\"", ")", ";", "}", "int", "n", "=", "Integer", ".", "parseInt", "(", "line", ")", ";", "if", "(", "n", "<=", "0", ")", "{", "throw", "new", "IOException", "(", "\"Invalid number of rows: \"", "+", "n", ")", ";", "}", "AttributeDataset", "data", "=", "new", "AttributeDataset", "(", "name", ",", "attributes", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "line", "=", "reader", ".", "readLine", "(", ")", ";", "if", "(", "line", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"Premature end of file.\"", ")", ";", "}", "tokens", "=", "line", ".", "split", "(", "\"\\t\"", ",", "-", "1", ")", ";", "if", "(", "tokens", ".", "length", "!=", "samples", ".", "length", "+", "1", ")", "{", "throw", "new", "IOException", "(", "String", ".", "format", "(", "\"Invalid number of elements of line %d: %d\"", ",", "i", "+", "4", ",", "tokens", ".", "length", ")", ")", ";", "}", "double", "[", "]", "x", "=", "new", "double", "[", "p", "]", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "p", ";", "j", "++", ")", "{", "x", "[", "j", "]", "=", "Double", ".", "valueOf", "(", "tokens", "[", "2", "*", "j", "+", "2", "]", ")", ";", "}", "AttributeDataset", ".", "Row", "datum", "=", "data", ".", "add", "(", "x", ")", ";", "datum", ".", "name", "=", "tokens", "[", "1", "]", ";", "datum", ".", "description", "=", "tokens", "[", "0", "]", ";", "}", "reader", ".", "close", "(", ")", ";", "return", "data", ";", "}" ]
Parse a RES dataset from an input stream. @param name the name of dataset. @param stream the input stream of data. @throws java.io.IOException
[ "Parse", "a", "RES", "dataset", "from", "an", "input", "stream", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/parser/microarray/RESParser.java#L158-L219
17,525
haifengl/smile
plot/src/main/java/smile/swing/table/PageTableModel.java
PageTableModel.setPageSize
public void setPageSize(int s) { if (s <= 0) { throw new IllegalArgumentException("non-positive page size: " + s); } if (s == pageSize) { return; } int oldPageSize = pageSize; pageSize = s; page = (oldPageSize * page) / pageSize; fireTableDataChanged(); }
java
public void setPageSize(int s) { if (s <= 0) { throw new IllegalArgumentException("non-positive page size: " + s); } if (s == pageSize) { return; } int oldPageSize = pageSize; pageSize = s; page = (oldPageSize * page) / pageSize; fireTableDataChanged(); }
[ "public", "void", "setPageSize", "(", "int", "s", ")", "{", "if", "(", "s", "<=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"non-positive page size: \"", "+", "s", ")", ";", "}", "if", "(", "s", "==", "pageSize", ")", "{", "return", ";", "}", "int", "oldPageSize", "=", "pageSize", ";", "pageSize", "=", "s", ";", "page", "=", "(", "oldPageSize", "*", "page", ")", "/", "pageSize", ";", "fireTableDataChanged", "(", ")", ";", "}" ]
Sets the page size. @param s the page size.
[ "Sets", "the", "page", "size", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/swing/table/PageTableModel.java#L179-L192
17,526
haifengl/smile
core/src/main/java/smile/neighbor/BKTree.java
BKTree.add
public void add(E datum) { if (root == null) { root = new Node(count++, datum); } else { root.add(datum); } }
java
public void add(E datum) { if (root == null) { root = new Node(count++, datum); } else { root.add(datum); } }
[ "public", "void", "add", "(", "E", "datum", ")", "{", "if", "(", "root", "==", "null", ")", "{", "root", "=", "new", "Node", "(", "count", "++", ",", "datum", ")", ";", "}", "else", "{", "root", ".", "add", "(", "datum", ")", ";", "}", "}" ]
Add a datum into the BK-tree.
[ "Add", "a", "datum", "into", "the", "BK", "-", "tree", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/neighbor/BKTree.java#L174-L180
17,527
haifengl/smile
core/src/main/java/smile/neighbor/BKTree.java
BKTree.search
private void search(Node node, E q, int k, List<Neighbor<E, E>> neighbors) { int d = (int) distance.d(node.object, q); if (d <= k) { if (node.object != q || !identicalExcluded) { neighbors.add(new Neighbor<>(node.object, node.object, node.index, d)); } } if (node.children != null) { int start = Math.max(1, d-k); int end = Math.min(node.children.size(), d+k+1); for (int i = start; i < end; i++) { Node child = node.children.get(i); if (child != null) { search(child, q, k, neighbors); } } } }
java
private void search(Node node, E q, int k, List<Neighbor<E, E>> neighbors) { int d = (int) distance.d(node.object, q); if (d <= k) { if (node.object != q || !identicalExcluded) { neighbors.add(new Neighbor<>(node.object, node.object, node.index, d)); } } if (node.children != null) { int start = Math.max(1, d-k); int end = Math.min(node.children.size(), d+k+1); for (int i = start; i < end; i++) { Node child = node.children.get(i); if (child != null) { search(child, q, k, neighbors); } } } }
[ "private", "void", "search", "(", "Node", "node", ",", "E", "q", ",", "int", "k", ",", "List", "<", "Neighbor", "<", "E", ",", "E", ">", ">", "neighbors", ")", "{", "int", "d", "=", "(", "int", ")", "distance", ".", "d", "(", "node", ".", "object", ",", "q", ")", ";", "if", "(", "d", "<=", "k", ")", "{", "if", "(", "node", ".", "object", "!=", "q", "||", "!", "identicalExcluded", ")", "{", "neighbors", ".", "add", "(", "new", "Neighbor", "<>", "(", "node", ".", "object", ",", "node", ".", "object", ",", "node", ".", "index", ",", "d", ")", ")", ";", "}", "}", "if", "(", "node", ".", "children", "!=", "null", ")", "{", "int", "start", "=", "Math", ".", "max", "(", "1", ",", "d", "-", "k", ")", ";", "int", "end", "=", "Math", ".", "min", "(", "node", ".", "children", ".", "size", "(", ")", ",", "d", "+", "k", "+", "1", ")", ";", "for", "(", "int", "i", "=", "start", ";", "i", "<", "end", ";", "i", "++", ")", "{", "Node", "child", "=", "node", ".", "children", ".", "get", "(", "i", ")", ";", "if", "(", "child", "!=", "null", ")", "{", "search", "(", "child", ",", "q", ",", "k", ",", "neighbors", ")", ";", "}", "}", "}", "}" ]
Do a range search in the given subtree. @param node the root of subtree. @param q the query object. @param k the range of query. @param neighbors the returned results of which d(x, target) &le; k.
[ "Do", "a", "range", "search", "in", "the", "given", "subtree", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/neighbor/BKTree.java#L204-L223
17,528
haifengl/smile
core/src/main/java/smile/taxonomy/Taxonomy.java
Taxonomy.getConcepts
private List<String> getConcepts(Concept c) { List<String> keywords = new ArrayList<>(); while (c != null) { if (c.synset != null) { keywords.addAll(c.synset); } if (c.children != null) { for (Concept child : c.children) { keywords.addAll(getConcepts(child)); } } } return keywords; }
java
private List<String> getConcepts(Concept c) { List<String> keywords = new ArrayList<>(); while (c != null) { if (c.synset != null) { keywords.addAll(c.synset); } if (c.children != null) { for (Concept child : c.children) { keywords.addAll(getConcepts(child)); } } } return keywords; }
[ "private", "List", "<", "String", ">", "getConcepts", "(", "Concept", "c", ")", "{", "List", "<", "String", ">", "keywords", "=", "new", "ArrayList", "<>", "(", ")", ";", "while", "(", "c", "!=", "null", ")", "{", "if", "(", "c", ".", "synset", "!=", "null", ")", "{", "keywords", ".", "addAll", "(", "c", ".", "synset", ")", ";", "}", "if", "(", "c", ".", "children", "!=", "null", ")", "{", "for", "(", "Concept", "child", ":", "c", ".", "children", ")", "{", "keywords", ".", "addAll", "(", "getConcepts", "(", "child", ")", ")", ";", "}", "}", "}", "return", "keywords", ";", "}" ]
Returns all named concepts from this taxonomy
[ "Returns", "all", "named", "concepts", "from", "this", "taxonomy" ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/taxonomy/Taxonomy.java#L86-L102
17,529
haifengl/smile
core/src/main/java/smile/wavelet/Wavelet.java
Wavelet.transform
public void transform(double[] a) { int n = a.length; if (!Math.isPower2(n)) { throw new IllegalArgumentException("The data vector size is not a power of 2."); } if (n < ncof) { throw new IllegalArgumentException("The data vector size is less than wavelet coefficient size."); } for (int nn = n; nn >= ncof; nn >>= 1) { forward(a, nn); } }
java
public void transform(double[] a) { int n = a.length; if (!Math.isPower2(n)) { throw new IllegalArgumentException("The data vector size is not a power of 2."); } if (n < ncof) { throw new IllegalArgumentException("The data vector size is less than wavelet coefficient size."); } for (int nn = n; nn >= ncof; nn >>= 1) { forward(a, nn); } }
[ "public", "void", "transform", "(", "double", "[", "]", "a", ")", "{", "int", "n", "=", "a", ".", "length", ";", "if", "(", "!", "Math", ".", "isPower2", "(", "n", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The data vector size is not a power of 2.\"", ")", ";", "}", "if", "(", "n", "<", "ncof", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The data vector size is less than wavelet coefficient size.\"", ")", ";", "}", "for", "(", "int", "nn", "=", "n", ";", "nn", ">=", "ncof", ";", "nn", ">>=", "1", ")", "{", "forward", "(", "a", ",", "nn", ")", ";", "}", "}" ]
Discrete wavelet transform.
[ "Discrete", "wavelet", "transform", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/wavelet/Wavelet.java#L141-L155
17,530
haifengl/smile
core/src/main/java/smile/wavelet/Wavelet.java
Wavelet.inverse
public void inverse(double[] a) { int n = a.length; if (!Math.isPower2(n)) { throw new IllegalArgumentException("The data vector size is not a power of 2."); } if (n < ncof) { throw new IllegalArgumentException("The data vector size is less than wavelet coefficient size."); } int start = n >> (int) Math.floor(Math.log2(n/(ncof-1))); for (int nn = start; nn <= n; nn <<= 1) { backward(a, nn); } }
java
public void inverse(double[] a) { int n = a.length; if (!Math.isPower2(n)) { throw new IllegalArgumentException("The data vector size is not a power of 2."); } if (n < ncof) { throw new IllegalArgumentException("The data vector size is less than wavelet coefficient size."); } int start = n >> (int) Math.floor(Math.log2(n/(ncof-1))); for (int nn = start; nn <= n; nn <<= 1) { backward(a, nn); } }
[ "public", "void", "inverse", "(", "double", "[", "]", "a", ")", "{", "int", "n", "=", "a", ".", "length", ";", "if", "(", "!", "Math", ".", "isPower2", "(", "n", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The data vector size is not a power of 2.\"", ")", ";", "}", "if", "(", "n", "<", "ncof", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The data vector size is less than wavelet coefficient size.\"", ")", ";", "}", "int", "start", "=", "n", ">>", "(", "int", ")", "Math", ".", "floor", "(", "Math", ".", "log2", "(", "n", "/", "(", "ncof", "-", "1", ")", ")", ")", ";", "for", "(", "int", "nn", "=", "start", ";", "nn", "<=", "n", ";", "nn", "<<=", "1", ")", "{", "backward", "(", "a", ",", "nn", ")", ";", "}", "}" ]
Inverse discrete wavelet transform.
[ "Inverse", "discrete", "wavelet", "transform", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/wavelet/Wavelet.java#L160-L175
17,531
haifengl/smile
nlp/src/main/java/smile/nlp/stemmer/LancasterStemmer.java
LancasterStemmer.firstVowel
private int firstVowel(String word, int last) { int i = 0; if ((i < last) && (!(vowel(word.charAt(i), 'a')))) { i++; } if (i != 0) { while ((i < last) && (!(vowel(word.charAt(i), word.charAt(i - 1))))) { i++; } } if (i < last) { return i; } return last; }
java
private int firstVowel(String word, int last) { int i = 0; if ((i < last) && (!(vowel(word.charAt(i), 'a')))) { i++; } if (i != 0) { while ((i < last) && (!(vowel(word.charAt(i), word.charAt(i - 1))))) { i++; } } if (i < last) { return i; } return last; }
[ "private", "int", "firstVowel", "(", "String", "word", ",", "int", "last", ")", "{", "int", "i", "=", "0", ";", "if", "(", "(", "i", "<", "last", ")", "&&", "(", "!", "(", "vowel", "(", "word", ".", "charAt", "(", "i", ")", ",", "'", "'", ")", ")", ")", ")", "{", "i", "++", ";", "}", "if", "(", "i", "!=", "0", ")", "{", "while", "(", "(", "i", "<", "last", ")", "&&", "(", "!", "(", "vowel", "(", "word", ".", "charAt", "(", "i", ")", ",", "word", ".", "charAt", "(", "i", "-", "1", ")", ")", ")", ")", ")", "{", "i", "++", ";", "}", "}", "if", "(", "i", "<", "last", ")", "{", "return", "i", ";", "}", "return", "last", ";", "}" ]
Checks lowercase word for position of the first vowel
[ "Checks", "lowercase", "word", "for", "position", "of", "the", "first", "vowel" ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/nlp/src/main/java/smile/nlp/stemmer/LancasterStemmer.java#L130-L144
17,532
haifengl/smile
nlp/src/main/java/smile/nlp/stemmer/LancasterStemmer.java
LancasterStemmer.stripPrefixes
private String stripPrefixes(String word) { String[] prefixes = {"kilo", "micro", "milli", "intra", "ultra", "mega", "nano", "pico", "pseudo"}; int last = prefixes.length; for (int i = 0; i < last; i++) { if ((word.startsWith(prefixes[i])) && (word.length() > prefixes[i].length())) { word = word.substring(prefixes[i].length()); return word; } } return word; }
java
private String stripPrefixes(String word) { String[] prefixes = {"kilo", "micro", "milli", "intra", "ultra", "mega", "nano", "pico", "pseudo"}; int last = prefixes.length; for (int i = 0; i < last; i++) { if ((word.startsWith(prefixes[i])) && (word.length() > prefixes[i].length())) { word = word.substring(prefixes[i].length()); return word; } } return word; }
[ "private", "String", "stripPrefixes", "(", "String", "word", ")", "{", "String", "[", "]", "prefixes", "=", "{", "\"kilo\"", ",", "\"micro\"", ",", "\"milli\"", ",", "\"intra\"", ",", "\"ultra\"", ",", "\"mega\"", ",", "\"nano\"", ",", "\"pico\"", ",", "\"pseudo\"", "}", ";", "int", "last", "=", "prefixes", ".", "length", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "last", ";", "i", "++", ")", "{", "if", "(", "(", "word", ".", "startsWith", "(", "prefixes", "[", "i", "]", ")", ")", "&&", "(", "word", ".", "length", "(", ")", ">", "prefixes", "[", "i", "]", ".", "length", "(", ")", ")", ")", "{", "word", "=", "word", ".", "substring", "(", "prefixes", "[", "i", "]", ".", "length", "(", ")", ")", ";", "return", "word", ";", "}", "}", "return", "word", ";", "}" ]
Removes prefixes so that suffix removal can commence.
[ "Removes", "prefixes", "so", "that", "suffix", "removal", "can", "commence", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/nlp/src/main/java/smile/nlp/stemmer/LancasterStemmer.java#L368-L381
17,533
haifengl/smile
nlp/src/main/java/smile/nlp/stemmer/LancasterStemmer.java
LancasterStemmer.cleanup
private String cleanup(String word) { int last = word.length(); String temp = ""; for (int i = 0; i < last; i++) { if ((word.charAt(i) >= 'a') & (word.charAt(i) <= 'z')) { temp += word.charAt(i); } } return temp; }
java
private String cleanup(String word) { int last = word.length(); String temp = ""; for (int i = 0; i < last; i++) { if ((word.charAt(i) >= 'a') & (word.charAt(i) <= 'z')) { temp += word.charAt(i); } } return temp; }
[ "private", "String", "cleanup", "(", "String", "word", ")", "{", "int", "last", "=", "word", ".", "length", "(", ")", ";", "String", "temp", "=", "\"\"", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "last", ";", "i", "++", ")", "{", "if", "(", "(", "word", ".", "charAt", "(", "i", ")", ">=", "'", "'", ")", "&", "(", "word", ".", "charAt", "(", "i", ")", "<=", "'", "'", ")", ")", "{", "temp", "+=", "word", ".", "charAt", "(", "i", ")", ";", "}", "}", "return", "temp", ";", "}" ]
Remove all non letter or digit characters from word
[ "Remove", "all", "non", "letter", "or", "digit", "characters", "from", "word" ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/nlp/src/main/java/smile/nlp/stemmer/LancasterStemmer.java#L386-L395
17,534
haifengl/smile
nlp/src/main/java/smile/nlp/pos/RegexPOSTagger.java
RegexPOSTagger.tag
public static PennTreebankPOS tag(String word) { for (int i = 0; i < REGEX.length; i++) { if (REGEX[i].matcher(word).matches()) { return REGEX_POS[i]; } } return null; }
java
public static PennTreebankPOS tag(String word) { for (int i = 0; i < REGEX.length; i++) { if (REGEX[i].matcher(word).matches()) { return REGEX_POS[i]; } } return null; }
[ "public", "static", "PennTreebankPOS", "tag", "(", "String", "word", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "REGEX", ".", "length", ";", "i", "++", ")", "{", "if", "(", "REGEX", "[", "i", "]", ".", "matcher", "(", "word", ")", ".", "matches", "(", ")", ")", "{", "return", "REGEX_POS", "[", "i", "]", ";", "}", "}", "return", "null", ";", "}" ]
Returns the POS tag of a given word based on the regular expression over word string. Returns null if no match.
[ "Returns", "the", "POS", "tag", "of", "a", "given", "word", "based", "on", "the", "regular", "expression", "over", "word", "string", ".", "Returns", "null", "if", "no", "match", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/nlp/src/main/java/smile/nlp/pos/RegexPOSTagger.java#L66-L74
17,535
haifengl/smile
data/src/main/java/smile/data/AttributeDataset.java
AttributeDataset.range
public AttributeDataset range(int from, int to) { AttributeDataset sub = new AttributeDataset(name+'['+from+", "+to+']', attributes, response); sub.description = description; for (int i = from; i < to; i++) { sub.add(get(i)); } return sub; }
java
public AttributeDataset range(int from, int to) { AttributeDataset sub = new AttributeDataset(name+'['+from+", "+to+']', attributes, response); sub.description = description; for (int i = from; i < to; i++) { sub.add(get(i)); } return sub; }
[ "public", "AttributeDataset", "range", "(", "int", "from", ",", "int", "to", ")", "{", "AttributeDataset", "sub", "=", "new", "AttributeDataset", "(", "name", "+", "'", "'", "+", "from", "+", "\", \"", "+", "to", "+", "'", "'", ",", "attributes", ",", "response", ")", ";", "sub", ".", "description", "=", "description", ";", "for", "(", "int", "i", "=", "from", ";", "i", "<", "to", ";", "i", "++", ")", "{", "sub", ".", "add", "(", "get", "(", "i", ")", ")", ";", "}", "return", "sub", ";", "}" ]
Returns the rows in the given range [from, to).
[ "Returns", "the", "rows", "in", "the", "given", "range", "[", "from", "to", ")", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/AttributeDataset.java#L295-L304
17,536
haifengl/smile
data/src/main/java/smile/data/AttributeDataset.java
AttributeDataset.columns
public AttributeDataset columns(String... cols) { Attribute[] attrs = new Attribute[cols.length]; int[] index = new int[cols.length]; for (int k = 0; k < cols.length; k++) { for (int j = 0; j < attributes.length; j++) { if (attributes[j].getName().equals(cols[k])) { index[k] = j; attrs[k] = attributes[j]; break; } } if (attrs[k] == null) { throw new IllegalArgumentException("Unknown column: " + cols[k]); } } AttributeDataset sub = new AttributeDataset(name, attrs, response); for (Datum<double[]> datum : data) { double[] x = new double[index.length]; for (int i = 0; i < x.length; i++) { x[i] = datum.x[index[i]]; } Row row = response == null ? sub.add(x) : sub.add(x, datum.y); row.name = datum.name; row.weight = datum.weight; row.description = datum.description; row.timestamp = datum.timestamp; } return sub; }
java
public AttributeDataset columns(String... cols) { Attribute[] attrs = new Attribute[cols.length]; int[] index = new int[cols.length]; for (int k = 0; k < cols.length; k++) { for (int j = 0; j < attributes.length; j++) { if (attributes[j].getName().equals(cols[k])) { index[k] = j; attrs[k] = attributes[j]; break; } } if (attrs[k] == null) { throw new IllegalArgumentException("Unknown column: " + cols[k]); } } AttributeDataset sub = new AttributeDataset(name, attrs, response); for (Datum<double[]> datum : data) { double[] x = new double[index.length]; for (int i = 0; i < x.length; i++) { x[i] = datum.x[index[i]]; } Row row = response == null ? sub.add(x) : sub.add(x, datum.y); row.name = datum.name; row.weight = datum.weight; row.description = datum.description; row.timestamp = datum.timestamp; } return sub; }
[ "public", "AttributeDataset", "columns", "(", "String", "...", "cols", ")", "{", "Attribute", "[", "]", "attrs", "=", "new", "Attribute", "[", "cols", ".", "length", "]", ";", "int", "[", "]", "index", "=", "new", "int", "[", "cols", ".", "length", "]", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "cols", ".", "length", ";", "k", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "attributes", ".", "length", ";", "j", "++", ")", "{", "if", "(", "attributes", "[", "j", "]", ".", "getName", "(", ")", ".", "equals", "(", "cols", "[", "k", "]", ")", ")", "{", "index", "[", "k", "]", "=", "j", ";", "attrs", "[", "k", "]", "=", "attributes", "[", "j", "]", ";", "break", ";", "}", "}", "if", "(", "attrs", "[", "k", "]", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Unknown column: \"", "+", "cols", "[", "k", "]", ")", ";", "}", "}", "AttributeDataset", "sub", "=", "new", "AttributeDataset", "(", "name", ",", "attrs", ",", "response", ")", ";", "for", "(", "Datum", "<", "double", "[", "]", ">", "datum", ":", "data", ")", "{", "double", "[", "]", "x", "=", "new", "double", "[", "index", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "x", ".", "length", ";", "i", "++", ")", "{", "x", "[", "i", "]", "=", "datum", ".", "x", "[", "index", "[", "i", "]", "]", ";", "}", "Row", "row", "=", "response", "==", "null", "?", "sub", ".", "add", "(", "x", ")", ":", "sub", ".", "add", "(", "x", ",", "datum", ".", "y", ")", ";", "row", ".", "name", "=", "datum", ".", "name", ";", "row", ".", "weight", "=", "datum", ".", "weight", ";", "row", ".", "description", "=", "datum", ".", "description", ";", "row", ".", "timestamp", "=", "datum", ".", "timestamp", ";", "}", "return", "sub", ";", "}" ]
Returns a dataset with selected columns.
[ "Returns", "a", "dataset", "with", "selected", "columns", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/AttributeDataset.java#L404-L435
17,537
haifengl/smile
data/src/main/java/smile/data/AttributeDataset.java
AttributeDataset.remove
public AttributeDataset remove(String... cols) { HashSet<String> remains = new HashSet<>(); for (Attribute attr : attributes) { remains.add(attr.getName()); } for (String col : cols) { remains.remove(col); } Attribute[] attrs = new Attribute[remains.size()]; int[] index = new int[remains.size()]; for (int j = 0, i = 0; j < attributes.length; j++) { if (remains.contains(attributes[j].getName())) { index[i] = j; attrs[i] = attributes[j]; i++; } } AttributeDataset sub = new AttributeDataset(name, attrs, response); for (Datum<double[]> datum : data) { double[] x = new double[index.length]; for (int i = 0; i < x.length; i++) { x[i] = datum.x[index[i]]; } Row row = response == null ? sub.add(x) : sub.add(x, datum.y); row.name = datum.name; row.weight = datum.weight; row.description = datum.description; row.timestamp = datum.timestamp; } return sub; }
java
public AttributeDataset remove(String... cols) { HashSet<String> remains = new HashSet<>(); for (Attribute attr : attributes) { remains.add(attr.getName()); } for (String col : cols) { remains.remove(col); } Attribute[] attrs = new Attribute[remains.size()]; int[] index = new int[remains.size()]; for (int j = 0, i = 0; j < attributes.length; j++) { if (remains.contains(attributes[j].getName())) { index[i] = j; attrs[i] = attributes[j]; i++; } } AttributeDataset sub = new AttributeDataset(name, attrs, response); for (Datum<double[]> datum : data) { double[] x = new double[index.length]; for (int i = 0; i < x.length; i++) { x[i] = datum.x[index[i]]; } Row row = response == null ? sub.add(x) : sub.add(x, datum.y); row.name = datum.name; row.weight = datum.weight; row.description = datum.description; row.timestamp = datum.timestamp; } return sub; }
[ "public", "AttributeDataset", "remove", "(", "String", "...", "cols", ")", "{", "HashSet", "<", "String", ">", "remains", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "Attribute", "attr", ":", "attributes", ")", "{", "remains", ".", "add", "(", "attr", ".", "getName", "(", ")", ")", ";", "}", "for", "(", "String", "col", ":", "cols", ")", "{", "remains", ".", "remove", "(", "col", ")", ";", "}", "Attribute", "[", "]", "attrs", "=", "new", "Attribute", "[", "remains", ".", "size", "(", ")", "]", ";", "int", "[", "]", "index", "=", "new", "int", "[", "remains", ".", "size", "(", ")", "]", ";", "for", "(", "int", "j", "=", "0", ",", "i", "=", "0", ";", "j", "<", "attributes", ".", "length", ";", "j", "++", ")", "{", "if", "(", "remains", ".", "contains", "(", "attributes", "[", "j", "]", ".", "getName", "(", ")", ")", ")", "{", "index", "[", "i", "]", "=", "j", ";", "attrs", "[", "i", "]", "=", "attributes", "[", "j", "]", ";", "i", "++", ";", "}", "}", "AttributeDataset", "sub", "=", "new", "AttributeDataset", "(", "name", ",", "attrs", ",", "response", ")", ";", "for", "(", "Datum", "<", "double", "[", "]", ">", "datum", ":", "data", ")", "{", "double", "[", "]", "x", "=", "new", "double", "[", "index", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "x", ".", "length", ";", "i", "++", ")", "{", "x", "[", "i", "]", "=", "datum", ".", "x", "[", "index", "[", "i", "]", "]", ";", "}", "Row", "row", "=", "response", "==", "null", "?", "sub", ".", "add", "(", "x", ")", ":", "sub", ".", "add", "(", "x", ",", "datum", ".", "y", ")", ";", "row", ".", "name", "=", "datum", ".", "name", ";", "row", ".", "weight", "=", "datum", ".", "weight", ";", "row", ".", "description", "=", "datum", ".", "description", ";", "row", ".", "timestamp", "=", "datum", ".", "timestamp", ";", "}", "return", "sub", ";", "}" ]
Returns a new dataset without given columns.
[ "Returns", "a", "new", "dataset", "without", "given", "columns", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/AttributeDataset.java#L438-L471
17,538
haifengl/smile
math/src/main/java/smile/math/matrix/BandMatrix.java
BandMatrix.det
public double det() { if (au == null) { decompose(); } double dd = d; for (int i = 0; i < n; i++) { dd *= au[i][0]; } return dd; }
java
public double det() { if (au == null) { decompose(); } double dd = d; for (int i = 0; i < n; i++) { dd *= au[i][0]; } return dd; }
[ "public", "double", "det", "(", ")", "{", "if", "(", "au", "==", "null", ")", "{", "decompose", "(", ")", ";", "}", "double", "dd", "=", "d", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "dd", "*=", "au", "[", "i", "]", "[", "0", "]", ";", "}", "return", "dd", ";", "}" ]
Returns the matrix determinant.
[ "Returns", "the", "matrix", "determinant", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/BandMatrix.java#L194-L205
17,539
haifengl/smile
math/src/main/java/smile/math/matrix/BandMatrix.java
BandMatrix.decompose
public void decompose() { final double TINY = 1.0e-40; int mm = m1 + m2 + 1; index = new int[n]; au = new double[n][mm]; al = new double[n][m1]; for (int i = 0; i < A.length; i++) { System.arraycopy(A[i], 0, au[i], 0, A[i].length); } double dum; int l = m1; for (int i = 0; i < m1; i++) { for (int j = m1 - i; j < mm; j++) { au[i][j - l] = au[i][j]; } l--; for (int j = mm - l - 1; j < mm; j++) au[i][j] = 0.0; } d = 1.0; l = m1; for (int k = 0; k < n; k++) { dum = au[k][0]; int i = k; if (l < n) { l++; } for (int j = k + 1; j < l; j++) { if (Math.abs(au[j][0]) > Math.abs(dum)) { dum = au[j][0]; i = j; } } index[k] = i + 1; if (dum == 0.0) { au[k][0] = TINY; } if (i != k) { d = -d; // swap au[k], au[i] double[] swap = au[k]; au[k] = au[i]; au[i] = swap; } for (i = k + 1; i < l; i++) { dum = au[i][0] / au[k][0]; al[k][i - k - 1] = dum; for (int j = 1; j < mm; j++) { au[i][j - 1] = au[i][j] - dum * au[k][j]; } au[i][mm - 1] = 0.0; } } }
java
public void decompose() { final double TINY = 1.0e-40; int mm = m1 + m2 + 1; index = new int[n]; au = new double[n][mm]; al = new double[n][m1]; for (int i = 0; i < A.length; i++) { System.arraycopy(A[i], 0, au[i], 0, A[i].length); } double dum; int l = m1; for (int i = 0; i < m1; i++) { for (int j = m1 - i; j < mm; j++) { au[i][j - l] = au[i][j]; } l--; for (int j = mm - l - 1; j < mm; j++) au[i][j] = 0.0; } d = 1.0; l = m1; for (int k = 0; k < n; k++) { dum = au[k][0]; int i = k; if (l < n) { l++; } for (int j = k + 1; j < l; j++) { if (Math.abs(au[j][0]) > Math.abs(dum)) { dum = au[j][0]; i = j; } } index[k] = i + 1; if (dum == 0.0) { au[k][0] = TINY; } if (i != k) { d = -d; // swap au[k], au[i] double[] swap = au[k]; au[k] = au[i]; au[i] = swap; } for (i = k + 1; i < l; i++) { dum = au[i][0] / au[k][0]; al[k][i - k - 1] = dum; for (int j = 1; j < mm; j++) { au[i][j - 1] = au[i][j] - dum * au[k][j]; } au[i][mm - 1] = 0.0; } } }
[ "public", "void", "decompose", "(", ")", "{", "final", "double", "TINY", "=", "1.0e-40", ";", "int", "mm", "=", "m1", "+", "m2", "+", "1", ";", "index", "=", "new", "int", "[", "n", "]", ";", "au", "=", "new", "double", "[", "n", "]", "[", "mm", "]", ";", "al", "=", "new", "double", "[", "n", "]", "[", "m1", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "A", ".", "length", ";", "i", "++", ")", "{", "System", ".", "arraycopy", "(", "A", "[", "i", "]", ",", "0", ",", "au", "[", "i", "]", ",", "0", ",", "A", "[", "i", "]", ".", "length", ")", ";", "}", "double", "dum", ";", "int", "l", "=", "m1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "m1", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "m1", "-", "i", ";", "j", "<", "mm", ";", "j", "++", ")", "{", "au", "[", "i", "]", "[", "j", "-", "l", "]", "=", "au", "[", "i", "]", "[", "j", "]", ";", "}", "l", "--", ";", "for", "(", "int", "j", "=", "mm", "-", "l", "-", "1", ";", "j", "<", "mm", ";", "j", "++", ")", "au", "[", "i", "]", "[", "j", "]", "=", "0.0", ";", "}", "d", "=", "1.0", ";", "l", "=", "m1", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "n", ";", "k", "++", ")", "{", "dum", "=", "au", "[", "k", "]", "[", "0", "]", ";", "int", "i", "=", "k", ";", "if", "(", "l", "<", "n", ")", "{", "l", "++", ";", "}", "for", "(", "int", "j", "=", "k", "+", "1", ";", "j", "<", "l", ";", "j", "++", ")", "{", "if", "(", "Math", ".", "abs", "(", "au", "[", "j", "]", "[", "0", "]", ")", ">", "Math", ".", "abs", "(", "dum", ")", ")", "{", "dum", "=", "au", "[", "j", "]", "[", "0", "]", ";", "i", "=", "j", ";", "}", "}", "index", "[", "k", "]", "=", "i", "+", "1", ";", "if", "(", "dum", "==", "0.0", ")", "{", "au", "[", "k", "]", "[", "0", "]", "=", "TINY", ";", "}", "if", "(", "i", "!=", "k", ")", "{", "d", "=", "-", "d", ";", "// swap au[k], au[i]", "double", "[", "]", "swap", "=", "au", "[", "k", "]", ";", "au", "[", "k", "]", "=", "au", "[", "i", "]", ";", "au", "[", "i", "]", "=", "swap", ";", "}", "for", "(", "i", "=", "k", "+", "1", ";", "i", "<", "l", ";", "i", "++", ")", "{", "dum", "=", "au", "[", "i", "]", "[", "0", "]", "/", "au", "[", "k", "]", "[", "0", "]", ";", "al", "[", "k", "]", "[", "i", "-", "k", "-", "1", "]", "=", "dum", ";", "for", "(", "int", "j", "=", "1", ";", "j", "<", "mm", ";", "j", "++", ")", "{", "au", "[", "i", "]", "[", "j", "-", "1", "]", "=", "au", "[", "i", "]", "[", "j", "]", "-", "dum", "*", "au", "[", "k", "]", "[", "j", "]", ";", "}", "au", "[", "i", "]", "[", "mm", "-", "1", "]", "=", "0.0", ";", "}", "}", "}" ]
LU decomposition.
[ "LU", "decomposition", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/BandMatrix.java#L210-L271
17,540
haifengl/smile
math/src/main/java/smile/math/matrix/BandMatrix.java
BandMatrix.improve
public void improve(double[] b, double[] x) { if (b.length != n || x.length != n) { throw new IllegalArgumentException(String.format("Row dimensions do not agree: A is %d x %d, but b is %d x 1 and x is %d x 1", n, n, b.length, x.length)); } // Calculate the right-hand side, accumulating the residual // in higher precision. double[] r = b.clone(); axpy(x, r, -1.0); // Solve for the error term. solve(r, r); // Subtract the error from the old solution. for (int i = 0; i < n; i++) { x[i] -= r[i]; } }
java
public void improve(double[] b, double[] x) { if (b.length != n || x.length != n) { throw new IllegalArgumentException(String.format("Row dimensions do not agree: A is %d x %d, but b is %d x 1 and x is %d x 1", n, n, b.length, x.length)); } // Calculate the right-hand side, accumulating the residual // in higher precision. double[] r = b.clone(); axpy(x, r, -1.0); // Solve for the error term. solve(r, r); // Subtract the error from the old solution. for (int i = 0; i < n; i++) { x[i] -= r[i]; } }
[ "public", "void", "improve", "(", "double", "[", "]", "b", ",", "double", "[", "]", "x", ")", "{", "if", "(", "b", ".", "length", "!=", "n", "||", "x", ".", "length", "!=", "n", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Row dimensions do not agree: A is %d x %d, but b is %d x 1 and x is %d x 1\"", ",", "n", ",", "n", ",", "b", ".", "length", ",", "x", ".", "length", ")", ")", ";", "}", "// Calculate the right-hand side, accumulating the residual", "// in higher precision.", "double", "[", "]", "r", "=", "b", ".", "clone", "(", ")", ";", "axpy", "(", "x", ",", "r", ",", "-", "1.0", ")", ";", "// Solve for the error term.", "solve", "(", "r", ",", "r", ")", ";", "// Subtract the error from the old solution.", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "x", "[", "i", "]", "-=", "r", "[", "i", "]", ";", "}", "}" ]
Iteratively improve a solution to linear equations. @param b right hand side of linear equations. @param x a solution to linear equations.
[ "Iteratively", "improve", "a", "solution", "to", "linear", "equations", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/BandMatrix.java#L476-L493
17,541
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/TangramEngine.java
TangramEngine.onScrolled
public void onScrolled() { // due to a bug in 21: https://code.google.com/p/android/issues/detail?id=162753, which cause getDecoratedStart() throws NullPointException // officially reported it has been fixed in v22 final int lastPosition = getLayoutManager().findLastVisibleItemPosition(); final int firstPosition = getLayoutManager().findFirstVisibleItemPosition(); int lastCardIndex = -1; int firstCardIndex = -1; int position = lastPosition; //find the last visible item in card for (int i = lastPosition; i >= firstPosition; i--) { lastCardIndex = mGroupBasicAdapter.findCardIdxFor(i); if (lastCardIndex >= 0) { position = i; break; } } for (int i = firstCardIndex; i <= lastPosition; i++) { firstCardIndex = mGroupBasicAdapter.findCardIdxFor(i); if (firstCardIndex >= 0) { break; } } if (lastCardIndex < 0 || firstCardIndex < 0) return; final CardLoadSupport loadSupport = getService(CardLoadSupport.class); if (loadSupport == null) return; List<Card> cards = mGroupBasicAdapter.getGroups(); //check the loadmore state of current card first range is inclusive-exclusive Card current = cards.get(lastCardIndex); Pair<Range<Integer>, Card> pair = mGroupBasicAdapter.getCardRange(lastCardIndex); if (pair != null && position >= pair.first.getUpper() - mPreLoadNumber) { // async load if (!TextUtils.isEmpty(current.load) && current.loaded) { // page load if (current.loadMore) { loadSupport.loadMore(current); loadSupport.reactiveDoLoadMore(current); } return; } } boolean loadedMore = false; for (int i = firstCardIndex; i < Math.min(lastCardIndex + mPreLoadNumber, cards.size()); i++) { Card c = cards.get(i); // async load if (!TextUtils.isEmpty(c.load) && !c.loaded) { // page load if (c.loadMore && !loadedMore) { // only load one load more card loadSupport.loadMore(c); loadSupport.reactiveDoLoadMore(c); loadedMore = true; } else { loadSupport.doLoad(c); loadSupport.reactiveDoLoad(c); } c.loaded = true; } } if (mEnableAutoLoadMore && mGroupBasicAdapter.getItemCount() - position < mPreLoadNumber) { loadMoreCard(); } }
java
public void onScrolled() { // due to a bug in 21: https://code.google.com/p/android/issues/detail?id=162753, which cause getDecoratedStart() throws NullPointException // officially reported it has been fixed in v22 final int lastPosition = getLayoutManager().findLastVisibleItemPosition(); final int firstPosition = getLayoutManager().findFirstVisibleItemPosition(); int lastCardIndex = -1; int firstCardIndex = -1; int position = lastPosition; //find the last visible item in card for (int i = lastPosition; i >= firstPosition; i--) { lastCardIndex = mGroupBasicAdapter.findCardIdxFor(i); if (lastCardIndex >= 0) { position = i; break; } } for (int i = firstCardIndex; i <= lastPosition; i++) { firstCardIndex = mGroupBasicAdapter.findCardIdxFor(i); if (firstCardIndex >= 0) { break; } } if (lastCardIndex < 0 || firstCardIndex < 0) return; final CardLoadSupport loadSupport = getService(CardLoadSupport.class); if (loadSupport == null) return; List<Card> cards = mGroupBasicAdapter.getGroups(); //check the loadmore state of current card first range is inclusive-exclusive Card current = cards.get(lastCardIndex); Pair<Range<Integer>, Card> pair = mGroupBasicAdapter.getCardRange(lastCardIndex); if (pair != null && position >= pair.first.getUpper() - mPreLoadNumber) { // async load if (!TextUtils.isEmpty(current.load) && current.loaded) { // page load if (current.loadMore) { loadSupport.loadMore(current); loadSupport.reactiveDoLoadMore(current); } return; } } boolean loadedMore = false; for (int i = firstCardIndex; i < Math.min(lastCardIndex + mPreLoadNumber, cards.size()); i++) { Card c = cards.get(i); // async load if (!TextUtils.isEmpty(c.load) && !c.loaded) { // page load if (c.loadMore && !loadedMore) { // only load one load more card loadSupport.loadMore(c); loadSupport.reactiveDoLoadMore(c); loadedMore = true; } else { loadSupport.doLoad(c); loadSupport.reactiveDoLoad(c); } c.loaded = true; } } if (mEnableAutoLoadMore && mGroupBasicAdapter.getItemCount() - position < mPreLoadNumber) { loadMoreCard(); } }
[ "public", "void", "onScrolled", "(", ")", "{", "// due to a bug in 21: https://code.google.com/p/android/issues/detail?id=162753, which cause getDecoratedStart() throws NullPointException", "// officially reported it has been fixed in v22", "final", "int", "lastPosition", "=", "getLayoutManager", "(", ")", ".", "findLastVisibleItemPosition", "(", ")", ";", "final", "int", "firstPosition", "=", "getLayoutManager", "(", ")", ".", "findFirstVisibleItemPosition", "(", ")", ";", "int", "lastCardIndex", "=", "-", "1", ";", "int", "firstCardIndex", "=", "-", "1", ";", "int", "position", "=", "lastPosition", ";", "//find the last visible item in card", "for", "(", "int", "i", "=", "lastPosition", ";", "i", ">=", "firstPosition", ";", "i", "--", ")", "{", "lastCardIndex", "=", "mGroupBasicAdapter", ".", "findCardIdxFor", "(", "i", ")", ";", "if", "(", "lastCardIndex", ">=", "0", ")", "{", "position", "=", "i", ";", "break", ";", "}", "}", "for", "(", "int", "i", "=", "firstCardIndex", ";", "i", "<=", "lastPosition", ";", "i", "++", ")", "{", "firstCardIndex", "=", "mGroupBasicAdapter", ".", "findCardIdxFor", "(", "i", ")", ";", "if", "(", "firstCardIndex", ">=", "0", ")", "{", "break", ";", "}", "}", "if", "(", "lastCardIndex", "<", "0", "||", "firstCardIndex", "<", "0", ")", "return", ";", "final", "CardLoadSupport", "loadSupport", "=", "getService", "(", "CardLoadSupport", ".", "class", ")", ";", "if", "(", "loadSupport", "==", "null", ")", "return", ";", "List", "<", "Card", ">", "cards", "=", "mGroupBasicAdapter", ".", "getGroups", "(", ")", ";", "//check the loadmore state of current card first range is inclusive-exclusive", "Card", "current", "=", "cards", ".", "get", "(", "lastCardIndex", ")", ";", "Pair", "<", "Range", "<", "Integer", ">", ",", "Card", ">", "pair", "=", "mGroupBasicAdapter", ".", "getCardRange", "(", "lastCardIndex", ")", ";", "if", "(", "pair", "!=", "null", "&&", "position", ">=", "pair", ".", "first", ".", "getUpper", "(", ")", "-", "mPreLoadNumber", ")", "{", "// async load", "if", "(", "!", "TextUtils", ".", "isEmpty", "(", "current", ".", "load", ")", "&&", "current", ".", "loaded", ")", "{", "// page load", "if", "(", "current", ".", "loadMore", ")", "{", "loadSupport", ".", "loadMore", "(", "current", ")", ";", "loadSupport", ".", "reactiveDoLoadMore", "(", "current", ")", ";", "}", "return", ";", "}", "}", "boolean", "loadedMore", "=", "false", ";", "for", "(", "int", "i", "=", "firstCardIndex", ";", "i", "<", "Math", ".", "min", "(", "lastCardIndex", "+", "mPreLoadNumber", ",", "cards", ".", "size", "(", ")", ")", ";", "i", "++", ")", "{", "Card", "c", "=", "cards", ".", "get", "(", "i", ")", ";", "// async load", "if", "(", "!", "TextUtils", ".", "isEmpty", "(", "c", ".", "load", ")", "&&", "!", "c", ".", "loaded", ")", "{", "// page load", "if", "(", "c", ".", "loadMore", "&&", "!", "loadedMore", ")", "{", "// only load one load more card", "loadSupport", ".", "loadMore", "(", "c", ")", ";", "loadSupport", ".", "reactiveDoLoadMore", "(", "c", ")", ";", "loadedMore", "=", "true", ";", "}", "else", "{", "loadSupport", ".", "doLoad", "(", "c", ")", ";", "loadSupport", ".", "reactiveDoLoad", "(", "c", ")", ";", "}", "c", ".", "loaded", "=", "true", ";", "}", "}", "if", "(", "mEnableAutoLoadMore", "&&", "mGroupBasicAdapter", ".", "getItemCount", "(", ")", "-", "position", "<", "mPreLoadNumber", ")", "{", "loadMoreCard", "(", ")", ";", "}", "}" ]
Call this method in RecyclerView's scroll listener. Would trigger the preload of card's data.
[ "Call", "this", "method", "in", "RecyclerView", "s", "scroll", "listener", ".", "Would", "trigger", "the", "preload", "of", "card", "s", "data", "." ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/TangramEngine.java#L162-L234
17,542
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/TangramEngine.java
TangramEngine.removeBatchBy
protected void removeBatchBy(int removeIdx) { if (mGroupBasicAdapter != null) { Pair<Range<Integer>, Card> cardPair = mGroupBasicAdapter.getCardRange(removeIdx); if (cardPair != null) { removeBatchBy(cardPair.second); } } }
java
protected void removeBatchBy(int removeIdx) { if (mGroupBasicAdapter != null) { Pair<Range<Integer>, Card> cardPair = mGroupBasicAdapter.getCardRange(removeIdx); if (cardPair != null) { removeBatchBy(cardPair.second); } } }
[ "protected", "void", "removeBatchBy", "(", "int", "removeIdx", ")", "{", "if", "(", "mGroupBasicAdapter", "!=", "null", ")", "{", "Pair", "<", "Range", "<", "Integer", ">", ",", "Card", ">", "cardPair", "=", "mGroupBasicAdapter", ".", "getCardRange", "(", "removeIdx", ")", ";", "if", "(", "cardPair", "!=", "null", ")", "{", "removeBatchBy", "(", "cardPair", ".", "second", ")", ";", "}", "}", "}" ]
Remove all cells in a card with target index @param removeIdx target card's index @since 2.1.0
[ "Remove", "all", "cells", "in", "a", "card", "with", "target", "index" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/TangramEngine.java#L710-L717
17,543
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/TangramEngine.java
TangramEngine.removeBatchBy
protected void removeBatchBy(Card group) { VirtualLayoutManager layoutManager = getLayoutManager(); if (group != null && mGroupBasicAdapter != null && layoutManager != null) { int cardIdx = mGroupBasicAdapter.findCardIdxForCard(group); List<LayoutHelper> layoutHelpers = layoutManager.getLayoutHelpers(); LayoutHelper emptyLayoutHelper = null; int removeItemCount = 0; if (layoutHelpers != null && cardIdx >= 0 && cardIdx < layoutHelpers.size()) { for (int i = 0, size = layoutHelpers.size(); i < size; i++) { LayoutHelper layoutHelper = layoutHelpers.get(i); int start = layoutHelper.getRange().getLower(); int end = layoutHelper.getRange().getUpper(); if (i < cardIdx) { // do nothing } else if (i == cardIdx) { removeItemCount = layoutHelper.getItemCount(); emptyLayoutHelper = layoutHelper; } else { layoutHelper.setRange(start - removeItemCount, end - removeItemCount); } } if (emptyLayoutHelper != null) { final List<LayoutHelper> newLayoutHelpers = new LinkedList<>(layoutHelpers); newLayoutHelpers.remove(emptyLayoutHelper); layoutManager.setLayoutHelpers(newLayoutHelpers); } mGroupBasicAdapter.removeComponents(group); } } }
java
protected void removeBatchBy(Card group) { VirtualLayoutManager layoutManager = getLayoutManager(); if (group != null && mGroupBasicAdapter != null && layoutManager != null) { int cardIdx = mGroupBasicAdapter.findCardIdxForCard(group); List<LayoutHelper> layoutHelpers = layoutManager.getLayoutHelpers(); LayoutHelper emptyLayoutHelper = null; int removeItemCount = 0; if (layoutHelpers != null && cardIdx >= 0 && cardIdx < layoutHelpers.size()) { for (int i = 0, size = layoutHelpers.size(); i < size; i++) { LayoutHelper layoutHelper = layoutHelpers.get(i); int start = layoutHelper.getRange().getLower(); int end = layoutHelper.getRange().getUpper(); if (i < cardIdx) { // do nothing } else if (i == cardIdx) { removeItemCount = layoutHelper.getItemCount(); emptyLayoutHelper = layoutHelper; } else { layoutHelper.setRange(start - removeItemCount, end - removeItemCount); } } if (emptyLayoutHelper != null) { final List<LayoutHelper> newLayoutHelpers = new LinkedList<>(layoutHelpers); newLayoutHelpers.remove(emptyLayoutHelper); layoutManager.setLayoutHelpers(newLayoutHelpers); } mGroupBasicAdapter.removeComponents(group); } } }
[ "protected", "void", "removeBatchBy", "(", "Card", "group", ")", "{", "VirtualLayoutManager", "layoutManager", "=", "getLayoutManager", "(", ")", ";", "if", "(", "group", "!=", "null", "&&", "mGroupBasicAdapter", "!=", "null", "&&", "layoutManager", "!=", "null", ")", "{", "int", "cardIdx", "=", "mGroupBasicAdapter", ".", "findCardIdxForCard", "(", "group", ")", ";", "List", "<", "LayoutHelper", ">", "layoutHelpers", "=", "layoutManager", ".", "getLayoutHelpers", "(", ")", ";", "LayoutHelper", "emptyLayoutHelper", "=", "null", ";", "int", "removeItemCount", "=", "0", ";", "if", "(", "layoutHelpers", "!=", "null", "&&", "cardIdx", ">=", "0", "&&", "cardIdx", "<", "layoutHelpers", ".", "size", "(", ")", ")", "{", "for", "(", "int", "i", "=", "0", ",", "size", "=", "layoutHelpers", ".", "size", "(", ")", ";", "i", "<", "size", ";", "i", "++", ")", "{", "LayoutHelper", "layoutHelper", "=", "layoutHelpers", ".", "get", "(", "i", ")", ";", "int", "start", "=", "layoutHelper", ".", "getRange", "(", ")", ".", "getLower", "(", ")", ";", "int", "end", "=", "layoutHelper", ".", "getRange", "(", ")", ".", "getUpper", "(", ")", ";", "if", "(", "i", "<", "cardIdx", ")", "{", "// do nothing", "}", "else", "if", "(", "i", "==", "cardIdx", ")", "{", "removeItemCount", "=", "layoutHelper", ".", "getItemCount", "(", ")", ";", "emptyLayoutHelper", "=", "layoutHelper", ";", "}", "else", "{", "layoutHelper", ".", "setRange", "(", "start", "-", "removeItemCount", ",", "end", "-", "removeItemCount", ")", ";", "}", "}", "if", "(", "emptyLayoutHelper", "!=", "null", ")", "{", "final", "List", "<", "LayoutHelper", ">", "newLayoutHelpers", "=", "new", "LinkedList", "<>", "(", "layoutHelpers", ")", ";", "newLayoutHelpers", ".", "remove", "(", "emptyLayoutHelper", ")", ";", "layoutManager", ".", "setLayoutHelpers", "(", "newLayoutHelpers", ")", ";", "}", "mGroupBasicAdapter", ".", "removeComponents", "(", "group", ")", ";", "}", "}", "}" ]
Remove all cells in a card. @param group @since 2.1.0
[ "Remove", "all", "cells", "in", "a", "card", "." ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/TangramEngine.java#L725-L754
17,544
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/TangramEngine.java
TangramEngine.replace
public void replace(BaseCell oldOne, BaseCell newOne) { VirtualLayoutManager layoutManager = getLayoutManager(); if (oldOne != null && newOne != null && mGroupBasicAdapter != null && layoutManager != null) { int replacePosition = mGroupBasicAdapter.getPositionByItem(oldOne); if (replacePosition >= 0) { int cardIdx = mGroupBasicAdapter.findCardIdxFor(replacePosition); Card card = mGroupBasicAdapter.getCardRange(cardIdx).second; card.replaceCell(oldOne, newOne); mGroupBasicAdapter.replaceComponent(Arrays.asList(oldOne), Arrays.asList(newOne)); } } }
java
public void replace(BaseCell oldOne, BaseCell newOne) { VirtualLayoutManager layoutManager = getLayoutManager(); if (oldOne != null && newOne != null && mGroupBasicAdapter != null && layoutManager != null) { int replacePosition = mGroupBasicAdapter.getPositionByItem(oldOne); if (replacePosition >= 0) { int cardIdx = mGroupBasicAdapter.findCardIdxFor(replacePosition); Card card = mGroupBasicAdapter.getCardRange(cardIdx).second; card.replaceCell(oldOne, newOne); mGroupBasicAdapter.replaceComponent(Arrays.asList(oldOne), Arrays.asList(newOne)); } } }
[ "public", "void", "replace", "(", "BaseCell", "oldOne", ",", "BaseCell", "newOne", ")", "{", "VirtualLayoutManager", "layoutManager", "=", "getLayoutManager", "(", ")", ";", "if", "(", "oldOne", "!=", "null", "&&", "newOne", "!=", "null", "&&", "mGroupBasicAdapter", "!=", "null", "&&", "layoutManager", "!=", "null", ")", "{", "int", "replacePosition", "=", "mGroupBasicAdapter", ".", "getPositionByItem", "(", "oldOne", ")", ";", "if", "(", "replacePosition", ">=", "0", ")", "{", "int", "cardIdx", "=", "mGroupBasicAdapter", ".", "findCardIdxFor", "(", "replacePosition", ")", ";", "Card", "card", "=", "mGroupBasicAdapter", ".", "getCardRange", "(", "cardIdx", ")", ".", "second", ";", "card", ".", "replaceCell", "(", "oldOne", ",", "newOne", ")", ";", "mGroupBasicAdapter", ".", "replaceComponent", "(", "Arrays", ".", "asList", "(", "oldOne", ")", ",", "Arrays", ".", "asList", "(", "newOne", ")", ")", ";", "}", "}", "}" ]
Replace cell one by one. @param oldOne @param newOne @since 2.1.0
[ "Replace", "cell", "one", "by", "one", "." ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/TangramEngine.java#L763-L774
17,545
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/TangramEngine.java
TangramEngine.replace
public void replace(Card parent, List<BaseCell> cells) { VirtualLayoutManager layoutManager = getLayoutManager(); if (parent != null && cells != null && cells.size() > 0 && mGroupBasicAdapter != null && layoutManager != null) { Card card = parent; List<BaseCell> oldChildren = new ArrayList<>(parent.getCells()); if (oldChildren.size() == cells.size()) { card.setCells(cells); mGroupBasicAdapter.replaceComponent(oldChildren, cells); } else { List<LayoutHelper> layoutHelpers = layoutManager.getLayoutHelpers(); int cardIdx = mGroupBasicAdapter.findCardIdxForCard(parent); int diff = 0; if (layoutHelpers != null && cardIdx >= 0 && cardIdx < layoutHelpers.size()) { for (int i = 0, size = layoutHelpers.size(); i < size; i++) { LayoutHelper layoutHelper = layoutHelpers.get(i); int start = layoutHelper.getRange().getLower(); int end = layoutHelper.getRange().getUpper(); if (i < cardIdx) { // do nothing } else if (i == cardIdx) { diff = cells.size() - layoutHelper.getItemCount(); layoutHelper.setItemCount(cells.size()); layoutHelper.setRange(start, end + diff); } else { layoutHelper.setRange(start + diff, end + diff); } } card.setCells(cells); mGroupBasicAdapter.replaceComponent(oldChildren, cells); } } } }
java
public void replace(Card parent, List<BaseCell> cells) { VirtualLayoutManager layoutManager = getLayoutManager(); if (parent != null && cells != null && cells.size() > 0 && mGroupBasicAdapter != null && layoutManager != null) { Card card = parent; List<BaseCell> oldChildren = new ArrayList<>(parent.getCells()); if (oldChildren.size() == cells.size()) { card.setCells(cells); mGroupBasicAdapter.replaceComponent(oldChildren, cells); } else { List<LayoutHelper> layoutHelpers = layoutManager.getLayoutHelpers(); int cardIdx = mGroupBasicAdapter.findCardIdxForCard(parent); int diff = 0; if (layoutHelpers != null && cardIdx >= 0 && cardIdx < layoutHelpers.size()) { for (int i = 0, size = layoutHelpers.size(); i < size; i++) { LayoutHelper layoutHelper = layoutHelpers.get(i); int start = layoutHelper.getRange().getLower(); int end = layoutHelper.getRange().getUpper(); if (i < cardIdx) { // do nothing } else if (i == cardIdx) { diff = cells.size() - layoutHelper.getItemCount(); layoutHelper.setItemCount(cells.size()); layoutHelper.setRange(start, end + diff); } else { layoutHelper.setRange(start + diff, end + diff); } } card.setCells(cells); mGroupBasicAdapter.replaceComponent(oldChildren, cells); } } } }
[ "public", "void", "replace", "(", "Card", "parent", ",", "List", "<", "BaseCell", ">", "cells", ")", "{", "VirtualLayoutManager", "layoutManager", "=", "getLayoutManager", "(", ")", ";", "if", "(", "parent", "!=", "null", "&&", "cells", "!=", "null", "&&", "cells", ".", "size", "(", ")", ">", "0", "&&", "mGroupBasicAdapter", "!=", "null", "&&", "layoutManager", "!=", "null", ")", "{", "Card", "card", "=", "parent", ";", "List", "<", "BaseCell", ">", "oldChildren", "=", "new", "ArrayList", "<>", "(", "parent", ".", "getCells", "(", ")", ")", ";", "if", "(", "oldChildren", ".", "size", "(", ")", "==", "cells", ".", "size", "(", ")", ")", "{", "card", ".", "setCells", "(", "cells", ")", ";", "mGroupBasicAdapter", ".", "replaceComponent", "(", "oldChildren", ",", "cells", ")", ";", "}", "else", "{", "List", "<", "LayoutHelper", ">", "layoutHelpers", "=", "layoutManager", ".", "getLayoutHelpers", "(", ")", ";", "int", "cardIdx", "=", "mGroupBasicAdapter", ".", "findCardIdxForCard", "(", "parent", ")", ";", "int", "diff", "=", "0", ";", "if", "(", "layoutHelpers", "!=", "null", "&&", "cardIdx", ">=", "0", "&&", "cardIdx", "<", "layoutHelpers", ".", "size", "(", ")", ")", "{", "for", "(", "int", "i", "=", "0", ",", "size", "=", "layoutHelpers", ".", "size", "(", ")", ";", "i", "<", "size", ";", "i", "++", ")", "{", "LayoutHelper", "layoutHelper", "=", "layoutHelpers", ".", "get", "(", "i", ")", ";", "int", "start", "=", "layoutHelper", ".", "getRange", "(", ")", ".", "getLower", "(", ")", ";", "int", "end", "=", "layoutHelper", ".", "getRange", "(", ")", ".", "getUpper", "(", ")", ";", "if", "(", "i", "<", "cardIdx", ")", "{", "// do nothing", "}", "else", "if", "(", "i", "==", "cardIdx", ")", "{", "diff", "=", "cells", ".", "size", "(", ")", "-", "layoutHelper", ".", "getItemCount", "(", ")", ";", "layoutHelper", ".", "setItemCount", "(", "cells", ".", "size", "(", ")", ")", ";", "layoutHelper", ".", "setRange", "(", "start", ",", "end", "+", "diff", ")", ";", "}", "else", "{", "layoutHelper", ".", "setRange", "(", "start", "+", "diff", ",", "end", "+", "diff", ")", ";", "}", "}", "card", ".", "setCells", "(", "cells", ")", ";", "mGroupBasicAdapter", ".", "replaceComponent", "(", "oldChildren", ",", "cells", ")", ";", "}", "}", "}", "}" ]
Replace parent card's children. Cells' size should be equal with parent's children size. @param parent @param cells @since 2.1.0
[ "Replace", "parent", "card", "s", "children", ".", "Cells", "size", "should", "be", "equal", "with", "parent", "s", "children", "size", "." ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/TangramEngine.java#L783-L815
17,546
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/TangramEngine.java
TangramEngine.replace
public void replace(Card oldOne, Card newOne) { VirtualLayoutManager layoutManager = getLayoutManager(); if (oldOne != null && newOne != null && mGroupBasicAdapter != null && layoutManager != null) { List<LayoutHelper> layoutHelpers = layoutManager.getLayoutHelpers(); int cardIdx = mGroupBasicAdapter.findCardIdxForCard(oldOne); if (layoutHelpers != null && cardIdx >= 0 && cardIdx < layoutHelpers.size()) { final List<LayoutHelper> newLayoutHelpers = new LinkedList<>(); for (int i = 0, size = layoutHelpers.size(); i < size; i++) { LayoutHelper layoutHelper = layoutHelpers.get(i); if (i == cardIdx) { layoutHelper = newOne.getLayoutHelper(); } newLayoutHelpers.add(layoutHelper); } layoutManager.setLayoutHelpers(newLayoutHelpers); mGroupBasicAdapter.replaceComponent(oldOne, newOne); } } }
java
public void replace(Card oldOne, Card newOne) { VirtualLayoutManager layoutManager = getLayoutManager(); if (oldOne != null && newOne != null && mGroupBasicAdapter != null && layoutManager != null) { List<LayoutHelper> layoutHelpers = layoutManager.getLayoutHelpers(); int cardIdx = mGroupBasicAdapter.findCardIdxForCard(oldOne); if (layoutHelpers != null && cardIdx >= 0 && cardIdx < layoutHelpers.size()) { final List<LayoutHelper> newLayoutHelpers = new LinkedList<>(); for (int i = 0, size = layoutHelpers.size(); i < size; i++) { LayoutHelper layoutHelper = layoutHelpers.get(i); if (i == cardIdx) { layoutHelper = newOne.getLayoutHelper(); } newLayoutHelpers.add(layoutHelper); } layoutManager.setLayoutHelpers(newLayoutHelpers); mGroupBasicAdapter.replaceComponent(oldOne, newOne); } } }
[ "public", "void", "replace", "(", "Card", "oldOne", ",", "Card", "newOne", ")", "{", "VirtualLayoutManager", "layoutManager", "=", "getLayoutManager", "(", ")", ";", "if", "(", "oldOne", "!=", "null", "&&", "newOne", "!=", "null", "&&", "mGroupBasicAdapter", "!=", "null", "&&", "layoutManager", "!=", "null", ")", "{", "List", "<", "LayoutHelper", ">", "layoutHelpers", "=", "layoutManager", ".", "getLayoutHelpers", "(", ")", ";", "int", "cardIdx", "=", "mGroupBasicAdapter", ".", "findCardIdxForCard", "(", "oldOne", ")", ";", "if", "(", "layoutHelpers", "!=", "null", "&&", "cardIdx", ">=", "0", "&&", "cardIdx", "<", "layoutHelpers", ".", "size", "(", ")", ")", "{", "final", "List", "<", "LayoutHelper", ">", "newLayoutHelpers", "=", "new", "LinkedList", "<>", "(", ")", ";", "for", "(", "int", "i", "=", "0", ",", "size", "=", "layoutHelpers", ".", "size", "(", ")", ";", "i", "<", "size", ";", "i", "++", ")", "{", "LayoutHelper", "layoutHelper", "=", "layoutHelpers", ".", "get", "(", "i", ")", ";", "if", "(", "i", "==", "cardIdx", ")", "{", "layoutHelper", "=", "newOne", ".", "getLayoutHelper", "(", ")", ";", "}", "newLayoutHelpers", ".", "add", "(", "layoutHelper", ")", ";", "}", "layoutManager", ".", "setLayoutHelpers", "(", "newLayoutHelpers", ")", ";", "mGroupBasicAdapter", ".", "replaceComponent", "(", "oldOne", ",", "newOne", ")", ";", "}", "}", "}" ]
Replace card one by one. New one's children size should be equal with old one's children size. @param oldOne @param newOne @since 2.1.0
[ "Replace", "card", "one", "by", "one", ".", "New", "one", "s", "children", "size", "should", "be", "equal", "with", "old", "one", "s", "children", "size", "." ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/TangramEngine.java#L824-L842
17,547
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/BaseTangramEngine.java
BaseTangramEngine.unbindView
public void unbindView() { if (mContentView != null) { this.mContentView.setAdapter(null); this.mContentView.setLayoutManager(null); this.mContentView = null; } }
java
public void unbindView() { if (mContentView != null) { this.mContentView.setAdapter(null); this.mContentView.setLayoutManager(null); this.mContentView = null; } }
[ "public", "void", "unbindView", "(", ")", "{", "if", "(", "mContentView", "!=", "null", ")", "{", "this", ".", "mContentView", ".", "setAdapter", "(", "null", ")", ";", "this", ".", "mContentView", ".", "setLayoutManager", "(", "null", ")", ";", "this", ".", "mContentView", "=", "null", ";", "}", "}" ]
Unbind the adapter and layoutManger to recyclerView. And also set null to them.
[ "Unbind", "the", "adapter", "and", "layoutManger", "to", "recyclerView", ".", "And", "also", "set", "null", "to", "them", "." ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/BaseTangramEngine.java#L206-L212
17,548
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/BaseTangramEngine.java
BaseTangramEngine.asOriginalDataConsumer
public Consumer<T> asOriginalDataConsumer() { return new Consumer<T>() { @Override public void accept(T t) throws Exception { setData(t); } }; }
java
public Consumer<T> asOriginalDataConsumer() { return new Consumer<T>() { @Override public void accept(T t) throws Exception { setData(t); } }; }
[ "public", "Consumer", "<", "T", ">", "asOriginalDataConsumer", "(", ")", "{", "return", "new", "Consumer", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "void", "accept", "(", "T", "t", ")", "throws", "Exception", "{", "setData", "(", "t", ")", ";", "}", "}", ";", "}" ]
Make engine as a consumer to accept origin data from user @return A consumer will call {@link BaseTangramEngine#setData(Object)} @since 3.0.0
[ "Make", "engine", "as", "a", "consumer", "to", "accept", "origin", "data", "from", "user" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/BaseTangramEngine.java#L410-L417
17,549
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/BaseTangramEngine.java
BaseTangramEngine.asParsedDataConsumer
public Consumer<List<C>> asParsedDataConsumer() { return new Consumer<List<C>>() { @Override public void accept(List<C> cs) throws Exception { setData(cs); } }; }
java
public Consumer<List<C>> asParsedDataConsumer() { return new Consumer<List<C>>() { @Override public void accept(List<C> cs) throws Exception { setData(cs); } }; }
[ "public", "Consumer", "<", "List", "<", "C", ">", ">", "asParsedDataConsumer", "(", ")", "{", "return", "new", "Consumer", "<", "List", "<", "C", ">", ">", "(", ")", "{", "@", "Override", "public", "void", "accept", "(", "List", "<", "C", ">", "cs", ")", "throws", "Exception", "{", "setData", "(", "cs", ")", ";", "}", "}", ";", "}" ]
Make engine as a consumer to accept parsed data from user @return A consumer will call {@link BaseTangramEngine#setData(List)} @since 3.0.0
[ "Make", "engine", "as", "a", "consumer", "to", "accept", "parsed", "data", "from", "user" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/BaseTangramEngine.java#L424-L431
17,550
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/BaseTangramEngine.java
BaseTangramEngine.removeData
@Deprecated public void removeData(int position) { Preconditions.checkState(mGroupBasicAdapter != null, "Must call bindView() first"); this.mGroupBasicAdapter.removeGroup(position); }
java
@Deprecated public void removeData(int position) { Preconditions.checkState(mGroupBasicAdapter != null, "Must call bindView() first"); this.mGroupBasicAdapter.removeGroup(position); }
[ "@", "Deprecated", "public", "void", "removeData", "(", "int", "position", ")", "{", "Preconditions", ".", "checkState", "(", "mGroupBasicAdapter", "!=", "null", ",", "\"Must call bindView() first\"", ")", ";", "this", ".", "mGroupBasicAdapter", ".", "removeGroup", "(", "position", ")", ";", "}" ]
Remove a card at target card position. It cause full screen item's rebinding, be careful. @param position the position of card in group
[ "Remove", "a", "card", "at", "target", "card", "position", ".", "It", "cause", "full", "screen", "item", "s", "rebinding", "be", "careful", "." ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/BaseTangramEngine.java#L469-L473
17,551
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/BaseTangramEngine.java
BaseTangramEngine.removeData
@Deprecated public void removeData(C data) { Preconditions.checkState(mGroupBasicAdapter != null, "Must call bindView() first"); this.mGroupBasicAdapter.removeGroup(data); }
java
@Deprecated public void removeData(C data) { Preconditions.checkState(mGroupBasicAdapter != null, "Must call bindView() first"); this.mGroupBasicAdapter.removeGroup(data); }
[ "@", "Deprecated", "public", "void", "removeData", "(", "C", "data", ")", "{", "Preconditions", ".", "checkState", "(", "mGroupBasicAdapter", "!=", "null", ",", "\"Must call bindView() first\"", ")", ";", "this", ".", "mGroupBasicAdapter", ".", "removeGroup", "(", "data", ")", ";", "}" ]
Remove the target card from list. It cause full screen item's rebinding, be careful. @param data Target card
[ "Remove", "the", "target", "card", "from", "list", ".", "It", "cause", "full", "screen", "item", "s", "rebinding", "be", "careful", "." ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/BaseTangramEngine.java#L479-L483
17,552
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/BaseTangramEngine.java
BaseTangramEngine.getCardRange
public Range<Integer> getCardRange(String id) { Preconditions.checkState(mGroupBasicAdapter != null, "Must call bindView() first"); return this.mGroupBasicAdapter.getCardRange(id); }
java
public Range<Integer> getCardRange(String id) { Preconditions.checkState(mGroupBasicAdapter != null, "Must call bindView() first"); return this.mGroupBasicAdapter.getCardRange(id); }
[ "public", "Range", "<", "Integer", ">", "getCardRange", "(", "String", "id", ")", "{", "Preconditions", ".", "checkState", "(", "mGroupBasicAdapter", "!=", "null", ",", "\"Must call bindView() first\"", ")", ";", "return", "this", ".", "mGroupBasicAdapter", ".", "getCardRange", "(", "id", ")", ";", "}" ]
Get card range by id @param id card id @return range instance
[ "Get", "card", "range", "by", "id" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/BaseTangramEngine.java#L500-L503
17,553
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/TangramEngine.java
TangramEngine.asUpdateCellConsumer
public Consumer<UpdateCellOp> asUpdateCellConsumer() { return new Consumer<UpdateCellOp>() { @Override public void accept(UpdateCellOp op) throws Exception { update(op.getArg1()); } }; }
java
public Consumer<UpdateCellOp> asUpdateCellConsumer() { return new Consumer<UpdateCellOp>() { @Override public void accept(UpdateCellOp op) throws Exception { update(op.getArg1()); } }; }
[ "public", "Consumer", "<", "UpdateCellOp", ">", "asUpdateCellConsumer", "(", ")", "{", "return", "new", "Consumer", "<", "UpdateCellOp", ">", "(", ")", "{", "@", "Override", "public", "void", "accept", "(", "UpdateCellOp", "op", ")", "throws", "Exception", "{", "update", "(", "op", ".", "getArg1", "(", ")", ")", ";", "}", "}", ";", "}" ]
Make engine as a consumer to accept cell'data change @return @since 3.0.0
[ "Make", "engine", "as", "a", "consumer", "to", "accept", "cell", "data", "change" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/TangramEngine.java#L1030-L1037
17,554
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/MVHelper.java
MVHelper.reset
public void reset() { methodMap.clear(); postBindMap.clear(); postUnBindMap.clear(); cellInitedMap.clear(); cellFlareIdMap.clear(); mvResolver.reset(); }
java
public void reset() { methodMap.clear(); postBindMap.clear(); postUnBindMap.clear(); cellInitedMap.clear(); cellFlareIdMap.clear(); mvResolver.reset(); }
[ "public", "void", "reset", "(", ")", "{", "methodMap", ".", "clear", "(", ")", ";", "postBindMap", ".", "clear", "(", ")", ";", "postUnBindMap", ".", "clear", "(", ")", ";", "cellInitedMap", ".", "clear", "(", ")", ";", "cellFlareIdMap", ".", "clear", "(", ")", ";", "mvResolver", ".", "reset", "(", ")", ";", "}" ]
FIXME sholud be called after original component's postUnBind method excuted
[ "FIXME", "sholud", "be", "called", "after", "original", "component", "s", "postUnBind", "method", "excuted" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/MVHelper.java#L96-L103
17,555
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/view/LinearScrollView.java
LinearScrollView.computeFirstCompletelyVisibleItemPositionForScrolledX
private int computeFirstCompletelyVisibleItemPositionForScrolledX(float[] starts) { if (lSCell == null || starts == null || starts.length <= 0) { return 0; } for (int i = 0; i < starts.length; i++) { if (starts[i] >= lSCell.currentDistance) { return i; } } return starts.length - 1; }
java
private int computeFirstCompletelyVisibleItemPositionForScrolledX(float[] starts) { if (lSCell == null || starts == null || starts.length <= 0) { return 0; } for (int i = 0; i < starts.length; i++) { if (starts[i] >= lSCell.currentDistance) { return i; } } return starts.length - 1; }
[ "private", "int", "computeFirstCompletelyVisibleItemPositionForScrolledX", "(", "float", "[", "]", "starts", ")", "{", "if", "(", "lSCell", "==", "null", "||", "starts", "==", "null", "||", "starts", ".", "length", "<=", "0", ")", "{", "return", "0", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "starts", ".", "length", ";", "i", "++", ")", "{", "if", "(", "starts", "[", "i", "]", ">=", "lSCell", ".", "currentDistance", ")", "{", "return", "i", ";", "}", "}", "return", "starts", ".", "length", "-", "1", ";", "}" ]
Find the first completely visible position. @param starts A recorder array to save each item's left position, including its margin. @return Position of first completely visible item.
[ "Find", "the", "first", "completely", "visible", "position", "." ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/view/LinearScrollView.java#L300-L310
17,556
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/dataparser/concrete/PojoGroupBasicAdapter.java
PojoGroupBasicAdapter.removeComponent
@Override public void removeComponent(int position) { if (mData != null && position >= 0 && position < mData.size()) { removeComponent(mData.get(position)); } }
java
@Override public void removeComponent(int position) { if (mData != null && position >= 0 && position < mData.size()) { removeComponent(mData.get(position)); } }
[ "@", "Override", "public", "void", "removeComponent", "(", "int", "position", ")", "{", "if", "(", "mData", "!=", "null", "&&", "position", ">=", "0", "&&", "position", "<", "mData", ".", "size", "(", ")", ")", "{", "removeComponent", "(", "mData", ".", "get", "(", "position", ")", ")", ";", "}", "}" ]
!!! Do not call this method directly. It's not designed for users. remove a component @param position the position to be removes
[ "!!!", "Do", "not", "call", "this", "method", "directly", ".", "It", "s", "not", "designed", "for", "users", ".", "remove", "a", "component" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/dataparser/concrete/PojoGroupBasicAdapter.java#L384-L389
17,557
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/dataparser/concrete/PojoGroupBasicAdapter.java
PojoGroupBasicAdapter.removeComponent
@Override public void removeComponent(BaseCell component) { int removePosition = getPositionByItem(component); if (mData != null && component != null && removePosition >= 0) { if (mCards != null) { List<Pair<Range<Integer>, Card>> newCards = new ArrayList<>(); for (int i = 0, size = mCards.size(); i < size; i++) { Pair<Range<Integer>, Card> pair = mCards.get(i); int start = pair.first.getLower(); int end = pair.first.getUpper(); if (end < removePosition) { //do nothing newCards.add(pair); } else if (start <= removePosition && removePosition < end) { int itemCount = end - start - 1; if (itemCount > 0) { Pair<Range<Integer>, Card> newPair = new Pair<>(Range.create(start, end - 1), pair.second); newCards.add(newPair); } } else if (removePosition <= start) { Pair<Range<Integer>, Card> newPair = new Pair<>(Range.create(start - 1, end - 1), pair.second); newCards.add(newPair); } } component.removed(); mCards.clear(); mCards.addAll(newCards); mData.remove(component); notifyItemRemoved(removePosition); int last = mLayoutManager.findLastVisibleItemPosition(); notifyItemRangeChanged(removePosition, last - removePosition); } } }
java
@Override public void removeComponent(BaseCell component) { int removePosition = getPositionByItem(component); if (mData != null && component != null && removePosition >= 0) { if (mCards != null) { List<Pair<Range<Integer>, Card>> newCards = new ArrayList<>(); for (int i = 0, size = mCards.size(); i < size; i++) { Pair<Range<Integer>, Card> pair = mCards.get(i); int start = pair.first.getLower(); int end = pair.first.getUpper(); if (end < removePosition) { //do nothing newCards.add(pair); } else if (start <= removePosition && removePosition < end) { int itemCount = end - start - 1; if (itemCount > 0) { Pair<Range<Integer>, Card> newPair = new Pair<>(Range.create(start, end - 1), pair.second); newCards.add(newPair); } } else if (removePosition <= start) { Pair<Range<Integer>, Card> newPair = new Pair<>(Range.create(start - 1, end - 1), pair.second); newCards.add(newPair); } } component.removed(); mCards.clear(); mCards.addAll(newCards); mData.remove(component); notifyItemRemoved(removePosition); int last = mLayoutManager.findLastVisibleItemPosition(); notifyItemRangeChanged(removePosition, last - removePosition); } } }
[ "@", "Override", "public", "void", "removeComponent", "(", "BaseCell", "component", ")", "{", "int", "removePosition", "=", "getPositionByItem", "(", "component", ")", ";", "if", "(", "mData", "!=", "null", "&&", "component", "!=", "null", "&&", "removePosition", ">=", "0", ")", "{", "if", "(", "mCards", "!=", "null", ")", "{", "List", "<", "Pair", "<", "Range", "<", "Integer", ">", ",", "Card", ">", ">", "newCards", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "int", "i", "=", "0", ",", "size", "=", "mCards", ".", "size", "(", ")", ";", "i", "<", "size", ";", "i", "++", ")", "{", "Pair", "<", "Range", "<", "Integer", ">", ",", "Card", ">", "pair", "=", "mCards", ".", "get", "(", "i", ")", ";", "int", "start", "=", "pair", ".", "first", ".", "getLower", "(", ")", ";", "int", "end", "=", "pair", ".", "first", ".", "getUpper", "(", ")", ";", "if", "(", "end", "<", "removePosition", ")", "{", "//do nothing", "newCards", ".", "add", "(", "pair", ")", ";", "}", "else", "if", "(", "start", "<=", "removePosition", "&&", "removePosition", "<", "end", ")", "{", "int", "itemCount", "=", "end", "-", "start", "-", "1", ";", "if", "(", "itemCount", ">", "0", ")", "{", "Pair", "<", "Range", "<", "Integer", ">", ",", "Card", ">", "newPair", "=", "new", "Pair", "<>", "(", "Range", ".", "create", "(", "start", ",", "end", "-", "1", ")", ",", "pair", ".", "second", ")", ";", "newCards", ".", "add", "(", "newPair", ")", ";", "}", "}", "else", "if", "(", "removePosition", "<=", "start", ")", "{", "Pair", "<", "Range", "<", "Integer", ">", ",", "Card", ">", "newPair", "=", "new", "Pair", "<>", "(", "Range", ".", "create", "(", "start", "-", "1", ",", "end", "-", "1", ")", ",", "pair", ".", "second", ")", ";", "newCards", ".", "add", "(", "newPair", ")", ";", "}", "}", "component", ".", "removed", "(", ")", ";", "mCards", ".", "clear", "(", ")", ";", "mCards", ".", "addAll", "(", "newCards", ")", ";", "mData", ".", "remove", "(", "component", ")", ";", "notifyItemRemoved", "(", "removePosition", ")", ";", "int", "last", "=", "mLayoutManager", ".", "findLastVisibleItemPosition", "(", ")", ";", "notifyItemRangeChanged", "(", "removePosition", ",", "last", "-", "removePosition", ")", ";", "}", "}", "}" ]
!!! Do not call this method directly. It's not designed for users. @param component the component to be removed
[ "!!!", "Do", "not", "call", "this", "method", "directly", ".", "It", "s", "not", "designed", "for", "users", "." ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/dataparser/concrete/PojoGroupBasicAdapter.java#L395-L429
17,558
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/DefaultResolverRegistry.java
DefaultResolverRegistry.registerCell
public <V extends View> void registerCell(String type, final @NonNull Class<V> viewClz) { if (viewHolderMap.get(type) == null) { mDefaultCellBinderResolver.register(type, new BaseCellBinder<>(viewClz, mMVHelper)); } else { mDefaultCellBinderResolver.register(type, new BaseCellBinder<ViewHolderCreator.ViewHolder, V>(viewHolderMap.get(type), mMVHelper)); } mMVHelper.resolver().register(type, viewClz); }
java
public <V extends View> void registerCell(String type, final @NonNull Class<V> viewClz) { if (viewHolderMap.get(type) == null) { mDefaultCellBinderResolver.register(type, new BaseCellBinder<>(viewClz, mMVHelper)); } else { mDefaultCellBinderResolver.register(type, new BaseCellBinder<ViewHolderCreator.ViewHolder, V>(viewHolderMap.get(type), mMVHelper)); } mMVHelper.resolver().register(type, viewClz); }
[ "public", "<", "V", "extends", "View", ">", "void", "registerCell", "(", "String", "type", ",", "final", "@", "NonNull", "Class", "<", "V", ">", "viewClz", ")", "{", "if", "(", "viewHolderMap", ".", "get", "(", "type", ")", "==", "null", ")", "{", "mDefaultCellBinderResolver", ".", "register", "(", "type", ",", "new", "BaseCellBinder", "<>", "(", "viewClz", ",", "mMVHelper", ")", ")", ";", "}", "else", "{", "mDefaultCellBinderResolver", ".", "register", "(", "type", ",", "new", "BaseCellBinder", "<", "ViewHolderCreator", ".", "ViewHolder", ",", "V", ">", "(", "viewHolderMap", ".", "get", "(", "type", ")", ",", "mMVHelper", ")", ")", ";", "}", "mMVHelper", ".", "resolver", "(", ")", ".", "register", "(", "type", ",", "viewClz", ")", ";", "}" ]
register cell with custom view class, the model of cell is provided with default type @param type @param viewClz @param <V>
[ "register", "cell", "with", "custom", "view", "class", "the", "model", "of", "cell", "is", "provided", "with", "default", "type" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/DefaultResolverRegistry.java#L67-L75
17,559
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/DefaultResolverRegistry.java
DefaultResolverRegistry.registerCard
public void registerCard(String type, Class<? extends Card> cardClz) { mDefaultCardResolver.register(type, cardClz); }
java
public void registerCard(String type, Class<? extends Card> cardClz) { mDefaultCardResolver.register(type, cardClz); }
[ "public", "void", "registerCard", "(", "String", "type", ",", "Class", "<", "?", "extends", "Card", ">", "cardClz", ")", "{", "mDefaultCardResolver", ".", "register", "(", "type", ",", "cardClz", ")", ";", "}" ]
register card with type and card class @param type @param cardClz
[ "register", "card", "with", "type", "and", "card", "class" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/DefaultResolverRegistry.java#L82-L84
17,560
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/support/SimpleClickSupport.java
SimpleClickSupport.onClick
public void onClick(View targetView, BaseCell cell, int eventType) { if (cell instanceof Cell) { onClick(targetView, (Cell) cell, eventType); } else { onClick(targetView, cell, eventType, null); } }
java
public void onClick(View targetView, BaseCell cell, int eventType) { if (cell instanceof Cell) { onClick(targetView, (Cell) cell, eventType); } else { onClick(targetView, cell, eventType, null); } }
[ "public", "void", "onClick", "(", "View", "targetView", ",", "BaseCell", "cell", ",", "int", "eventType", ")", "{", "if", "(", "cell", "instanceof", "Cell", ")", "{", "onClick", "(", "targetView", ",", "(", "Cell", ")", "cell", ",", "eventType", ")", ";", "}", "else", "{", "onClick", "(", "targetView", ",", "cell", ",", "eventType", ",", "null", ")", ";", "}", "}" ]
Handler click event on item @param targetView the view that trigger the click event, not the view respond the cell! @param cell the corresponding cell @param eventType click event type, defined by developer.
[ "Handler", "click", "event", "on", "item" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/support/SimpleClickSupport.java#L124-L130
17,561
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/core/adapter/BinderViewHolder.java
BinderViewHolder.bind
public void bind(C data) { if (itemView == null || controller == null) { return; } this.controller.mountView(data, itemView); this.data = data; }
java
public void bind(C data) { if (itemView == null || controller == null) { return; } this.controller.mountView(data, itemView); this.data = data; }
[ "public", "void", "bind", "(", "C", "data", ")", "{", "if", "(", "itemView", "==", "null", "||", "controller", "==", "null", ")", "{", "return", ";", "}", "this", ".", "controller", ".", "mountView", "(", "data", ",", "itemView", ")", ";", "this", ".", "data", "=", "data", ";", "}" ]
Bind data to inner view @param data
[ "Bind", "data", "to", "inner", "view" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/core/adapter/BinderViewHolder.java#L57-L63
17,562
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/core/adapter/BinderViewHolder.java
BinderViewHolder.unbind
public void unbind() { if (itemView == null || controller == null) { return; } if (data != null) { this.controller.unmountView(data, itemView); } }
java
public void unbind() { if (itemView == null || controller == null) { return; } if (data != null) { this.controller.unmountView(data, itemView); } }
[ "public", "void", "unbind", "(", ")", "{", "if", "(", "itemView", "==", "null", "||", "controller", "==", "null", ")", "{", "return", ";", "}", "if", "(", "data", "!=", "null", ")", "{", "this", ".", "controller", ".", "unmountView", "(", "data", ",", "itemView", ")", ";", "}", "}" ]
unbind the data, make the view re-usable
[ "unbind", "the", "data", "make", "the", "view", "re", "-", "usable" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/core/adapter/BinderViewHolder.java#L68-L75
17,563
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/structure/BaseCell.java
BaseCell.setTag
public void setTag(int key, Object value) { if (mTag == null) { mTag = new SparseArray<>(); } mTag.put(key, value); }
java
public void setTag(int key, Object value) { if (mTag == null) { mTag = new SparseArray<>(); } mTag.put(key, value); }
[ "public", "void", "setTag", "(", "int", "key", ",", "Object", "value", ")", "{", "if", "(", "mTag", "==", "null", ")", "{", "mTag", "=", "new", "SparseArray", "<>", "(", ")", ";", "}", "mTag", ".", "put", "(", "key", ",", "value", ")", ";", "}" ]
bind a tag to baseCell @param key @param value
[ "bind", "a", "tag", "to", "baseCell" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/structure/BaseCell.java#L350-L355
17,564
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/TangramBuilder.java
TangramBuilder.init
public static void init(@NonNull final Context context, IInnerImageSetter innerImageSetter, Class<? extends ImageView> imageClazz) { if (sInitialized) { return; } //noinspection ConstantConditions Preconditions.checkArgument(context != null, "context should not be null"); Preconditions .checkArgument(innerImageSetter != null, "innerImageSetter should not be null"); Preconditions.checkArgument(imageClazz != null, "imageClazz should not be null"); TangramViewMetrics.initWith(context.getApplicationContext()); ImageUtils.sImageClass = imageClazz; ImageUtils.setImageSetter(innerImageSetter); sInitialized = true; }
java
public static void init(@NonNull final Context context, IInnerImageSetter innerImageSetter, Class<? extends ImageView> imageClazz) { if (sInitialized) { return; } //noinspection ConstantConditions Preconditions.checkArgument(context != null, "context should not be null"); Preconditions .checkArgument(innerImageSetter != null, "innerImageSetter should not be null"); Preconditions.checkArgument(imageClazz != null, "imageClazz should not be null"); TangramViewMetrics.initWith(context.getApplicationContext()); ImageUtils.sImageClass = imageClazz; ImageUtils.setImageSetter(innerImageSetter); sInitialized = true; }
[ "public", "static", "void", "init", "(", "@", "NonNull", "final", "Context", "context", ",", "IInnerImageSetter", "innerImageSetter", ",", "Class", "<", "?", "extends", "ImageView", ">", "imageClazz", ")", "{", "if", "(", "sInitialized", ")", "{", "return", ";", "}", "//noinspection ConstantConditions", "Preconditions", ".", "checkArgument", "(", "context", "!=", "null", ",", "\"context should not be null\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "innerImageSetter", "!=", "null", ",", "\"innerImageSetter should not be null\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "imageClazz", "!=", "null", ",", "\"imageClazz should not be null\"", ")", ";", "TangramViewMetrics", ".", "initWith", "(", "context", ".", "getApplicationContext", "(", ")", ")", ";", "ImageUtils", ".", "sImageClass", "=", "imageClazz", ";", "ImageUtils", ".", "setImageSetter", "(", "innerImageSetter", ")", ";", "sInitialized", "=", "true", ";", "}" ]
init global Tangram environment. @param context the app context @param innerImageSetter an ImagerSetter to load image, see {@link ImageUtils} @param imageClazz a custom ImageView class, used to construct an imageView instance.
[ "init", "global", "Tangram", "environment", "." ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/TangramBuilder.java#L266-L280
17,565
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/util/ImageUtils.java
ImageUtils.createImageInstance
public static ImageView createImageInstance(Context context) { if (sImageClass != null) { if (imageViewConstructor == null) { try { imageViewConstructor = sImageClass.getConstructor(Context.class); } catch (NoSuchMethodException e) { e.printStackTrace(); } } if (imageViewConstructor != null) { try { return (ImageView) imageViewConstructor.newInstance(context); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } return null; }
java
public static ImageView createImageInstance(Context context) { if (sImageClass != null) { if (imageViewConstructor == null) { try { imageViewConstructor = sImageClass.getConstructor(Context.class); } catch (NoSuchMethodException e) { e.printStackTrace(); } } if (imageViewConstructor != null) { try { return (ImageView) imageViewConstructor.newInstance(context); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } return null; }
[ "public", "static", "ImageView", "createImageInstance", "(", "Context", "context", ")", "{", "if", "(", "sImageClass", "!=", "null", ")", "{", "if", "(", "imageViewConstructor", "==", "null", ")", "{", "try", "{", "imageViewConstructor", "=", "sImageClass", ".", "getConstructor", "(", "Context", ".", "class", ")", ";", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "if", "(", "imageViewConstructor", "!=", "null", ")", "{", "try", "{", "return", "(", "ImageView", ")", "imageViewConstructor", ".", "newInstance", "(", "context", ")", ";", "}", "catch", "(", "InstantiationException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}", "return", "null", ";", "}" ]
create a custom ImageView instance @param context activity context @return an instance
[ "create", "a", "custom", "ImageView", "instance" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/util/ImageUtils.java#L57-L79
17,566
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/view/LinearScrollView.java
LinearScrollView.setIndicatorMeasure
private void setIndicatorMeasure(View indicator, int width, int height, int margin) { if (indicator != null) { ViewGroup.LayoutParams layoutParams = indicator.getLayoutParams(); layoutParams.width = width; layoutParams.height = height; if (margin > 0) { if (layoutParams instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams frameLayoutParams = (FrameLayout.LayoutParams) layoutParams; frameLayoutParams.topMargin = margin; } else if (layoutParams instanceof LayoutParams) { LayoutParams linearLayoutParams = (LayoutParams) layoutParams; linearLayoutParams.topMargin = margin; } } indicator.setLayoutParams(layoutParams); } }
java
private void setIndicatorMeasure(View indicator, int width, int height, int margin) { if (indicator != null) { ViewGroup.LayoutParams layoutParams = indicator.getLayoutParams(); layoutParams.width = width; layoutParams.height = height; if (margin > 0) { if (layoutParams instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams frameLayoutParams = (FrameLayout.LayoutParams) layoutParams; frameLayoutParams.topMargin = margin; } else if (layoutParams instanceof LayoutParams) { LayoutParams linearLayoutParams = (LayoutParams) layoutParams; linearLayoutParams.topMargin = margin; } } indicator.setLayoutParams(layoutParams); } }
[ "private", "void", "setIndicatorMeasure", "(", "View", "indicator", ",", "int", "width", ",", "int", "height", ",", "int", "margin", ")", "{", "if", "(", "indicator", "!=", "null", ")", "{", "ViewGroup", ".", "LayoutParams", "layoutParams", "=", "indicator", ".", "getLayoutParams", "(", ")", ";", "layoutParams", ".", "width", "=", "width", ";", "layoutParams", ".", "height", "=", "height", ";", "if", "(", "margin", ">", "0", ")", "{", "if", "(", "layoutParams", "instanceof", "FrameLayout", ".", "LayoutParams", ")", "{", "FrameLayout", ".", "LayoutParams", "frameLayoutParams", "=", "(", "FrameLayout", ".", "LayoutParams", ")", "layoutParams", ";", "frameLayoutParams", ".", "topMargin", "=", "margin", ";", "}", "else", "if", "(", "layoutParams", "instanceof", "LayoutParams", ")", "{", "LayoutParams", "linearLayoutParams", "=", "(", "LayoutParams", ")", "layoutParams", ";", "linearLayoutParams", ".", "topMargin", "=", "margin", ";", "}", "}", "indicator", ".", "setLayoutParams", "(", "layoutParams", ")", ";", "}", "}" ]
Set indicator measure @param indicator indicator view @param width indicator width @param height indicator height @param margin indicator top margin
[ "Set", "indicator", "measure" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/view/LinearScrollView.java#L283-L300
17,567
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/eventbus/Event.java
Event.appendArg
public void appendArg(String key, String value) { if (args != null) { args.put(key, value); } }
java
public void appendArg(String key, String value) { if (args != null) { args.put(key, value); } }
[ "public", "void", "appendArg", "(", "String", "key", ",", "String", "value", ")", "{", "if", "(", "args", "!=", "null", ")", "{", "args", ".", "put", "(", "key", ",", "value", ")", ";", "}", "}" ]
Append arg to map @param key @param value
[ "Append", "arg", "to", "map" ]
caa57f54e009c8dacd34a2322d5761956ebed321
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/eventbus/Event.java#L66-L70
17,568
gocd/gocd
config/config-api/src/main/java/com/thoughtworks/go/domain/config/Configuration.java
Configuration.getPropertyMetadataAndValuesAsMap
public Map<String, Map<String, Object>> getPropertyMetadataAndValuesAsMap() { Map<String, Map<String, Object>> configMap = new HashMap<>(); for (ConfigurationProperty property : this) { Map<String, Object> mapValue = new HashMap<>(); mapValue.put("isSecure", property.isSecure()); if (property.isSecure()) { mapValue.put(VALUE_KEY, property.getEncryptedValue()); } else { final String value = property.getConfigurationValue() == null ? null : property.getConfigurationValue().getValue(); mapValue.put(VALUE_KEY, value); } mapValue.put("displayValue", property.getDisplayValue()); configMap.put(property.getConfigKeyName(), mapValue); } return configMap; }
java
public Map<String, Map<String, Object>> getPropertyMetadataAndValuesAsMap() { Map<String, Map<String, Object>> configMap = new HashMap<>(); for (ConfigurationProperty property : this) { Map<String, Object> mapValue = new HashMap<>(); mapValue.put("isSecure", property.isSecure()); if (property.isSecure()) { mapValue.put(VALUE_KEY, property.getEncryptedValue()); } else { final String value = property.getConfigurationValue() == null ? null : property.getConfigurationValue().getValue(); mapValue.put(VALUE_KEY, value); } mapValue.put("displayValue", property.getDisplayValue()); configMap.put(property.getConfigKeyName(), mapValue); } return configMap; }
[ "public", "Map", "<", "String", ",", "Map", "<", "String", ",", "Object", ">", ">", "getPropertyMetadataAndValuesAsMap", "(", ")", "{", "Map", "<", "String", ",", "Map", "<", "String", ",", "Object", ">", ">", "configMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "ConfigurationProperty", "property", ":", "this", ")", "{", "Map", "<", "String", ",", "Object", ">", "mapValue", "=", "new", "HashMap", "<>", "(", ")", ";", "mapValue", ".", "put", "(", "\"isSecure\"", ",", "property", ".", "isSecure", "(", ")", ")", ";", "if", "(", "property", ".", "isSecure", "(", ")", ")", "{", "mapValue", ".", "put", "(", "VALUE_KEY", ",", "property", ".", "getEncryptedValue", "(", ")", ")", ";", "}", "else", "{", "final", "String", "value", "=", "property", ".", "getConfigurationValue", "(", ")", "==", "null", "?", "null", ":", "property", ".", "getConfigurationValue", "(", ")", ".", "getValue", "(", ")", ";", "mapValue", ".", "put", "(", "VALUE_KEY", ",", "value", ")", ";", "}", "mapValue", ".", "put", "(", "\"displayValue\"", ",", "property", ".", "getDisplayValue", "(", ")", ")", ";", "configMap", ".", "put", "(", "property", ".", "getConfigKeyName", "(", ")", ",", "mapValue", ")", ";", "}", "return", "configMap", ";", "}" ]
Used in erb
[ "Used", "in", "erb" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/config/config-api/src/main/java/com/thoughtworks/go/domain/config/Configuration.java#L175-L190
17,569
gocd/gocd
common/src/main/java/com/thoughtworks/go/buildsession/BuildSession.java
BuildSession.cancel
public boolean cancel(int timeout, TimeUnit timeoutUnit) throws InterruptedException { if (isCanceled()) { return true; } cancelLatch.countDown(); try { return doneLatch.await(timeout, timeoutUnit); } finally { new DefaultCurrentProcess().infanticide(); } }
java
public boolean cancel(int timeout, TimeUnit timeoutUnit) throws InterruptedException { if (isCanceled()) { return true; } cancelLatch.countDown(); try { return doneLatch.await(timeout, timeoutUnit); } finally { new DefaultCurrentProcess().infanticide(); } }
[ "public", "boolean", "cancel", "(", "int", "timeout", ",", "TimeUnit", "timeoutUnit", ")", "throws", "InterruptedException", "{", "if", "(", "isCanceled", "(", ")", ")", "{", "return", "true", ";", "}", "cancelLatch", ".", "countDown", "(", ")", ";", "try", "{", "return", "doneLatch", ".", "await", "(", "timeout", ",", "timeoutUnit", ")", ";", "}", "finally", "{", "new", "DefaultCurrentProcess", "(", ")", ".", "infanticide", "(", ")", ";", "}", "}" ]
Cancel build and wait for build session done @return {@code true} if the build session is done and {@code false} if time out happens
[ "Cancel", "build", "and", "wait", "for", "build", "session", "done" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/common/src/main/java/com/thoughtworks/go/buildsession/BuildSession.java#L118-L130
17,570
gocd/gocd
common/src/main/java/com/thoughtworks/go/domain/NotificationFilter.java
NotificationFilter.toMap
public Map<String, Object> toMap() { HashMap<String, Object> map = new HashMap<>(); map.put("id", id); map.put("pipelineName", pipelineName); map.put("stageName", stageName); map.put("myCheckin", myCheckin); map.put("event", event.toString()); return map; }
java
public Map<String, Object> toMap() { HashMap<String, Object> map = new HashMap<>(); map.put("id", id); map.put("pipelineName", pipelineName); map.put("stageName", stageName); map.put("myCheckin", myCheckin); map.put("event", event.toString()); return map; }
[ "public", "Map", "<", "String", ",", "Object", ">", "toMap", "(", ")", "{", "HashMap", "<", "String", ",", "Object", ">", "map", "=", "new", "HashMap", "<>", "(", ")", ";", "map", ".", "put", "(", "\"id\"", ",", "id", ")", ";", "map", ".", "put", "(", "\"pipelineName\"", ",", "pipelineName", ")", ";", "map", ".", "put", "(", "\"stageName\"", ",", "stageName", ")", ";", "map", ".", "put", "(", "\"myCheckin\"", ",", "myCheckin", ")", ";", "map", ".", "put", "(", "\"event\"", ",", "event", ".", "toString", "(", ")", ")", ";", "return", "map", ";", "}" ]
Used for JSON serialization in Rails @return a Map representation of this {@link NotificationFilter} instance that is serializable by JRuby
[ "Used", "for", "JSON", "serialization", "in", "Rails" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/common/src/main/java/com/thoughtworks/go/domain/NotificationFilter.java#L108-L118
17,571
gocd/gocd
util/src/main/java/com/thoughtworks/go/utils/CommandUtils.java
CommandUtils.quoteArgument
public static String quoteArgument(String argument) { if (QUOTED_STRING.matcher(argument).matches() || !UNESCAPED_SPACE_OR_QUOTES.matcher(argument).find()) { // assume the argument is well-formed if it's already quoted or if there are no unescaped spaces or quotes return argument; } return String.format("\"%s\"", DOUBLE_QUOTE.matcher(argument).replaceAll(Matcher.quoteReplacement("\\") + "$1")); }
java
public static String quoteArgument(String argument) { if (QUOTED_STRING.matcher(argument).matches() || !UNESCAPED_SPACE_OR_QUOTES.matcher(argument).find()) { // assume the argument is well-formed if it's already quoted or if there are no unescaped spaces or quotes return argument; } return String.format("\"%s\"", DOUBLE_QUOTE.matcher(argument).replaceAll(Matcher.quoteReplacement("\\") + "$1")); }
[ "public", "static", "String", "quoteArgument", "(", "String", "argument", ")", "{", "if", "(", "QUOTED_STRING", ".", "matcher", "(", "argument", ")", ".", "matches", "(", ")", "||", "!", "UNESCAPED_SPACE_OR_QUOTES", ".", "matcher", "(", "argument", ")", ".", "find", "(", ")", ")", "{", "// assume the argument is well-formed if it's already quoted or if there are no unescaped spaces or quotes", "return", "argument", ";", "}", "return", "String", ".", "format", "(", "\"\\\"%s\\\"\"", ",", "DOUBLE_QUOTE", ".", "matcher", "(", "argument", ")", ".", "replaceAll", "(", "Matcher", ".", "quoteReplacement", "(", "\"\\\\\"", ")", "+", "\"$1\"", ")", ")", ";", "}" ]
Surrounds a string with double quotes if it is not already surrounded by single or double quotes, or if it contains unescaped spaces, single quotes, or double quotes. When surrounding with double quotes, this method will only escape double quotes in the String. This method assumes the argument is well-formed if it was already surrounded by either single or double quotes. @param argument String to quote @return the quoted String, if not already quoted
[ "Surrounds", "a", "string", "with", "double", "quotes", "if", "it", "is", "not", "already", "surrounded", "by", "single", "or", "double", "quotes", "or", "if", "it", "contains", "unescaped", "spaces", "single", "quotes", "or", "double", "quotes", ".", "When", "surrounding", "with", "double", "quotes", "this", "method", "will", "only", "escape", "double", "quotes", "in", "the", "String", "." ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/util/src/main/java/com/thoughtworks/go/utils/CommandUtils.java#L81-L88
17,572
gocd/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/config/Options.java
Options.set
public <T> void set(Option<T> option, T value) { findOption(option).setValue(value); }
java
public <T> void set(Option<T> option, T value) { findOption(option).setValue(value); }
[ "public", "<", "T", ">", "void", "set", "(", "Option", "<", "T", ">", "option", ",", "T", "value", ")", "{", "findOption", "(", "option", ")", ".", "setValue", "(", "value", ")", ";", "}" ]
Finds matching option by option name and sets specified value @param option the option used for matching @param value the value to be set to matched option @param <T> the type of the option
[ "Finds", "matching", "option", "by", "option", "name", "and", "sets", "specified", "value" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/config/Options.java#L47-L49
17,573
gocd/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/config/Options.java
Options.findOption
public <T> Option<T> findOption(Option<T> option) { for (Option candidateOption : options) { if (candidateOption.hasSameNameAs(option)) { return candidateOption; } } throw new RuntimeException("You tried to set an unexpected option"); }
java
public <T> Option<T> findOption(Option<T> option) { for (Option candidateOption : options) { if (candidateOption.hasSameNameAs(option)) { return candidateOption; } } throw new RuntimeException("You tried to set an unexpected option"); }
[ "public", "<", "T", ">", "Option", "<", "T", ">", "findOption", "(", "Option", "<", "T", ">", "option", ")", "{", "for", "(", "Option", "candidateOption", ":", "options", ")", "{", "if", "(", "candidateOption", ".", "hasSameNameAs", "(", "option", ")", ")", "{", "return", "candidateOption", ";", "}", "}", "throw", "new", "RuntimeException", "(", "\"You tried to set an unexpected option\"", ")", ";", "}" ]
Finds matching option by option name @param option the option used for matching @param <T> the type of the option @return matched option @throws RuntimeException when matching option not found
[ "Finds", "matching", "option", "by", "option", "name" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/config/Options.java#L58-L65
17,574
gocd/gocd
server/src/main/java/com/thoughtworks/go/server/service/PipelineService.java
PipelineService.getRevisionsBasedOnDependenciesForDebug
public String getRevisionsBasedOnDependenciesForDebug(CaseInsensitiveString pipelineName, final Integer targetIterationCount) { CruiseConfig cruiseConfig = goConfigService.getCurrentConfig(); FanInGraph fanInGraph = new FanInGraph(cruiseConfig, pipelineName, materialRepository, pipelineDao, systemEnvironment, materialConfigConverter); final String[] iterationData = {null}; fanInGraph.setFanInEventListener((iterationCount, dependencyFanInNodes) -> { if (iterationCount == targetIterationCount) { iterationData[0] = new GsonBuilder().setExclusionStrategies(getGsonExclusionStrategy()).create().toJson(dependencyFanInNodes); } }); PipelineConfig pipelineConfig = goConfigService.pipelineConfigNamed(pipelineName); Materials materials = materialConfigConverter.toMaterials(pipelineConfig.materialConfigs()); MaterialRevisions actualRevisions = new MaterialRevisions(); for (Material material : materials) { actualRevisions.addAll(materialRepository.findLatestModification(material)); } MaterialRevisions materialRevisions = fanInGraph.computeRevisions(actualRevisions, pipelineTimeline); if (iterationData[0] == null) { iterationData[0] = new GsonBuilder().setExclusionStrategies(getGsonExclusionStrategy()).create().toJson(materialRevisions); } return iterationData[0]; }
java
public String getRevisionsBasedOnDependenciesForDebug(CaseInsensitiveString pipelineName, final Integer targetIterationCount) { CruiseConfig cruiseConfig = goConfigService.getCurrentConfig(); FanInGraph fanInGraph = new FanInGraph(cruiseConfig, pipelineName, materialRepository, pipelineDao, systemEnvironment, materialConfigConverter); final String[] iterationData = {null}; fanInGraph.setFanInEventListener((iterationCount, dependencyFanInNodes) -> { if (iterationCount == targetIterationCount) { iterationData[0] = new GsonBuilder().setExclusionStrategies(getGsonExclusionStrategy()).create().toJson(dependencyFanInNodes); } }); PipelineConfig pipelineConfig = goConfigService.pipelineConfigNamed(pipelineName); Materials materials = materialConfigConverter.toMaterials(pipelineConfig.materialConfigs()); MaterialRevisions actualRevisions = new MaterialRevisions(); for (Material material : materials) { actualRevisions.addAll(materialRepository.findLatestModification(material)); } MaterialRevisions materialRevisions = fanInGraph.computeRevisions(actualRevisions, pipelineTimeline); if (iterationData[0] == null) { iterationData[0] = new GsonBuilder().setExclusionStrategies(getGsonExclusionStrategy()).create().toJson(materialRevisions); } return iterationData[0]; }
[ "public", "String", "getRevisionsBasedOnDependenciesForDebug", "(", "CaseInsensitiveString", "pipelineName", ",", "final", "Integer", "targetIterationCount", ")", "{", "CruiseConfig", "cruiseConfig", "=", "goConfigService", ".", "getCurrentConfig", "(", ")", ";", "FanInGraph", "fanInGraph", "=", "new", "FanInGraph", "(", "cruiseConfig", ",", "pipelineName", ",", "materialRepository", ",", "pipelineDao", ",", "systemEnvironment", ",", "materialConfigConverter", ")", ";", "final", "String", "[", "]", "iterationData", "=", "{", "null", "}", ";", "fanInGraph", ".", "setFanInEventListener", "(", "(", "iterationCount", ",", "dependencyFanInNodes", ")", "->", "{", "if", "(", "iterationCount", "==", "targetIterationCount", ")", "{", "iterationData", "[", "0", "]", "=", "new", "GsonBuilder", "(", ")", ".", "setExclusionStrategies", "(", "getGsonExclusionStrategy", "(", ")", ")", ".", "create", "(", ")", ".", "toJson", "(", "dependencyFanInNodes", ")", ";", "}", "}", ")", ";", "PipelineConfig", "pipelineConfig", "=", "goConfigService", ".", "pipelineConfigNamed", "(", "pipelineName", ")", ";", "Materials", "materials", "=", "materialConfigConverter", ".", "toMaterials", "(", "pipelineConfig", ".", "materialConfigs", "(", ")", ")", ";", "MaterialRevisions", "actualRevisions", "=", "new", "MaterialRevisions", "(", ")", ";", "for", "(", "Material", "material", ":", "materials", ")", "{", "actualRevisions", ".", "addAll", "(", "materialRepository", ".", "findLatestModification", "(", "material", ")", ")", ";", "}", "MaterialRevisions", "materialRevisions", "=", "fanInGraph", ".", "computeRevisions", "(", "actualRevisions", ",", "pipelineTimeline", ")", ";", "if", "(", "iterationData", "[", "0", "]", "==", "null", ")", "{", "iterationData", "[", "0", "]", "=", "new", "GsonBuilder", "(", ")", ".", "setExclusionStrategies", "(", "getGsonExclusionStrategy", "(", ")", ")", ".", "create", "(", ")", ".", "toJson", "(", "materialRevisions", ")", ";", "}", "return", "iterationData", "[", "0", "]", ";", "}" ]
This is for debugging purposes
[ "This", "is", "for", "debugging", "purposes" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/server/src/main/java/com/thoughtworks/go/server/service/PipelineService.java#L227-L247
17,575
gocd/gocd
server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java
MaterialRepository.saveModification
public void saveModification(MaterialInstance materialInstance, Modification modification) { modification.setMaterialInstance(materialInstance); try { getHibernateTemplate().saveOrUpdate(modification); removeLatestCachedModification(materialInstance, modification); removeCachedModificationCountFor(materialInstance); removeCachedModificationsFor(materialInstance); } catch (Exception e) { String message = "Cannot save modification " + modification; LOGGER.error(message, e); throw new RuntimeException(message, e); } }
java
public void saveModification(MaterialInstance materialInstance, Modification modification) { modification.setMaterialInstance(materialInstance); try { getHibernateTemplate().saveOrUpdate(modification); removeLatestCachedModification(materialInstance, modification); removeCachedModificationCountFor(materialInstance); removeCachedModificationsFor(materialInstance); } catch (Exception e) { String message = "Cannot save modification " + modification; LOGGER.error(message, e); throw new RuntimeException(message, e); } }
[ "public", "void", "saveModification", "(", "MaterialInstance", "materialInstance", ",", "Modification", "modification", ")", "{", "modification", ".", "setMaterialInstance", "(", "materialInstance", ")", ";", "try", "{", "getHibernateTemplate", "(", ")", ".", "saveOrUpdate", "(", "modification", ")", ";", "removeLatestCachedModification", "(", "materialInstance", ",", "modification", ")", ";", "removeCachedModificationCountFor", "(", "materialInstance", ")", ";", "removeCachedModificationsFor", "(", "materialInstance", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "String", "message", "=", "\"Cannot save modification \"", "+", "modification", ";", "LOGGER", ".", "error", "(", "message", ",", "e", ")", ";", "throw", "new", "RuntimeException", "(", "message", ",", "e", ")", ";", "}", "}" ]
Used in tests
[ "Used", "in", "tests" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java#L439-L451
17,576
gocd/gocd
server/src/main/java/com/thoughtworks/go/server/domain/user/PipelineSelections.java
PipelineSelections.ensurePipelineVisible
public boolean ensurePipelineVisible(CaseInsensitiveString pipelineToAdd) { boolean modified = false; for (DashboardFilter f : viewFilters.filters()) { modified = modified || f.allowPipeline(pipelineToAdd); } return modified; }
java
public boolean ensurePipelineVisible(CaseInsensitiveString pipelineToAdd) { boolean modified = false; for (DashboardFilter f : viewFilters.filters()) { modified = modified || f.allowPipeline(pipelineToAdd); } return modified; }
[ "public", "boolean", "ensurePipelineVisible", "(", "CaseInsensitiveString", "pipelineToAdd", ")", "{", "boolean", "modified", "=", "false", ";", "for", "(", "DashboardFilter", "f", ":", "viewFilters", ".", "filters", "(", ")", ")", "{", "modified", "=", "modified", "||", "f", ".", "allowPipeline", "(", "pipelineToAdd", ")", ";", "}", "return", "modified", ";", "}" ]
Allows pipeline to be visible to entire filter set; generally used as an after-hook on pipeline creation. @param pipelineToAdd - the name of the pipeline @return true if any filters were modified, false if all filters are unchanged
[ "Allows", "pipeline", "to", "be", "visible", "to", "entire", "filter", "set", ";", "generally", "used", "as", "an", "after", "-", "hook", "on", "pipeline", "creation", "." ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/server/src/main/java/com/thoughtworks/go/server/domain/user/PipelineSelections.java#L144-L152
17,577
gocd/gocd
server/src/main/java/com/thoughtworks/go/server/dao/VersionInfoSqlMapDao.java
VersionInfoSqlMapDao.deleteAll
void deleteAll() { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { sessionFactory.getCurrentSession().createQuery("DELETE FROM VersionInfo").executeUpdate(); } }); }
java
void deleteAll() { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { sessionFactory.getCurrentSession().createQuery("DELETE FROM VersionInfo").executeUpdate(); } }); }
[ "void", "deleteAll", "(", ")", "{", "transactionTemplate", ".", "execute", "(", "new", "TransactionCallbackWithoutResult", "(", ")", "{", "@", "Override", "protected", "void", "doInTransactionWithoutResult", "(", "TransactionStatus", "status", ")", "{", "sessionFactory", ".", "getCurrentSession", "(", ")", ".", "createQuery", "(", "\"DELETE FROM VersionInfo\"", ")", ".", "executeUpdate", "(", ")", ";", "}", "}", ")", ";", "}" ]
used only in tests
[ "used", "only", "in", "tests" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/server/src/main/java/com/thoughtworks/go/server/dao/VersionInfoSqlMapDao.java#L62-L69
17,578
gocd/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/DefaultGoApiResponse.java
DefaultGoApiResponse.incompleteRequest
public static DefaultGoApiResponse incompleteRequest(String responseBody) { DefaultGoApiResponse defaultGoApiResponse = new DefaultGoApiResponse(412); defaultGoApiResponse.setResponseBody(responseBody); return defaultGoApiResponse; }
java
public static DefaultGoApiResponse incompleteRequest(String responseBody) { DefaultGoApiResponse defaultGoApiResponse = new DefaultGoApiResponse(412); defaultGoApiResponse.setResponseBody(responseBody); return defaultGoApiResponse; }
[ "public", "static", "DefaultGoApiResponse", "incompleteRequest", "(", "String", "responseBody", ")", "{", "DefaultGoApiResponse", "defaultGoApiResponse", "=", "new", "DefaultGoApiResponse", "(", "412", ")", ";", "defaultGoApiResponse", ".", "setResponseBody", "(", "responseBody", ")", ";", "return", "defaultGoApiResponse", ";", "}" ]
Creates an instance DefaultGoApiResponse which represents incomplete request with response code 412 @param responseBody Response body @return an instance of DefaultGoApiResponse
[ "Creates", "an", "instance", "DefaultGoApiResponse", "which", "represents", "incomplete", "request", "with", "response", "code", "412" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/DefaultGoApiResponse.java#L54-L58
17,579
gocd/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/DefaultGoApiResponse.java
DefaultGoApiResponse.badRequest
public static DefaultGoApiResponse badRequest(String responseBody) { DefaultGoApiResponse defaultGoApiResponse = new DefaultGoApiResponse(400); defaultGoApiResponse.setResponseBody(responseBody); return defaultGoApiResponse; }
java
public static DefaultGoApiResponse badRequest(String responseBody) { DefaultGoApiResponse defaultGoApiResponse = new DefaultGoApiResponse(400); defaultGoApiResponse.setResponseBody(responseBody); return defaultGoApiResponse; }
[ "public", "static", "DefaultGoApiResponse", "badRequest", "(", "String", "responseBody", ")", "{", "DefaultGoApiResponse", "defaultGoApiResponse", "=", "new", "DefaultGoApiResponse", "(", "400", ")", ";", "defaultGoApiResponse", ".", "setResponseBody", "(", "responseBody", ")", ";", "return", "defaultGoApiResponse", ";", "}" ]
Creates an instance DefaultGoApiResponse which represents bad request with response code 400 @param responseBody Response body @return an instance of DefaultGoApiResponse
[ "Creates", "an", "instance", "DefaultGoApiResponse", "which", "represents", "bad", "request", "with", "response", "code", "400" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/DefaultGoApiResponse.java#L66-L70
17,580
gocd/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/DefaultGoApiResponse.java
DefaultGoApiResponse.error
public static DefaultGoApiResponse error(String responseBody) { DefaultGoApiResponse defaultGoApiResponse = new DefaultGoApiResponse(500); defaultGoApiResponse.setResponseBody(responseBody); return defaultGoApiResponse; }
java
public static DefaultGoApiResponse error(String responseBody) { DefaultGoApiResponse defaultGoApiResponse = new DefaultGoApiResponse(500); defaultGoApiResponse.setResponseBody(responseBody); return defaultGoApiResponse; }
[ "public", "static", "DefaultGoApiResponse", "error", "(", "String", "responseBody", ")", "{", "DefaultGoApiResponse", "defaultGoApiResponse", "=", "new", "DefaultGoApiResponse", "(", "500", ")", ";", "defaultGoApiResponse", ".", "setResponseBody", "(", "responseBody", ")", ";", "return", "defaultGoApiResponse", ";", "}" ]
Creates an instance DefaultGoApiResponse which represents error request with response code 500 @param responseBody Response body @return an instance of DefaultGoApiResponse
[ "Creates", "an", "instance", "DefaultGoApiResponse", "which", "represents", "error", "request", "with", "response", "code", "500" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/DefaultGoApiResponse.java#L78-L82
17,581
gocd/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/DefaultGoApiResponse.java
DefaultGoApiResponse.success
public static DefaultGoApiResponse success(String responseBody) { DefaultGoApiResponse defaultGoApiResponse = new DefaultGoApiResponse(SUCCESS_RESPONSE_CODE); defaultGoApiResponse.setResponseBody(responseBody); return defaultGoApiResponse; }
java
public static DefaultGoApiResponse success(String responseBody) { DefaultGoApiResponse defaultGoApiResponse = new DefaultGoApiResponse(SUCCESS_RESPONSE_CODE); defaultGoApiResponse.setResponseBody(responseBody); return defaultGoApiResponse; }
[ "public", "static", "DefaultGoApiResponse", "success", "(", "String", "responseBody", ")", "{", "DefaultGoApiResponse", "defaultGoApiResponse", "=", "new", "DefaultGoApiResponse", "(", "SUCCESS_RESPONSE_CODE", ")", ";", "defaultGoApiResponse", ".", "setResponseBody", "(", "responseBody", ")", ";", "return", "defaultGoApiResponse", ";", "}" ]
Creates an instance DefaultGoApiResponse which represents success request with response code 200 @param responseBody Json formatted response body @return an instance of DefaultGoApiResponse
[ "Creates", "an", "instance", "DefaultGoApiResponse", "which", "represents", "success", "request", "with", "response", "code", "200" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/DefaultGoApiResponse.java#L90-L94
17,582
gocd/gocd
commandline/src/main/java/com/thoughtworks/go/util/command/CommandLine.java
CommandLine.getCommandLine
String[] getCommandLine() { List<String> args = new ArrayList<>(); if (executable != null) { args.add(executable); } for (int i = 0; i < arguments.size(); i++) { CommandArgument argument = arguments.get(i); args.add(argument.forCommandLine()); } return args.toArray(new String[args.size()]); }
java
String[] getCommandLine() { List<String> args = new ArrayList<>(); if (executable != null) { args.add(executable); } for (int i = 0; i < arguments.size(); i++) { CommandArgument argument = arguments.get(i); args.add(argument.forCommandLine()); } return args.toArray(new String[args.size()]); }
[ "String", "[", "]", "getCommandLine", "(", ")", "{", "List", "<", "String", ">", "args", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "executable", "!=", "null", ")", "{", "args", ".", "add", "(", "executable", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "arguments", ".", "size", "(", ")", ";", "i", "++", ")", "{", "CommandArgument", "argument", "=", "arguments", ".", "get", "(", "i", ")", ";", "args", ".", "add", "(", "argument", ".", "forCommandLine", "(", ")", ")", ";", "}", "return", "args", ".", "toArray", "(", "new", "String", "[", "args", ".", "size", "(", ")", "]", ")", ";", "}" ]
Returns the executable and all defined arguments.
[ "Returns", "the", "executable", "and", "all", "defined", "arguments", "." ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/commandline/src/main/java/com/thoughtworks/go/util/command/CommandLine.java#L101-L111
17,583
gocd/gocd
commandline/src/main/java/com/thoughtworks/go/util/command/CommandLine.java
CommandLine.setWorkingDirectory
public void setWorkingDirectory(String path) { if (path != null) { File dir = new File(path); checkWorkingDir(dir); workingDir = dir; } else { workingDir = null; } }
java
public void setWorkingDirectory(String path) { if (path != null) { File dir = new File(path); checkWorkingDir(dir); workingDir = dir; } else { workingDir = null; } }
[ "public", "void", "setWorkingDirectory", "(", "String", "path", ")", "{", "if", "(", "path", "!=", "null", ")", "{", "File", "dir", "=", "new", "File", "(", "path", ")", ";", "checkWorkingDir", "(", "dir", ")", ";", "workingDir", "=", "dir", ";", "}", "else", "{", "workingDir", "=", "null", ";", "}", "}" ]
Sets execution directory.
[ "Sets", "execution", "directory", "." ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/commandline/src/main/java/com/thoughtworks/go/util/command/CommandLine.java#L232-L240
17,584
gocd/gocd
commandline/src/main/java/com/thoughtworks/go/util/command/CommandLine.java
CommandLine.checkWorkingDir
private void checkWorkingDir(File dir) { if (dir != null) { if (!dir.exists()) { throw new CommandLineException("Working directory \"" + dir.getAbsolutePath() + "\" does not exist!"); } else if (!dir.isDirectory()) { throw new CommandLineException("Path \"" + dir.getAbsolutePath() + "\" does not specify a " + "directory."); } } }
java
private void checkWorkingDir(File dir) { if (dir != null) { if (!dir.exists()) { throw new CommandLineException("Working directory \"" + dir.getAbsolutePath() + "\" does not exist!"); } else if (!dir.isDirectory()) { throw new CommandLineException("Path \"" + dir.getAbsolutePath() + "\" does not specify a " + "directory."); } } }
[ "private", "void", "checkWorkingDir", "(", "File", "dir", ")", "{", "if", "(", "dir", "!=", "null", ")", "{", "if", "(", "!", "dir", ".", "exists", "(", ")", ")", "{", "throw", "new", "CommandLineException", "(", "\"Working directory \\\"\"", "+", "dir", ".", "getAbsolutePath", "(", ")", "+", "\"\\\" does not exist!\"", ")", ";", "}", "else", "if", "(", "!", "dir", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "CommandLineException", "(", "\"Path \\\"\"", "+", "dir", ".", "getAbsolutePath", "(", ")", "+", "\"\\\" does not specify a \"", "+", "\"directory.\"", ")", ";", "}", "}", "}" ]
and not a valid working directory
[ "and", "not", "a", "valid", "working", "directory" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/commandline/src/main/java/com/thoughtworks/go/util/command/CommandLine.java#L252-L261
17,585
gocd/gocd
common/src/main/java/com/thoughtworks/go/security/X509CertificateGenerator.java
X509CertificateGenerator.verifySigned
boolean verifySigned(File keystore, Certificate agentCertificate) { try { KeyStore store = KeyStore.getInstance("JKS"); FileInputStream inputStream = new FileInputStream(keystore); store.load(inputStream, PASSWORD_AS_CHAR_ARRAY); IOUtils.closeQuietly(inputStream); KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store.getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY)); Certificate intermediateCertificate = intermediateEntry.getCertificate(); agentCertificate.verify(intermediateCertificate.getPublicKey()); return true; } catch (Exception e) { return false; } }
java
boolean verifySigned(File keystore, Certificate agentCertificate) { try { KeyStore store = KeyStore.getInstance("JKS"); FileInputStream inputStream = new FileInputStream(keystore); store.load(inputStream, PASSWORD_AS_CHAR_ARRAY); IOUtils.closeQuietly(inputStream); KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store.getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY)); Certificate intermediateCertificate = intermediateEntry.getCertificate(); agentCertificate.verify(intermediateCertificate.getPublicKey()); return true; } catch (Exception e) { return false; } }
[ "boolean", "verifySigned", "(", "File", "keystore", ",", "Certificate", "agentCertificate", ")", "{", "try", "{", "KeyStore", "store", "=", "KeyStore", ".", "getInstance", "(", "\"JKS\"", ")", ";", "FileInputStream", "inputStream", "=", "new", "FileInputStream", "(", "keystore", ")", ";", "store", ".", "load", "(", "inputStream", ",", "PASSWORD_AS_CHAR_ARRAY", ")", ";", "IOUtils", ".", "closeQuietly", "(", "inputStream", ")", ";", "KeyStore", ".", "PrivateKeyEntry", "intermediateEntry", "=", "(", "KeyStore", ".", "PrivateKeyEntry", ")", "store", ".", "getEntry", "(", "\"ca-intermediate\"", ",", "new", "KeyStore", ".", "PasswordProtection", "(", "PASSWORD_AS_CHAR_ARRAY", ")", ")", ";", "Certificate", "intermediateCertificate", "=", "intermediateEntry", ".", "getCertificate", "(", ")", ";", "agentCertificate", ".", "verify", "(", "intermediateCertificate", ".", "getPublicKey", "(", ")", ")", ";", "return", "true", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "false", ";", "}", "}" ]
Used for testing
[ "Used", "for", "testing" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/common/src/main/java/com/thoughtworks/go/security/X509CertificateGenerator.java#L241-L255
17,586
gocd/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/logging/Logger.java
Logger.debug
public void debug(String message) { if (loggingService == null) { System.out.println(message); return; } loggingService.debug(pluginId, loggerName, message); }
java
public void debug(String message) { if (loggingService == null) { System.out.println(message); return; } loggingService.debug(pluginId, loggerName, message); }
[ "public", "void", "debug", "(", "String", "message", ")", "{", "if", "(", "loggingService", "==", "null", ")", "{", "System", ".", "out", ".", "println", "(", "message", ")", ";", "return", ";", "}", "loggingService", ".", "debug", "(", "pluginId", ",", "loggerName", ",", "message", ")", ";", "}" ]
Messages to be logged in debug mode. @param message a string containing the message to be logged.
[ "Messages", "to", "be", "logged", "in", "debug", "mode", "." ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/logging/Logger.java#L61-L67
17,587
gocd/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/logging/Logger.java
Logger.info
public void info(String message, Object arg1, Object arg2) { if (loggingService == null) { System.out.println(message); return; } loggingService.info(pluginId, loggerName, message, arg1, arg2); }
java
public void info(String message, Object arg1, Object arg2) { if (loggingService == null) { System.out.println(message); return; } loggingService.info(pluginId, loggerName, message, arg1, arg2); }
[ "public", "void", "info", "(", "String", "message", ",", "Object", "arg1", ",", "Object", "arg2", ")", "{", "if", "(", "loggingService", "==", "null", ")", "{", "System", ".", "out", ".", "println", "(", "message", ")", ";", "return", ";", "}", "loggingService", ".", "info", "(", "pluginId", ",", "loggerName", ",", "message", ",", "arg1", ",", "arg2", ")", ";", "}" ]
Messages to be logged in info mode according to the specified format and arguments. <p>This form avoids unnecessary object creation when the logger is disabled for the INFO level. </p> @param message the format string. @param arg1 the first argument @param arg2 the second argument
[ "Messages", "to", "be", "logged", "in", "info", "mode", "according", "to", "the", "specified", "format", "and", "arguments", "." ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/logging/Logger.java#L194-L200
17,588
gocd/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/logging/Logger.java
Logger.error
public void error(String message) { if (loggingService == null) { System.err.println(message); return; } loggingService.error(pluginId, loggerName, message); }
java
public void error(String message) { if (loggingService == null) { System.err.println(message); return; } loggingService.error(pluginId, loggerName, message); }
[ "public", "void", "error", "(", "String", "message", ")", "{", "if", "(", "loggingService", "==", "null", ")", "{", "System", ".", "err", ".", "println", "(", "message", ")", ";", "return", ";", "}", "loggingService", ".", "error", "(", "pluginId", ",", "loggerName", ",", "message", ")", ";", "}" ]
Messages to be logged in error mode. @param message a string containing the message to be logged.
[ "Messages", "to", "be", "logged", "in", "error", "mode", "." ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/logging/Logger.java#L307-L313
17,589
gocd/gocd
config/config-api/src/main/java/com/thoughtworks/go/config/pluggabletask/PluggableTask.java
PluggableTask.isValid
public boolean isValid() { if (PluggableTaskConfigStore.store().preferenceFor(pluginConfiguration.getId()) == null) { addError(TYPE, String.format("Could not find plugin for given pluggable id:[%s].", pluginConfiguration.getId())); } configuration.validateTree(); return (errors.isEmpty() && !configuration.hasErrors()); }
java
public boolean isValid() { if (PluggableTaskConfigStore.store().preferenceFor(pluginConfiguration.getId()) == null) { addError(TYPE, String.format("Could not find plugin for given pluggable id:[%s].", pluginConfiguration.getId())); } configuration.validateTree(); return (errors.isEmpty() && !configuration.hasErrors()); }
[ "public", "boolean", "isValid", "(", ")", "{", "if", "(", "PluggableTaskConfigStore", ".", "store", "(", ")", ".", "preferenceFor", "(", "pluginConfiguration", ".", "getId", "(", ")", ")", "==", "null", ")", "{", "addError", "(", "TYPE", ",", "String", ".", "format", "(", "\"Could not find plugin for given pluggable id:[%s].\"", ",", "pluginConfiguration", ".", "getId", "(", ")", ")", ")", ";", "}", "configuration", ".", "validateTree", "(", ")", ";", "return", "(", "errors", ".", "isEmpty", "(", ")", "&&", "!", "configuration", ".", "hasErrors", "(", ")", ")", ";", "}" ]
This method is called from PluggableTaskService to validate Tasks.
[ "This", "method", "is", "called", "from", "PluggableTaskService", "to", "validate", "Tasks", "." ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/config/config-api/src/main/java/com/thoughtworks/go/config/pluggabletask/PluggableTask.java#L159-L167
17,590
gocd/gocd
server/src/main/java/com/thoughtworks/go/server/service/JobInstanceService.java
JobInstanceService.internalUpdateJobStateAndResult
private void internalUpdateJobStateAndResult(final JobInstance job) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { jobInstanceDao.updateStateAndResult(job); if (job.isCompleted()) { buildPropertiesService.saveCruiseProperties(job); } } }); }
java
private void internalUpdateJobStateAndResult(final JobInstance job) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { jobInstanceDao.updateStateAndResult(job); if (job.isCompleted()) { buildPropertiesService.saveCruiseProperties(job); } } }); }
[ "private", "void", "internalUpdateJobStateAndResult", "(", "final", "JobInstance", "job", ")", "{", "transactionTemplate", ".", "execute", "(", "new", "TransactionCallbackWithoutResult", "(", ")", "{", "protected", "void", "doInTransactionWithoutResult", "(", "TransactionStatus", "status", ")", "{", "jobInstanceDao", ".", "updateStateAndResult", "(", "job", ")", ";", "if", "(", "job", ".", "isCompleted", "(", ")", ")", "{", "buildPropertiesService", ".", "saveCruiseProperties", "(", "job", ")", ";", "}", "}", "}", ")", ";", "}" ]
This method exists only so that we can scope the transaction properly
[ "This", "method", "exists", "only", "so", "that", "we", "can", "scope", "the", "transaction", "properly" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/server/src/main/java/com/thoughtworks/go/server/service/JobInstanceService.java#L158-L167
17,591
gocd/gocd
common/src/main/java/com/thoughtworks/go/serverhealth/ServerHealthService.java
ServerHealthService.onTimer
public synchronized void onTimer() { CruiseConfig currentConfig = applicationContext.getBean(CruiseConfigProvider.class).getCurrentConfig(); purgeStaleHealthMessages(currentConfig); LOG.debug("Recomputing material to pipeline mappings."); HashMap<ServerHealthState, Set<String>> erroredPipelines = new HashMap<>(); for (Map.Entry<HealthStateType, ServerHealthState> entry : serverHealth.entrySet()) { erroredPipelines.put(entry.getValue(), entry.getValue().getPipelineNames(currentConfig)); } pipelinesWithErrors = erroredPipelines; LOG.debug("Done recomputing material to pipeline mappings."); }
java
public synchronized void onTimer() { CruiseConfig currentConfig = applicationContext.getBean(CruiseConfigProvider.class).getCurrentConfig(); purgeStaleHealthMessages(currentConfig); LOG.debug("Recomputing material to pipeline mappings."); HashMap<ServerHealthState, Set<String>> erroredPipelines = new HashMap<>(); for (Map.Entry<HealthStateType, ServerHealthState> entry : serverHealth.entrySet()) { erroredPipelines.put(entry.getValue(), entry.getValue().getPipelineNames(currentConfig)); } pipelinesWithErrors = erroredPipelines; LOG.debug("Done recomputing material to pipeline mappings."); }
[ "public", "synchronized", "void", "onTimer", "(", ")", "{", "CruiseConfig", "currentConfig", "=", "applicationContext", ".", "getBean", "(", "CruiseConfigProvider", ".", "class", ")", ".", "getCurrentConfig", "(", ")", ";", "purgeStaleHealthMessages", "(", "currentConfig", ")", ";", "LOG", ".", "debug", "(", "\"Recomputing material to pipeline mappings.\"", ")", ";", "HashMap", "<", "ServerHealthState", ",", "Set", "<", "String", ">", ">", "erroredPipelines", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "HealthStateType", ",", "ServerHealthState", ">", "entry", ":", "serverHealth", ".", "entrySet", "(", ")", ")", "{", "erroredPipelines", ".", "put", "(", "entry", ".", "getValue", "(", ")", ",", "entry", ".", "getValue", "(", ")", ".", "getPipelineNames", "(", "currentConfig", ")", ")", ";", "}", "pipelinesWithErrors", "=", "erroredPipelines", ";", "LOG", ".", "debug", "(", "\"Done recomputing material to pipeline mappings.\"", ")", ";", "}" ]
called from spring timer
[ "called", "from", "spring", "timer" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/common/src/main/java/com/thoughtworks/go/serverhealth/ServerHealthService.java#L81-L93
17,592
gocd/gocd
domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java
P4Material._p4
P4Client _p4(File workDir, ConsoleOutputStreamConsumer consumer, boolean failOnError) throws Exception { String clientName = clientName(workDir); return P4Client.fromServerAndPort(getFingerprint(), serverAndPort, userName, getPassword(), clientName, this.useTickets, workDir, p4view(clientName), consumer, failOnError); }
java
P4Client _p4(File workDir, ConsoleOutputStreamConsumer consumer, boolean failOnError) throws Exception { String clientName = clientName(workDir); return P4Client.fromServerAndPort(getFingerprint(), serverAndPort, userName, getPassword(), clientName, this.useTickets, workDir, p4view(clientName), consumer, failOnError); }
[ "P4Client", "_p4", "(", "File", "workDir", ",", "ConsoleOutputStreamConsumer", "consumer", ",", "boolean", "failOnError", ")", "throws", "Exception", "{", "String", "clientName", "=", "clientName", "(", "workDir", ")", ";", "return", "P4Client", ".", "fromServerAndPort", "(", "getFingerprint", "(", ")", ",", "serverAndPort", ",", "userName", ",", "getPassword", "(", ")", ",", "clientName", ",", "this", ".", "useTickets", ",", "workDir", ",", "p4view", "(", "clientName", ")", ",", "consumer", ",", "failOnError", ")", ";", "}" ]
not for use externally, created for testing convenience
[ "not", "for", "use", "externally", "created", "for", "testing", "convenience" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java#L211-L214
17,593
gocd/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/validation/ValidationResult.java
ValidationResult.getMessages
public List<String> getMessages() { List<String> errorMessages = new ArrayList<>(); for (ValidationError error : errors) { errorMessages.add(error.getMessage()); } return errorMessages; }
java
public List<String> getMessages() { List<String> errorMessages = new ArrayList<>(); for (ValidationError error : errors) { errorMessages.add(error.getMessage()); } return errorMessages; }
[ "public", "List", "<", "String", ">", "getMessages", "(", ")", "{", "List", "<", "String", ">", "errorMessages", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "ValidationError", "error", ":", "errors", ")", "{", "errorMessages", ".", "add", "(", "error", ".", "getMessage", "(", ")", ")", ";", "}", "return", "errorMessages", ";", "}" ]
Collects error message string as list from all the errors in the container @return error message as list of string
[ "Collects", "error", "message", "string", "as", "list", "from", "all", "the", "errors", "in", "the", "container" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/validation/ValidationResult.java#L84-L90
17,594
gocd/gocd
server/src/main/java/com/thoughtworks/go/config/GoFileConfigDataSource.java
GoFileConfigDataSource.writeWithLock
@Deprecated public synchronized GoConfigSaveResult writeWithLock(UpdateConfigCommand updatingCommand, GoConfigHolder configHolder) { try { // Need to convert to xml before we try to write it to the config file. // If our cruiseConfig fails XSD validation, we don't want to write it incorrectly. GoConfigHolder validatedConfigHolder; List<PartialConfig> lastKnownPartials = cachedGoPartials.lastKnownPartials(); List<PartialConfig> lastValidPartials = cachedGoPartials.lastValidPartials(); try { validatedConfigHolder = trySavingConfig(updatingCommand, configHolder, lastKnownPartials); updateMergedConfigForEdit(validatedConfigHolder, lastKnownPartials); } catch (Exception e) { if (lastKnownPartials.isEmpty() || areKnownPartialsSameAsValidPartials(lastKnownPartials, lastValidPartials)) { throw e; } else { LOGGER.warn("Merged config update operation failed on LATEST {} partials. Falling back to using LAST VALID {} partials. Exception message was: {}", lastKnownPartials.size(), lastValidPartials.size(), e.getMessage(), e); try { validatedConfigHolder = trySavingConfig(updatingCommand, configHolder, lastValidPartials); updateMergedConfigForEdit(validatedConfigHolder, lastValidPartials); LOGGER.info("Update operation on merged configuration succeeded with old {} LAST VALID partials.", lastValidPartials.size()); } catch (GoConfigInvalidException fallbackFailed) { LOGGER.warn("Merged config update operation failed using fallback LAST VALID {} partials. Exception message was: {}", lastValidPartials.size(), fallbackFailed.getMessage(), fallbackFailed); throw new GoConfigInvalidMergeException(lastValidPartials, fallbackFailed); } } } ConfigSaveState configSaveState = shouldMergeConfig(updatingCommand, configHolder) ? ConfigSaveState.MERGED : ConfigSaveState.UPDATED; return new GoConfigSaveResult(validatedConfigHolder, configSaveState); } catch (ConfigFileHasChangedException e) { LOGGER.warn("Configuration file could not be merged successfully after a concurrent edit: {}", e.getMessage(), e); throw e; } catch (GoConfigInvalidException e) { LOGGER.warn("Configuration file is invalid: {}", e.getMessage(), e); throw bomb(e.getMessage(), e); } catch (Exception e) { LOGGER.error("Configuration file is not valid: {}", e.getMessage(), e); throw bomb(e.getMessage(), e); } finally { LOGGER.debug("[Config Save] Done writing with lock"); } }
java
@Deprecated public synchronized GoConfigSaveResult writeWithLock(UpdateConfigCommand updatingCommand, GoConfigHolder configHolder) { try { // Need to convert to xml before we try to write it to the config file. // If our cruiseConfig fails XSD validation, we don't want to write it incorrectly. GoConfigHolder validatedConfigHolder; List<PartialConfig> lastKnownPartials = cachedGoPartials.lastKnownPartials(); List<PartialConfig> lastValidPartials = cachedGoPartials.lastValidPartials(); try { validatedConfigHolder = trySavingConfig(updatingCommand, configHolder, lastKnownPartials); updateMergedConfigForEdit(validatedConfigHolder, lastKnownPartials); } catch (Exception e) { if (lastKnownPartials.isEmpty() || areKnownPartialsSameAsValidPartials(lastKnownPartials, lastValidPartials)) { throw e; } else { LOGGER.warn("Merged config update operation failed on LATEST {} partials. Falling back to using LAST VALID {} partials. Exception message was: {}", lastKnownPartials.size(), lastValidPartials.size(), e.getMessage(), e); try { validatedConfigHolder = trySavingConfig(updatingCommand, configHolder, lastValidPartials); updateMergedConfigForEdit(validatedConfigHolder, lastValidPartials); LOGGER.info("Update operation on merged configuration succeeded with old {} LAST VALID partials.", lastValidPartials.size()); } catch (GoConfigInvalidException fallbackFailed) { LOGGER.warn("Merged config update operation failed using fallback LAST VALID {} partials. Exception message was: {}", lastValidPartials.size(), fallbackFailed.getMessage(), fallbackFailed); throw new GoConfigInvalidMergeException(lastValidPartials, fallbackFailed); } } } ConfigSaveState configSaveState = shouldMergeConfig(updatingCommand, configHolder) ? ConfigSaveState.MERGED : ConfigSaveState.UPDATED; return new GoConfigSaveResult(validatedConfigHolder, configSaveState); } catch (ConfigFileHasChangedException e) { LOGGER.warn("Configuration file could not be merged successfully after a concurrent edit: {}", e.getMessage(), e); throw e; } catch (GoConfigInvalidException e) { LOGGER.warn("Configuration file is invalid: {}", e.getMessage(), e); throw bomb(e.getMessage(), e); } catch (Exception e) { LOGGER.error("Configuration file is not valid: {}", e.getMessage(), e); throw bomb(e.getMessage(), e); } finally { LOGGER.debug("[Config Save] Done writing with lock"); } }
[ "@", "Deprecated", "public", "synchronized", "GoConfigSaveResult", "writeWithLock", "(", "UpdateConfigCommand", "updatingCommand", ",", "GoConfigHolder", "configHolder", ")", "{", "try", "{", "// Need to convert to xml before we try to write it to the config file.", "// If our cruiseConfig fails XSD validation, we don't want to write it incorrectly.", "GoConfigHolder", "validatedConfigHolder", ";", "List", "<", "PartialConfig", ">", "lastKnownPartials", "=", "cachedGoPartials", ".", "lastKnownPartials", "(", ")", ";", "List", "<", "PartialConfig", ">", "lastValidPartials", "=", "cachedGoPartials", ".", "lastValidPartials", "(", ")", ";", "try", "{", "validatedConfigHolder", "=", "trySavingConfig", "(", "updatingCommand", ",", "configHolder", ",", "lastKnownPartials", ")", ";", "updateMergedConfigForEdit", "(", "validatedConfigHolder", ",", "lastKnownPartials", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "if", "(", "lastKnownPartials", ".", "isEmpty", "(", ")", "||", "areKnownPartialsSameAsValidPartials", "(", "lastKnownPartials", ",", "lastValidPartials", ")", ")", "{", "throw", "e", ";", "}", "else", "{", "LOGGER", ".", "warn", "(", "\"Merged config update operation failed on LATEST {} partials. Falling back to using LAST VALID {} partials. Exception message was: {}\"", ",", "lastKnownPartials", ".", "size", "(", ")", ",", "lastValidPartials", ".", "size", "(", ")", ",", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "try", "{", "validatedConfigHolder", "=", "trySavingConfig", "(", "updatingCommand", ",", "configHolder", ",", "lastValidPartials", ")", ";", "updateMergedConfigForEdit", "(", "validatedConfigHolder", ",", "lastValidPartials", ")", ";", "LOGGER", ".", "info", "(", "\"Update operation on merged configuration succeeded with old {} LAST VALID partials.\"", ",", "lastValidPartials", ".", "size", "(", ")", ")", ";", "}", "catch", "(", "GoConfigInvalidException", "fallbackFailed", ")", "{", "LOGGER", ".", "warn", "(", "\"Merged config update operation failed using fallback LAST VALID {} partials. Exception message was: {}\"", ",", "lastValidPartials", ".", "size", "(", ")", ",", "fallbackFailed", ".", "getMessage", "(", ")", ",", "fallbackFailed", ")", ";", "throw", "new", "GoConfigInvalidMergeException", "(", "lastValidPartials", ",", "fallbackFailed", ")", ";", "}", "}", "}", "ConfigSaveState", "configSaveState", "=", "shouldMergeConfig", "(", "updatingCommand", ",", "configHolder", ")", "?", "ConfigSaveState", ".", "MERGED", ":", "ConfigSaveState", ".", "UPDATED", ";", "return", "new", "GoConfigSaveResult", "(", "validatedConfigHolder", ",", "configSaveState", ")", ";", "}", "catch", "(", "ConfigFileHasChangedException", "e", ")", "{", "LOGGER", ".", "warn", "(", "\"Configuration file could not be merged successfully after a concurrent edit: {}\"", ",", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "throw", "e", ";", "}", "catch", "(", "GoConfigInvalidException", "e", ")", "{", "LOGGER", ".", "warn", "(", "\"Configuration file is invalid: {}\"", ",", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "throw", "bomb", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOGGER", ".", "error", "(", "\"Configuration file is not valid: {}\"", ",", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "throw", "bomb", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "finally", "{", "LOGGER", ".", "debug", "(", "\"[Config Save] Done writing with lock\"", ")", ";", "}", "}" ]
This method should be removed once we have API's for all entities which should use writeEntityWithLock and full config save should use writeFullConfigWithLock
[ "This", "method", "should", "be", "removed", "once", "we", "have", "API", "s", "for", "all", "entities", "which", "should", "use", "writeEntityWithLock", "and", "full", "config", "save", "should", "use", "writeFullConfigWithLock" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/server/src/main/java/com/thoughtworks/go/config/GoFileConfigDataSource.java#L307-L349
17,595
gocd/gocd
domain/src/main/java/com/thoughtworks/go/domain/BuildCommand.java
BuildCommand.export
public static BuildCommand export(String name, String value, boolean isSecure) { return new BuildCommand("export", map("name", name, "value", value, "secure", String.valueOf(isSecure))); }
java
public static BuildCommand export(String name, String value, boolean isSecure) { return new BuildCommand("export", map("name", name, "value", value, "secure", String.valueOf(isSecure))); }
[ "public", "static", "BuildCommand", "export", "(", "String", "name", ",", "String", "value", ",", "boolean", "isSecure", ")", "{", "return", "new", "BuildCommand", "(", "\"export\"", ",", "map", "(", "\"name\"", ",", "name", ",", "\"value\"", ",", "value", ",", "\"secure\"", ",", "String", ".", "valueOf", "(", "isSecure", ")", ")", ")", ";", "}" ]
set environment variable with displaying it
[ "set", "environment", "variable", "with", "displaying", "it" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/domain/src/main/java/com/thoughtworks/go/domain/BuildCommand.java#L86-L88
17,596
gocd/gocd
base/src/main/java/com/thoughtworks/go/util/SelectorUtils.java
SelectorUtils.tokenizePath
public static Vector tokenizePath (String path, String separator) { Vector ret = new Vector(); if (FileUtil.isAbsolutePath(path)) { String[] s = FileUtil.dissect(path); ret.add(s[0]); path = s[1]; } StringTokenizer st = new StringTokenizer(path, separator); while (st.hasMoreTokens()) { ret.addElement(st.nextToken()); } return ret; }
java
public static Vector tokenizePath (String path, String separator) { Vector ret = new Vector(); if (FileUtil.isAbsolutePath(path)) { String[] s = FileUtil.dissect(path); ret.add(s[0]); path = s[1]; } StringTokenizer st = new StringTokenizer(path, separator); while (st.hasMoreTokens()) { ret.addElement(st.nextToken()); } return ret; }
[ "public", "static", "Vector", "tokenizePath", "(", "String", "path", ",", "String", "separator", ")", "{", "Vector", "ret", "=", "new", "Vector", "(", ")", ";", "if", "(", "FileUtil", ".", "isAbsolutePath", "(", "path", ")", ")", "{", "String", "[", "]", "s", "=", "FileUtil", ".", "dissect", "(", "path", ")", ";", "ret", ".", "add", "(", "s", "[", "0", "]", ")", ";", "path", "=", "s", "[", "1", "]", ";", "}", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "path", ",", "separator", ")", ";", "while", "(", "st", ".", "hasMoreTokens", "(", ")", ")", "{", "ret", ".", "addElement", "(", "st", ".", "nextToken", "(", ")", ")", ";", "}", "return", "ret", ";", "}" ]
Breaks a path up into a Vector of path elements, tokenizing on @param path Path to tokenize. Must not be <code>null</code>. @param separator the separator against which to tokenize. @return a Vector of path elements from the tokenized path @since Ant 1.6
[ "Breaks", "a", "path", "up", "into", "a", "Vector", "of", "path", "elements", "tokenizing", "on" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/base/src/main/java/com/thoughtworks/go/util/SelectorUtils.java#L487-L499
17,597
gocd/gocd
base/src/main/java/com/thoughtworks/go/util/SelectorUtils.java
SelectorUtils.rtrimWildcardTokens
public static String rtrimWildcardTokens(String input) { String[] tokens = tokenizePathAsArray(input); StringBuilder sb = new StringBuilder(); for (int i = 0; i < tokens.length; i++) { if (hasWildcards(tokens[i])) { break; } if (i > 0 && sb.charAt(sb.length() - 1) != File.separatorChar) { sb.append(File.separatorChar); } sb.append(tokens[i]); } return sb.toString(); }
java
public static String rtrimWildcardTokens(String input) { String[] tokens = tokenizePathAsArray(input); StringBuilder sb = new StringBuilder(); for (int i = 0; i < tokens.length; i++) { if (hasWildcards(tokens[i])) { break; } if (i > 0 && sb.charAt(sb.length() - 1) != File.separatorChar) { sb.append(File.separatorChar); } sb.append(tokens[i]); } return sb.toString(); }
[ "public", "static", "String", "rtrimWildcardTokens", "(", "String", "input", ")", "{", "String", "[", "]", "tokens", "=", "tokenizePathAsArray", "(", "input", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tokens", ".", "length", ";", "i", "++", ")", "{", "if", "(", "hasWildcards", "(", "tokens", "[", "i", "]", ")", ")", "{", "break", ";", "}", "if", "(", "i", ">", "0", "&&", "sb", ".", "charAt", "(", "sb", ".", "length", "(", ")", "-", "1", ")", "!=", "File", ".", "separatorChar", ")", "{", "sb", ".", "append", "(", "File", ".", "separatorChar", ")", ";", "}", "sb", ".", "append", "(", "tokens", "[", "i", "]", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
removes from a pattern all tokens to the right containing wildcards @param input the input string @return the leftmost part of the pattern without wildcards
[ "removes", "from", "a", "pattern", "all", "tokens", "to", "the", "right", "containing", "wildcards" ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/base/src/main/java/com/thoughtworks/go/util/SelectorUtils.java#L584-L597
17,598
gocd/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/execution/ExecutionResult.java
ExecutionResult.failure
public static ExecutionResult failure(String message) { ExecutionResult executionResult = new ExecutionResult(); executionResult.withErrorMessages(message); return executionResult; }
java
public static ExecutionResult failure(String message) { ExecutionResult executionResult = new ExecutionResult(); executionResult.withErrorMessages(message); return executionResult; }
[ "public", "static", "ExecutionResult", "failure", "(", "String", "message", ")", "{", "ExecutionResult", "executionResult", "=", "new", "ExecutionResult", "(", ")", ";", "executionResult", ".", "withErrorMessages", "(", "message", ")", ";", "return", "executionResult", ";", "}" ]
Mark the result as 'Failure'. @param message More details about the failure. @return A new ExecutionResult instance, which is marked as 'Failure'.
[ "Mark", "the", "result", "as", "Failure", "." ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/execution/ExecutionResult.java#L45-L49
17,599
gocd/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/execution/ExecutionResult.java
ExecutionResult.success
public static ExecutionResult success(String message) { ExecutionResult executionResult = new ExecutionResult(); executionResult.withSuccessMessages(message); return executionResult; }
java
public static ExecutionResult success(String message) { ExecutionResult executionResult = new ExecutionResult(); executionResult.withSuccessMessages(message); return executionResult; }
[ "public", "static", "ExecutionResult", "success", "(", "String", "message", ")", "{", "ExecutionResult", "executionResult", "=", "new", "ExecutionResult", "(", ")", ";", "executionResult", ".", "withSuccessMessages", "(", "message", ")", ";", "return", "executionResult", ";", "}" ]
Mark the result as 'Success'. @param message More details about the run. @return A new ExecutionResult instance, which is marked as 'Success'.
[ "Mark", "the", "result", "as", "Success", "." ]
59a8480e23d6c06de39127635108dff57603cb71
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/response/execution/ExecutionResult.java#L57-L61