repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
michael-rapp/AndroidBottomSheet
library/src/main/java/de/mrapp/android/bottomsheet/model/Item.java
Item.setIcon
public final void setIcon(@NonNull final Context context, @DrawableRes final int resourceId) { """ Sets the item's icon. @param context The context, which should be used, as an instance of the class {@link Context}. The context may not be null @param resourceId The resource id of the icon, which should be set, as an {@link Integer} value. The resource id must correspond to a valid drawable resource """ setIcon(ContextCompat.getDrawable(context, resourceId)); }
java
public final void setIcon(@NonNull final Context context, @DrawableRes final int resourceId) { setIcon(ContextCompat.getDrawable(context, resourceId)); }
[ "public", "final", "void", "setIcon", "(", "@", "NonNull", "final", "Context", "context", ",", "@", "DrawableRes", "final", "int", "resourceId", ")", "{", "setIcon", "(", "ContextCompat", ".", "getDrawable", "(", "context", ",", "resourceId", ")", ")", ";", "}" ]
Sets the item's icon. @param context The context, which should be used, as an instance of the class {@link Context}. The context may not be null @param resourceId The resource id of the icon, which should be set, as an {@link Integer} value. The resource id must correspond to a valid drawable resource
[ "Sets", "the", "item", "s", "icon", "." ]
train
https://github.com/michael-rapp/AndroidBottomSheet/blob/6e4690ee9f63b14a7b143d3a3717b5f8a11ca503/library/src/main/java/de/mrapp/android/bottomsheet/model/Item.java#L113-L115
baratine/baratine
kraken/src/main/java/com/caucho/v5/kelp/BlockTree.java
BlockTree.fillEntries
void fillEntries(TableKelp table, TreeSet<TreeEntry> set, int index) { """ /* void write(MaukaDatabase db, WriteStream os, int index) throws IOException { byte []buffer = getBuffer(); int keyLength = db.getKeyLength(); int len = 2 * keyLength + 5; for (int ptr = index; ptr < BLOCK_SIZE; ptr += len) { int code = buffer[ptr] & 0xff; if (code != INSERT) { continue; } int pid = BitsUtil.readInt(buffer, ptr + len - 4); if (pid == 0) { throw new IllegalStateException(); } os.write(buffer, ptr + 1, len - 1); } } """ byte []buffer = getBuffer(); int keyLength = table.getKeyLength(); int len = table.row().getTreeItemLength(); for (int ptr = index; ptr < BLOCK_SIZE; ptr += len) { int code = buffer[ptr] & 0xff; int min = ptr + 1; int max = min + keyLength; int valueOffset = max + keyLength; byte []minKey = new byte[keyLength]; byte []maxKey = new byte[keyLength]; System.arraycopy(buffer, min, minKey, 0, keyLength); System.arraycopy(buffer, max, maxKey, 0, keyLength); int pid = BitsUtil.readInt(buffer, valueOffset); TreeEntry entry = new TreeEntry(minKey, maxKey, code, pid); set.add(entry); } }
java
void fillEntries(TableKelp table, TreeSet<TreeEntry> set, int index) { byte []buffer = getBuffer(); int keyLength = table.getKeyLength(); int len = table.row().getTreeItemLength(); for (int ptr = index; ptr < BLOCK_SIZE; ptr += len) { int code = buffer[ptr] & 0xff; int min = ptr + 1; int max = min + keyLength; int valueOffset = max + keyLength; byte []minKey = new byte[keyLength]; byte []maxKey = new byte[keyLength]; System.arraycopy(buffer, min, minKey, 0, keyLength); System.arraycopy(buffer, max, maxKey, 0, keyLength); int pid = BitsUtil.readInt(buffer, valueOffset); TreeEntry entry = new TreeEntry(minKey, maxKey, code, pid); set.add(entry); } }
[ "void", "fillEntries", "(", "TableKelp", "table", ",", "TreeSet", "<", "TreeEntry", ">", "set", ",", "int", "index", ")", "{", "byte", "[", "]", "buffer", "=", "getBuffer", "(", ")", ";", "int", "keyLength", "=", "table", ".", "getKeyLength", "(", ")", ";", "int", "len", "=", "table", ".", "row", "(", ")", ".", "getTreeItemLength", "(", ")", ";", "for", "(", "int", "ptr", "=", "index", ";", "ptr", "<", "BLOCK_SIZE", ";", "ptr", "+=", "len", ")", "{", "int", "code", "=", "buffer", "[", "ptr", "]", "&", "0xff", ";", "int", "min", "=", "ptr", "+", "1", ";", "int", "max", "=", "min", "+", "keyLength", ";", "int", "valueOffset", "=", "max", "+", "keyLength", ";", "byte", "[", "]", "minKey", "=", "new", "byte", "[", "keyLength", "]", ";", "byte", "[", "]", "maxKey", "=", "new", "byte", "[", "keyLength", "]", ";", "System", ".", "arraycopy", "(", "buffer", ",", "min", ",", "minKey", ",", "0", ",", "keyLength", ")", ";", "System", ".", "arraycopy", "(", "buffer", ",", "max", ",", "maxKey", ",", "0", ",", "keyLength", ")", ";", "int", "pid", "=", "BitsUtil", ".", "readInt", "(", "buffer", ",", "valueOffset", ")", ";", "TreeEntry", "entry", "=", "new", "TreeEntry", "(", "minKey", ",", "maxKey", ",", "code", ",", "pid", ")", ";", "set", ".", "add", "(", "entry", ")", ";", "}", "}" ]
/* void write(MaukaDatabase db, WriteStream os, int index) throws IOException { byte []buffer = getBuffer(); int keyLength = db.getKeyLength(); int len = 2 * keyLength + 5; for (int ptr = index; ptr < BLOCK_SIZE; ptr += len) { int code = buffer[ptr] & 0xff; if (code != INSERT) { continue; } int pid = BitsUtil.readInt(buffer, ptr + len - 4); if (pid == 0) { throw new IllegalStateException(); } os.write(buffer, ptr + 1, len - 1); } }
[ "/", "*", "void", "write", "(", "MaukaDatabase", "db", "WriteStream", "os", "int", "index", ")", "throws", "IOException", "{", "byte", "[]", "buffer", "=", "getBuffer", "()", ";" ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/kraken/src/main/java/com/caucho/v5/kelp/BlockTree.java#L355-L383
cdk/cdk
tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java
MolecularFormulaManipulator.getElementCount
public static int getElementCount(IMolecularFormula formula, String symbol) { """ Occurrences of a given element in a molecular formula. @param formula the formula @param symbol element symbol (e.g. C for carbon) @return number of the times the element occurs @see #getElementCount(IMolecularFormula, IElement) """ return getElementCount(formula, formula.getBuilder().newInstance(IElement.class, symbol)); }
java
public static int getElementCount(IMolecularFormula formula, String symbol) { return getElementCount(formula, formula.getBuilder().newInstance(IElement.class, symbol)); }
[ "public", "static", "int", "getElementCount", "(", "IMolecularFormula", "formula", ",", "String", "symbol", ")", "{", "return", "getElementCount", "(", "formula", ",", "formula", ".", "getBuilder", "(", ")", ".", "newInstance", "(", "IElement", ".", "class", ",", "symbol", ")", ")", ";", "}" ]
Occurrences of a given element in a molecular formula. @param formula the formula @param symbol element symbol (e.g. C for carbon) @return number of the times the element occurs @see #getElementCount(IMolecularFormula, IElement)
[ "Occurrences", "of", "a", "given", "element", "in", "a", "molecular", "formula", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java#L156-L158
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/collidable/selector/SelectorRefresher.java
SelectorRefresher.createStart
private StateUpdater createStart(Cursor cursor, SelectorModel model, StateUpdater check, StateUpdater select) { """ Create start action. @param cursor The cursor reference. @param model The selector model. @param check The check action. @param select The selection action. @return The start action. """ return (extrp, current) -> { StateUpdater next = current; if (!model.isEnabled()) { next = check; } else if (model.getSelectionClick() == cursor.getClick()) { checkBeginSelection(cursor, model); if (model.isSelecting()) { next = select; } } return next; }; }
java
private StateUpdater createStart(Cursor cursor, SelectorModel model, StateUpdater check, StateUpdater select) { return (extrp, current) -> { StateUpdater next = current; if (!model.isEnabled()) { next = check; } else if (model.getSelectionClick() == cursor.getClick()) { checkBeginSelection(cursor, model); if (model.isSelecting()) { next = select; } } return next; }; }
[ "private", "StateUpdater", "createStart", "(", "Cursor", "cursor", ",", "SelectorModel", "model", ",", "StateUpdater", "check", ",", "StateUpdater", "select", ")", "{", "return", "(", "extrp", ",", "current", ")", "->", "{", "StateUpdater", "next", "=", "current", ";", "if", "(", "!", "model", ".", "isEnabled", "(", ")", ")", "{", "next", "=", "check", ";", "}", "else", "if", "(", "model", ".", "getSelectionClick", "(", ")", "==", "cursor", ".", "getClick", "(", ")", ")", "{", "checkBeginSelection", "(", "cursor", ",", "model", ")", ";", "if", "(", "model", ".", "isSelecting", "(", ")", ")", "{", "next", "=", "select", ";", "}", "}", "return", "next", ";", "}", ";", "}" ]
Create start action. @param cursor The cursor reference. @param model The selector model. @param check The check action. @param select The selection action. @return The start action.
[ "Create", "start", "action", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/collidable/selector/SelectorRefresher.java#L130-L149
jenetics/jenetics
jenetics/src/main/java/io/jenetics/engine/Codecs.java
Codecs.ofSubSet
public static <T> Codec<ISeq<T>, BitGene> ofSubSet( final ISeq<? extends T> basicSet ) { """ The subset {@code Codec} can be used for problems where it is required to find the best <b>variable-sized</b> subset from given basic set. A typical usage example of the returned {@code Codec} is the Knapsack problem. <p> The following code snippet shows a simplified variation of the Knapsack problem. <pre>{@code public final class Main { // The basic set from where to choose an 'optimal' subset. private final static ISeq<Integer> SET = ISeq.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Fitness function directly takes an 'int' value. private static int fitness(final ISeq<Integer> subset) { assert(subset.size() <= SET.size()); final int size = subset.stream() .collect(Collectors.summingInt(Integer::intValue)); return size <= 20 ? size : 0; } public static void main(final String[] args) { final Engine<BitGene, Double> engine = Engine .builder(Main::fitness, codec.ofSubSet(SET)) .build(); ... } } }</pre> @param <T> the element type of the basic set @param basicSet the basic set, from where to choose the <i>optimal</i> subset. @return a new codec which can be used for modelling <i>subset</i> problems. @throws NullPointerException if the given {@code basicSet} is {@code null}; {@code null} elements are allowed. @throws IllegalArgumentException if the {@code basicSet} size is smaller than one. """ requireNonNull(basicSet); require.positive(basicSet.length()); return Codec.of( Genotype.of(BitChromosome.of(basicSet.length())), gt -> gt.getChromosome() .as(BitChromosome.class).ones() .<T>mapToObj(basicSet) .collect(ISeq.toISeq()) ); }
java
public static <T> Codec<ISeq<T>, BitGene> ofSubSet( final ISeq<? extends T> basicSet ) { requireNonNull(basicSet); require.positive(basicSet.length()); return Codec.of( Genotype.of(BitChromosome.of(basicSet.length())), gt -> gt.getChromosome() .as(BitChromosome.class).ones() .<T>mapToObj(basicSet) .collect(ISeq.toISeq()) ); }
[ "public", "static", "<", "T", ">", "Codec", "<", "ISeq", "<", "T", ">", ",", "BitGene", ">", "ofSubSet", "(", "final", "ISeq", "<", "?", "extends", "T", ">", "basicSet", ")", "{", "requireNonNull", "(", "basicSet", ")", ";", "require", ".", "positive", "(", "basicSet", ".", "length", "(", ")", ")", ";", "return", "Codec", ".", "of", "(", "Genotype", ".", "of", "(", "BitChromosome", ".", "of", "(", "basicSet", ".", "length", "(", ")", ")", ")", ",", "gt", "->", "gt", ".", "getChromosome", "(", ")", ".", "as", "(", "BitChromosome", ".", "class", ")", ".", "ones", "(", ")", ".", "<", "T", ">", "mapToObj", "(", "basicSet", ")", ".", "collect", "(", "ISeq", ".", "toISeq", "(", ")", ")", ")", ";", "}" ]
The subset {@code Codec} can be used for problems where it is required to find the best <b>variable-sized</b> subset from given basic set. A typical usage example of the returned {@code Codec} is the Knapsack problem. <p> The following code snippet shows a simplified variation of the Knapsack problem. <pre>{@code public final class Main { // The basic set from where to choose an 'optimal' subset. private final static ISeq<Integer> SET = ISeq.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Fitness function directly takes an 'int' value. private static int fitness(final ISeq<Integer> subset) { assert(subset.size() <= SET.size()); final int size = subset.stream() .collect(Collectors.summingInt(Integer::intValue)); return size <= 20 ? size : 0; } public static void main(final String[] args) { final Engine<BitGene, Double> engine = Engine .builder(Main::fitness, codec.ofSubSet(SET)) .build(); ... } } }</pre> @param <T> the element type of the basic set @param basicSet the basic set, from where to choose the <i>optimal</i> subset. @return a new codec which can be used for modelling <i>subset</i> problems. @throws NullPointerException if the given {@code basicSet} is {@code null}; {@code null} elements are allowed. @throws IllegalArgumentException if the {@code basicSet} size is smaller than one.
[ "The", "subset", "{", "@code", "Codec", "}", "can", "be", "used", "for", "problems", "where", "it", "is", "required", "to", "find", "the", "best", "<b", ">", "variable", "-", "sized<", "/", "b", ">", "subset", "from", "given", "basic", "set", ".", "A", "typical", "usage", "example", "of", "the", "returned", "{", "@code", "Codec", "}", "is", "the", "Knapsack", "problem", ".", "<p", ">", "The", "following", "code", "snippet", "shows", "a", "simplified", "variation", "of", "the", "Knapsack", "problem", ".", "<pre", ">", "{", "@code", "public", "final", "class", "Main", "{", "//", "The", "basic", "set", "from", "where", "to", "choose", "an", "optimal", "subset", ".", "private", "final", "static", "ISeq<Integer", ">", "SET", "=", "ISeq", ".", "of", "(", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", ")", ";" ]
train
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/engine/Codecs.java#L770-L783
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/constraint/ChocoMapper.java
ChocoMapper.mapView
public void mapView(Class<? extends ModelView> c, Class<? extends ChocoView> cc) { """ Register a mapping between an api-side view and its choco implementation. It is expected from the implementation to exhibit a constructor that takes the api-side constraint as argument. @param c the api-side view @param cc the choco implementation @throws IllegalArgumentException if there is no suitable constructor for the choco implementation """ views.put(c, cc); }
java
public void mapView(Class<? extends ModelView> c, Class<? extends ChocoView> cc) { views.put(c, cc); }
[ "public", "void", "mapView", "(", "Class", "<", "?", "extends", "ModelView", ">", "c", ",", "Class", "<", "?", "extends", "ChocoView", ">", "cc", ")", "{", "views", ".", "put", "(", "c", ",", "cc", ")", ";", "}" ]
Register a mapping between an api-side view and its choco implementation. It is expected from the implementation to exhibit a constructor that takes the api-side constraint as argument. @param c the api-side view @param cc the choco implementation @throws IllegalArgumentException if there is no suitable constructor for the choco implementation
[ "Register", "a", "mapping", "between", "an", "api", "-", "side", "view", "and", "its", "choco", "implementation", ".", "It", "is", "expected", "from", "the", "implementation", "to", "exhibit", "a", "constructor", "that", "takes", "the", "api", "-", "side", "constraint", "as", "argument", "." ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/constraint/ChocoMapper.java#L152-L154
OpenBEL/openbel-framework
org.openbel.framework.core/src/main/java/org/openbel/framework/core/SimpleApplication.java
SimpleApplication.printHelp
private void printHelp(Options o, boolean exit, OutputStream os) { """ Write command-line help to the provided stream. If {@code exit} is {@code true}, exit with status code {@link #EXIT_FAILURE}. @param o Options @param exit Exit flag """ final PrintWriter pw = new PrintWriter(os); final String syntax = getUsage(); String header = getApplicationName(); header = header.concat("\nOptions:"); HelpFormatter hf = new HelpFormatter(); hf.printHelp(pw, 80, syntax, header, o, 2, 2, null, false); pw.flush(); if (exit) { bail(SUCCESS); } }
java
private void printHelp(Options o, boolean exit, OutputStream os) { final PrintWriter pw = new PrintWriter(os); final String syntax = getUsage(); String header = getApplicationName(); header = header.concat("\nOptions:"); HelpFormatter hf = new HelpFormatter(); hf.printHelp(pw, 80, syntax, header, o, 2, 2, null, false); pw.flush(); if (exit) { bail(SUCCESS); } }
[ "private", "void", "printHelp", "(", "Options", "o", ",", "boolean", "exit", ",", "OutputStream", "os", ")", "{", "final", "PrintWriter", "pw", "=", "new", "PrintWriter", "(", "os", ")", ";", "final", "String", "syntax", "=", "getUsage", "(", ")", ";", "String", "header", "=", "getApplicationName", "(", ")", ";", "header", "=", "header", ".", "concat", "(", "\"\\nOptions:\"", ")", ";", "HelpFormatter", "hf", "=", "new", "HelpFormatter", "(", ")", ";", "hf", ".", "printHelp", "(", "pw", ",", "80", ",", "syntax", ",", "header", ",", "o", ",", "2", ",", "2", ",", "null", ",", "false", ")", ";", "pw", ".", "flush", "(", ")", ";", "if", "(", "exit", ")", "{", "bail", "(", "SUCCESS", ")", ";", "}", "}" ]
Write command-line help to the provided stream. If {@code exit} is {@code true}, exit with status code {@link #EXIT_FAILURE}. @param o Options @param exit Exit flag
[ "Write", "command", "-", "line", "help", "to", "the", "provided", "stream", ".", "If", "{", "@code", "exit", "}", "is", "{", "@code", "true", "}", "exit", "with", "status", "code", "{", "@link", "#EXIT_FAILURE", "}", "." ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.core/src/main/java/org/openbel/framework/core/SimpleApplication.java#L381-L393
astrapi69/jaulp-wicket
jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/application/ApplicationExtensions.java
ApplicationExtensions.getRealPath
public static String getRealPath(final WebApplication application, final String path) { """ Gets the real path corresponding to the given virtual path from the given WebApplication. This method gets decorated the method of the {@link javax.servlet.ServletContext#getRealPath(String)}. @param application the wicket application @param path the virtual path to be translated to a real path @return the real path, or null if the translation cannot be performed """ final String realPath = application.getServletContext().getRealPath(path); if ((null != realPath) && !realPath.isEmpty()) { return realPath; } return ""; }
java
public static String getRealPath(final WebApplication application, final String path) { final String realPath = application.getServletContext().getRealPath(path); if ((null != realPath) && !realPath.isEmpty()) { return realPath; } return ""; }
[ "public", "static", "String", "getRealPath", "(", "final", "WebApplication", "application", ",", "final", "String", "path", ")", "{", "final", "String", "realPath", "=", "application", ".", "getServletContext", "(", ")", ".", "getRealPath", "(", "path", ")", ";", "if", "(", "(", "null", "!=", "realPath", ")", "&&", "!", "realPath", ".", "isEmpty", "(", ")", ")", "{", "return", "realPath", ";", "}", "return", "\"\"", ";", "}" ]
Gets the real path corresponding to the given virtual path from the given WebApplication. This method gets decorated the method of the {@link javax.servlet.ServletContext#getRealPath(String)}. @param application the wicket application @param path the virtual path to be translated to a real path @return the real path, or null if the translation cannot be performed
[ "Gets", "the", "real", "path", "corresponding", "to", "the", "given", "virtual", "path", "from", "the", "given", "WebApplication", ".", "This", "method", "gets", "decorated", "the", "method", "of", "the", "{", "@link", "javax", ".", "servlet", ".", "ServletContext#getRealPath", "(", "String", ")", "}", "." ]
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/application/ApplicationExtensions.java#L150-L158
looly/hutool
hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java
ImgUtil.cut
public static BufferedImage cut(Image srcImage, Rectangle rectangle) { """ 图像切割(按指定起点坐标和宽高切割) @param srcImage 源图像 @param rectangle 矩形对象,表示矩形区域的x,y,width,height @return {@link BufferedImage} @since 3.1.0 """ return Img.from(srcImage).setPositionBaseCentre(false).cut(rectangle).getImg(); }
java
public static BufferedImage cut(Image srcImage, Rectangle rectangle) { return Img.from(srcImage).setPositionBaseCentre(false).cut(rectangle).getImg(); }
[ "public", "static", "BufferedImage", "cut", "(", "Image", "srcImage", ",", "Rectangle", "rectangle", ")", "{", "return", "Img", ".", "from", "(", "srcImage", ")", ".", "setPositionBaseCentre", "(", "false", ")", ".", "cut", "(", "rectangle", ")", ".", "getImg", "(", ")", ";", "}" ]
图像切割(按指定起点坐标和宽高切割) @param srcImage 源图像 @param rectangle 矩形对象,表示矩形区域的x,y,width,height @return {@link BufferedImage} @since 3.1.0
[ "图像切割", "(", "按指定起点坐标和宽高切割", ")" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L331-L333
joniles/mpxj
src/main/java/net/sf/mpxj/ResourceAssignment.java
ResourceAssignment.setDate
public void setDate(int index, Date value) { """ Set a date value. @param index date index (1-10) @param value date value """ set(selectField(AssignmentFieldLists.CUSTOM_DATE, index), value); }
java
public void setDate(int index, Date value) { set(selectField(AssignmentFieldLists.CUSTOM_DATE, index), value); }
[ "public", "void", "setDate", "(", "int", "index", ",", "Date", "value", ")", "{", "set", "(", "selectField", "(", "AssignmentFieldLists", ".", "CUSTOM_DATE", ",", "index", ")", ",", "value", ")", ";", "}" ]
Set a date value. @param index date index (1-10) @param value date value
[ "Set", "a", "date", "value", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ResourceAssignment.java#L1584-L1587
jamesagnew/hapi-fhir
hapi-fhir-structures-dstu/src/main/java/ca/uhn/fhir/rest/server/interceptor/AuditingInterceptor.java
AuditingInterceptor.makeObjectDetail
protected ObjectDetail makeObjectDetail(String type, String value) { """ Helper method to create an ObjectDetail from a pair of Strings. @param type the type of the ObjectDetail @param value the value of the ObejctDetail to be encoded @return an ObjectDetail of the given type and value """ ObjectDetail detail = new ObjectDetail(); if (type != null) detail.setType(type); if (value != null) detail.setValue(value.getBytes()); return detail; }
java
protected ObjectDetail makeObjectDetail(String type, String value) { ObjectDetail detail = new ObjectDetail(); if (type != null) detail.setType(type); if (value != null) detail.setValue(value.getBytes()); return detail; }
[ "protected", "ObjectDetail", "makeObjectDetail", "(", "String", "type", ",", "String", "value", ")", "{", "ObjectDetail", "detail", "=", "new", "ObjectDetail", "(", ")", ";", "if", "(", "type", "!=", "null", ")", "detail", ".", "setType", "(", "type", ")", ";", "if", "(", "value", "!=", "null", ")", "detail", ".", "setValue", "(", "value", ".", "getBytes", "(", ")", ")", ";", "return", "detail", ";", "}" ]
Helper method to create an ObjectDetail from a pair of Strings. @param type the type of the ObjectDetail @param value the value of the ObejctDetail to be encoded @return an ObjectDetail of the given type and value
[ "Helper", "method", "to", "create", "an", "ObjectDetail", "from", "a", "pair", "of", "Strings", "." ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-structures-dstu/src/main/java/ca/uhn/fhir/rest/server/interceptor/AuditingInterceptor.java#L332-L339
CloudSlang/score
worker/worker-execution/score-worker-execution-impl/src/main/java/io/cloudslang/worker/execution/services/ExecutionServiceImpl.java
ExecutionServiceImpl.handlePausedFlow
protected boolean handlePausedFlow(Execution execution) throws InterruptedException { """ check if the execution should be Paused, and pause it if needed """ String branchId = execution.getSystemContext().getBranchId(); PauseReason reason = findPauseReason(execution.getExecutionId(), branchId); if (reason != null) { // need to pause the execution pauseFlow(reason, execution); return true; } return false; }
java
protected boolean handlePausedFlow(Execution execution) throws InterruptedException { String branchId = execution.getSystemContext().getBranchId(); PauseReason reason = findPauseReason(execution.getExecutionId(), branchId); if (reason != null) { // need to pause the execution pauseFlow(reason, execution); return true; } return false; }
[ "protected", "boolean", "handlePausedFlow", "(", "Execution", "execution", ")", "throws", "InterruptedException", "{", "String", "branchId", "=", "execution", ".", "getSystemContext", "(", ")", ".", "getBranchId", "(", ")", ";", "PauseReason", "reason", "=", "findPauseReason", "(", "execution", ".", "getExecutionId", "(", ")", ",", "branchId", ")", ";", "if", "(", "reason", "!=", "null", ")", "{", "// need to pause the execution", "pauseFlow", "(", "reason", ",", "execution", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
check if the execution should be Paused, and pause it if needed
[ "check", "if", "the", "execution", "should", "be", "Paused", "and", "pause", "it", "if", "needed" ]
train
https://github.com/CloudSlang/score/blob/796134e917843f4d95a90f7740d69dc5257a1a0e/worker/worker-execution/score-worker-execution-impl/src/main/java/io/cloudslang/worker/execution/services/ExecutionServiceImpl.java#L270-L278
kurbatov/firmata4j
src/main/java/org/firmata4j/ssd1306/MonochromeCanvas.java
MonochromeCanvas.drawImage
public void drawImage(int x, int y, BufferedImage image, boolean opaque, boolean invert) { """ Draws an image. The image is grayscalled before drawing. @param x @param y @param image an image to draw @param opaque if true, 0 - bits is drawn in background color, if false - the color of corresponding pixel doesn't change @param invert true to make dark pixels of the image be drawn as bright pixels on screen """ drawBitmap(x, y, convertToBitmap(image, invert), opaque); }
java
public void drawImage(int x, int y, BufferedImage image, boolean opaque, boolean invert) { drawBitmap(x, y, convertToBitmap(image, invert), opaque); }
[ "public", "void", "drawImage", "(", "int", "x", ",", "int", "y", ",", "BufferedImage", "image", ",", "boolean", "opaque", ",", "boolean", "invert", ")", "{", "drawBitmap", "(", "x", ",", "y", ",", "convertToBitmap", "(", "image", ",", "invert", ")", ",", "opaque", ")", ";", "}" ]
Draws an image. The image is grayscalled before drawing. @param x @param y @param image an image to draw @param opaque if true, 0 - bits is drawn in background color, if false - the color of corresponding pixel doesn't change @param invert true to make dark pixels of the image be drawn as bright pixels on screen
[ "Draws", "an", "image", ".", "The", "image", "is", "grayscalled", "before", "drawing", "." ]
train
https://github.com/kurbatov/firmata4j/blob/1bf75cd7f4f8d11dc2a91cf2bc6808f583d9a4ea/src/main/java/org/firmata4j/ssd1306/MonochromeCanvas.java#L566-L568
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ObjectDataTypesInner.java
ObjectDataTypesInner.listFieldsByModuleAndTypeAsync
public Observable<List<TypeFieldInner>> listFieldsByModuleAndTypeAsync(String resourceGroupName, String automationAccountName, String moduleName, String typeName) { """ Retrieve a list of fields of a given type identified by module name. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param moduleName The name of module. @param typeName The name of type. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;TypeFieldInner&gt; object """ return listFieldsByModuleAndTypeWithServiceResponseAsync(resourceGroupName, automationAccountName, moduleName, typeName).map(new Func1<ServiceResponse<List<TypeFieldInner>>, List<TypeFieldInner>>() { @Override public List<TypeFieldInner> call(ServiceResponse<List<TypeFieldInner>> response) { return response.body(); } }); }
java
public Observable<List<TypeFieldInner>> listFieldsByModuleAndTypeAsync(String resourceGroupName, String automationAccountName, String moduleName, String typeName) { return listFieldsByModuleAndTypeWithServiceResponseAsync(resourceGroupName, automationAccountName, moduleName, typeName).map(new Func1<ServiceResponse<List<TypeFieldInner>>, List<TypeFieldInner>>() { @Override public List<TypeFieldInner> call(ServiceResponse<List<TypeFieldInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "TypeFieldInner", ">", ">", "listFieldsByModuleAndTypeAsync", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "moduleName", ",", "String", "typeName", ")", "{", "return", "listFieldsByModuleAndTypeWithServiceResponseAsync", "(", "resourceGroupName", ",", "automationAccountName", ",", "moduleName", ",", "typeName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "List", "<", "TypeFieldInner", ">", ">", ",", "List", "<", "TypeFieldInner", ">", ">", "(", ")", "{", "@", "Override", "public", "List", "<", "TypeFieldInner", ">", "call", "(", "ServiceResponse", "<", "List", "<", "TypeFieldInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Retrieve a list of fields of a given type identified by module name. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param moduleName The name of module. @param typeName The name of type. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;TypeFieldInner&gt; object
[ "Retrieve", "a", "list", "of", "fields", "of", "a", "given", "type", "identified", "by", "module", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ObjectDataTypesInner.java#L106-L113
netheosgithub/pcs_api
java/src/main/java/net/netheos/pcsapi/models/CUploadRequest.java
CUploadRequest.getByteSource
public ByteSource getByteSource() { """ If no progress listener has been set, return the byte source set in constructor, otherwise decorate it for progress. @return the byte source to be used for upload operation. """ ByteSource bs = byteSource; if ( progressListener != null ) { bs = new ProgressByteSource( bs, progressListener ); } return bs; }
java
public ByteSource getByteSource() { ByteSource bs = byteSource; if ( progressListener != null ) { bs = new ProgressByteSource( bs, progressListener ); } return bs; }
[ "public", "ByteSource", "getByteSource", "(", ")", "{", "ByteSource", "bs", "=", "byteSource", ";", "if", "(", "progressListener", "!=", "null", ")", "{", "bs", "=", "new", "ProgressByteSource", "(", "bs", ",", "progressListener", ")", ";", "}", "return", "bs", ";", "}" ]
If no progress listener has been set, return the byte source set in constructor, otherwise decorate it for progress. @return the byte source to be used for upload operation.
[ "If", "no", "progress", "listener", "has", "been", "set", "return", "the", "byte", "source", "set", "in", "constructor", "otherwise", "decorate", "it", "for", "progress", "." ]
train
https://github.com/netheosgithub/pcs_api/blob/20691e52e144014f99ca75cb7dedc7ba0c18586c/java/src/main/java/net/netheos/pcsapi/models/CUploadRequest.java#L114-L121
tvesalainen/util
vfs/src/main/java/org/vesalainen/vfs/Env.java
Env.getFileFormat
public static final FileFormat getFileFormat(Path path, Map<String, ?> env) { """ Returns FileFormat either from env or using default value which is TAR_GNU for tar and CPIO_CRC for others. @param path @param env @return """ FileFormat fmt = (FileFormat) env.get(FORMAT); String filename = path.getFileName().toString(); if (fmt == null) { if (filename.endsWith(".tar.gz") || filename.endsWith(".tar") || filename.endsWith(".deb")) { fmt = TAR_GNU; } else { fmt = CPIO_CRC; } } return fmt; }
java
public static final FileFormat getFileFormat(Path path, Map<String, ?> env) { FileFormat fmt = (FileFormat) env.get(FORMAT); String filename = path.getFileName().toString(); if (fmt == null) { if (filename.endsWith(".tar.gz") || filename.endsWith(".tar") || filename.endsWith(".deb")) { fmt = TAR_GNU; } else { fmt = CPIO_CRC; } } return fmt; }
[ "public", "static", "final", "FileFormat", "getFileFormat", "(", "Path", "path", ",", "Map", "<", "String", ",", "?", ">", "env", ")", "{", "FileFormat", "fmt", "=", "(", "FileFormat", ")", "env", ".", "get", "(", "FORMAT", ")", ";", "String", "filename", "=", "path", ".", "getFileName", "(", ")", ".", "toString", "(", ")", ";", "if", "(", "fmt", "==", "null", ")", "{", "if", "(", "filename", ".", "endsWith", "(", "\".tar.gz\"", ")", "||", "filename", ".", "endsWith", "(", "\".tar\"", ")", "||", "filename", ".", "endsWith", "(", "\".deb\"", ")", ")", "{", "fmt", "=", "TAR_GNU", ";", "}", "else", "{", "fmt", "=", "CPIO_CRC", ";", "}", "}", "return", "fmt", ";", "}" ]
Returns FileFormat either from env or using default value which is TAR_GNU for tar and CPIO_CRC for others. @param path @param env @return
[ "Returns", "FileFormat", "either", "from", "env", "or", "using", "default", "value", "which", "is", "TAR_GNU", "for", "tar", "and", "CPIO_CRC", "for", "others", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/vfs/src/main/java/org/vesalainen/vfs/Env.java#L81-L97
cesarferreira/AndroidQuickUtils
library/src/main/java/quickutils/core/categories/date.java
date.getDayAsString
public static String getDayAsString(int day, String format) { """ Gets a date with a desired format as a String @param day Can be: <li>QuickUtils.date.YESTERDAY</li><li> QuickUtils.date.TODAY</li><li>QuickUtils.date.TOMORROW</li> @param format desired format (e.g. "yyyy-MM-dd HH:mm:ss") @return returns a day with the given format """ SimpleDateFormat simpleFormat = new SimpleDateFormat(format); return simpleFormat.format(getDayAsDate(day)); }
java
public static String getDayAsString(int day, String format) { SimpleDateFormat simpleFormat = new SimpleDateFormat(format); return simpleFormat.format(getDayAsDate(day)); }
[ "public", "static", "String", "getDayAsString", "(", "int", "day", ",", "String", "format", ")", "{", "SimpleDateFormat", "simpleFormat", "=", "new", "SimpleDateFormat", "(", "format", ")", ";", "return", "simpleFormat", ".", "format", "(", "getDayAsDate", "(", "day", ")", ")", ";", "}" ]
Gets a date with a desired format as a String @param day Can be: <li>QuickUtils.date.YESTERDAY</li><li> QuickUtils.date.TODAY</li><li>QuickUtils.date.TOMORROW</li> @param format desired format (e.g. "yyyy-MM-dd HH:mm:ss") @return returns a day with the given format
[ "Gets", "a", "date", "with", "a", "desired", "format", "as", "a", "String" ]
train
https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/categories/date.java#L87-L90
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpSubsystemChannel.java
SftpSubsystemChannel.renameFile
public void renameFile(String oldpath, String newpath) throws SftpStatusException, SshException { """ Rename an existing file. @param oldpath @param newpath @throws SftpStatusException , SshException """ if (version < 2) { throw new SftpStatusException( SftpStatusException.SSH_FX_OP_UNSUPPORTED, "Renaming files is not supported by the server SFTP version " + String.valueOf(version)); } try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_RENAME); msg.writeInt(requestId.longValue()); msg.writeString(oldpath, CHARSET_ENCODING); msg.writeString(newpath, CHARSET_ENCODING); sendMessage(msg); getOKRequestStatus(requestId); } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } EventServiceImplementation .getInstance() .fireEvent( (new Event(this, J2SSHEventCodes.EVENT_SFTP_FILE_RENAMED, true)) .addAttribute( J2SSHEventCodes.ATTRIBUTE_FILE_NAME, oldpath) .addAttribute( J2SSHEventCodes.ATTRIBUTE_FILE_NEW_NAME, newpath)); }
java
public void renameFile(String oldpath, String newpath) throws SftpStatusException, SshException { if (version < 2) { throw new SftpStatusException( SftpStatusException.SSH_FX_OP_UNSUPPORTED, "Renaming files is not supported by the server SFTP version " + String.valueOf(version)); } try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_RENAME); msg.writeInt(requestId.longValue()); msg.writeString(oldpath, CHARSET_ENCODING); msg.writeString(newpath, CHARSET_ENCODING); sendMessage(msg); getOKRequestStatus(requestId); } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } EventServiceImplementation .getInstance() .fireEvent( (new Event(this, J2SSHEventCodes.EVENT_SFTP_FILE_RENAMED, true)) .addAttribute( J2SSHEventCodes.ATTRIBUTE_FILE_NAME, oldpath) .addAttribute( J2SSHEventCodes.ATTRIBUTE_FILE_NEW_NAME, newpath)); }
[ "public", "void", "renameFile", "(", "String", "oldpath", ",", "String", "newpath", ")", "throws", "SftpStatusException", ",", "SshException", "{", "if", "(", "version", "<", "2", ")", "{", "throw", "new", "SftpStatusException", "(", "SftpStatusException", ".", "SSH_FX_OP_UNSUPPORTED", ",", "\"Renaming files is not supported by the server SFTP version \"", "+", "String", ".", "valueOf", "(", "version", ")", ")", ";", "}", "try", "{", "UnsignedInteger32", "requestId", "=", "nextRequestId", "(", ")", ";", "Packet", "msg", "=", "createPacket", "(", ")", ";", "msg", ".", "write", "(", "SSH_FXP_RENAME", ")", ";", "msg", ".", "writeInt", "(", "requestId", ".", "longValue", "(", ")", ")", ";", "msg", ".", "writeString", "(", "oldpath", ",", "CHARSET_ENCODING", ")", ";", "msg", ".", "writeString", "(", "newpath", ",", "CHARSET_ENCODING", ")", ";", "sendMessage", "(", "msg", ")", ";", "getOKRequestStatus", "(", "requestId", ")", ";", "}", "catch", "(", "SshIOException", "ex", ")", "{", "throw", "ex", ".", "getRealException", "(", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "SshException", "(", "ex", ")", ";", "}", "EventServiceImplementation", ".", "getInstance", "(", ")", ".", "fireEvent", "(", "(", "new", "Event", "(", "this", ",", "J2SSHEventCodes", ".", "EVENT_SFTP_FILE_RENAMED", ",", "true", ")", ")", ".", "addAttribute", "(", "J2SSHEventCodes", ".", "ATTRIBUTE_FILE_NAME", ",", "oldpath", ")", ".", "addAttribute", "(", "J2SSHEventCodes", ".", "ATTRIBUTE_FILE_NEW_NAME", ",", "newpath", ")", ")", ";", "}" ]
Rename an existing file. @param oldpath @param newpath @throws SftpStatusException , SshException
[ "Rename", "an", "existing", "file", "." ]
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpSubsystemChannel.java#L1742-L1778
jive/pnky-promise
src/main/java/com/jive/foss/pnky/Pnky.java
Pnky.composeAsync
public static <V> PnkyPromise<V> composeAsync(final ThrowingSupplier<PnkyPromise<V>> operation, final Executor executor) { """ Creates a new {@link PnkyPromise future} that completes when the future returned by the supplied operation completes, executing the operation on the supplied executor. If the operation completes normally, the returned future completes with the result of the future returned by the function. If the operation throws an exception, the returned future completes exceptionally with the thrown exception. @param operation the operation to perform @param executor the executor to process the operation on @return a new {@link PnkyPromise future} """ final Pnky<V> pnky = Pnky.create(); executor.execute(new Runnable() { @Override public void run() { if (pnky.state.compareAndSet(WAITING, RUNNING)) { try { operation.get().alwaysAccept(new ThrowingBiConsumer<V, Throwable>() { @Override public void accept(final V result, final Throwable error) throws Throwable { if (error != null) { pnky.reject(error); } else { pnky.resolve(result); } } }); } catch (final Throwable e) { pnky.reject(e); } } } }); return pnky; }
java
public static <V> PnkyPromise<V> composeAsync(final ThrowingSupplier<PnkyPromise<V>> operation, final Executor executor) { final Pnky<V> pnky = Pnky.create(); executor.execute(new Runnable() { @Override public void run() { if (pnky.state.compareAndSet(WAITING, RUNNING)) { try { operation.get().alwaysAccept(new ThrowingBiConsumer<V, Throwable>() { @Override public void accept(final V result, final Throwable error) throws Throwable { if (error != null) { pnky.reject(error); } else { pnky.resolve(result); } } }); } catch (final Throwable e) { pnky.reject(e); } } } }); return pnky; }
[ "public", "static", "<", "V", ">", "PnkyPromise", "<", "V", ">", "composeAsync", "(", "final", "ThrowingSupplier", "<", "PnkyPromise", "<", "V", ">", ">", "operation", ",", "final", "Executor", "executor", ")", "{", "final", "Pnky", "<", "V", ">", "pnky", "=", "Pnky", ".", "create", "(", ")", ";", "executor", ".", "execute", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "pnky", ".", "state", ".", "compareAndSet", "(", "WAITING", ",", "RUNNING", ")", ")", "{", "try", "{", "operation", ".", "get", "(", ")", ".", "alwaysAccept", "(", "new", "ThrowingBiConsumer", "<", "V", ",", "Throwable", ">", "(", ")", "{", "@", "Override", "public", "void", "accept", "(", "final", "V", "result", ",", "final", "Throwable", "error", ")", "throws", "Throwable", "{", "if", "(", "error", "!=", "null", ")", "{", "pnky", ".", "reject", "(", "error", ")", ";", "}", "else", "{", "pnky", ".", "resolve", "(", "result", ")", ";", "}", "}", "}", ")", ";", "}", "catch", "(", "final", "Throwable", "e", ")", "{", "pnky", ".", "reject", "(", "e", ")", ";", "}", "}", "}", "}", ")", ";", "return", "pnky", ";", "}" ]
Creates a new {@link PnkyPromise future} that completes when the future returned by the supplied operation completes, executing the operation on the supplied executor. If the operation completes normally, the returned future completes with the result of the future returned by the function. If the operation throws an exception, the returned future completes exceptionally with the thrown exception. @param operation the operation to perform @param executor the executor to process the operation on @return a new {@link PnkyPromise future}
[ "Creates", "a", "new", "{", "@link", "PnkyPromise", "future", "}", "that", "completes", "when", "the", "future", "returned", "by", "the", "supplied", "operation", "completes", "executing", "the", "operation", "on", "the", "supplied", "executor", ".", "If", "the", "operation", "completes", "normally", "the", "returned", "future", "completes", "with", "the", "result", "of", "the", "future", "returned", "by", "the", "function", ".", "If", "the", "operation", "throws", "an", "exception", "the", "returned", "future", "completes", "exceptionally", "with", "the", "thrown", "exception", "." ]
train
https://github.com/jive/pnky-promise/blob/07ec2f0a8bdf7b53420b8c4f6644b0659c874e10/src/main/java/com/jive/foss/pnky/Pnky.java#L783-L822
joniles/mpxj
src/main/java/net/sf/mpxj/json/JsonWriter.java
JsonWriter.writeRelationList
private void writeRelationList(String fieldName, Object value) throws IOException { """ Write a relation list field to the JSON file. @param fieldName field name @param value field value """ @SuppressWarnings("unchecked") List<Relation> list = (List<Relation>) value; if (!list.isEmpty()) { m_writer.writeStartList(fieldName); for (Relation relation : list) { m_writer.writeStartObject(null); writeIntegerField("task_unique_id", relation.getTargetTask().getUniqueID()); writeDurationField("lag", relation.getLag()); writeStringField("type", relation.getType()); m_writer.writeEndObject(); } m_writer.writeEndList(); } }
java
private void writeRelationList(String fieldName, Object value) throws IOException { @SuppressWarnings("unchecked") List<Relation> list = (List<Relation>) value; if (!list.isEmpty()) { m_writer.writeStartList(fieldName); for (Relation relation : list) { m_writer.writeStartObject(null); writeIntegerField("task_unique_id", relation.getTargetTask().getUniqueID()); writeDurationField("lag", relation.getLag()); writeStringField("type", relation.getType()); m_writer.writeEndObject(); } m_writer.writeEndList(); } }
[ "private", "void", "writeRelationList", "(", "String", "fieldName", ",", "Object", "value", ")", "throws", "IOException", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "List", "<", "Relation", ">", "list", "=", "(", "List", "<", "Relation", ">", ")", "value", ";", "if", "(", "!", "list", ".", "isEmpty", "(", ")", ")", "{", "m_writer", ".", "writeStartList", "(", "fieldName", ")", ";", "for", "(", "Relation", "relation", ":", "list", ")", "{", "m_writer", ".", "writeStartObject", "(", "null", ")", ";", "writeIntegerField", "(", "\"task_unique_id\"", ",", "relation", ".", "getTargetTask", "(", ")", ".", "getUniqueID", "(", ")", ")", ";", "writeDurationField", "(", "\"lag\"", ",", "relation", ".", "getLag", "(", ")", ")", ";", "writeStringField", "(", "\"type\"", ",", "relation", ".", "getType", "(", ")", ")", ";", "m_writer", ".", "writeEndObject", "(", ")", ";", "}", "m_writer", ".", "writeEndList", "(", ")", ";", "}", "}" ]
Write a relation list field to the JSON file. @param fieldName field name @param value field value
[ "Write", "a", "relation", "list", "field", "to", "the", "JSON", "file", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/json/JsonWriter.java#L527-L544
groupon/monsoon
remote_history/src/main/java/com/groupon/monsoon/remote/history/AbstractServer.java
AbstractServer.newTscStream
private static stream_response newTscStream(Stream<TimeSeriesCollection> tsc, int fetch) { """ Create a new TimeSeriesCollection iterator from the given stream. """ final BufferedIterator<TimeSeriesCollection> iter = new BufferedIterator(tsc.iterator(), TSC_QUEUE_SIZE); final long idx = TSC_ITERS_ALLOC.getAndIncrement(); final IteratorAndCookie<TimeSeriesCollection> iterAndCookie = new IteratorAndCookie<>(iter); TSC_ITERS.put(idx, iterAndCookie); final List<TimeSeriesCollection> result = fetchFromIter(iter, fetch, MAX_TSC_FETCH); EncDec.NewIterResponse<TimeSeriesCollection> responseObj = new EncDec.NewIterResponse<>(idx, result, iter.atEnd(), iterAndCookie.getCookie()); LOG.log(Level.FINE, "responseObj = {0}", responseObj); return EncDec.encodeStreamResponse(responseObj); }
java
private static stream_response newTscStream(Stream<TimeSeriesCollection> tsc, int fetch) { final BufferedIterator<TimeSeriesCollection> iter = new BufferedIterator(tsc.iterator(), TSC_QUEUE_SIZE); final long idx = TSC_ITERS_ALLOC.getAndIncrement(); final IteratorAndCookie<TimeSeriesCollection> iterAndCookie = new IteratorAndCookie<>(iter); TSC_ITERS.put(idx, iterAndCookie); final List<TimeSeriesCollection> result = fetchFromIter(iter, fetch, MAX_TSC_FETCH); EncDec.NewIterResponse<TimeSeriesCollection> responseObj = new EncDec.NewIterResponse<>(idx, result, iter.atEnd(), iterAndCookie.getCookie()); LOG.log(Level.FINE, "responseObj = {0}", responseObj); return EncDec.encodeStreamResponse(responseObj); }
[ "private", "static", "stream_response", "newTscStream", "(", "Stream", "<", "TimeSeriesCollection", ">", "tsc", ",", "int", "fetch", ")", "{", "final", "BufferedIterator", "<", "TimeSeriesCollection", ">", "iter", "=", "new", "BufferedIterator", "(", "tsc", ".", "iterator", "(", ")", ",", "TSC_QUEUE_SIZE", ")", ";", "final", "long", "idx", "=", "TSC_ITERS_ALLOC", ".", "getAndIncrement", "(", ")", ";", "final", "IteratorAndCookie", "<", "TimeSeriesCollection", ">", "iterAndCookie", "=", "new", "IteratorAndCookie", "<>", "(", "iter", ")", ";", "TSC_ITERS", ".", "put", "(", "idx", ",", "iterAndCookie", ")", ";", "final", "List", "<", "TimeSeriesCollection", ">", "result", "=", "fetchFromIter", "(", "iter", ",", "fetch", ",", "MAX_TSC_FETCH", ")", ";", "EncDec", ".", "NewIterResponse", "<", "TimeSeriesCollection", ">", "responseObj", "=", "new", "EncDec", ".", "NewIterResponse", "<>", "(", "idx", ",", "result", ",", "iter", ".", "atEnd", "(", ")", ",", "iterAndCookie", ".", "getCookie", "(", ")", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"responseObj = {0}\"", ",", "responseObj", ")", ";", "return", "EncDec", ".", "encodeStreamResponse", "(", "responseObj", ")", ";", "}" ]
Create a new TimeSeriesCollection iterator from the given stream.
[ "Create", "a", "new", "TimeSeriesCollection", "iterator", "from", "the", "given", "stream", "." ]
train
https://github.com/groupon/monsoon/blob/eb68d72ba4c01fe018dc981097dbee033908f5c7/remote_history/src/main/java/com/groupon/monsoon/remote/history/AbstractServer.java#L167-L178
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/cfg/CompositeProcessEnginePlugin.java
CompositeProcessEnginePlugin.addProcessEnginePlugin
public CompositeProcessEnginePlugin addProcessEnginePlugin(ProcessEnginePlugin plugin, ProcessEnginePlugin... additionalPlugins) { """ Add one (or more) plugins. @param plugin first plugin @param additionalPlugins additional vararg plugins @return self for fluent usage """ return this.addProcessEnginePlugins(toList(plugin, additionalPlugins)); }
java
public CompositeProcessEnginePlugin addProcessEnginePlugin(ProcessEnginePlugin plugin, ProcessEnginePlugin... additionalPlugins) { return this.addProcessEnginePlugins(toList(plugin, additionalPlugins)); }
[ "public", "CompositeProcessEnginePlugin", "addProcessEnginePlugin", "(", "ProcessEnginePlugin", "plugin", ",", "ProcessEnginePlugin", "...", "additionalPlugins", ")", "{", "return", "this", ".", "addProcessEnginePlugins", "(", "toList", "(", "plugin", ",", "additionalPlugins", ")", ")", ";", "}" ]
Add one (or more) plugins. @param plugin first plugin @param additionalPlugins additional vararg plugins @return self for fluent usage
[ "Add", "one", "(", "or", "more", ")", "plugins", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/cfg/CompositeProcessEnginePlugin.java#L72-L74
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/AcroFields.java
AcroFields.regenerateField
public boolean regenerateField(String name) throws IOException, DocumentException { """ Regenerates the field appearance. This is useful when you change a field property, but not its value, for instance form.setFieldProperty("f", "bgcolor", Color.BLUE, null); This won't have any effect, unless you use regenerateField("f") after changing the property. @param name the fully qualified field name or the partial name in the case of XFA forms @throws IOException on error @throws DocumentException on error @return <CODE>true</CODE> if the field was found and changed, <CODE>false</CODE> otherwise """ String value = getField(name); return setField(name, value, value); }
java
public boolean regenerateField(String name) throws IOException, DocumentException { String value = getField(name); return setField(name, value, value); }
[ "public", "boolean", "regenerateField", "(", "String", "name", ")", "throws", "IOException", ",", "DocumentException", "{", "String", "value", "=", "getField", "(", "name", ")", ";", "return", "setField", "(", "name", ",", "value", ",", "value", ")", ";", "}" ]
Regenerates the field appearance. This is useful when you change a field property, but not its value, for instance form.setFieldProperty("f", "bgcolor", Color.BLUE, null); This won't have any effect, unless you use regenerateField("f") after changing the property. @param name the fully qualified field name or the partial name in the case of XFA forms @throws IOException on error @throws DocumentException on error @return <CODE>true</CODE> if the field was found and changed, <CODE>false</CODE> otherwise
[ "Regenerates", "the", "field", "appearance", ".", "This", "is", "useful", "when", "you", "change", "a", "field", "property", "but", "not", "its", "value", "for", "instance", "form", ".", "setFieldProperty", "(", "f", "bgcolor", "Color", ".", "BLUE", "null", ")", ";", "This", "won", "t", "have", "any", "effect", "unless", "you", "use", "regenerateField", "(", "f", ")", "after", "changing", "the", "property", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/AcroFields.java#L1263-L1266
watchrabbit/rabbit-commons
src/main/java/com/watchrabbit/commons/sleep/Sleep.java
Sleep.untilTrue
public static Boolean untilTrue(Callable<Boolean> callable, long timeout, TimeUnit unit) throws SystemException { """ Causes the current thread to wait until the callable is returning {@code true}, or the specified waiting time elapses. <p> If the callable returns {@code false} then this method returns immediately with the value returned by callable. <p> Any {@code InterruptedException}'s are suppress and logged. Any {@code Exception}'s thrown by callable are propagate as SystemException @param callable callable checked by this method @param timeout the maximum time to wait @param unit the time unit of the {@code timeout} argument @return {@code Boolean} returned by callable method @throws SystemException if callable throws exception """ return SleepBuilder.<Boolean>sleep() .withComparer(argument -> argument) .withTimeout(timeout, unit) .withStatement(callable) .build(); }
java
public static Boolean untilTrue(Callable<Boolean> callable, long timeout, TimeUnit unit) throws SystemException { return SleepBuilder.<Boolean>sleep() .withComparer(argument -> argument) .withTimeout(timeout, unit) .withStatement(callable) .build(); }
[ "public", "static", "Boolean", "untilTrue", "(", "Callable", "<", "Boolean", ">", "callable", ",", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "SystemException", "{", "return", "SleepBuilder", ".", "<", "Boolean", ">", "sleep", "(", ")", ".", "withComparer", "(", "argument", "->", "argument", ")", ".", "withTimeout", "(", "timeout", ",", "unit", ")", ".", "withStatement", "(", "callable", ")", ".", "build", "(", ")", ";", "}" ]
Causes the current thread to wait until the callable is returning {@code true}, or the specified waiting time elapses. <p> If the callable returns {@code false} then this method returns immediately with the value returned by callable. <p> Any {@code InterruptedException}'s are suppress and logged. Any {@code Exception}'s thrown by callable are propagate as SystemException @param callable callable checked by this method @param timeout the maximum time to wait @param unit the time unit of the {@code timeout} argument @return {@code Boolean} returned by callable method @throws SystemException if callable throws exception
[ "Causes", "the", "current", "thread", "to", "wait", "until", "the", "callable", "is", "returning", "{", "@code", "true", "}", "or", "the", "specified", "waiting", "time", "elapses", "." ]
train
https://github.com/watchrabbit/rabbit-commons/blob/b11c9f804b5ab70b9264635c34a02f5029bd2a5d/src/main/java/com/watchrabbit/commons/sleep/Sleep.java#L65-L71
jenkinsci/jenkins
core/src/main/java/hudson/tools/ToolLocationNodeProperty.java
ToolLocationNodeProperty.getToolHome
@Deprecated public static String getToolHome(Node node, ToolInstallation installation, TaskListener log) throws IOException, InterruptedException { """ Checks if the location of the tool is overridden for the given node, and if so, return the node-specific home directory. Otherwise return {@code installation.getHome()} <p> This is the core logic behind {@link NodeSpecific#forNode(Node, TaskListener)} for {@link ToolInstallation}. @return never null. @deprecated since 2009-04-09. Use {@link ToolInstallation#translateFor(Node,TaskListener)} """ String result = null; // node-specific configuration takes precedence ToolLocationNodeProperty property = node.getNodeProperties().get(ToolLocationNodeProperty.class); if (property != null) { result = property.getHome(installation); } if (result != null) { return result; } // consult translators for (ToolLocationTranslator t : ToolLocationTranslator.all()) { result = t.getToolHome(node, installation, log); if (result != null) { return result; } } // fall back is no-op return installation.getHome(); }
java
@Deprecated public static String getToolHome(Node node, ToolInstallation installation, TaskListener log) throws IOException, InterruptedException { String result = null; // node-specific configuration takes precedence ToolLocationNodeProperty property = node.getNodeProperties().get(ToolLocationNodeProperty.class); if (property != null) { result = property.getHome(installation); } if (result != null) { return result; } // consult translators for (ToolLocationTranslator t : ToolLocationTranslator.all()) { result = t.getToolHome(node, installation, log); if (result != null) { return result; } } // fall back is no-op return installation.getHome(); }
[ "@", "Deprecated", "public", "static", "String", "getToolHome", "(", "Node", "node", ",", "ToolInstallation", "installation", ",", "TaskListener", "log", ")", "throws", "IOException", ",", "InterruptedException", "{", "String", "result", "=", "null", ";", "// node-specific configuration takes precedence", "ToolLocationNodeProperty", "property", "=", "node", ".", "getNodeProperties", "(", ")", ".", "get", "(", "ToolLocationNodeProperty", ".", "class", ")", ";", "if", "(", "property", "!=", "null", ")", "{", "result", "=", "property", ".", "getHome", "(", "installation", ")", ";", "}", "if", "(", "result", "!=", "null", ")", "{", "return", "result", ";", "}", "// consult translators", "for", "(", "ToolLocationTranslator", "t", ":", "ToolLocationTranslator", ".", "all", "(", ")", ")", "{", "result", "=", "t", ".", "getToolHome", "(", "node", ",", "installation", ",", "log", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "return", "result", ";", "}", "}", "// fall back is no-op", "return", "installation", ".", "getHome", "(", ")", ";", "}" ]
Checks if the location of the tool is overridden for the given node, and if so, return the node-specific home directory. Otherwise return {@code installation.getHome()} <p> This is the core logic behind {@link NodeSpecific#forNode(Node, TaskListener)} for {@link ToolInstallation}. @return never null. @deprecated since 2009-04-09. Use {@link ToolInstallation#translateFor(Node,TaskListener)}
[ "Checks", "if", "the", "location", "of", "the", "tool", "is", "overridden", "for", "the", "given", "node", "and", "if", "so", "return", "the", "node", "-", "specific", "home", "directory", ".", "Otherwise", "return", "{", "@code", "installation", ".", "getHome", "()", "}" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/tools/ToolLocationNodeProperty.java#L94-L117
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/IntrospectionUtils.java
IntrospectionUtils.getWriteMethodName
public static String getWriteMethodName(Field field, String prefix) { """ Returns the name of the method that can be used to write (or set) the given field. @param field the name of the field @param prefix the prefix for the write method (e.g. set, with, etc.). @return the name of the write method. """ return prefix == null ? field.getName() : (prefix + getCapitalizedName(field.getName())); }
java
public static String getWriteMethodName(Field field, String prefix) { return prefix == null ? field.getName() : (prefix + getCapitalizedName(field.getName())); }
[ "public", "static", "String", "getWriteMethodName", "(", "Field", "field", ",", "String", "prefix", ")", "{", "return", "prefix", "==", "null", "?", "field", ".", "getName", "(", ")", ":", "(", "prefix", "+", "getCapitalizedName", "(", "field", ".", "getName", "(", ")", ")", ")", ";", "}" ]
Returns the name of the method that can be used to write (or set) the given field. @param field the name of the field @param prefix the prefix for the write method (e.g. set, with, etc.). @return the name of the write method.
[ "Returns", "the", "name", "of", "the", "method", "that", "can", "be", "used", "to", "write", "(", "or", "set", ")", "the", "given", "field", "." ]
train
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/IntrospectionUtils.java#L230-L233
jpelzer/pelzer-util
src/main/java/com/pelzer/util/PropertyManager.java
PropertyManager.getLocalizedProperty
public synchronized static String getLocalizedProperty(final String namespace, final String key, final String defaultValue) { """ Allows retrieval of localized properties set up for SPECIFIC hosts. Calling getLocalizedProperty("foo.bar.BLAH") on the machine 'wintermute' is equivilant to doing getProperty("WINTERMUTE.foo.bar.BLAH"). Machine names are always uppercase, and never have sub-domains (ie WINTERMUTE and not WINTERMUTE.PELZER.COM) """ if (namespace == null || namespace.equals("")) return getProperty("", hostname + "." + key, defaultValue); return getProperty(hostname + "." + namespace, key, defaultValue); }
java
public synchronized static String getLocalizedProperty(final String namespace, final String key, final String defaultValue) { if (namespace == null || namespace.equals("")) return getProperty("", hostname + "." + key, defaultValue); return getProperty(hostname + "." + namespace, key, defaultValue); }
[ "public", "synchronized", "static", "String", "getLocalizedProperty", "(", "final", "String", "namespace", ",", "final", "String", "key", ",", "final", "String", "defaultValue", ")", "{", "if", "(", "namespace", "==", "null", "||", "namespace", ".", "equals", "(", "\"\"", ")", ")", "return", "getProperty", "(", "\"\"", ",", "hostname", "+", "\".\"", "+", "key", ",", "defaultValue", ")", ";", "return", "getProperty", "(", "hostname", "+", "\".\"", "+", "namespace", ",", "key", ",", "defaultValue", ")", ";", "}" ]
Allows retrieval of localized properties set up for SPECIFIC hosts. Calling getLocalizedProperty("foo.bar.BLAH") on the machine 'wintermute' is equivilant to doing getProperty("WINTERMUTE.foo.bar.BLAH"). Machine names are always uppercase, and never have sub-domains (ie WINTERMUTE and not WINTERMUTE.PELZER.COM)
[ "Allows", "retrieval", "of", "localized", "properties", "set", "up", "for", "SPECIFIC", "hosts", ".", "Calling", "getLocalizedProperty", "(", "foo", ".", "bar", ".", "BLAH", ")", "on", "the", "machine", "wintermute", "is", "equivilant", "to", "doing", "getProperty", "(", "WINTERMUTE", ".", "foo", ".", "bar", ".", "BLAH", ")", ".", "Machine", "names", "are", "always", "uppercase", "and", "never", "have", "sub", "-", "domains", "(", "ie", "WINTERMUTE", "and", "not", "WINTERMUTE", ".", "PELZER", ".", "COM", ")" ]
train
https://github.com/jpelzer/pelzer-util/blob/ec14f2573fd977d1442dba5d1507a264f5ea9aa6/src/main/java/com/pelzer/util/PropertyManager.java#L117-L121
calrissian/mango
mango-core/src/main/java/org/calrissian/mango/net/IPv6.java
IPv6.cidrRange
public static Range<IPv6> cidrRange(String cidr) { """ Parses the provided CIDR string and produces a closed {@link Range} encapsulating all IPv6 addresses between the network and broadcast addresses in the subnet represented by the CIDR. """ try { MoreInetAddresses.CidrInfo cidrInfo = parseCIDR(cidr); if (cidrInfo.getNetwork() instanceof Inet6Address && cidrInfo.getBroadcast() instanceof Inet6Address) { return closed(new IPv6((Inet6Address) cidrInfo.getNetwork()), new IPv6((Inet6Address) cidrInfo.getBroadcast())); } } catch (Exception ignored) {} throw new IllegalArgumentException(format("Invalid IPv6 cidr representation %s", cidr)); }
java
public static Range<IPv6> cidrRange(String cidr) { try { MoreInetAddresses.CidrInfo cidrInfo = parseCIDR(cidr); if (cidrInfo.getNetwork() instanceof Inet6Address && cidrInfo.getBroadcast() instanceof Inet6Address) { return closed(new IPv6((Inet6Address) cidrInfo.getNetwork()), new IPv6((Inet6Address) cidrInfo.getBroadcast())); } } catch (Exception ignored) {} throw new IllegalArgumentException(format("Invalid IPv6 cidr representation %s", cidr)); }
[ "public", "static", "Range", "<", "IPv6", ">", "cidrRange", "(", "String", "cidr", ")", "{", "try", "{", "MoreInetAddresses", ".", "CidrInfo", "cidrInfo", "=", "parseCIDR", "(", "cidr", ")", ";", "if", "(", "cidrInfo", ".", "getNetwork", "(", ")", "instanceof", "Inet6Address", "&&", "cidrInfo", ".", "getBroadcast", "(", ")", "instanceof", "Inet6Address", ")", "{", "return", "closed", "(", "new", "IPv6", "(", "(", "Inet6Address", ")", "cidrInfo", ".", "getNetwork", "(", ")", ")", ",", "new", "IPv6", "(", "(", "Inet6Address", ")", "cidrInfo", ".", "getBroadcast", "(", ")", ")", ")", ";", "}", "}", "catch", "(", "Exception", "ignored", ")", "{", "}", "throw", "new", "IllegalArgumentException", "(", "format", "(", "\"Invalid IPv6 cidr representation %s\"", ",", "cidr", ")", ")", ";", "}" ]
Parses the provided CIDR string and produces a closed {@link Range} encapsulating all IPv6 addresses between the network and broadcast addresses in the subnet represented by the CIDR.
[ "Parses", "the", "provided", "CIDR", "string", "and", "produces", "a", "closed", "{" ]
train
https://github.com/calrissian/mango/blob/a95aa5e77af9aa0e629787228d80806560023452/mango-core/src/main/java/org/calrissian/mango/net/IPv6.java#L63-L76
jcuda/jcufft
JCufftJava/src/main/java/jcuda/jcufft/cufftHandle.java
cufftHandle.setSize
void setSize(int x, int y, int z) { """ Set the size of this plan @param x Size in x @param y Size in y @param z Size in z """ this.sizeX = x; this.sizeY = y; this.sizeZ = z; }
java
void setSize(int x, int y, int z) { this.sizeX = x; this.sizeY = y; this.sizeZ = z; }
[ "void", "setSize", "(", "int", "x", ",", "int", "y", ",", "int", "z", ")", "{", "this", ".", "sizeX", "=", "x", ";", "this", ".", "sizeY", "=", "y", ";", "this", ".", "sizeZ", "=", "z", ";", "}" ]
Set the size of this plan @param x Size in x @param y Size in y @param z Size in z
[ "Set", "the", "size", "of", "this", "plan" ]
train
https://github.com/jcuda/jcufft/blob/833c87ffb0864f7ee7270fddef8af57f48939b3a/JCufftJava/src/main/java/jcuda/jcufft/cufftHandle.java#L137-L142
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Database.java
Database.setPermissions
public void setPermissions(String userNameorApikey, EnumSet<Permissions> permissions) { """ Set permissions for a user/apiKey on this database. <p> Note this method is only applicable to databases that support the <a target="_blank" href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#authorization"> Cloudant authorization API </a> such as Cloudant DBaaS. For unsupported databases consider using the /db/_security endpoint. </p> <p>Example usage to set read-only access for a new key on the "example" database:</p> <pre> {@code // generate an API key ApiKey key = client.generateApiKey(); // get the "example" database Database db = client.database("example", false); // set read-only permissions db.setPermissions(key.getKey(), EnumSet.<Permissions>of(Permissions._reader)); } </pre> @param userNameorApikey the user or key to apply permissions to @param permissions permissions to grant @throws UnsupportedOperationException if called on a database that does not provide the Cloudant authorization API @see CloudantClient#generateApiKey() @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#roles" target="_blank">Roles</a> @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#modifying-permissions" target="_blank">Modifying permissions</a> """ assertNotEmpty(userNameorApikey, "userNameorApikey"); assertNotEmpty(permissions, "permissions"); final JsonArray jsonPermissions = new JsonArray(); for (Permissions s : permissions) { final JsonPrimitive permission = new JsonPrimitive(s.toString()); jsonPermissions.add(permission); } // get existing permissions JsonObject perms = getPermissionsObject(); // now set back JsonElement elem = perms.get("cloudant"); if (elem == null) { perms.addProperty("_id", "_security"); elem = new JsonObject(); perms.add("cloudant", elem); } elem.getAsJsonObject().add(userNameorApikey, jsonPermissions); HttpConnection put = Http.PUT(apiV2DBSecurityURI, "application/json"); put.setRequestBody(client.getGson().toJson(perms)); // CouchDbExceptions will be thrown for non-2XX cases client.couchDbClient.executeToResponse(put); }
java
public void setPermissions(String userNameorApikey, EnumSet<Permissions> permissions) { assertNotEmpty(userNameorApikey, "userNameorApikey"); assertNotEmpty(permissions, "permissions"); final JsonArray jsonPermissions = new JsonArray(); for (Permissions s : permissions) { final JsonPrimitive permission = new JsonPrimitive(s.toString()); jsonPermissions.add(permission); } // get existing permissions JsonObject perms = getPermissionsObject(); // now set back JsonElement elem = perms.get("cloudant"); if (elem == null) { perms.addProperty("_id", "_security"); elem = new JsonObject(); perms.add("cloudant", elem); } elem.getAsJsonObject().add(userNameorApikey, jsonPermissions); HttpConnection put = Http.PUT(apiV2DBSecurityURI, "application/json"); put.setRequestBody(client.getGson().toJson(perms)); // CouchDbExceptions will be thrown for non-2XX cases client.couchDbClient.executeToResponse(put); }
[ "public", "void", "setPermissions", "(", "String", "userNameorApikey", ",", "EnumSet", "<", "Permissions", ">", "permissions", ")", "{", "assertNotEmpty", "(", "userNameorApikey", ",", "\"userNameorApikey\"", ")", ";", "assertNotEmpty", "(", "permissions", ",", "\"permissions\"", ")", ";", "final", "JsonArray", "jsonPermissions", "=", "new", "JsonArray", "(", ")", ";", "for", "(", "Permissions", "s", ":", "permissions", ")", "{", "final", "JsonPrimitive", "permission", "=", "new", "JsonPrimitive", "(", "s", ".", "toString", "(", ")", ")", ";", "jsonPermissions", ".", "add", "(", "permission", ")", ";", "}", "// get existing permissions", "JsonObject", "perms", "=", "getPermissionsObject", "(", ")", ";", "// now set back", "JsonElement", "elem", "=", "perms", ".", "get", "(", "\"cloudant\"", ")", ";", "if", "(", "elem", "==", "null", ")", "{", "perms", ".", "addProperty", "(", "\"_id\"", ",", "\"_security\"", ")", ";", "elem", "=", "new", "JsonObject", "(", ")", ";", "perms", ".", "add", "(", "\"cloudant\"", ",", "elem", ")", ";", "}", "elem", ".", "getAsJsonObject", "(", ")", ".", "add", "(", "userNameorApikey", ",", "jsonPermissions", ")", ";", "HttpConnection", "put", "=", "Http", ".", "PUT", "(", "apiV2DBSecurityURI", ",", "\"application/json\"", ")", ";", "put", ".", "setRequestBody", "(", "client", ".", "getGson", "(", ")", ".", "toJson", "(", "perms", ")", ")", ";", "// CouchDbExceptions will be thrown for non-2XX cases", "client", ".", "couchDbClient", ".", "executeToResponse", "(", "put", ")", ";", "}" ]
Set permissions for a user/apiKey on this database. <p> Note this method is only applicable to databases that support the <a target="_blank" href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#authorization"> Cloudant authorization API </a> such as Cloudant DBaaS. For unsupported databases consider using the /db/_security endpoint. </p> <p>Example usage to set read-only access for a new key on the "example" database:</p> <pre> {@code // generate an API key ApiKey key = client.generateApiKey(); // get the "example" database Database db = client.database("example", false); // set read-only permissions db.setPermissions(key.getKey(), EnumSet.<Permissions>of(Permissions._reader)); } </pre> @param userNameorApikey the user or key to apply permissions to @param permissions permissions to grant @throws UnsupportedOperationException if called on a database that does not provide the Cloudant authorization API @see CloudantClient#generateApiKey() @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#roles" target="_blank">Roles</a> @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#modifying-permissions" target="_blank">Modifying permissions</a>
[ "Set", "permissions", "for", "a", "user", "/", "apiKey", "on", "this", "database", ".", "<p", ">", "Note", "this", "method", "is", "only", "applicable", "to", "databases", "that", "support", "the", "<a", "target", "=", "_blank", "href", "=", "https", ":", "//", "console", ".", "bluemix", ".", "net", "/", "docs", "/", "services", "/", "Cloudant", "/", "api", "/", "authorization", ".", "html#authorization", ">", "Cloudant", "authorization", "API", "<", "/", "a", ">", "such", "as", "Cloudant", "DBaaS", ".", "For", "unsupported", "databases", "consider", "using", "the", "/", "db", "/", "_security", "endpoint", ".", "<", "/", "p", ">", "<p", ">", "Example", "usage", "to", "set", "read", "-", "only", "access", "for", "a", "new", "key", "on", "the", "example", "database", ":", "<", "/", "p", ">", "<pre", ">", "{", "@code", "//", "generate", "an", "API", "key", "ApiKey", "key", "=", "client", ".", "generateApiKey", "()", ";" ]
train
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Database.java#L160-L185
deeplearning4j/deeplearning4j
datavec/datavec-spark/src/main/java/org/datavec/spark/transform/AnalyzeSpark.java
AnalyzeSpark.analyzeQuality
public static DataQualityAnalysis analyzeQuality(final Schema schema, final JavaRDD<List<Writable>> data) { """ Analyze the data quality of data - provides a report on missing values, values that don't comply with schema, etc @param schema Schema for data @param data Data to analyze @return DataQualityAnalysis object """ int nColumns = schema.numColumns(); List<QualityAnalysisState> states = data.aggregate(null, new BiFunctionAdapter<>(new QualityAnalysisAddFunction(schema)), new BiFunctionAdapter<>(new QualityAnalysisCombineFunction())); List<ColumnQuality> list = new ArrayList<>(nColumns); for (QualityAnalysisState qualityState : states) { list.add(qualityState.getColumnQuality()); } return new DataQualityAnalysis(schema, list); }
java
public static DataQualityAnalysis analyzeQuality(final Schema schema, final JavaRDD<List<Writable>> data) { int nColumns = schema.numColumns(); List<QualityAnalysisState> states = data.aggregate(null, new BiFunctionAdapter<>(new QualityAnalysisAddFunction(schema)), new BiFunctionAdapter<>(new QualityAnalysisCombineFunction())); List<ColumnQuality> list = new ArrayList<>(nColumns); for (QualityAnalysisState qualityState : states) { list.add(qualityState.getColumnQuality()); } return new DataQualityAnalysis(schema, list); }
[ "public", "static", "DataQualityAnalysis", "analyzeQuality", "(", "final", "Schema", "schema", ",", "final", "JavaRDD", "<", "List", "<", "Writable", ">", ">", "data", ")", "{", "int", "nColumns", "=", "schema", ".", "numColumns", "(", ")", ";", "List", "<", "QualityAnalysisState", ">", "states", "=", "data", ".", "aggregate", "(", "null", ",", "new", "BiFunctionAdapter", "<>", "(", "new", "QualityAnalysisAddFunction", "(", "schema", ")", ")", ",", "new", "BiFunctionAdapter", "<>", "(", "new", "QualityAnalysisCombineFunction", "(", ")", ")", ")", ";", "List", "<", "ColumnQuality", ">", "list", "=", "new", "ArrayList", "<>", "(", "nColumns", ")", ";", "for", "(", "QualityAnalysisState", "qualityState", ":", "states", ")", "{", "list", ".", "add", "(", "qualityState", ".", "getColumnQuality", "(", ")", ")", ";", "}", "return", "new", "DataQualityAnalysis", "(", "schema", ",", "list", ")", ";", "}" ]
Analyze the data quality of data - provides a report on missing values, values that don't comply with schema, etc @param schema Schema for data @param data Data to analyze @return DataQualityAnalysis object
[ "Analyze", "the", "data", "quality", "of", "data", "-", "provides", "a", "report", "on", "missing", "values", "values", "that", "don", "t", "comply", "with", "schema", "etc" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-spark/src/main/java/org/datavec/spark/transform/AnalyzeSpark.java#L288-L300
OpenLiberty/open-liberty
dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/BatchUpdateDaemon.java
BatchUpdateDaemon.pushCacheEntry
public synchronized void pushCacheEntry(CacheEntry cacheEntry, DCache cache) { """ This allows a cache entry to be added to the BatchUpdateDaemon. The cache entry will be added to all caches. @param cacheEntry The cache entry to be added. """ BatchUpdateList bul = getUpdateList(cache); bul.pushCacheEntryEvents.add(cacheEntry); }
java
public synchronized void pushCacheEntry(CacheEntry cacheEntry, DCache cache) { BatchUpdateList bul = getUpdateList(cache); bul.pushCacheEntryEvents.add(cacheEntry); }
[ "public", "synchronized", "void", "pushCacheEntry", "(", "CacheEntry", "cacheEntry", ",", "DCache", "cache", ")", "{", "BatchUpdateList", "bul", "=", "getUpdateList", "(", "cache", ")", ";", "bul", ".", "pushCacheEntryEvents", ".", "add", "(", "cacheEntry", ")", ";", "}" ]
This allows a cache entry to be added to the BatchUpdateDaemon. The cache entry will be added to all caches. @param cacheEntry The cache entry to be added.
[ "This", "allows", "a", "cache", "entry", "to", "be", "added", "to", "the", "BatchUpdateDaemon", ".", "The", "cache", "entry", "will", "be", "added", "to", "all", "caches", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/BatchUpdateDaemon.java#L191-L194
cdk/cdk
display/renderbasic/src/main/java/org/openscience/cdk/renderer/AbstractRenderer.java
AbstractRenderer.setupTransformToFit
void setupTransformToFit(Rectangle2D screenBounds, Rectangle2D modelBounds, boolean reset) { """ Sets the transformation needed to draw the model on the canvas when the diagram needs to fit the screen. @param screenBounds the bounding box of the draw area @param modelBounds the bounding box of the model @param reset if true, model center will be set to the modelBounds center and the scale will be re-calculated """ double scale = rendererModel.getParameter(Scale.class).getValue(); if (screenBounds == null) return; setDrawCenter(screenBounds.getCenterX(), screenBounds.getCenterY()); double drawWidth = screenBounds.getWidth(); double drawHeight = screenBounds.getHeight(); double diagramWidth = modelBounds.getWidth() * scale; double diagramHeight = modelBounds.getHeight() * scale; setZoomToFit(drawWidth, drawHeight, diagramWidth, diagramHeight); // this controls whether editing a molecule causes it to re-center // with each change or not if (reset || rendererModel.getParameter(FitToScreen.class).getValue()) { setModelCenter(modelBounds.getCenterX(), modelBounds.getCenterY()); } setup(); }
java
void setupTransformToFit(Rectangle2D screenBounds, Rectangle2D modelBounds, boolean reset) { double scale = rendererModel.getParameter(Scale.class).getValue(); if (screenBounds == null) return; setDrawCenter(screenBounds.getCenterX(), screenBounds.getCenterY()); double drawWidth = screenBounds.getWidth(); double drawHeight = screenBounds.getHeight(); double diagramWidth = modelBounds.getWidth() * scale; double diagramHeight = modelBounds.getHeight() * scale; setZoomToFit(drawWidth, drawHeight, diagramWidth, diagramHeight); // this controls whether editing a molecule causes it to re-center // with each change or not if (reset || rendererModel.getParameter(FitToScreen.class).getValue()) { setModelCenter(modelBounds.getCenterX(), modelBounds.getCenterY()); } setup(); }
[ "void", "setupTransformToFit", "(", "Rectangle2D", "screenBounds", ",", "Rectangle2D", "modelBounds", ",", "boolean", "reset", ")", "{", "double", "scale", "=", "rendererModel", ".", "getParameter", "(", "Scale", ".", "class", ")", ".", "getValue", "(", ")", ";", "if", "(", "screenBounds", "==", "null", ")", "return", ";", "setDrawCenter", "(", "screenBounds", ".", "getCenterX", "(", ")", ",", "screenBounds", ".", "getCenterY", "(", ")", ")", ";", "double", "drawWidth", "=", "screenBounds", ".", "getWidth", "(", ")", ";", "double", "drawHeight", "=", "screenBounds", ".", "getHeight", "(", ")", ";", "double", "diagramWidth", "=", "modelBounds", ".", "getWidth", "(", ")", "*", "scale", ";", "double", "diagramHeight", "=", "modelBounds", ".", "getHeight", "(", ")", "*", "scale", ";", "setZoomToFit", "(", "drawWidth", ",", "drawHeight", ",", "diagramWidth", ",", "diagramHeight", ")", ";", "// this controls whether editing a molecule causes it to re-center", "// with each change or not", "if", "(", "reset", "||", "rendererModel", ".", "getParameter", "(", "FitToScreen", ".", "class", ")", ".", "getValue", "(", ")", ")", "{", "setModelCenter", "(", "modelBounds", ".", "getCenterX", "(", ")", ",", "modelBounds", ".", "getCenterY", "(", ")", ")", ";", "}", "setup", "(", ")", ";", "}" ]
Sets the transformation needed to draw the model on the canvas when the diagram needs to fit the screen. @param screenBounds the bounding box of the draw area @param modelBounds the bounding box of the model @param reset if true, model center will be set to the modelBounds center and the scale will be re-calculated
[ "Sets", "the", "transformation", "needed", "to", "draw", "the", "model", "on", "the", "canvas", "when", "the", "diagram", "needs", "to", "fit", "the", "screen", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/display/renderbasic/src/main/java/org/openscience/cdk/renderer/AbstractRenderer.java#L448-L471
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworksInner.java
VirtualNetworksInner.createOrUpdateAsync
public Observable<VirtualNetworkInner> createOrUpdateAsync(String resourceGroupName, String virtualNetworkName, VirtualNetworkInner parameters) { """ Creates or updates a virtual network in the specified resource group. @param resourceGroupName The name of the resource group. @param virtualNetworkName The name of the virtual network. @param parameters Parameters supplied to the create or update virtual network operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, virtualNetworkName, parameters).map(new Func1<ServiceResponse<VirtualNetworkInner>, VirtualNetworkInner>() { @Override public VirtualNetworkInner call(ServiceResponse<VirtualNetworkInner> response) { return response.body(); } }); }
java
public Observable<VirtualNetworkInner> createOrUpdateAsync(String resourceGroupName, String virtualNetworkName, VirtualNetworkInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, virtualNetworkName, parameters).map(new Func1<ServiceResponse<VirtualNetworkInner>, VirtualNetworkInner>() { @Override public VirtualNetworkInner call(ServiceResponse<VirtualNetworkInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VirtualNetworkInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkName", ",", "VirtualNetworkInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "VirtualNetworkInner", ">", ",", "VirtualNetworkInner", ">", "(", ")", "{", "@", "Override", "public", "VirtualNetworkInner", "call", "(", "ServiceResponse", "<", "VirtualNetworkInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Creates or updates a virtual network in the specified resource group. @param resourceGroupName The name of the resource group. @param virtualNetworkName The name of the virtual network. @param parameters Parameters supplied to the create or update virtual network operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Creates", "or", "updates", "a", "virtual", "network", "in", "the", "specified", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworksInner.java#L483-L490
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.rotationZYX
public Matrix4f rotationZYX(float angleZ, float angleY, float angleX) { """ Set this matrix to a rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation of <code>angleY</code> radians about the Y axis and followed by a rotation of <code>angleX</code> radians about the X axis. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> This method is equivalent to calling: <code>rotationZ(angleZ).rotateY(angleY).rotateX(angleX)</code> @param angleZ the angle to rotate about Z @param angleY the angle to rotate about Y @param angleX the angle to rotate about X @return this """ float sinX = (float) Math.sin(angleX); float cosX = (float) Math.cosFromSin(sinX, angleX); float sinY = (float) Math.sin(angleY); float cosY = (float) Math.cosFromSin(sinY, angleY); float sinZ = (float) Math.sin(angleZ); float cosZ = (float) Math.cosFromSin(sinZ, angleZ); float m_sinZ = -sinZ; float m_sinY = -sinY; float m_sinX = -sinX; // rotateZ float nm00 = cosZ; float nm01 = sinZ; float nm10 = m_sinZ; float nm11 = cosZ; // rotateY float nm20 = nm00 * sinY; float nm21 = nm01 * sinY; float nm22 = cosY; this._m00(nm00 * cosY); this._m01(nm01 * cosY); this._m02(m_sinY); this._m03(0.0f); // rotateX this._m10(nm10 * cosX + nm20 * sinX); this._m11(nm11 * cosX + nm21 * sinX); this._m12(nm22 * sinX); this._m13(0.0f); this._m20(nm10 * m_sinX + nm20 * cosX); this._m21(nm11 * m_sinX + nm21 * cosX); this._m22(nm22 * cosX); this._m23(0.0f); // set last column to identity this._m30(0.0f); this._m31(0.0f); this._m32(0.0f); this._m33(1.0f); _properties(PROPERTY_AFFINE | PROPERTY_ORTHONORMAL); return this; }
java
public Matrix4f rotationZYX(float angleZ, float angleY, float angleX) { float sinX = (float) Math.sin(angleX); float cosX = (float) Math.cosFromSin(sinX, angleX); float sinY = (float) Math.sin(angleY); float cosY = (float) Math.cosFromSin(sinY, angleY); float sinZ = (float) Math.sin(angleZ); float cosZ = (float) Math.cosFromSin(sinZ, angleZ); float m_sinZ = -sinZ; float m_sinY = -sinY; float m_sinX = -sinX; // rotateZ float nm00 = cosZ; float nm01 = sinZ; float nm10 = m_sinZ; float nm11 = cosZ; // rotateY float nm20 = nm00 * sinY; float nm21 = nm01 * sinY; float nm22 = cosY; this._m00(nm00 * cosY); this._m01(nm01 * cosY); this._m02(m_sinY); this._m03(0.0f); // rotateX this._m10(nm10 * cosX + nm20 * sinX); this._m11(nm11 * cosX + nm21 * sinX); this._m12(nm22 * sinX); this._m13(0.0f); this._m20(nm10 * m_sinX + nm20 * cosX); this._m21(nm11 * m_sinX + nm21 * cosX); this._m22(nm22 * cosX); this._m23(0.0f); // set last column to identity this._m30(0.0f); this._m31(0.0f); this._m32(0.0f); this._m33(1.0f); _properties(PROPERTY_AFFINE | PROPERTY_ORTHONORMAL); return this; }
[ "public", "Matrix4f", "rotationZYX", "(", "float", "angleZ", ",", "float", "angleY", ",", "float", "angleX", ")", "{", "float", "sinX", "=", "(", "float", ")", "Math", ".", "sin", "(", "angleX", ")", ";", "float", "cosX", "=", "(", "float", ")", "Math", ".", "cosFromSin", "(", "sinX", ",", "angleX", ")", ";", "float", "sinY", "=", "(", "float", ")", "Math", ".", "sin", "(", "angleY", ")", ";", "float", "cosY", "=", "(", "float", ")", "Math", ".", "cosFromSin", "(", "sinY", ",", "angleY", ")", ";", "float", "sinZ", "=", "(", "float", ")", "Math", ".", "sin", "(", "angleZ", ")", ";", "float", "cosZ", "=", "(", "float", ")", "Math", ".", "cosFromSin", "(", "sinZ", ",", "angleZ", ")", ";", "float", "m_sinZ", "=", "-", "sinZ", ";", "float", "m_sinY", "=", "-", "sinY", ";", "float", "m_sinX", "=", "-", "sinX", ";", "// rotateZ", "float", "nm00", "=", "cosZ", ";", "float", "nm01", "=", "sinZ", ";", "float", "nm10", "=", "m_sinZ", ";", "float", "nm11", "=", "cosZ", ";", "// rotateY", "float", "nm20", "=", "nm00", "*", "sinY", ";", "float", "nm21", "=", "nm01", "*", "sinY", ";", "float", "nm22", "=", "cosY", ";", "this", ".", "_m00", "(", "nm00", "*", "cosY", ")", ";", "this", ".", "_m01", "(", "nm01", "*", "cosY", ")", ";", "this", ".", "_m02", "(", "m_sinY", ")", ";", "this", ".", "_m03", "(", "0.0f", ")", ";", "// rotateX", "this", ".", "_m10", "(", "nm10", "*", "cosX", "+", "nm20", "*", "sinX", ")", ";", "this", ".", "_m11", "(", "nm11", "*", "cosX", "+", "nm21", "*", "sinX", ")", ";", "this", ".", "_m12", "(", "nm22", "*", "sinX", ")", ";", "this", ".", "_m13", "(", "0.0f", ")", ";", "this", ".", "_m20", "(", "nm10", "*", "m_sinX", "+", "nm20", "*", "cosX", ")", ";", "this", ".", "_m21", "(", "nm11", "*", "m_sinX", "+", "nm21", "*", "cosX", ")", ";", "this", ".", "_m22", "(", "nm22", "*", "cosX", ")", ";", "this", ".", "_m23", "(", "0.0f", ")", ";", "// set last column to identity", "this", ".", "_m30", "(", "0.0f", ")", ";", "this", ".", "_m31", "(", "0.0f", ")", ";", "this", ".", "_m32", "(", "0.0f", ")", ";", "this", ".", "_m33", "(", "1.0f", ")", ";", "_properties", "(", "PROPERTY_AFFINE", "|", "PROPERTY_ORTHONORMAL", ")", ";", "return", "this", ";", "}" ]
Set this matrix to a rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation of <code>angleY</code> radians about the Y axis and followed by a rotation of <code>angleX</code> radians about the X axis. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> This method is equivalent to calling: <code>rotationZ(angleZ).rotateY(angleY).rotateX(angleX)</code> @param angleZ the angle to rotate about Z @param angleY the angle to rotate about Y @param angleX the angle to rotate about X @return this
[ "Set", "this", "matrix", "to", "a", "rotation", "of", "<code", ">", "angleZ<", "/", "code", ">", "radians", "about", "the", "Z", "axis", "followed", "by", "a", "rotation", "of", "<code", ">", "angleY<", "/", "code", ">", "radians", "about", "the", "Y", "axis", "and", "followed", "by", "a", "rotation", "of", "<code", ">", "angleX<", "/", "code", ">", "radians", "about", "the", "X", "axis", ".", "<p", ">", "When", "used", "with", "a", "right", "-", "handed", "coordinate", "system", "the", "produced", "rotation", "will", "rotate", "a", "vector", "counter", "-", "clockwise", "around", "the", "rotation", "axis", "when", "viewing", "along", "the", "negative", "axis", "direction", "towards", "the", "origin", ".", "When", "used", "with", "a", "left", "-", "handed", "coordinate", "system", "the", "rotation", "is", "clockwise", ".", "<p", ">", "This", "method", "is", "equivalent", "to", "calling", ":", "<code", ">", "rotationZ", "(", "angleZ", ")", ".", "rotateY", "(", "angleY", ")", ".", "rotateX", "(", "angleX", ")", "<", "/", "code", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L3664-L3704
dyu/protostuff-1.0.x
protostuff-me/src/main/java/com/dyuproject/protostuff/me/IOUtil.java
IOUtil.mergeDelimitedFrom
static int mergeDelimitedFrom(DataInput in, Object message, Schema schema, boolean decodeNestedMessageAsGroup) throws IOException { """ Used by the code generated messages that implement {@link java.io.Externalizable}. Merges from the {@link DataInput}. """ final byte size = in.readByte(); final int len = 0 == (size & 0x80) ? size : CodedInput.readRawVarint32(in, size); if(len < 0) throw ProtobufException.negativeSize(); if(len != 0) { // not an empty message if(len > CodedInput.DEFAULT_BUFFER_SIZE && in instanceof InputStream) { // message too big final CodedInput input = new CodedInput(new LimitedInputStream((InputStream)in, len), decodeNestedMessageAsGroup); schema.mergeFrom(input, message); input.checkLastTagWas(0); } else { final byte[] buf = new byte[len]; in.readFully(buf, 0, len); final ByteArrayInput input = new ByteArrayInput(buf, 0, len, decodeNestedMessageAsGroup); try { schema.mergeFrom(input, message); } catch(ArrayIndexOutOfBoundsException e) { throw ProtobufException.truncatedMessage(e); } input.checkLastTagWas(0); } } // check it since this message is embedded in the DataInput. if(!schema.isInitialized(message)) throw new UninitializedMessageException(message, schema); return len; }
java
static int mergeDelimitedFrom(DataInput in, Object message, Schema schema, boolean decodeNestedMessageAsGroup) throws IOException { final byte size = in.readByte(); final int len = 0 == (size & 0x80) ? size : CodedInput.readRawVarint32(in, size); if(len < 0) throw ProtobufException.negativeSize(); if(len != 0) { // not an empty message if(len > CodedInput.DEFAULT_BUFFER_SIZE && in instanceof InputStream) { // message too big final CodedInput input = new CodedInput(new LimitedInputStream((InputStream)in, len), decodeNestedMessageAsGroup); schema.mergeFrom(input, message); input.checkLastTagWas(0); } else { final byte[] buf = new byte[len]; in.readFully(buf, 0, len); final ByteArrayInput input = new ByteArrayInput(buf, 0, len, decodeNestedMessageAsGroup); try { schema.mergeFrom(input, message); } catch(ArrayIndexOutOfBoundsException e) { throw ProtobufException.truncatedMessage(e); } input.checkLastTagWas(0); } } // check it since this message is embedded in the DataInput. if(!schema.isInitialized(message)) throw new UninitializedMessageException(message, schema); return len; }
[ "static", "int", "mergeDelimitedFrom", "(", "DataInput", "in", ",", "Object", "message", ",", "Schema", "schema", ",", "boolean", "decodeNestedMessageAsGroup", ")", "throws", "IOException", "{", "final", "byte", "size", "=", "in", ".", "readByte", "(", ")", ";", "final", "int", "len", "=", "0", "==", "(", "size", "&", "0x80", ")", "?", "size", ":", "CodedInput", ".", "readRawVarint32", "(", "in", ",", "size", ")", ";", "if", "(", "len", "<", "0", ")", "throw", "ProtobufException", ".", "negativeSize", "(", ")", ";", "if", "(", "len", "!=", "0", ")", "{", "// not an empty message\r", "if", "(", "len", ">", "CodedInput", ".", "DEFAULT_BUFFER_SIZE", "&&", "in", "instanceof", "InputStream", ")", "{", "// message too big\r", "final", "CodedInput", "input", "=", "new", "CodedInput", "(", "new", "LimitedInputStream", "(", "(", "InputStream", ")", "in", ",", "len", ")", ",", "decodeNestedMessageAsGroup", ")", ";", "schema", ".", "mergeFrom", "(", "input", ",", "message", ")", ";", "input", ".", "checkLastTagWas", "(", "0", ")", ";", "}", "else", "{", "final", "byte", "[", "]", "buf", "=", "new", "byte", "[", "len", "]", ";", "in", ".", "readFully", "(", "buf", ",", "0", ",", "len", ")", ";", "final", "ByteArrayInput", "input", "=", "new", "ByteArrayInput", "(", "buf", ",", "0", ",", "len", ",", "decodeNestedMessageAsGroup", ")", ";", "try", "{", "schema", ".", "mergeFrom", "(", "input", ",", "message", ")", ";", "}", "catch", "(", "ArrayIndexOutOfBoundsException", "e", ")", "{", "throw", "ProtobufException", ".", "truncatedMessage", "(", "e", ")", ";", "}", "input", ".", "checkLastTagWas", "(", "0", ")", ";", "}", "}", "// check it since this message is embedded in the DataInput.\r", "if", "(", "!", "schema", ".", "isInitialized", "(", "message", ")", ")", "throw", "new", "UninitializedMessageException", "(", "message", ",", "schema", ")", ";", "return", "len", ";", "}" ]
Used by the code generated messages that implement {@link java.io.Externalizable}. Merges from the {@link DataInput}.
[ "Used", "by", "the", "code", "generated", "messages", "that", "implement", "{" ]
train
https://github.com/dyu/protostuff-1.0.x/blob/d7c964ec20da3fe44699d86ee95c2677ddffde96/protostuff-me/src/main/java/com/dyuproject/protostuff/me/IOUtil.java#L175-L218
tzaeschke/zoodb
src/org/zoodb/internal/util/ReflTools.java
ReflTools.getInt
public static int getInt(Object obj, String fieldName) { """ Read the value of the field <tt>fieldName</tt> of object <tt>obj</tt>. @param obj The object @param fieldName The field name @return the value of the field. """ try { return getField(obj.getClass(), fieldName).getInt(obj); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
java
public static int getInt(Object obj, String fieldName) { try { return getField(obj.getClass(), fieldName).getInt(obj); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
[ "public", "static", "int", "getInt", "(", "Object", "obj", ",", "String", "fieldName", ")", "{", "try", "{", "return", "getField", "(", "obj", ".", "getClass", "(", ")", ",", "fieldName", ")", ".", "getInt", "(", "obj", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Read the value of the field <tt>fieldName</tt> of object <tt>obj</tt>. @param obj The object @param fieldName The field name @return the value of the field.
[ "Read", "the", "value", "of", "the", "field", "<tt", ">", "fieldName<", "/", "tt", ">", "of", "object", "<tt", ">", "obj<", "/", "tt", ">", "." ]
train
https://github.com/tzaeschke/zoodb/blob/058d0ff161a8ee9d53244c433aca97ee9c654410/src/org/zoodb/internal/util/ReflTools.java#L137-L145
spring-projects/spring-boot
spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java
InitializrService.loadServiceCapabilities
public Object loadServiceCapabilities(String serviceUrl) throws IOException { """ Loads the service capabilities of the service at the specified URL. If the service supports generating a textual representation of the capabilities, it is returned, otherwise {@link InitializrServiceMetadata} is returned. @param serviceUrl to url of the initializer service @return the service capabilities (as a String) or the {@link InitializrServiceMetadata} describing the service @throws IOException if the service capabilities cannot be loaded """ HttpGet request = new HttpGet(serviceUrl); request.setHeader( new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES)); CloseableHttpResponse httpResponse = execute(request, serviceUrl, "retrieve help"); validateResponse(httpResponse, serviceUrl); HttpEntity httpEntity = httpResponse.getEntity(); ContentType contentType = ContentType.getOrDefault(httpEntity); if (contentType.getMimeType().equals("text/plain")) { return getContent(httpEntity); } return parseJsonMetadata(httpEntity); }
java
public Object loadServiceCapabilities(String serviceUrl) throws IOException { HttpGet request = new HttpGet(serviceUrl); request.setHeader( new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES)); CloseableHttpResponse httpResponse = execute(request, serviceUrl, "retrieve help"); validateResponse(httpResponse, serviceUrl); HttpEntity httpEntity = httpResponse.getEntity(); ContentType contentType = ContentType.getOrDefault(httpEntity); if (contentType.getMimeType().equals("text/plain")) { return getContent(httpEntity); } return parseJsonMetadata(httpEntity); }
[ "public", "Object", "loadServiceCapabilities", "(", "String", "serviceUrl", ")", "throws", "IOException", "{", "HttpGet", "request", "=", "new", "HttpGet", "(", "serviceUrl", ")", ";", "request", ".", "setHeader", "(", "new", "BasicHeader", "(", "HttpHeaders", ".", "ACCEPT", ",", "ACCEPT_SERVICE_CAPABILITIES", ")", ")", ";", "CloseableHttpResponse", "httpResponse", "=", "execute", "(", "request", ",", "serviceUrl", ",", "\"retrieve help\"", ")", ";", "validateResponse", "(", "httpResponse", ",", "serviceUrl", ")", ";", "HttpEntity", "httpEntity", "=", "httpResponse", ".", "getEntity", "(", ")", ";", "ContentType", "contentType", "=", "ContentType", ".", "getOrDefault", "(", "httpEntity", ")", ";", "if", "(", "contentType", ".", "getMimeType", "(", ")", ".", "equals", "(", "\"text/plain\"", ")", ")", "{", "return", "getContent", "(", "httpEntity", ")", ";", "}", "return", "parseJsonMetadata", "(", "httpEntity", ")", ";", "}" ]
Loads the service capabilities of the service at the specified URL. If the service supports generating a textual representation of the capabilities, it is returned, otherwise {@link InitializrServiceMetadata} is returned. @param serviceUrl to url of the initializer service @return the service capabilities (as a String) or the {@link InitializrServiceMetadata} describing the service @throws IOException if the service capabilities cannot be loaded
[ "Loads", "the", "service", "capabilities", "of", "the", "service", "at", "the", "specified", "URL", ".", "If", "the", "service", "supports", "generating", "a", "textual", "representation", "of", "the", "capabilities", "it", "is", "returned", "otherwise", "{" ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java#L122-L135
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/factory/filter/binary/FactoryThresholdBinary.java
FactoryThresholdBinary.localOtsu
public static <T extends ImageGray<T>> InputToBinary<T> localOtsu(ConfigLength regionWidth, double scale, boolean down, boolean otsu2, double tuning, Class<T> inputType) { """ Applies a local Otsu threshold @see ThresholdLocalOtsu @param regionWidth About how wide and tall you wish a block to be in pixels. @param scale Scale factor adjust for threshold. 1.0 means no change. @param down Should it threshold up or down. @param tuning Tuning parameter. 0 = standard Otsu. Greater than 0 will penalize zero texture. @param inputType Type of input image @return Filter to binary """ if( BOverrideFactoryThresholdBinary.localOtsu != null ) return BOverrideFactoryThresholdBinary.localOtsu.handle(otsu2,regionWidth, tuning, scale, down, inputType); ThresholdLocalOtsu otsu; if(BoofConcurrency.USE_CONCURRENT ) { otsu = new ThresholdLocalOtsu_MT(otsu2, regionWidth, tuning, scale, down); } else { otsu = new ThresholdLocalOtsu(otsu2, regionWidth, tuning, scale, down); } return new InputToBinarySwitch<>(otsu, inputType); }
java
public static <T extends ImageGray<T>> InputToBinary<T> localOtsu(ConfigLength regionWidth, double scale, boolean down, boolean otsu2, double tuning, Class<T> inputType) { if( BOverrideFactoryThresholdBinary.localOtsu != null ) return BOverrideFactoryThresholdBinary.localOtsu.handle(otsu2,regionWidth, tuning, scale, down, inputType); ThresholdLocalOtsu otsu; if(BoofConcurrency.USE_CONCURRENT ) { otsu = new ThresholdLocalOtsu_MT(otsu2, regionWidth, tuning, scale, down); } else { otsu = new ThresholdLocalOtsu(otsu2, regionWidth, tuning, scale, down); } return new InputToBinarySwitch<>(otsu, inputType); }
[ "public", "static", "<", "T", "extends", "ImageGray", "<", "T", ">", ">", "InputToBinary", "<", "T", ">", "localOtsu", "(", "ConfigLength", "regionWidth", ",", "double", "scale", ",", "boolean", "down", ",", "boolean", "otsu2", ",", "double", "tuning", ",", "Class", "<", "T", ">", "inputType", ")", "{", "if", "(", "BOverrideFactoryThresholdBinary", ".", "localOtsu", "!=", "null", ")", "return", "BOverrideFactoryThresholdBinary", ".", "localOtsu", ".", "handle", "(", "otsu2", ",", "regionWidth", ",", "tuning", ",", "scale", ",", "down", ",", "inputType", ")", ";", "ThresholdLocalOtsu", "otsu", ";", "if", "(", "BoofConcurrency", ".", "USE_CONCURRENT", ")", "{", "otsu", "=", "new", "ThresholdLocalOtsu_MT", "(", "otsu2", ",", "regionWidth", ",", "tuning", ",", "scale", ",", "down", ")", ";", "}", "else", "{", "otsu", "=", "new", "ThresholdLocalOtsu", "(", "otsu2", ",", "regionWidth", ",", "tuning", ",", "scale", ",", "down", ")", ";", "}", "return", "new", "InputToBinarySwitch", "<>", "(", "otsu", ",", "inputType", ")", ";", "}" ]
Applies a local Otsu threshold @see ThresholdLocalOtsu @param regionWidth About how wide and tall you wish a block to be in pixels. @param scale Scale factor adjust for threshold. 1.0 means no change. @param down Should it threshold up or down. @param tuning Tuning parameter. 0 = standard Otsu. Greater than 0 will penalize zero texture. @param inputType Type of input image @return Filter to binary
[ "Applies", "a", "local", "Otsu", "threshold" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/factory/filter/binary/FactoryThresholdBinary.java#L128-L140
haraldk/TwelveMonkeys
imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickDrawContext.java
QuickDrawContext.fillRoundRect
public void fillRoundRect(final Rectangle2D pRectangle, int pArcW, int pArcH, Pattern pPattern) { """ FillRoundRect(r,int,int,pat) // fills a rectangle's interior with any pattern you specify. The procedure transfers the pattern with the patCopy pattern mode, which directly copies your requested pattern into the shape. @param pRectangle the rectangle to fill @param pArcW width of the oval defining the rounded corner. @param pArcH height of the oval defining the rounded corner. @param pPattern the pattern to use """ fillShape(toRoundRect(pRectangle, pArcW, pArcH), pPattern); }
java
public void fillRoundRect(final Rectangle2D pRectangle, int pArcW, int pArcH, Pattern pPattern) { fillShape(toRoundRect(pRectangle, pArcW, pArcH), pPattern); }
[ "public", "void", "fillRoundRect", "(", "final", "Rectangle2D", "pRectangle", ",", "int", "pArcW", ",", "int", "pArcH", ",", "Pattern", "pPattern", ")", "{", "fillShape", "(", "toRoundRect", "(", "pRectangle", ",", "pArcW", ",", "pArcH", ")", ",", "pPattern", ")", ";", "}" ]
FillRoundRect(r,int,int,pat) // fills a rectangle's interior with any pattern you specify. The procedure transfers the pattern with the patCopy pattern mode, which directly copies your requested pattern into the shape. @param pRectangle the rectangle to fill @param pArcW width of the oval defining the rounded corner. @param pArcH height of the oval defining the rounded corner. @param pPattern the pattern to use
[ "FillRoundRect", "(", "r", "int", "int", "pat", ")", "//", "fills", "a", "rectangle", "s", "interior", "with", "any", "pattern", "you", "specify", ".", "The", "procedure", "transfers", "the", "pattern", "with", "the", "patCopy", "pattern", "mode", "which", "directly", "copies", "your", "requested", "pattern", "into", "the", "shape", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickDrawContext.java#L620-L622
TimeAndSpaceIO/SmoothieMap
src/main/java/net/openhft/smoothie/SmoothieMap.java
SmoothieMap.forEach
@Override public final void forEach(BiConsumer<? super K, ? super V> action) { """ Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. Actions are performed in the order of {@linkplain #entrySet() entry set} iteration. Exceptions thrown by the action are relayed to the caller. @param action The action to be performed for each entry @throws NullPointerException if the specified action is null @throws ConcurrentModificationException if any structural modification of the map (new entry insertion or an entry removal) is detected during iteration @see #forEachWhile(BiPredicate) """ Objects.requireNonNull(action); int mc = this.modCount; Segment<K, V> segment; for (long segmentIndex = 0; segmentIndex >= 0; segmentIndex = nextSegmentIndex(segmentIndex, segment)) { (segment = segment(segmentIndex)).forEach(action); } if (mc != modCount) throw new ConcurrentModificationException(); }
java
@Override public final void forEach(BiConsumer<? super K, ? super V> action) { Objects.requireNonNull(action); int mc = this.modCount; Segment<K, V> segment; for (long segmentIndex = 0; segmentIndex >= 0; segmentIndex = nextSegmentIndex(segmentIndex, segment)) { (segment = segment(segmentIndex)).forEach(action); } if (mc != modCount) throw new ConcurrentModificationException(); }
[ "@", "Override", "public", "final", "void", "forEach", "(", "BiConsumer", "<", "?", "super", "K", ",", "?", "super", "V", ">", "action", ")", "{", "Objects", ".", "requireNonNull", "(", "action", ")", ";", "int", "mc", "=", "this", ".", "modCount", ";", "Segment", "<", "K", ",", "V", ">", "segment", ";", "for", "(", "long", "segmentIndex", "=", "0", ";", "segmentIndex", ">=", "0", ";", "segmentIndex", "=", "nextSegmentIndex", "(", "segmentIndex", ",", "segment", ")", ")", "{", "(", "segment", "=", "segment", "(", "segmentIndex", ")", ")", ".", "forEach", "(", "action", ")", ";", "}", "if", "(", "mc", "!=", "modCount", ")", "throw", "new", "ConcurrentModificationException", "(", ")", ";", "}" ]
Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. Actions are performed in the order of {@linkplain #entrySet() entry set} iteration. Exceptions thrown by the action are relayed to the caller. @param action The action to be performed for each entry @throws NullPointerException if the specified action is null @throws ConcurrentModificationException if any structural modification of the map (new entry insertion or an entry removal) is detected during iteration @see #forEachWhile(BiPredicate)
[ "Performs", "the", "given", "action", "for", "each", "entry", "in", "this", "map", "until", "all", "entries", "have", "been", "processed", "or", "the", "action", "throws", "an", "exception", ".", "Actions", "are", "performed", "in", "the", "order", "of", "{", "@linkplain", "#entrySet", "()", "entry", "set", "}", "iteration", ".", "Exceptions", "thrown", "by", "the", "action", "are", "relayed", "to", "the", "caller", "." ]
train
https://github.com/TimeAndSpaceIO/SmoothieMap/blob/c798f6cae1d377f6913e8821a1fcf5bf45ee0412/src/main/java/net/openhft/smoothie/SmoothieMap.java#L1048-L1059
ontop/ontop
mapping/sql/core/src/main/java/it/unibz/inf/ontop/spec/mapping/parser/impl/RAExpression.java
RAExpression.naturalJoin
public static RAExpression naturalJoin(RAExpression re1, RAExpression re2, TermFactory termFactory) throws IllegalJoinException { """ NATURAL JOIN @param re1 a {@link RAExpression} @param re2 a {@link RAExpression} @return a {@link RAExpression} @throws IllegalJoinException if the same alias occurs in both arguments or one of the shared attributes is ambiguous """ ImmutableSet<QuotedID> shared = RAExpressionAttributes.getShared(re1.attributes, re2.attributes); RAExpressionAttributes attributes = RAExpressionAttributes.joinUsing(re1.attributes, re2.attributes, shared); return new RAExpression(union(re1.dataAtoms, re2.dataAtoms), union(re1.filterAtoms, re2.filterAtoms, getJoinOnFilter(re1.attributes, re2.attributes, shared, termFactory)), attributes, termFactory); }
java
public static RAExpression naturalJoin(RAExpression re1, RAExpression re2, TermFactory termFactory) throws IllegalJoinException { ImmutableSet<QuotedID> shared = RAExpressionAttributes.getShared(re1.attributes, re2.attributes); RAExpressionAttributes attributes = RAExpressionAttributes.joinUsing(re1.attributes, re2.attributes, shared); return new RAExpression(union(re1.dataAtoms, re2.dataAtoms), union(re1.filterAtoms, re2.filterAtoms, getJoinOnFilter(re1.attributes, re2.attributes, shared, termFactory)), attributes, termFactory); }
[ "public", "static", "RAExpression", "naturalJoin", "(", "RAExpression", "re1", ",", "RAExpression", "re2", ",", "TermFactory", "termFactory", ")", "throws", "IllegalJoinException", "{", "ImmutableSet", "<", "QuotedID", ">", "shared", "=", "RAExpressionAttributes", ".", "getShared", "(", "re1", ".", "attributes", ",", "re2", ".", "attributes", ")", ";", "RAExpressionAttributes", "attributes", "=", "RAExpressionAttributes", ".", "joinUsing", "(", "re1", ".", "attributes", ",", "re2", ".", "attributes", ",", "shared", ")", ";", "return", "new", "RAExpression", "(", "union", "(", "re1", ".", "dataAtoms", ",", "re2", ".", "dataAtoms", ")", ",", "union", "(", "re1", ".", "filterAtoms", ",", "re2", ".", "filterAtoms", ",", "getJoinOnFilter", "(", "re1", ".", "attributes", ",", "re2", ".", "attributes", ",", "shared", ",", "termFactory", ")", ")", ",", "attributes", ",", "termFactory", ")", ";", "}" ]
NATURAL JOIN @param re1 a {@link RAExpression} @param re2 a {@link RAExpression} @return a {@link RAExpression} @throws IllegalJoinException if the same alias occurs in both arguments or one of the shared attributes is ambiguous
[ "NATURAL", "JOIN" ]
train
https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/mapping/sql/core/src/main/java/it/unibz/inf/ontop/spec/mapping/parser/impl/RAExpression.java#L105-L117
alkacon/opencms-core
src/org/opencms/ui/CmsUserIconHelper.java
CmsUserIconHelper.handleImageUpload
public boolean handleImageUpload(CmsObject cms, CmsUser user, String uploadedFile) { """ Handles a user image upload. The uploaded file will be scaled and save as a new file beneath /system/userimages/, the original file will be deleted.<p> @param cms the cms context @param user the user @param uploadedFile the uploaded file @return <code>true</code> in case the image was set successfully """ boolean result = false; try { setUserImage(cms, user, uploadedFile); result = true; } catch (CmsException e) { LOG.error("Error setting user image.", e); } try { cms.lockResource(uploadedFile); cms.deleteResource(uploadedFile, CmsResource.DELETE_REMOVE_SIBLINGS); } catch (CmsException e) { LOG.error("Error deleting user image temp file.", e); } return result; }
java
public boolean handleImageUpload(CmsObject cms, CmsUser user, String uploadedFile) { boolean result = false; try { setUserImage(cms, user, uploadedFile); result = true; } catch (CmsException e) { LOG.error("Error setting user image.", e); } try { cms.lockResource(uploadedFile); cms.deleteResource(uploadedFile, CmsResource.DELETE_REMOVE_SIBLINGS); } catch (CmsException e) { LOG.error("Error deleting user image temp file.", e); } return result; }
[ "public", "boolean", "handleImageUpload", "(", "CmsObject", "cms", ",", "CmsUser", "user", ",", "String", "uploadedFile", ")", "{", "boolean", "result", "=", "false", ";", "try", "{", "setUserImage", "(", "cms", ",", "user", ",", "uploadedFile", ")", ";", "result", "=", "true", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "LOG", ".", "error", "(", "\"Error setting user image.\"", ",", "e", ")", ";", "}", "try", "{", "cms", ".", "lockResource", "(", "uploadedFile", ")", ";", "cms", ".", "deleteResource", "(", "uploadedFile", ",", "CmsResource", ".", "DELETE_REMOVE_SIBLINGS", ")", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "LOG", ".", "error", "(", "\"Error deleting user image temp file.\"", ",", "e", ")", ";", "}", "return", "result", ";", "}" ]
Handles a user image upload. The uploaded file will be scaled and save as a new file beneath /system/userimages/, the original file will be deleted.<p> @param cms the cms context @param user the user @param uploadedFile the uploaded file @return <code>true</code> in case the image was set successfully
[ "Handles", "a", "user", "image", "upload", ".", "The", "uploaded", "file", "will", "be", "scaled", "and", "save", "as", "a", "new", "file", "beneath", "/", "system", "/", "userimages", "/", "the", "original", "file", "will", "be", "deleted", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/CmsUserIconHelper.java#L259-L275
thinkaurelius/faunus
src/main/java/com/thinkaurelius/faunus/FaunusPipeline.java
FaunusPipeline.groupCount
public FaunusPipeline groupCount(final String keyClosure, final String valueClosure) { """ Apply the provided closure to the incoming element to determine the grouping key. Then apply the value closure to the current element to determine the count increment. The results are stored in the jobs sideeffect file in HDFS. @return the extended FaunusPipeline. """ this.state.assertNotLocked(); this.compiler.addMapReduce(GroupCountMapReduce.Map.class, GroupCountMapReduce.Combiner.class, GroupCountMapReduce.Reduce.class, Text.class, LongWritable.class, Text.class, LongWritable.class, GroupCountMapReduce.createConfiguration(this.state.getElementType(), this.validateClosure(keyClosure), this.validateClosure(valueClosure))); makeMapReduceString(GroupCountMapReduce.class); return this; }
java
public FaunusPipeline groupCount(final String keyClosure, final String valueClosure) { this.state.assertNotLocked(); this.compiler.addMapReduce(GroupCountMapReduce.Map.class, GroupCountMapReduce.Combiner.class, GroupCountMapReduce.Reduce.class, Text.class, LongWritable.class, Text.class, LongWritable.class, GroupCountMapReduce.createConfiguration(this.state.getElementType(), this.validateClosure(keyClosure), this.validateClosure(valueClosure))); makeMapReduceString(GroupCountMapReduce.class); return this; }
[ "public", "FaunusPipeline", "groupCount", "(", "final", "String", "keyClosure", ",", "final", "String", "valueClosure", ")", "{", "this", ".", "state", ".", "assertNotLocked", "(", ")", ";", "this", ".", "compiler", ".", "addMapReduce", "(", "GroupCountMapReduce", ".", "Map", ".", "class", ",", "GroupCountMapReduce", ".", "Combiner", ".", "class", ",", "GroupCountMapReduce", ".", "Reduce", ".", "class", ",", "Text", ".", "class", ",", "LongWritable", ".", "class", ",", "Text", ".", "class", ",", "LongWritable", ".", "class", ",", "GroupCountMapReduce", ".", "createConfiguration", "(", "this", ".", "state", ".", "getElementType", "(", ")", ",", "this", ".", "validateClosure", "(", "keyClosure", ")", ",", "this", ".", "validateClosure", "(", "valueClosure", ")", ")", ")", ";", "makeMapReduceString", "(", "GroupCountMapReduce", ".", "class", ")", ";", "return", "this", ";", "}" ]
Apply the provided closure to the incoming element to determine the grouping key. Then apply the value closure to the current element to determine the count increment. The results are stored in the jobs sideeffect file in HDFS. @return the extended FaunusPipeline.
[ "Apply", "the", "provided", "closure", "to", "the", "incoming", "element", "to", "determine", "the", "grouping", "key", ".", "Then", "apply", "the", "value", "closure", "to", "the", "current", "element", "to", "determine", "the", "count", "increment", ".", "The", "results", "are", "stored", "in", "the", "jobs", "sideeffect", "file", "in", "HDFS", "." ]
train
https://github.com/thinkaurelius/faunus/blob/1eb8494eeb3fe3b84a98d810d304ba01d55b0d6e/src/main/java/com/thinkaurelius/faunus/FaunusPipeline.java#L935-L951
xm-online/xm-commons
xm-commons-tenant/src/main/java/com/icthh/xm/commons/tenant/TenantContextUtils.java
TenantContextUtils.setTenant
public static void setTenant(TenantContextHolder holder, String tenantKeyValue) { """ Sets current thread tenant. @param holder tenant contexts holder @param tenantKeyValue tenant key value """ holder.getPrivilegedContext().setTenant(buildTenant(tenantKeyValue)); }
java
public static void setTenant(TenantContextHolder holder, String tenantKeyValue) { holder.getPrivilegedContext().setTenant(buildTenant(tenantKeyValue)); }
[ "public", "static", "void", "setTenant", "(", "TenantContextHolder", "holder", ",", "String", "tenantKeyValue", ")", "{", "holder", ".", "getPrivilegedContext", "(", ")", ".", "setTenant", "(", "buildTenant", "(", "tenantKeyValue", ")", ")", ";", "}" ]
Sets current thread tenant. @param holder tenant contexts holder @param tenantKeyValue tenant key value
[ "Sets", "current", "thread", "tenant", "." ]
train
https://github.com/xm-online/xm-commons/blob/43eb2273adb96f40830d7b905ee3a767b8715caf/xm-commons-tenant/src/main/java/com/icthh/xm/commons/tenant/TenantContextUtils.java#L67-L69
b3log/latke
latke-core/src/main/java/org/json/JSONArray.java
JSONArray.optEnum
public <E extends Enum<E>> E optEnum(Class<E> clazz, int index, E defaultValue) { """ Get the enum value associated with a key. @param <E> Enum Type @param clazz The type of enum to retrieve. @param index The index must be between 0 and length() - 1. @param defaultValue The default in case the value is not found @return The enum value at the index location or defaultValue if the value is not found or cannot be assigned to clazz """ try { Object val = this.opt(index); if (JSONObject.NULL.equals(val)) { return defaultValue; } if (clazz.isAssignableFrom(val.getClass())) { // we just checked it! @SuppressWarnings("unchecked") E myE = (E) val; return myE; } return Enum.valueOf(clazz, val.toString()); } catch (IllegalArgumentException e) { return defaultValue; } catch (NullPointerException e) { return defaultValue; } }
java
public <E extends Enum<E>> E optEnum(Class<E> clazz, int index, E defaultValue) { try { Object val = this.opt(index); if (JSONObject.NULL.equals(val)) { return defaultValue; } if (clazz.isAssignableFrom(val.getClass())) { // we just checked it! @SuppressWarnings("unchecked") E myE = (E) val; return myE; } return Enum.valueOf(clazz, val.toString()); } catch (IllegalArgumentException e) { return defaultValue; } catch (NullPointerException e) { return defaultValue; } }
[ "public", "<", "E", "extends", "Enum", "<", "E", ">", ">", "E", "optEnum", "(", "Class", "<", "E", ">", "clazz", ",", "int", "index", ",", "E", "defaultValue", ")", "{", "try", "{", "Object", "val", "=", "this", ".", "opt", "(", "index", ")", ";", "if", "(", "JSONObject", ".", "NULL", ".", "equals", "(", "val", ")", ")", "{", "return", "defaultValue", ";", "}", "if", "(", "clazz", ".", "isAssignableFrom", "(", "val", ".", "getClass", "(", ")", ")", ")", "{", "// we just checked it!", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "E", "myE", "=", "(", "E", ")", "val", ";", "return", "myE", ";", "}", "return", "Enum", ".", "valueOf", "(", "clazz", ",", "val", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "return", "defaultValue", ";", "}", "catch", "(", "NullPointerException", "e", ")", "{", "return", "defaultValue", ";", "}", "}" ]
Get the enum value associated with a key. @param <E> Enum Type @param clazz The type of enum to retrieve. @param index The index must be between 0 and length() - 1. @param defaultValue The default in case the value is not found @return The enum value at the index location or defaultValue if the value is not found or cannot be assigned to clazz
[ "Get", "the", "enum", "value", "associated", "with", "a", "key", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L678-L696
EsotericSoftware/kryonet
src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java
ObjectSpace.getRegisteredObject
static Object getRegisteredObject (Connection connection, int objectID) { """ Returns the first object registered with the specified ID in any of the ObjectSpaces the specified connection belongs to. """ ObjectSpace[] instances = ObjectSpace.instances; for (int i = 0, n = instances.length; i < n; i++) { ObjectSpace objectSpace = instances[i]; // Check if the connection is in this ObjectSpace. Connection[] connections = objectSpace.connections; for (int j = 0; j < connections.length; j++) { if (connections[j] != connection) continue; // Find an object with the objectID. Object object = objectSpace.idToObject.get(objectID); if (object != null) return object; } } return null; }
java
static Object getRegisteredObject (Connection connection, int objectID) { ObjectSpace[] instances = ObjectSpace.instances; for (int i = 0, n = instances.length; i < n; i++) { ObjectSpace objectSpace = instances[i]; // Check if the connection is in this ObjectSpace. Connection[] connections = objectSpace.connections; for (int j = 0; j < connections.length; j++) { if (connections[j] != connection) continue; // Find an object with the objectID. Object object = objectSpace.idToObject.get(objectID); if (object != null) return object; } } return null; }
[ "static", "Object", "getRegisteredObject", "(", "Connection", "connection", ",", "int", "objectID", ")", "{", "ObjectSpace", "[", "]", "instances", "=", "ObjectSpace", ".", "instances", ";", "for", "(", "int", "i", "=", "0", ",", "n", "=", "instances", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "ObjectSpace", "objectSpace", "=", "instances", "[", "i", "]", ";", "// Check if the connection is in this ObjectSpace.", "Connection", "[", "]", "connections", "=", "objectSpace", ".", "connections", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "connections", ".", "length", ";", "j", "++", ")", "{", "if", "(", "connections", "[", "j", "]", "!=", "connection", ")", "continue", ";", "// Find an object with the objectID.", "Object", "object", "=", "objectSpace", ".", "idToObject", ".", "get", "(", "objectID", ")", ";", "if", "(", "object", "!=", "null", ")", "return", "object", ";", "}", "}", "return", "null", ";", "}" ]
Returns the first object registered with the specified ID in any of the ObjectSpaces the specified connection belongs to.
[ "Returns", "the", "first", "object", "registered", "with", "the", "specified", "ID", "in", "any", "of", "the", "ObjectSpaces", "the", "specified", "connection", "belongs", "to", "." ]
train
https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java#L651-L665
OpenLiberty/open-liberty
dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/MonitoringProxyActivator.java
MonitoringProxyActivator.getTargetInternalName
String getTargetInternalName(String sourceInternalName, String targetPackage) { """ Get the class internal name that should be used where moving the internal class across packages. @param sourceInternalName the internal name of the template class @param targetPackage the package to move the class to @return the target class name """ StringBuilder targetInternalName = new StringBuilder(); targetInternalName.append(targetPackage.replaceAll("\\.", "/")); int lastSlashIndex = sourceInternalName.lastIndexOf('/'); targetInternalName.append(sourceInternalName.substring(lastSlashIndex)); return targetInternalName.toString(); }
java
String getTargetInternalName(String sourceInternalName, String targetPackage) { StringBuilder targetInternalName = new StringBuilder(); targetInternalName.append(targetPackage.replaceAll("\\.", "/")); int lastSlashIndex = sourceInternalName.lastIndexOf('/'); targetInternalName.append(sourceInternalName.substring(lastSlashIndex)); return targetInternalName.toString(); }
[ "String", "getTargetInternalName", "(", "String", "sourceInternalName", ",", "String", "targetPackage", ")", "{", "StringBuilder", "targetInternalName", "=", "new", "StringBuilder", "(", ")", ";", "targetInternalName", ".", "append", "(", "targetPackage", ".", "replaceAll", "(", "\"\\\\.\"", ",", "\"/\"", ")", ")", ";", "int", "lastSlashIndex", "=", "sourceInternalName", ".", "lastIndexOf", "(", "'", "'", ")", ";", "targetInternalName", ".", "append", "(", "sourceInternalName", ".", "substring", "(", "lastSlashIndex", ")", ")", ";", "return", "targetInternalName", ".", "toString", "(", ")", ";", "}" ]
Get the class internal name that should be used where moving the internal class across packages. @param sourceInternalName the internal name of the template class @param targetPackage the package to move the class to @return the target class name
[ "Get", "the", "class", "internal", "name", "that", "should", "be", "used", "where", "moving", "the", "internal", "class", "across", "packages", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/MonitoringProxyActivator.java#L335-L343
thelinmichael/spotify-web-api-java
src/main/java/com/wrapper/spotify/SpotifyApi.java
SpotifyApi.followPlaylist
public FollowPlaylistRequest.Builder followPlaylist(String owner_id, String playlist_id, boolean public_) { """ Add the current user as a follower of a playlist. @param owner_id The Spotify user ID of the person who owns the playlist. @param playlist_id The Spotify ID of the playlist. Any playlist can be followed, regardless of its public/private status, as long as you know its playlist ID. @param public_ Default: true. If true the playlist will be included in user's public playlists, if false it will remain private. To be able to follow playlists privately, the user must have granted the playlist-modify-private scope. @return A {@link FollowPlaylistRequest.Builder}. @see <a href="https://developer.spotify.com/web-api/user-guide/#spotify-uris-and-ids">Spotify: URLs &amp; IDs</a> """ return new FollowPlaylistRequest.Builder(accessToken) .setDefaults(httpManager, scheme, host, port) .owner_id(owner_id) .playlist_id(playlist_id) .public_(public_); }
java
public FollowPlaylistRequest.Builder followPlaylist(String owner_id, String playlist_id, boolean public_) { return new FollowPlaylistRequest.Builder(accessToken) .setDefaults(httpManager, scheme, host, port) .owner_id(owner_id) .playlist_id(playlist_id) .public_(public_); }
[ "public", "FollowPlaylistRequest", ".", "Builder", "followPlaylist", "(", "String", "owner_id", ",", "String", "playlist_id", ",", "boolean", "public_", ")", "{", "return", "new", "FollowPlaylistRequest", ".", "Builder", "(", "accessToken", ")", ".", "setDefaults", "(", "httpManager", ",", "scheme", ",", "host", ",", "port", ")", ".", "owner_id", "(", "owner_id", ")", ".", "playlist_id", "(", "playlist_id", ")", ".", "public_", "(", "public_", ")", ";", "}" ]
Add the current user as a follower of a playlist. @param owner_id The Spotify user ID of the person who owns the playlist. @param playlist_id The Spotify ID of the playlist. Any playlist can be followed, regardless of its public/private status, as long as you know its playlist ID. @param public_ Default: true. If true the playlist will be included in user's public playlists, if false it will remain private. To be able to follow playlists privately, the user must have granted the playlist-modify-private scope. @return A {@link FollowPlaylistRequest.Builder}. @see <a href="https://developer.spotify.com/web-api/user-guide/#spotify-uris-and-ids">Spotify: URLs &amp; IDs</a>
[ "Add", "the", "current", "user", "as", "a", "follower", "of", "a", "playlist", "." ]
train
https://github.com/thelinmichael/spotify-web-api-java/blob/c06b8512344c0310d0c1df362fa267879021da2e/src/main/java/com/wrapper/spotify/SpotifyApi.java#L681-L687
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/cluster/clusterinstance_binding.java
clusterinstance_binding.get
public static clusterinstance_binding get(nitro_service service, Long clid) throws Exception { """ Use this API to fetch clusterinstance_binding resource of given name . """ clusterinstance_binding obj = new clusterinstance_binding(); obj.set_clid(clid); clusterinstance_binding response = (clusterinstance_binding) obj.get_resource(service); return response; }
java
public static clusterinstance_binding get(nitro_service service, Long clid) throws Exception{ clusterinstance_binding obj = new clusterinstance_binding(); obj.set_clid(clid); clusterinstance_binding response = (clusterinstance_binding) obj.get_resource(service); return response; }
[ "public", "static", "clusterinstance_binding", "get", "(", "nitro_service", "service", ",", "Long", "clid", ")", "throws", "Exception", "{", "clusterinstance_binding", "obj", "=", "new", "clusterinstance_binding", "(", ")", ";", "obj", ".", "set_clid", "(", "clid", ")", ";", "clusterinstance_binding", "response", "=", "(", "clusterinstance_binding", ")", "obj", ".", "get_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch clusterinstance_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "clusterinstance_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/cluster/clusterinstance_binding.java#L115-L120
imsweb/seerapi-client-java
src/main/java/com/imsweb/seerapi/client/staging/cs/CsStagingData.java
CsStagingData.setSsf
public void setSsf(Integer id, String ssf) { """ Set the specified input site-specific factor @param id site-specific factor number @param ssf site-specfic factor value """ if (id < 1 || id > 25) throw new IllegalStateException("Site specific factor must be between 1 and 25."); setInput(INPUT_SSF_PREFIX + id, ssf); }
java
public void setSsf(Integer id, String ssf) { if (id < 1 || id > 25) throw new IllegalStateException("Site specific factor must be between 1 and 25."); setInput(INPUT_SSF_PREFIX + id, ssf); }
[ "public", "void", "setSsf", "(", "Integer", "id", ",", "String", "ssf", ")", "{", "if", "(", "id", "<", "1", "||", "id", ">", "25", ")", "throw", "new", "IllegalStateException", "(", "\"Site specific factor must be between 1 and 25.\"", ")", ";", "setInput", "(", "INPUT_SSF_PREFIX", "+", "id", ",", "ssf", ")", ";", "}" ]
Set the specified input site-specific factor @param id site-specific factor number @param ssf site-specfic factor value
[ "Set", "the", "specified", "input", "site", "-", "specific", "factor" ]
train
https://github.com/imsweb/seerapi-client-java/blob/04f509961c3a5ece7b232ecb8d8cb8f89d810a85/src/main/java/com/imsweb/seerapi/client/staging/cs/CsStagingData.java#L203-L208
rollbar/rollbar-java
rollbar-android/src/main/java/com/rollbar/android/Rollbar.java
Rollbar.reportException
@Deprecated public static void reportException(final Throwable throwable, final String level, final String description, final Map<String, String> params) { """ report an exception to Rollbar, specifying the level, adding a custom description, and including extra data. @param throwable the exception that occurred. @param level the severity level. @param description the extra description. @param params the extra custom data. """ ensureInit(new Runnable() { @Override public void run() { notifier.log(throwable, params != null ? Collections.<String, Object>unmodifiableMap(params) : null, description, Level.lookupByName(level)); } }); }
java
@Deprecated public static void reportException(final Throwable throwable, final String level, final String description, final Map<String, String> params) { ensureInit(new Runnable() { @Override public void run() { notifier.log(throwable, params != null ? Collections.<String, Object>unmodifiableMap(params) : null, description, Level.lookupByName(level)); } }); }
[ "@", "Deprecated", "public", "static", "void", "reportException", "(", "final", "Throwable", "throwable", ",", "final", "String", "level", ",", "final", "String", "description", ",", "final", "Map", "<", "String", ",", "String", ">", "params", ")", "{", "ensureInit", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "notifier", ".", "log", "(", "throwable", ",", "params", "!=", "null", "?", "Collections", ".", "<", "String", ",", "Object", ">", "unmodifiableMap", "(", "params", ")", ":", "null", ",", "description", ",", "Level", ".", "lookupByName", "(", "level", ")", ")", ";", "}", "}", ")", ";", "}" ]
report an exception to Rollbar, specifying the level, adding a custom description, and including extra data. @param throwable the exception that occurred. @param level the severity level. @param description the extra description. @param params the extra custom data.
[ "report", "an", "exception", "to", "Rollbar", "specifying", "the", "level", "adding", "a", "custom", "description", "and", "including", "extra", "data", "." ]
train
https://github.com/rollbar/rollbar-java/blob/5eb4537d1363722b51cfcce55b427cbd8489f17b/rollbar-android/src/main/java/com/rollbar/android/Rollbar.java#L845-L853
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_store/FSSpecStore.java
FSSpecStore.getPathForURI
protected Path getPathForURI(Path fsSpecStoreDirPath, URI uri, String version) { """ Construct a file path given URI and version of a spec. @param fsSpecStoreDirPath The directory path for specs. @param uri Uri as the identifier of JobSpec @return """ return PathUtils.addExtension(PathUtils.mergePaths(fsSpecStoreDirPath, new Path(uri)), version); }
java
protected Path getPathForURI(Path fsSpecStoreDirPath, URI uri, String version) { return PathUtils.addExtension(PathUtils.mergePaths(fsSpecStoreDirPath, new Path(uri)), version); }
[ "protected", "Path", "getPathForURI", "(", "Path", "fsSpecStoreDirPath", ",", "URI", "uri", ",", "String", "version", ")", "{", "return", "PathUtils", ".", "addExtension", "(", "PathUtils", ".", "mergePaths", "(", "fsSpecStoreDirPath", ",", "new", "Path", "(", "uri", ")", ")", ",", "version", ")", ";", "}" ]
Construct a file path given URI and version of a spec. @param fsSpecStoreDirPath The directory path for specs. @param uri Uri as the identifier of JobSpec @return
[ "Construct", "a", "file", "path", "given", "URI", "and", "version", "of", "a", "spec", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_store/FSSpecStore.java#L332-L334
UrielCh/ovh-java-sdk
ovh-java-sdk-dbaastimeseries/src/main/java/net/minidev/ovh/api/ApiOvhDbaastimeseries.java
ApiOvhDbaastimeseries.serviceName_token_opentsdb_POST
public OvhOpenTSDBToken serviceName_token_opentsdb_POST(String serviceName, String description, String permission, OvhTag[] tags) throws IOException { """ Create a OpenTSDB token REST: POST /dbaas/timeseries/{serviceName}/token/opentsdb @param serviceName [required] Service Name @param description [required] Token description @param permission [required] Permission @param tags [required] Tags to apply API beta """ String qPath = "/dbaas/timeseries/{serviceName}/token/opentsdb"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "permission", permission); addBody(o, "tags", tags); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOpenTSDBToken.class); }
java
public OvhOpenTSDBToken serviceName_token_opentsdb_POST(String serviceName, String description, String permission, OvhTag[] tags) throws IOException { String qPath = "/dbaas/timeseries/{serviceName}/token/opentsdb"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "permission", permission); addBody(o, "tags", tags); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOpenTSDBToken.class); }
[ "public", "OvhOpenTSDBToken", "serviceName_token_opentsdb_POST", "(", "String", "serviceName", ",", "String", "description", ",", "String", "permission", ",", "OvhTag", "[", "]", "tags", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dbaas/timeseries/{serviceName}/token/opentsdb\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"description\"", ",", "description", ")", ";", "addBody", "(", "o", ",", "\"permission\"", ",", "permission", ")", ";", "addBody", "(", "o", ",", "\"tags\"", ",", "tags", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhOpenTSDBToken", ".", "class", ")", ";", "}" ]
Create a OpenTSDB token REST: POST /dbaas/timeseries/{serviceName}/token/opentsdb @param serviceName [required] Service Name @param description [required] Token description @param permission [required] Permission @param tags [required] Tags to apply API beta
[ "Create", "a", "OpenTSDB", "token" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dbaastimeseries/src/main/java/net/minidev/ovh/api/ApiOvhDbaastimeseries.java#L151-L160
Netflix/ribbon
ribbon-loadbalancer/src/main/java/com/netflix/client/ClientFactory.java
ClientFactory.getNamedLoadBalancer
public static synchronized ILoadBalancer getNamedLoadBalancer(String name, Class<? extends IClientConfig> configClass) { """ Get the load balancer associated with the name, or create one with an instance of configClass if does not exist @throws RuntimeException if any error occurs @see #registerNamedLoadBalancerFromProperties(String, Class) """ ILoadBalancer lb = namedLBMap.get(name); if (lb != null) { return lb; } else { try { lb = registerNamedLoadBalancerFromProperties(name, configClass); } catch (ClientException e) { throw new RuntimeException("Unable to create load balancer", e); } return lb; } }
java
public static synchronized ILoadBalancer getNamedLoadBalancer(String name, Class<? extends IClientConfig> configClass) { ILoadBalancer lb = namedLBMap.get(name); if (lb != null) { return lb; } else { try { lb = registerNamedLoadBalancerFromProperties(name, configClass); } catch (ClientException e) { throw new RuntimeException("Unable to create load balancer", e); } return lb; } }
[ "public", "static", "synchronized", "ILoadBalancer", "getNamedLoadBalancer", "(", "String", "name", ",", "Class", "<", "?", "extends", "IClientConfig", ">", "configClass", ")", "{", "ILoadBalancer", "lb", "=", "namedLBMap", ".", "get", "(", "name", ")", ";", "if", "(", "lb", "!=", "null", ")", "{", "return", "lb", ";", "}", "else", "{", "try", "{", "lb", "=", "registerNamedLoadBalancerFromProperties", "(", "name", ",", "configClass", ")", ";", "}", "catch", "(", "ClientException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Unable to create load balancer\"", ",", "e", ")", ";", "}", "return", "lb", ";", "}", "}" ]
Get the load balancer associated with the name, or create one with an instance of configClass if does not exist @throws RuntimeException if any error occurs @see #registerNamedLoadBalancerFromProperties(String, Class)
[ "Get", "the", "load", "balancer", "associated", "with", "the", "name", "or", "create", "one", "with", "an", "instance", "of", "configClass", "if", "does", "not", "exist" ]
train
https://github.com/Netflix/ribbon/blob/d15cd7715b0bf2f64ae6ca98c5e4d184f178e261/ribbon-loadbalancer/src/main/java/com/netflix/client/ClientFactory.java#L158-L170
wisdom-framework/wisdom
core/application-configuration/src/main/java/org/wisdom/configuration/ConfigurationImpl.java
ConfigurationImpl.getOrDie
@Override public String getOrDie(String key) { """ The "die" method forces this key to be set. Otherwise a runtime exception will be thrown. @param key the key @return the String or a IllegalArgumentException will be thrown. """ String value = get(key); if (value == null) { throw new IllegalArgumentException(String.format(ERROR_KEYNOTFOUND, key)); } else { return value; } }
java
@Override public String getOrDie(String key) { String value = get(key); if (value == null) { throw new IllegalArgumentException(String.format(ERROR_KEYNOTFOUND, key)); } else { return value; } }
[ "@", "Override", "public", "String", "getOrDie", "(", "String", "key", ")", "{", "String", "value", "=", "get", "(", "key", ")", ";", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "ERROR_KEYNOTFOUND", ",", "key", ")", ")", ";", "}", "else", "{", "return", "value", ";", "}", "}" ]
The "die" method forces this key to be set. Otherwise a runtime exception will be thrown. @param key the key @return the String or a IllegalArgumentException will be thrown.
[ "The", "die", "method", "forces", "this", "key", "to", "be", "set", ".", "Otherwise", "a", "runtime", "exception", "will", "be", "thrown", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/application-configuration/src/main/java/org/wisdom/configuration/ConfigurationImpl.java#L327-L335
apache/groovy
subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java
NioGroovyMethods.withDataOutputStream
public static <T> T withDataOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.DataOutputStream") Closure<T> closure) throws IOException { """ Create a new DataOutputStream for this file and passes it into the closure. This method ensures the stream is closed after the closure returns. @param self a Path @param closure a closure @return the value returned by the closure @throws java.io.IOException if an IOException occurs. @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.OutputStream, groovy.lang.Closure) @since 2.3.0 """ return IOGroovyMethods.withStream(newDataOutputStream(self), closure); }
java
public static <T> T withDataOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.DataOutputStream") Closure<T> closure) throws IOException { return IOGroovyMethods.withStream(newDataOutputStream(self), closure); }
[ "public", "static", "<", "T", ">", "T", "withDataOutputStream", "(", "Path", "self", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"java.io.DataOutputStream\"", ")", "Closure", "<", "T", ">", "closure", ")", "throws", "IOException", "{", "return", "IOGroovyMethods", ".", "withStream", "(", "newDataOutputStream", "(", "self", ")", ",", "closure", ")", ";", "}" ]
Create a new DataOutputStream for this file and passes it into the closure. This method ensures the stream is closed after the closure returns. @param self a Path @param closure a closure @return the value returned by the closure @throws java.io.IOException if an IOException occurs. @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.OutputStream, groovy.lang.Closure) @since 2.3.0
[ "Create", "a", "new", "DataOutputStream", "for", "this", "file", "and", "passes", "it", "into", "the", "closure", ".", "This", "method", "ensures", "the", "stream", "is", "closed", "after", "the", "closure", "returns", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L1515-L1517
thymeleaf/thymeleaf
src/main/java/org/thymeleaf/engine/EngineEventUtils.java
EngineEventUtils.computeAttributeExpression
public static IStandardExpression computeAttributeExpression( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue) { """ /* The idea behind this method is to cache in the Attribute object itself the IStandardExpression object corresponding with the expression to be executed, so that we don't have to hit the expression cache at all """ if (!(tag instanceof AbstractProcessableElementTag)) { return parseAttributeExpression(context, attributeValue); } final AbstractProcessableElementTag processableElementTag = (AbstractProcessableElementTag)tag; final Attribute attribute = (Attribute) processableElementTag.getAttribute(attributeName); IStandardExpression expression = attribute.getCachedStandardExpression(); if (expression != null) { return expression; } expression = parseAttributeExpression(context, attributeValue); // If the expression has been correctly parsed AND it does not contain preprocessing marks (_), nor it is a FragmentExpression, cache it! if (expression != null && !(expression instanceof FragmentExpression) && attributeValue.indexOf('_') < 0) { attribute.setCachedStandardExpression(expression); } return expression; }
java
public static IStandardExpression computeAttributeExpression( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue) { if (!(tag instanceof AbstractProcessableElementTag)) { return parseAttributeExpression(context, attributeValue); } final AbstractProcessableElementTag processableElementTag = (AbstractProcessableElementTag)tag; final Attribute attribute = (Attribute) processableElementTag.getAttribute(attributeName); IStandardExpression expression = attribute.getCachedStandardExpression(); if (expression != null) { return expression; } expression = parseAttributeExpression(context, attributeValue); // If the expression has been correctly parsed AND it does not contain preprocessing marks (_), nor it is a FragmentExpression, cache it! if (expression != null && !(expression instanceof FragmentExpression) && attributeValue.indexOf('_') < 0) { attribute.setCachedStandardExpression(expression); } return expression; }
[ "public", "static", "IStandardExpression", "computeAttributeExpression", "(", "final", "ITemplateContext", "context", ",", "final", "IProcessableElementTag", "tag", ",", "final", "AttributeName", "attributeName", ",", "final", "String", "attributeValue", ")", "{", "if", "(", "!", "(", "tag", "instanceof", "AbstractProcessableElementTag", ")", ")", "{", "return", "parseAttributeExpression", "(", "context", ",", "attributeValue", ")", ";", "}", "final", "AbstractProcessableElementTag", "processableElementTag", "=", "(", "AbstractProcessableElementTag", ")", "tag", ";", "final", "Attribute", "attribute", "=", "(", "Attribute", ")", "processableElementTag", ".", "getAttribute", "(", "attributeName", ")", ";", "IStandardExpression", "expression", "=", "attribute", ".", "getCachedStandardExpression", "(", ")", ";", "if", "(", "expression", "!=", "null", ")", "{", "return", "expression", ";", "}", "expression", "=", "parseAttributeExpression", "(", "context", ",", "attributeValue", ")", ";", "// If the expression has been correctly parsed AND it does not contain preprocessing marks (_), nor it is a FragmentExpression, cache it!", "if", "(", "expression", "!=", "null", "&&", "!", "(", "expression", "instanceof", "FragmentExpression", ")", "&&", "attributeValue", ".", "indexOf", "(", "'", "'", ")", "<", "0", ")", "{", "attribute", ".", "setCachedStandardExpression", "(", "expression", ")", ";", "}", "return", "expression", ";", "}" ]
/* The idea behind this method is to cache in the Attribute object itself the IStandardExpression object corresponding with the expression to be executed, so that we don't have to hit the expression cache at all
[ "/", "*", "The", "idea", "behind", "this", "method", "is", "to", "cache", "in", "the", "Attribute", "object", "itself", "the", "IStandardExpression", "object", "corresponding", "with", "the", "expression", "to", "be", "executed", "so", "that", "we", "don", "t", "have", "to", "hit", "the", "expression", "cache", "at", "all" ]
train
https://github.com/thymeleaf/thymeleaf/blob/2b0e6d6d7571fbe638904b5fd222fc9e77188879/src/main/java/org/thymeleaf/engine/EngineEventUtils.java#L192-L215
mfornos/humanize
humanize-slim/src/main/java/humanize/Humanize.java
Humanize.oxford
public static String oxford(Collection<?> items, int limit, String limitStr) { """ <p> Converts a list of items to a human readable string with an optional limit. </p> @param items The items collection @param limit The number of items to print. -1 for unbounded. @param limitStr The string to be appended after extra items. Null or "" for default. @return human readable representation of a bounded list of items """ return oxford(items.toArray(), limit, limitStr); }
java
public static String oxford(Collection<?> items, int limit, String limitStr) { return oxford(items.toArray(), limit, limitStr); }
[ "public", "static", "String", "oxford", "(", "Collection", "<", "?", ">", "items", ",", "int", "limit", ",", "String", "limitStr", ")", "{", "return", "oxford", "(", "items", ".", "toArray", "(", ")", ",", "limit", ",", "limitStr", ")", ";", "}" ]
<p> Converts a list of items to a human readable string with an optional limit. </p> @param items The items collection @param limit The number of items to print. -1 for unbounded. @param limitStr The string to be appended after extra items. Null or "" for default. @return human readable representation of a bounded list of items
[ "<p", ">", "Converts", "a", "list", "of", "items", "to", "a", "human", "readable", "string", "with", "an", "optional", "limit", ".", "<", "/", "p", ">" ]
train
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L1805-L1808
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java
BoneCPConfig.setQueryExecuteTimeLimit
public void setQueryExecuteTimeLimit(long queryExecuteTimeLimit, TimeUnit timeUnit) { """ Queries taking longer than this limit to execute are logged. @param queryExecuteTimeLimit the limit to set in milliseconds. @param timeUnit """ this.queryExecuteTimeLimitInMs = TimeUnit.MILLISECONDS.convert(queryExecuteTimeLimit, timeUnit); }
java
public void setQueryExecuteTimeLimit(long queryExecuteTimeLimit, TimeUnit timeUnit) { this.queryExecuteTimeLimitInMs = TimeUnit.MILLISECONDS.convert(queryExecuteTimeLimit, timeUnit); }
[ "public", "void", "setQueryExecuteTimeLimit", "(", "long", "queryExecuteTimeLimit", ",", "TimeUnit", "timeUnit", ")", "{", "this", ".", "queryExecuteTimeLimitInMs", "=", "TimeUnit", ".", "MILLISECONDS", ".", "convert", "(", "queryExecuteTimeLimit", ",", "timeUnit", ")", ";", "}" ]
Queries taking longer than this limit to execute are logged. @param queryExecuteTimeLimit the limit to set in milliseconds. @param timeUnit
[ "Queries", "taking", "longer", "than", "this", "limit", "to", "execute", "are", "logged", "." ]
train
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java#L919-L921
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/uac/LocalSubjectUserAccessControl.java
LocalSubjectUserAccessControl.verifyPermission
private void verifyPermission(Subject subject, String permission) throws UnauthorizedException { """ Verifies whether the user has a specific permission. If not it throws a standard UnauthorizedException. @throws UnauthorizedException User did not have the permission """ if (!subject.hasPermission(permission)) { throw new UnauthorizedException(); } }
java
private void verifyPermission(Subject subject, String permission) throws UnauthorizedException { if (!subject.hasPermission(permission)) { throw new UnauthorizedException(); } }
[ "private", "void", "verifyPermission", "(", "Subject", "subject", ",", "String", "permission", ")", "throws", "UnauthorizedException", "{", "if", "(", "!", "subject", ".", "hasPermission", "(", "permission", ")", ")", "{", "throw", "new", "UnauthorizedException", "(", ")", ";", "}", "}" ]
Verifies whether the user has a specific permission. If not it throws a standard UnauthorizedException. @throws UnauthorizedException User did not have the permission
[ "Verifies", "whether", "the", "user", "has", "a", "specific", "permission", ".", "If", "not", "it", "throws", "a", "standard", "UnauthorizedException", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/uac/LocalSubjectUserAccessControl.java#L583-L588
tvesalainen/bcc
src/main/java/org/vesalainen/bcc/ClassFile.java
ClassFile.referencesMethod
public boolean referencesMethod(ExecutableElement method) { """ Return true if class contains method ref to given method @param method @return """ TypeElement declaringClass = (TypeElement) method.getEnclosingElement(); String fullyQualifiedname = declaringClass.getQualifiedName().toString(); String name = method.getSimpleName().toString(); assert name.indexOf('.') == -1; String descriptor = Descriptor.getDesriptor(method); return getRefIndex(Methodref.class, fullyQualifiedname, name, descriptor) != -1; }
java
public boolean referencesMethod(ExecutableElement method) { TypeElement declaringClass = (TypeElement) method.getEnclosingElement(); String fullyQualifiedname = declaringClass.getQualifiedName().toString(); String name = method.getSimpleName().toString(); assert name.indexOf('.') == -1; String descriptor = Descriptor.getDesriptor(method); return getRefIndex(Methodref.class, fullyQualifiedname, name, descriptor) != -1; }
[ "public", "boolean", "referencesMethod", "(", "ExecutableElement", "method", ")", "{", "TypeElement", "declaringClass", "=", "(", "TypeElement", ")", "method", ".", "getEnclosingElement", "(", ")", ";", "String", "fullyQualifiedname", "=", "declaringClass", ".", "getQualifiedName", "(", ")", ".", "toString", "(", ")", ";", "String", "name", "=", "method", ".", "getSimpleName", "(", ")", ".", "toString", "(", ")", ";", "assert", "name", ".", "indexOf", "(", "'", "'", ")", "==", "-", "1", ";", "String", "descriptor", "=", "Descriptor", ".", "getDesriptor", "(", "method", ")", ";", "return", "getRefIndex", "(", "Methodref", ".", "class", ",", "fullyQualifiedname", ",", "name", ",", "descriptor", ")", "!=", "-", "1", ";", "}" ]
Return true if class contains method ref to given method @param method @return
[ "Return", "true", "if", "class", "contains", "method", "ref", "to", "given", "method" ]
train
https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/ClassFile.java#L636-L644
axibase/atsd-api-java
src/main/java/com/axibase/tsd/model/data/series/Sample.java
Sample.ofTimeText
public static Sample ofTimeText(long time, String textValue) { """ Creates a new {@link Sample} with time and text value specified @param time time in milliseconds from 1970-01-01 00:00:00 @param textValue the text value of the sample @return the Sample with specified fields """ return new Sample(time, null, null, textValue); }
java
public static Sample ofTimeText(long time, String textValue) { return new Sample(time, null, null, textValue); }
[ "public", "static", "Sample", "ofTimeText", "(", "long", "time", ",", "String", "textValue", ")", "{", "return", "new", "Sample", "(", "time", ",", "null", ",", "null", ",", "textValue", ")", ";", "}" ]
Creates a new {@link Sample} with time and text value specified @param time time in milliseconds from 1970-01-01 00:00:00 @param textValue the text value of the sample @return the Sample with specified fields
[ "Creates", "a", "new", "{", "@link", "Sample", "}", "with", "time", "and", "text", "value", "specified" ]
train
https://github.com/axibase/atsd-api-java/blob/63a0767d08b202dad2ebef4372ff947d6fba0246/src/main/java/com/axibase/tsd/model/data/series/Sample.java#L118-L120
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/datanode/BlockWithChecksumFileReader.java
BlockWithChecksumFileReader.getGenerationStampFromSeperateChecksumFile
static long getGenerationStampFromSeperateChecksumFile(String[] listdir, String blockName) { """ Find the metadata file for the specified block file. Return the generation stamp from the name of the metafile. """ for (int j = 0; j < listdir.length; j++) { String path = listdir[j]; if (!path.startsWith(blockName)) { continue; } String[] vals = StringUtils.split(path, '_'); if (vals.length != 3) { // blk, blkid, genstamp.meta continue; } String[] str = StringUtils.split(vals[2], '.'); if (str.length != 2) { continue; } return Long.parseLong(str[0]); } DataNode.LOG.warn("Block " + blockName + " does not have a metafile!"); return Block.GRANDFATHER_GENERATION_STAMP; }
java
static long getGenerationStampFromSeperateChecksumFile(String[] listdir, String blockName) { for (int j = 0; j < listdir.length; j++) { String path = listdir[j]; if (!path.startsWith(blockName)) { continue; } String[] vals = StringUtils.split(path, '_'); if (vals.length != 3) { // blk, blkid, genstamp.meta continue; } String[] str = StringUtils.split(vals[2], '.'); if (str.length != 2) { continue; } return Long.parseLong(str[0]); } DataNode.LOG.warn("Block " + blockName + " does not have a metafile!"); return Block.GRANDFATHER_GENERATION_STAMP; }
[ "static", "long", "getGenerationStampFromSeperateChecksumFile", "(", "String", "[", "]", "listdir", ",", "String", "blockName", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "listdir", ".", "length", ";", "j", "++", ")", "{", "String", "path", "=", "listdir", "[", "j", "]", ";", "if", "(", "!", "path", ".", "startsWith", "(", "blockName", ")", ")", "{", "continue", ";", "}", "String", "[", "]", "vals", "=", "StringUtils", ".", "split", "(", "path", ",", "'", "'", ")", ";", "if", "(", "vals", ".", "length", "!=", "3", ")", "{", "// blk, blkid, genstamp.meta", "continue", ";", "}", "String", "[", "]", "str", "=", "StringUtils", ".", "split", "(", "vals", "[", "2", "]", ",", "'", "'", ")", ";", "if", "(", "str", ".", "length", "!=", "2", ")", "{", "continue", ";", "}", "return", "Long", ".", "parseLong", "(", "str", "[", "0", "]", ")", ";", "}", "DataNode", ".", "LOG", ".", "warn", "(", "\"Block \"", "+", "blockName", "+", "\" does not have a metafile!\"", ")", ";", "return", "Block", ".", "GRANDFATHER_GENERATION_STAMP", ";", "}" ]
Find the metadata file for the specified block file. Return the generation stamp from the name of the metafile.
[ "Find", "the", "metadata", "file", "for", "the", "specified", "block", "file", ".", "Return", "the", "generation", "stamp", "from", "the", "name", "of", "the", "metafile", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/datanode/BlockWithChecksumFileReader.java#L397-L416
liferay/com-liferay-commerce
commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPSpecificationOptionWrapper.java
CPSpecificationOptionWrapper.getDescription
@Override public String getDescription(String languageId, boolean useDefault) { """ Returns the localized description of this cp specification option in the language, optionally using the default language if no localization exists for the requested language. @param languageId the ID of the language @param useDefault whether to use the default language if no localization exists for the requested language @return the localized description of this cp specification option """ return _cpSpecificationOption.getDescription(languageId, useDefault); }
java
@Override public String getDescription(String languageId, boolean useDefault) { return _cpSpecificationOption.getDescription(languageId, useDefault); }
[ "@", "Override", "public", "String", "getDescription", "(", "String", "languageId", ",", "boolean", "useDefault", ")", "{", "return", "_cpSpecificationOption", ".", "getDescription", "(", "languageId", ",", "useDefault", ")", ";", "}" ]
Returns the localized description of this cp specification option in the language, optionally using the default language if no localization exists for the requested language. @param languageId the ID of the language @param useDefault whether to use the default language if no localization exists for the requested language @return the localized description of this cp specification option
[ "Returns", "the", "localized", "description", "of", "this", "cp", "specification", "option", "in", "the", "language", "optionally", "using", "the", "default", "language", "if", "no", "localization", "exists", "for", "the", "requested", "language", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPSpecificationOptionWrapper.java#L287-L290
datasalt/pangool
core/src/main/java/com/datasalt/pangool/utils/HadoopUtils.java
HadoopUtils.fileToString
public static String fileToString(FileSystem fs, Path path) throws IOException { """ Reads the content of a file into a String. Return null if the file does not exist. """ if(!fs.exists(path)) { return null; } InputStream is = fs.open(path); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); char[] buff = new char[256]; StringBuilder sb = new StringBuilder(); int read; while((read = br.read(buff)) != -1) { sb.append(buff, 0, read); } br.close(); return sb.toString(); }
java
public static String fileToString(FileSystem fs, Path path) throws IOException { if(!fs.exists(path)) { return null; } InputStream is = fs.open(path); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); char[] buff = new char[256]; StringBuilder sb = new StringBuilder(); int read; while((read = br.read(buff)) != -1) { sb.append(buff, 0, read); } br.close(); return sb.toString(); }
[ "public", "static", "String", "fileToString", "(", "FileSystem", "fs", ",", "Path", "path", ")", "throws", "IOException", "{", "if", "(", "!", "fs", ".", "exists", "(", "path", ")", ")", "{", "return", "null", ";", "}", "InputStream", "is", "=", "fs", ".", "open", "(", "path", ")", ";", "InputStreamReader", "isr", "=", "new", "InputStreamReader", "(", "is", ")", ";", "BufferedReader", "br", "=", "new", "BufferedReader", "(", "isr", ")", ";", "char", "[", "]", "buff", "=", "new", "char", "[", "256", "]", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "int", "read", ";", "while", "(", "(", "read", "=", "br", ".", "read", "(", "buff", ")", ")", "!=", "-", "1", ")", "{", "sb", ".", "append", "(", "buff", ",", "0", ",", "read", ")", ";", "}", "br", ".", "close", "(", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Reads the content of a file into a String. Return null if the file does not exist.
[ "Reads", "the", "content", "of", "a", "file", "into", "a", "String", ".", "Return", "null", "if", "the", "file", "does", "not", "exist", "." ]
train
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/utils/HadoopUtils.java#L71-L87
pippo-java/pippo
pippo-core/src/main/java/ro/pippo/core/PippoSettings.java
PippoSettings.getBoolean
public boolean getBoolean(String name, boolean defaultValue) { """ Returns the boolean value for the specified name. If the name does not exist or the value for the name can not be interpreted as a boolean, the defaultValue is returned. @param name @param defaultValue @return name value or defaultValue """ String value = getString(name, null); if (!StringUtils.isNullOrEmpty(value)) { return Boolean.parseBoolean(value.trim()); } return defaultValue; }
java
public boolean getBoolean(String name, boolean defaultValue) { String value = getString(name, null); if (!StringUtils.isNullOrEmpty(value)) { return Boolean.parseBoolean(value.trim()); } return defaultValue; }
[ "public", "boolean", "getBoolean", "(", "String", "name", ",", "boolean", "defaultValue", ")", "{", "String", "value", "=", "getString", "(", "name", ",", "null", ")", ";", "if", "(", "!", "StringUtils", ".", "isNullOrEmpty", "(", "value", ")", ")", "{", "return", "Boolean", ".", "parseBoolean", "(", "value", ".", "trim", "(", ")", ")", ";", "}", "return", "defaultValue", ";", "}" ]
Returns the boolean value for the specified name. If the name does not exist or the value for the name can not be interpreted as a boolean, the defaultValue is returned. @param name @param defaultValue @return name value or defaultValue
[ "Returns", "the", "boolean", "value", "for", "the", "specified", "name", ".", "If", "the", "name", "does", "not", "exist", "or", "the", "value", "for", "the", "name", "can", "not", "be", "interpreted", "as", "a", "boolean", "the", "defaultValue", "is", "returned", "." ]
train
https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/PippoSettings.java#L477-L484
FasterXML/woodstox
src/main/java/com/ctc/wstx/io/StreamBootstrapper.java
StreamBootstrapper.getInstance
public static StreamBootstrapper getInstance(String pubId, SystemId sysId, byte[] data, int start, int end) { """ Factory method used when the underlying data provider is a pre-allocated block source, and no stream is used. Additionally the buffer passed is not owned by the bootstrapper or Reader that is created, so it is not to be recycled. """ return new StreamBootstrapper(pubId, sysId, data, start, end); }
java
public static StreamBootstrapper getInstance(String pubId, SystemId sysId, byte[] data, int start, int end) { return new StreamBootstrapper(pubId, sysId, data, start, end); }
[ "public", "static", "StreamBootstrapper", "getInstance", "(", "String", "pubId", ",", "SystemId", "sysId", ",", "byte", "[", "]", "data", ",", "int", "start", ",", "int", "end", ")", "{", "return", "new", "StreamBootstrapper", "(", "pubId", ",", "sysId", ",", "data", ",", "start", ",", "end", ")", ";", "}" ]
Factory method used when the underlying data provider is a pre-allocated block source, and no stream is used. Additionally the buffer passed is not owned by the bootstrapper or Reader that is created, so it is not to be recycled.
[ "Factory", "method", "used", "when", "the", "underlying", "data", "provider", "is", "a", "pre", "-", "allocated", "block", "source", "and", "no", "stream", "is", "used", ".", "Additionally", "the", "buffer", "passed", "is", "not", "owned", "by", "the", "bootstrapper", "or", "Reader", "that", "is", "created", "so", "it", "is", "not", "to", "be", "recycled", "." ]
train
https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/io/StreamBootstrapper.java#L147-L150
twitter/hraven
hraven-core/src/main/java/com/twitter/hraven/datasource/JobHistoryRawService.java
JobHistoryRawService.getStatusAgg
public boolean getStatusAgg(byte[] row, byte[] col) throws IOException { """ creates a Get to be fetch daily aggregation status from the RAW table @param row key @return {@link Get} @throws IOException """ Get g = new Get(row); g.addColumn(Constants.INFO_FAM_BYTES, col); Table rawTable = null; Cell cell = null; try { rawTable = hbaseConnection .getTable(TableName.valueOf(Constants.HISTORY_RAW_TABLE)); Result r = rawTable.get(g); cell = r.getColumnLatestCell(Constants.INFO_FAM_BYTES, col); } finally { if (rawTable != null) { rawTable.close(); } } boolean status = false; try { if (cell != null) { status = Bytes.toBoolean(CellUtil.cloneValue(cell)); } } catch (IllegalArgumentException iae) { LOG.error("Caught " + iae); } LOG.info("Returning from Raw, " + Bytes.toString(col) + " for this job=" + status); return status; }
java
public boolean getStatusAgg(byte[] row, byte[] col) throws IOException { Get g = new Get(row); g.addColumn(Constants.INFO_FAM_BYTES, col); Table rawTable = null; Cell cell = null; try { rawTable = hbaseConnection .getTable(TableName.valueOf(Constants.HISTORY_RAW_TABLE)); Result r = rawTable.get(g); cell = r.getColumnLatestCell(Constants.INFO_FAM_BYTES, col); } finally { if (rawTable != null) { rawTable.close(); } } boolean status = false; try { if (cell != null) { status = Bytes.toBoolean(CellUtil.cloneValue(cell)); } } catch (IllegalArgumentException iae) { LOG.error("Caught " + iae); } LOG.info("Returning from Raw, " + Bytes.toString(col) + " for this job=" + status); return status; }
[ "public", "boolean", "getStatusAgg", "(", "byte", "[", "]", "row", ",", "byte", "[", "]", "col", ")", "throws", "IOException", "{", "Get", "g", "=", "new", "Get", "(", "row", ")", ";", "g", ".", "addColumn", "(", "Constants", ".", "INFO_FAM_BYTES", ",", "col", ")", ";", "Table", "rawTable", "=", "null", ";", "Cell", "cell", "=", "null", ";", "try", "{", "rawTable", "=", "hbaseConnection", ".", "getTable", "(", "TableName", ".", "valueOf", "(", "Constants", ".", "HISTORY_RAW_TABLE", ")", ")", ";", "Result", "r", "=", "rawTable", ".", "get", "(", "g", ")", ";", "cell", "=", "r", ".", "getColumnLatestCell", "(", "Constants", ".", "INFO_FAM_BYTES", ",", "col", ")", ";", "}", "finally", "{", "if", "(", "rawTable", "!=", "null", ")", "{", "rawTable", ".", "close", "(", ")", ";", "}", "}", "boolean", "status", "=", "false", ";", "try", "{", "if", "(", "cell", "!=", "null", ")", "{", "status", "=", "Bytes", ".", "toBoolean", "(", "CellUtil", ".", "cloneValue", "(", "cell", ")", ")", ";", "}", "}", "catch", "(", "IllegalArgumentException", "iae", ")", "{", "LOG", ".", "error", "(", "\"Caught \"", "+", "iae", ")", ";", "}", "LOG", ".", "info", "(", "\"Returning from Raw, \"", "+", "Bytes", ".", "toString", "(", "col", ")", "+", "\" for this job=\"", "+", "status", ")", ";", "return", "status", ";", "}" ]
creates a Get to be fetch daily aggregation status from the RAW table @param row key @return {@link Get} @throws IOException
[ "creates", "a", "Get", "to", "be", "fetch", "daily", "aggregation", "status", "from", "the", "RAW", "table" ]
train
https://github.com/twitter/hraven/blob/e35996b6e2f016bcd18db0bad320be7c93d95208/hraven-core/src/main/java/com/twitter/hraven/datasource/JobHistoryRawService.java#L608-L634
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabasesInner.java
DatabasesInner.beginImportMethod
public ImportExportResponseInner beginImportMethod(String resourceGroupName, String serverName, ImportRequest parameters) { """ Imports a bacpac into a new database. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param parameters The required parameters for importing a Bacpac into a database. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ImportExportResponseInner object if successful. """ return beginImportMethodWithServiceResponseAsync(resourceGroupName, serverName, parameters).toBlocking().single().body(); }
java
public ImportExportResponseInner beginImportMethod(String resourceGroupName, String serverName, ImportRequest parameters) { return beginImportMethodWithServiceResponseAsync(resourceGroupName, serverName, parameters).toBlocking().single().body(); }
[ "public", "ImportExportResponseInner", "beginImportMethod", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "ImportRequest", "parameters", ")", "{", "return", "beginImportMethodWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Imports a bacpac into a new database. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param parameters The required parameters for importing a Bacpac into a database. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ImportExportResponseInner object if successful.
[ "Imports", "a", "bacpac", "into", "a", "new", "database", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabasesInner.java#L1814-L1816
Cornutum/tcases
tcases-io/src/main/java/org/cornutum/tcases/io/ProjectJson.java
ProjectJson.asSystemInputDef
private static SystemInputDef asSystemInputDef( JsonValue json) { """ Returns the system input definition represented by the given JSON value. """ try { SystemInputDef systemInput = null; if( json != null && json.getValueType() == OBJECT) { systemInput = SystemInputJson.asSystemInputDef( (JsonObject) json); } return systemInput; } catch( Exception e) { throw new ProjectException( "Error reading input definition", e); } }
java
private static SystemInputDef asSystemInputDef( JsonValue json) { try { SystemInputDef systemInput = null; if( json != null && json.getValueType() == OBJECT) { systemInput = SystemInputJson.asSystemInputDef( (JsonObject) json); } return systemInput; } catch( Exception e) { throw new ProjectException( "Error reading input definition", e); } }
[ "private", "static", "SystemInputDef", "asSystemInputDef", "(", "JsonValue", "json", ")", "{", "try", "{", "SystemInputDef", "systemInput", "=", "null", ";", "if", "(", "json", "!=", "null", "&&", "json", ".", "getValueType", "(", ")", "==", "OBJECT", ")", "{", "systemInput", "=", "SystemInputJson", ".", "asSystemInputDef", "(", "(", "JsonObject", ")", "json", ")", ";", "}", "return", "systemInput", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "ProjectException", "(", "\"Error reading input definition\"", ",", "e", ")", ";", "}", "}" ]
Returns the system input definition represented by the given JSON value.
[ "Returns", "the", "system", "input", "definition", "represented", "by", "the", "given", "JSON", "value", "." ]
train
https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-io/src/main/java/org/cornutum/tcases/io/ProjectJson.java#L75-L91
pravega/pravega
controller/src/main/java/io/pravega/controller/metrics/TransactionMetrics.java
TransactionMetrics.commitTransaction
public void commitTransaction(String scope, String streamName, Duration latency) { """ This method increments the global and Stream-related counters of committed Transactions and reports the latency of the operation. @param scope Scope. @param streamName Name of the Stream. @param latency Latency of the commit Transaction operation. """ DYNAMIC_LOGGER.incCounterValue(globalMetricName(COMMIT_TRANSACTION), 1); DYNAMIC_LOGGER.incCounterValue(COMMIT_TRANSACTION, 1, streamTags(scope, streamName)); commitTransactionLatency.reportSuccessValue(latency.toMillis()); }
java
public void commitTransaction(String scope, String streamName, Duration latency) { DYNAMIC_LOGGER.incCounterValue(globalMetricName(COMMIT_TRANSACTION), 1); DYNAMIC_LOGGER.incCounterValue(COMMIT_TRANSACTION, 1, streamTags(scope, streamName)); commitTransactionLatency.reportSuccessValue(latency.toMillis()); }
[ "public", "void", "commitTransaction", "(", "String", "scope", ",", "String", "streamName", ",", "Duration", "latency", ")", "{", "DYNAMIC_LOGGER", ".", "incCounterValue", "(", "globalMetricName", "(", "COMMIT_TRANSACTION", ")", ",", "1", ")", ";", "DYNAMIC_LOGGER", ".", "incCounterValue", "(", "COMMIT_TRANSACTION", ",", "1", ",", "streamTags", "(", "scope", ",", "streamName", ")", ")", ";", "commitTransactionLatency", ".", "reportSuccessValue", "(", "latency", ".", "toMillis", "(", ")", ")", ";", "}" ]
This method increments the global and Stream-related counters of committed Transactions and reports the latency of the operation. @param scope Scope. @param streamName Name of the Stream. @param latency Latency of the commit Transaction operation.
[ "This", "method", "increments", "the", "global", "and", "Stream", "-", "related", "counters", "of", "committed", "Transactions", "and", "reports", "the", "latency", "of", "the", "operation", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/metrics/TransactionMetrics.java#L71-L75
phax/ph-oton
ph-oton-security/src/main/java/com/helger/photon/security/token/accesstoken/AccessToken.java
AccessToken.createAccessTokenValidFromNow
@Nonnull public static AccessToken createAccessTokenValidFromNow (@Nullable final String sTokenString) { """ Create a new access token that is valid from now on for an infinite amount of time. @param sTokenString The existing token string. May be <code>null</code> in which case a new token string is created. @return Never <code>null</code>. """ // Length 66 so that the Base64 encoding does not add the "==" signs // Length must be dividable by 3 final String sRealTokenString = StringHelper.hasText (sTokenString) ? sTokenString : createNewTokenString (66); return new AccessToken (sRealTokenString, PDTFactory.getCurrentLocalDateTime (), null, new RevocationStatus ()); }
java
@Nonnull public static AccessToken createAccessTokenValidFromNow (@Nullable final String sTokenString) { // Length 66 so that the Base64 encoding does not add the "==" signs // Length must be dividable by 3 final String sRealTokenString = StringHelper.hasText (sTokenString) ? sTokenString : createNewTokenString (66); return new AccessToken (sRealTokenString, PDTFactory.getCurrentLocalDateTime (), null, new RevocationStatus ()); }
[ "@", "Nonnull", "public", "static", "AccessToken", "createAccessTokenValidFromNow", "(", "@", "Nullable", "final", "String", "sTokenString", ")", "{", "// Length 66 so that the Base64 encoding does not add the \"==\" signs", "// Length must be dividable by 3", "final", "String", "sRealTokenString", "=", "StringHelper", ".", "hasText", "(", "sTokenString", ")", "?", "sTokenString", ":", "createNewTokenString", "(", "66", ")", ";", "return", "new", "AccessToken", "(", "sRealTokenString", ",", "PDTFactory", ".", "getCurrentLocalDateTime", "(", ")", ",", "null", ",", "new", "RevocationStatus", "(", ")", ")", ";", "}" ]
Create a new access token that is valid from now on for an infinite amount of time. @param sTokenString The existing token string. May be <code>null</code> in which case a new token string is created. @return Never <code>null</code>.
[ "Create", "a", "new", "access", "token", "that", "is", "valid", "from", "now", "on", "for", "an", "infinite", "amount", "of", "time", "." ]
train
https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-security/src/main/java/com/helger/photon/security/token/accesstoken/AccessToken.java#L154-L161
btrplace/scheduler
btrpsl/src/main/java/org/btrplace/btrpsl/SymbolsTable.java
SymbolsTable.popTable
public boolean popTable() { """ Pop the table. Every variable created after the last pushTable() are removed from the table. The table can not be poped if it was not at least pushed once earlier. @return {@code true} if the table has been popped successfully. {@code false} otherwise """ if (currentLevel > 0) { //Remove all the variable having a level equals to currentLevel for (Iterator<Map.Entry<String, Integer>> ite = level.entrySet().iterator(); ite.hasNext(); ) { Map.Entry<String, Integer> e = ite.next(); if (e.getValue() == currentLevel) { ite.remove(); type.remove(e.getKey()); } } currentLevel--; return true; } return false; }
java
public boolean popTable() { if (currentLevel > 0) { //Remove all the variable having a level equals to currentLevel for (Iterator<Map.Entry<String, Integer>> ite = level.entrySet().iterator(); ite.hasNext(); ) { Map.Entry<String, Integer> e = ite.next(); if (e.getValue() == currentLevel) { ite.remove(); type.remove(e.getKey()); } } currentLevel--; return true; } return false; }
[ "public", "boolean", "popTable", "(", ")", "{", "if", "(", "currentLevel", ">", "0", ")", "{", "//Remove all the variable having a level equals to currentLevel", "for", "(", "Iterator", "<", "Map", ".", "Entry", "<", "String", ",", "Integer", ">", ">", "ite", "=", "level", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "ite", ".", "hasNext", "(", ")", ";", ")", "{", "Map", ".", "Entry", "<", "String", ",", "Integer", ">", "e", "=", "ite", ".", "next", "(", ")", ";", "if", "(", "e", ".", "getValue", "(", ")", "==", "currentLevel", ")", "{", "ite", ".", "remove", "(", ")", ";", "type", ".", "remove", "(", "e", ".", "getKey", "(", ")", ")", ";", "}", "}", "currentLevel", "--", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Pop the table. Every variable created after the last pushTable() are removed from the table. The table can not be poped if it was not at least pushed once earlier. @return {@code true} if the table has been popped successfully. {@code false} otherwise
[ "Pop", "the", "table", ".", "Every", "variable", "created", "after", "the", "last", "pushTable", "()", "are", "removed", "from", "the", "table", ".", "The", "table", "can", "not", "be", "poped", "if", "it", "was", "not", "at", "least", "pushed", "once", "earlier", "." ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/btrpsl/src/main/java/org/btrplace/btrpsl/SymbolsTable.java#L181-L195
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_network_private_networkId_DELETE
public void project_serviceName_network_private_networkId_DELETE(String serviceName, String networkId) throws IOException { """ Delete private network REST: DELETE /cloud/project/{serviceName}/network/private/{networkId} @param networkId [required] Network id @param serviceName [required] Project name """ String qPath = "/cloud/project/{serviceName}/network/private/{networkId}"; StringBuilder sb = path(qPath, serviceName, networkId); exec(qPath, "DELETE", sb.toString(), null); }
java
public void project_serviceName_network_private_networkId_DELETE(String serviceName, String networkId) throws IOException { String qPath = "/cloud/project/{serviceName}/network/private/{networkId}"; StringBuilder sb = path(qPath, serviceName, networkId); exec(qPath, "DELETE", sb.toString(), null); }
[ "public", "void", "project_serviceName_network_private_networkId_DELETE", "(", "String", "serviceName", ",", "String", "networkId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/network/private/{networkId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "networkId", ")", ";", "exec", "(", "qPath", ",", "\"DELETE\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "}" ]
Delete private network REST: DELETE /cloud/project/{serviceName}/network/private/{networkId} @param networkId [required] Network id @param serviceName [required] Project name
[ "Delete", "private", "network" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L768-L772
RobAustin/low-latency-primitive-concurrent-queues
src/main/java/uk/co/boundedbuffer/ConcurrentBlockingLongQueue.java
ConcurrentBlockingLongQueue.poll
public long poll(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { """ Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available. @param timeout how long to wait before giving up, in units of <tt>unit</tt> @param unit a <tt>TimeUnit</tt> determining how to interpret the <tt>timeout</tt> parameter @return the head of this queue, or throws a <tt>TimeoutException</tt> if the specified waiting time elapses before an element is available @throws InterruptedException if interrupted while waiting @throws java.util.concurrent.TimeoutException if timeout time is exceeded """ final int readLocation = this.consumerReadLocation; int nextReadLocation = blockForReadSpace(timeout, unit, readLocation); // purposely non volatile as the read memory barrier occurred when we read 'writeLocation' final long value = data[readLocation]; setReadLocation(nextReadLocation); return value; }
java
public long poll(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { final int readLocation = this.consumerReadLocation; int nextReadLocation = blockForReadSpace(timeout, unit, readLocation); // purposely non volatile as the read memory barrier occurred when we read 'writeLocation' final long value = data[readLocation]; setReadLocation(nextReadLocation); return value; }
[ "public", "long", "poll", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "InterruptedException", ",", "TimeoutException", "{", "final", "int", "readLocation", "=", "this", ".", "consumerReadLocation", ";", "int", "nextReadLocation", "=", "blockForReadSpace", "(", "timeout", ",", "unit", ",", "readLocation", ")", ";", "// purposely non volatile as the read memory barrier occurred when we read 'writeLocation'", "final", "long", "value", "=", "data", "[", "readLocation", "]", ";", "setReadLocation", "(", "nextReadLocation", ")", ";", "return", "value", ";", "}" ]
Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available. @param timeout how long to wait before giving up, in units of <tt>unit</tt> @param unit a <tt>TimeUnit</tt> determining how to interpret the <tt>timeout</tt> parameter @return the head of this queue, or throws a <tt>TimeoutException</tt> if the specified waiting time elapses before an element is available @throws InterruptedException if interrupted while waiting @throws java.util.concurrent.TimeoutException if timeout time is exceeded
[ "Retrieves", "and", "removes", "the", "head", "of", "this", "queue", "waiting", "up", "to", "the", "specified", "wait", "time", "if", "necessary", "for", "an", "element", "to", "become", "available", "." ]
train
https://github.com/RobAustin/low-latency-primitive-concurrent-queues/blob/ffcf95a8135750c0b23cd486346a1f68a4724b1c/src/main/java/uk/co/boundedbuffer/ConcurrentBlockingLongQueue.java#L298-L310
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_acl_POST
public OvhAcl project_serviceName_acl_POST(String serviceName, String accountId, OvhAclTypeEnum type) throws IOException { """ Create new ACL REST: POST /cloud/project/{serviceName}/acl @param type [required] Acl type @param accountId [required] Deleguates rights to @param serviceName [required] The project id """ String qPath = "/cloud/project/{serviceName}/acl"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "accountId", accountId); addBody(o, "type", type); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhAcl.class); }
java
public OvhAcl project_serviceName_acl_POST(String serviceName, String accountId, OvhAclTypeEnum type) throws IOException { String qPath = "/cloud/project/{serviceName}/acl"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "accountId", accountId); addBody(o, "type", type); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhAcl.class); }
[ "public", "OvhAcl", "project_serviceName_acl_POST", "(", "String", "serviceName", ",", "String", "accountId", ",", "OvhAclTypeEnum", "type", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/acl\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"accountId\"", ",", "accountId", ")", ";", "addBody", "(", "o", ",", "\"type\"", ",", "type", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhAcl", ".", "class", ")", ";", "}" ]
Create new ACL REST: POST /cloud/project/{serviceName}/acl @param type [required] Acl type @param accountId [required] Deleguates rights to @param serviceName [required] The project id
[ "Create", "new", "ACL" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L363-L371
ironjacamar/ironjacamar
sjc/src/main/java/org/ironjacamar/sjc/maven/AbstractHostPortMojo.java
AbstractHostPortMojo.isCommandAvailable
protected boolean isCommandAvailable(String command) throws Throwable { """ Is a command available @param command The command name @return True if available; otherwise false @exception Throwable If an error occurs """ Socket socket = null; try { socket = new Socket(host, port); ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); output.writeUTF("getcommand"); output.writeInt(1); output.writeUTF(command); output.flush(); ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); Serializable result = (Serializable)input.readObject(); if (result == null || !(result instanceof Throwable)) return true; return false; } finally { if (socket != null) { try { socket.close(); } catch (IOException ioe) { // Ignore } } } }
java
protected boolean isCommandAvailable(String command) throws Throwable { Socket socket = null; try { socket = new Socket(host, port); ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); output.writeUTF("getcommand"); output.writeInt(1); output.writeUTF(command); output.flush(); ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); Serializable result = (Serializable)input.readObject(); if (result == null || !(result instanceof Throwable)) return true; return false; } finally { if (socket != null) { try { socket.close(); } catch (IOException ioe) { // Ignore } } } }
[ "protected", "boolean", "isCommandAvailable", "(", "String", "command", ")", "throws", "Throwable", "{", "Socket", "socket", "=", "null", ";", "try", "{", "socket", "=", "new", "Socket", "(", "host", ",", "port", ")", ";", "ObjectOutputStream", "output", "=", "new", "ObjectOutputStream", "(", "socket", ".", "getOutputStream", "(", ")", ")", ";", "output", ".", "writeUTF", "(", "\"getcommand\"", ")", ";", "output", ".", "writeInt", "(", "1", ")", ";", "output", ".", "writeUTF", "(", "command", ")", ";", "output", ".", "flush", "(", ")", ";", "ObjectInputStream", "input", "=", "new", "ObjectInputStream", "(", "socket", ".", "getInputStream", "(", ")", ")", ";", "Serializable", "result", "=", "(", "Serializable", ")", "input", ".", "readObject", "(", ")", ";", "if", "(", "result", "==", "null", "||", "!", "(", "result", "instanceof", "Throwable", ")", ")", "return", "true", ";", "return", "false", ";", "}", "finally", "{", "if", "(", "socket", "!=", "null", ")", "{", "try", "{", "socket", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "// Ignore", "}", "}", "}", "}" ]
Is a command available @param command The command name @return True if available; otherwise false @exception Throwable If an error occurs
[ "Is", "a", "command", "available" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/sjc/src/main/java/org/ironjacamar/sjc/maven/AbstractHostPortMojo.java#L109-L146
hal/core
gui/src/main/java/org/jboss/as/console/client/widgets/tables/DataProviderFilter.java
DataProviderFilter.reset
public void reset() { """ a new backup if the data provider list will be made. <br/> you need to do it when the data provider gets new records. """ origVisibleRange = new Range(0, this.delegate.getList().size()); snapshot(); clearFilter(); filter.setText(""); }
java
public void reset() { origVisibleRange = new Range(0, this.delegate.getList().size()); snapshot(); clearFilter(); filter.setText(""); }
[ "public", "void", "reset", "(", ")", "{", "origVisibleRange", "=", "new", "Range", "(", "0", ",", "this", ".", "delegate", ".", "getList", "(", ")", ".", "size", "(", ")", ")", ";", "snapshot", "(", ")", ";", "clearFilter", "(", ")", ";", "filter", ".", "setText", "(", "\"\"", ")", ";", "}" ]
a new backup if the data provider list will be made. <br/> you need to do it when the data provider gets new records.
[ "a", "new", "backup", "if", "the", "data", "provider", "list", "will", "be", "made", ".", "<br", "/", ">", "you", "need", "to", "do", "it", "when", "the", "data", "provider", "gets", "new", "records", "." ]
train
https://github.com/hal/core/blob/d6d03f0bb128dc0470f5dc75fdb1ea1014400602/gui/src/main/java/org/jboss/as/console/client/widgets/tables/DataProviderFilter.java#L65-L70
VoltDB/voltdb
third_party/java/src/com/google_voltpatches/common/util/concurrent/Uninterruptibles.java
Uninterruptibles.getUninterruptibly
@CanIgnoreReturnValue @GwtIncompatible // TODO public static <V> V getUninterruptibly(Future<V> future, long timeout, TimeUnit unit) throws ExecutionException, TimeoutException { """ Invokes {@code future.}{@link Future#get(long, TimeUnit) get(timeout, unit)} uninterruptibly. <p>Similar methods: <ul> <li>To retrieve a result from a {@code Future} that is already done, use {@link Futures#getDone Futures.getDone}. <li>To treat {@link InterruptedException} uniformly with other exceptions, use {@link Futures#getChecked(Future, Class, long, TimeUnit) Futures.getChecked}. <li>To get uninterruptibility and remove checked exceptions, use {@link Futures#getUnchecked}. </ul> @throws ExecutionException if the computation threw an exception @throws CancellationException if the computation was cancelled @throws TimeoutException if the wait timed out """ boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // Future treats negative timeouts just like zero. return future.get(remainingNanos, NANOSECONDS); } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
java
@CanIgnoreReturnValue @GwtIncompatible // TODO public static <V> V getUninterruptibly(Future<V> future, long timeout, TimeUnit unit) throws ExecutionException, TimeoutException { boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // Future treats negative timeouts just like zero. return future.get(remainingNanos, NANOSECONDS); } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
[ "@", "CanIgnoreReturnValue", "@", "GwtIncompatible", "// TODO", "public", "static", "<", "V", ">", "V", "getUninterruptibly", "(", "Future", "<", "V", ">", "future", ",", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "ExecutionException", ",", "TimeoutException", "{", "boolean", "interrupted", "=", "false", ";", "try", "{", "long", "remainingNanos", "=", "unit", ".", "toNanos", "(", "timeout", ")", ";", "long", "end", "=", "System", ".", "nanoTime", "(", ")", "+", "remainingNanos", ";", "while", "(", "true", ")", "{", "try", "{", "// Future treats negative timeouts just like zero.", "return", "future", ".", "get", "(", "remainingNanos", ",", "NANOSECONDS", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "interrupted", "=", "true", ";", "remainingNanos", "=", "end", "-", "System", ".", "nanoTime", "(", ")", ";", "}", "}", "}", "finally", "{", "if", "(", "interrupted", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "}", "}", "}" ]
Invokes {@code future.}{@link Future#get(long, TimeUnit) get(timeout, unit)} uninterruptibly. <p>Similar methods: <ul> <li>To retrieve a result from a {@code Future} that is already done, use {@link Futures#getDone Futures.getDone}. <li>To treat {@link InterruptedException} uniformly with other exceptions, use {@link Futures#getChecked(Future, Class, long, TimeUnit) Futures.getChecked}. <li>To get uninterruptibility and remove checked exceptions, use {@link Futures#getUnchecked}. </ul> @throws ExecutionException if the computation threw an exception @throws CancellationException if the computation was cancelled @throws TimeoutException if the wait timed out
[ "Invokes", "{", "@code", "future", ".", "}", "{", "@link", "Future#get", "(", "long", "TimeUnit", ")", "get", "(", "timeout", "unit", ")", "}", "uninterruptibly", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/com/google_voltpatches/common/util/concurrent/Uninterruptibles.java#L171-L194
unbescape/unbescape
src/main/java/org/unbescape/uri/UriEscape.java
UriEscape.escapeUriPath
public static void escapeUriPath(final char[] text, final int offset, final int len, final Writer writer) throws IOException { """ <p> Perform am URI path <strong>escape</strong> operation on a <tt>char[]</tt> input using <tt>UTF-8</tt> as encoding. </p> <p> The following are the only allowed chars in an URI path (will not be escaped): </p> <ul> <li><tt>A-Z a-z 0-9</tt></li> <li><tt>- . _ ~</tt></li> <li><tt>! $ &amp; ' ( ) * + , ; =</tt></li> <li><tt>: @</tt></li> <li><tt>/</tt></li> </ul> <p> All other chars will be escaped by converting them to the sequence of bytes that represents them in the <tt>UTF-8</tt> and then representing each byte in <tt>%HH</tt> syntax, being <tt>HH</tt> the hexadecimal representation of the byte. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>char[]</tt> to be escaped. @param offset the position in <tt>text</tt> at which the escape operation should start. @param len the number of characters in <tt>text</tt> that should be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs """ escapeUriPath(text, offset, len, writer, DEFAULT_ENCODING); }
java
public static void escapeUriPath(final char[] text, final int offset, final int len, final Writer writer) throws IOException { escapeUriPath(text, offset, len, writer, DEFAULT_ENCODING); }
[ "public", "static", "void", "escapeUriPath", "(", "final", "char", "[", "]", "text", ",", "final", "int", "offset", ",", "final", "int", "len", ",", "final", "Writer", "writer", ")", "throws", "IOException", "{", "escapeUriPath", "(", "text", ",", "offset", ",", "len", ",", "writer", ",", "DEFAULT_ENCODING", ")", ";", "}" ]
<p> Perform am URI path <strong>escape</strong> operation on a <tt>char[]</tt> input using <tt>UTF-8</tt> as encoding. </p> <p> The following are the only allowed chars in an URI path (will not be escaped): </p> <ul> <li><tt>A-Z a-z 0-9</tt></li> <li><tt>- . _ ~</tt></li> <li><tt>! $ &amp; ' ( ) * + , ; =</tt></li> <li><tt>: @</tt></li> <li><tt>/</tt></li> </ul> <p> All other chars will be escaped by converting them to the sequence of bytes that represents them in the <tt>UTF-8</tt> and then representing each byte in <tt>%HH</tt> syntax, being <tt>HH</tt> the hexadecimal representation of the byte. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>char[]</tt> to be escaped. @param offset the position in <tt>text</tt> at which the escape operation should start. @param len the number of characters in <tt>text</tt> that should be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs
[ "<p", ">", "Perform", "am", "URI", "path", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "char", "[]", "<", "/", "tt", ">", "input", "using", "<tt", ">", "UTF", "-", "8<", "/", "tt", ">", "as", "encoding", ".", "<", "/", "p", ">", "<p", ">", "The", "following", "are", "the", "only", "allowed", "chars", "in", "an", "URI", "path", "(", "will", "not", "be", "escaped", ")", ":", "<", "/", "p", ">", "<ul", ">", "<li", ">", "<tt", ">", "A", "-", "Z", "a", "-", "z", "0", "-", "9<", "/", "tt", ">", "<", "/", "li", ">", "<li", ">", "<tt", ">", "-", ".", "_", "~<", "/", "tt", ">", "<", "/", "li", ">", "<li", ">", "<tt", ">", "!", "$", "&amp", ";", "(", ")", "*", "+", ";", "=", "<", "/", "tt", ">", "<", "/", "li", ">", "<li", ">", "<tt", ">", ":", "@<", "/", "tt", ">", "<", "/", "li", ">", "<li", ">", "<tt", ">", "/", "<", "/", "tt", ">", "<", "/", "li", ">", "<", "/", "ul", ">", "<p", ">", "All", "other", "chars", "will", "be", "escaped", "by", "converting", "them", "to", "the", "sequence", "of", "bytes", "that", "represents", "them", "in", "the", "<tt", ">", "UTF", "-", "8<", "/", "tt", ">", "and", "then", "representing", "each", "byte", "in", "<tt", ">", "%HH<", "/", "tt", ">", "syntax", "being", "<tt", ">", "HH<", "/", "tt", ">", "the", "hexadecimal", "representation", "of", "the", "byte", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "is", "<strong", ">", "thread", "-", "safe<", "/", "strong", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L1146-L1149
jMetal/jMetal
jmetal-core/src/main/java/org/uma/jmetal/util/neighborhood/util/TwoDimensionalMesh.java
TwoDimensionalMesh.getNeighbors
public List<S> getNeighbors(List<S> solutionList, int solutionPosition) { """ Returns the north,south, east, and west solutions of a given solution @param solutionList the solution set from where the neighbors are taken @param solutionPosition Represents the position of the solution """ if (solutionList == null) { throw new JMetalException("The solution list is null") ; } else if (solutionList.size() == 0) { throw new JMetalException("The solution list is empty") ; } else if (solutionPosition < 0) { throw new JMetalException("The solution position value is negative: " + solutionPosition) ; } else if (solutionList.size() != rows * columns) { throw new JMetalException("The solution list size " + solutionList.size() + " is not" + "equal to the grid size: " + rows + " * " + columns) ; } else if (solutionPosition >= solutionList.size()) { throw new JMetalException("The solution position value " + solutionPosition + " is equal or greater than the solution list size " + solutionList.size()) ; } return findNeighbors(solutionList, solutionPosition, neighborhood); }
java
public List<S> getNeighbors(List<S> solutionList, int solutionPosition) { if (solutionList == null) { throw new JMetalException("The solution list is null") ; } else if (solutionList.size() == 0) { throw new JMetalException("The solution list is empty") ; } else if (solutionPosition < 0) { throw new JMetalException("The solution position value is negative: " + solutionPosition) ; } else if (solutionList.size() != rows * columns) { throw new JMetalException("The solution list size " + solutionList.size() + " is not" + "equal to the grid size: " + rows + " * " + columns) ; } else if (solutionPosition >= solutionList.size()) { throw new JMetalException("The solution position value " + solutionPosition + " is equal or greater than the solution list size " + solutionList.size()) ; } return findNeighbors(solutionList, solutionPosition, neighborhood); }
[ "public", "List", "<", "S", ">", "getNeighbors", "(", "List", "<", "S", ">", "solutionList", ",", "int", "solutionPosition", ")", "{", "if", "(", "solutionList", "==", "null", ")", "{", "throw", "new", "JMetalException", "(", "\"The solution list is null\"", ")", ";", "}", "else", "if", "(", "solutionList", ".", "size", "(", ")", "==", "0", ")", "{", "throw", "new", "JMetalException", "(", "\"The solution list is empty\"", ")", ";", "}", "else", "if", "(", "solutionPosition", "<", "0", ")", "{", "throw", "new", "JMetalException", "(", "\"The solution position value is negative: \"", "+", "solutionPosition", ")", ";", "}", "else", "if", "(", "solutionList", ".", "size", "(", ")", "!=", "rows", "*", "columns", ")", "{", "throw", "new", "JMetalException", "(", "\"The solution list size \"", "+", "solutionList", ".", "size", "(", ")", "+", "\" is not\"", "+", "\"equal to the grid size: \"", "+", "rows", "+", "\" * \"", "+", "columns", ")", ";", "}", "else", "if", "(", "solutionPosition", ">=", "solutionList", ".", "size", "(", ")", ")", "{", "throw", "new", "JMetalException", "(", "\"The solution position value \"", "+", "solutionPosition", "+", "\" is equal or greater than the solution list size \"", "+", "solutionList", ".", "size", "(", ")", ")", ";", "}", "return", "findNeighbors", "(", "solutionList", ",", "solutionPosition", ",", "neighborhood", ")", ";", "}" ]
Returns the north,south, east, and west solutions of a given solution @param solutionList the solution set from where the neighbors are taken @param solutionPosition Represents the position of the solution
[ "Returns", "the", "north", "south", "east", "and", "west", "solutions", "of", "a", "given", "solution", "@param", "solutionList", "the", "solution", "set", "from", "where", "the", "neighbors", "are", "taken", "@param", "solutionPosition", "Represents", "the", "position", "of", "the", "solution" ]
train
https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-core/src/main/java/org/uma/jmetal/util/neighborhood/util/TwoDimensionalMesh.java#L119-L137
AltBeacon/android-beacon-library
lib/src/main/java/org/altbeacon/beacon/service/ScanHelper.java
ScanHelper.getScanCallbackIntent
PendingIntent getScanCallbackIntent() { """ Low power scan results in the background will be delivered via Intent """ Intent intent = new Intent(mContext, StartupBroadcastReceiver.class); intent.putExtra("o-scan", true); return PendingIntent.getBroadcast(mContext,0, intent, PendingIntent.FLAG_UPDATE_CURRENT); }
java
PendingIntent getScanCallbackIntent() { Intent intent = new Intent(mContext, StartupBroadcastReceiver.class); intent.putExtra("o-scan", true); return PendingIntent.getBroadcast(mContext,0, intent, PendingIntent.FLAG_UPDATE_CURRENT); }
[ "PendingIntent", "getScanCallbackIntent", "(", ")", "{", "Intent", "intent", "=", "new", "Intent", "(", "mContext", ",", "StartupBroadcastReceiver", ".", "class", ")", ";", "intent", ".", "putExtra", "(", "\"o-scan\"", ",", "true", ")", ";", "return", "PendingIntent", ".", "getBroadcast", "(", "mContext", ",", "0", ",", "intent", ",", "PendingIntent", ".", "FLAG_UPDATE_CURRENT", ")", ";", "}" ]
Low power scan results in the background will be delivered via Intent
[ "Low", "power", "scan", "results", "in", "the", "background", "will", "be", "delivered", "via", "Intent" ]
train
https://github.com/AltBeacon/android-beacon-library/blob/f7f3a323ea7415d53e7bd695ff6a01f1501d5dc3/lib/src/main/java/org/altbeacon/beacon/service/ScanHelper.java#L250-L254
dbracewell/mango
src/main/java/com/davidbracewell/config/Config.java
Config.setProperty
@SneakyThrows public static void setProperty(String name, String value) { """ Sets the value of a property. @param name the name of the property @param value the value of the property """ getInstance().properties.put(name, value); if (name.toLowerCase().endsWith(".level")) { String className = name.substring(0, name.length() - ".level".length()); LogManager.getLogManager().setLevel(className, Level.parse(value.trim().toUpperCase())); } if (name.equals("com.davidbracewell.logging.logfile")) { LogManager.addFileHandler(value); } if (name.toLowerCase().startsWith(SYSTEM_PROPERTY)) { String systemSetting = name.substring(SYSTEM_PROPERTY.length()); System.setProperty(systemSetting, value); } log.finest("Setting property {0} to value of {1}", name, value); }
java
@SneakyThrows public static void setProperty(String name, String value) { getInstance().properties.put(name, value); if (name.toLowerCase().endsWith(".level")) { String className = name.substring(0, name.length() - ".level".length()); LogManager.getLogManager().setLevel(className, Level.parse(value.trim().toUpperCase())); } if (name.equals("com.davidbracewell.logging.logfile")) { LogManager.addFileHandler(value); } if (name.toLowerCase().startsWith(SYSTEM_PROPERTY)) { String systemSetting = name.substring(SYSTEM_PROPERTY.length()); System.setProperty(systemSetting, value); } log.finest("Setting property {0} to value of {1}", name, value); }
[ "@", "SneakyThrows", "public", "static", "void", "setProperty", "(", "String", "name", ",", "String", "value", ")", "{", "getInstance", "(", ")", ".", "properties", ".", "put", "(", "name", ",", "value", ")", ";", "if", "(", "name", ".", "toLowerCase", "(", ")", ".", "endsWith", "(", "\".level\"", ")", ")", "{", "String", "className", "=", "name", ".", "substring", "(", "0", ",", "name", ".", "length", "(", ")", "-", "\".level\"", ".", "length", "(", ")", ")", ";", "LogManager", ".", "getLogManager", "(", ")", ".", "setLevel", "(", "className", ",", "Level", ".", "parse", "(", "value", ".", "trim", "(", ")", ".", "toUpperCase", "(", ")", ")", ")", ";", "}", "if", "(", "name", ".", "equals", "(", "\"com.davidbracewell.logging.logfile\"", ")", ")", "{", "LogManager", ".", "addFileHandler", "(", "value", ")", ";", "}", "if", "(", "name", ".", "toLowerCase", "(", ")", ".", "startsWith", "(", "SYSTEM_PROPERTY", ")", ")", "{", "String", "systemSetting", "=", "name", ".", "substring", "(", "SYSTEM_PROPERTY", ".", "length", "(", ")", ")", ";", "System", ".", "setProperty", "(", "systemSetting", ",", "value", ")", ";", "}", "log", ".", "finest", "(", "\"Setting property {0} to value of {1}\"", ",", "name", ",", "value", ")", ";", "}" ]
Sets the value of a property. @param name the name of the property @param value the value of the property
[ "Sets", "the", "value", "of", "a", "property", "." ]
train
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/config/Config.java#L718-L733
Azure/azure-sdk-for-java
compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetsInner.java
VirtualMachineScaleSetsInner.redeployAsync
public Observable<OperationStatusResponseInner> redeployAsync(String resourceGroupName, String vmScaleSetName) { """ Redeploy one or more virtual machines in a VM scale set. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return redeployWithServiceResponseAsync(resourceGroupName, vmScaleSetName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Override public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) { return response.body(); } }); }
java
public Observable<OperationStatusResponseInner> redeployAsync(String resourceGroupName, String vmScaleSetName) { return redeployWithServiceResponseAsync(resourceGroupName, vmScaleSetName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Override public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "OperationStatusResponseInner", ">", "redeployAsync", "(", "String", "resourceGroupName", ",", "String", "vmScaleSetName", ")", "{", "return", "redeployWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmScaleSetName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "OperationStatusResponseInner", ">", ",", "OperationStatusResponseInner", ">", "(", ")", "{", "@", "Override", "public", "OperationStatusResponseInner", "call", "(", "ServiceResponse", "<", "OperationStatusResponseInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Redeploy one or more virtual machines in a VM scale set. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Redeploy", "one", "or", "more", "virtual", "machines", "in", "a", "VM", "scale", "set", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetsInner.java#L2889-L2896
OpenLiberty/open-liberty
dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/client/DataModelSerializer.java
DataModelSerializer.serializeAsStream
public static void serializeAsStream(Object o, OutputStream s) throws IOException { """ Convert a POJO into Serialized JSON form. @param o the POJO to serialize @param s the OutputStream to write to.. @throws IOException when there are problems creating the JSON. """ try { JsonStructure builtJsonObject = findFieldsToSerialize(o).mainObject; Map<String, Object> config = new HashMap<String, Object>(); config.put(JsonGenerator.PRETTY_PRINTING, true); JsonWriterFactory writerFactory = Json.createWriterFactory(config); JsonWriter streamWriter = writerFactory.createWriter(s); streamWriter.write(builtJsonObject); } catch (IllegalStateException ise) { // the reflective attempt to build the object failed. throw new IOException("Unable to build JSON for Object", ise); } catch (JsonException e) { throw new IOException("Unable to build JSON for Object", e); } }
java
public static void serializeAsStream(Object o, OutputStream s) throws IOException { try { JsonStructure builtJsonObject = findFieldsToSerialize(o).mainObject; Map<String, Object> config = new HashMap<String, Object>(); config.put(JsonGenerator.PRETTY_PRINTING, true); JsonWriterFactory writerFactory = Json.createWriterFactory(config); JsonWriter streamWriter = writerFactory.createWriter(s); streamWriter.write(builtJsonObject); } catch (IllegalStateException ise) { // the reflective attempt to build the object failed. throw new IOException("Unable to build JSON for Object", ise); } catch (JsonException e) { throw new IOException("Unable to build JSON for Object", e); } }
[ "public", "static", "void", "serializeAsStream", "(", "Object", "o", ",", "OutputStream", "s", ")", "throws", "IOException", "{", "try", "{", "JsonStructure", "builtJsonObject", "=", "findFieldsToSerialize", "(", "o", ")", ".", "mainObject", ";", "Map", "<", "String", ",", "Object", ">", "config", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "config", ".", "put", "(", "JsonGenerator", ".", "PRETTY_PRINTING", ",", "true", ")", ";", "JsonWriterFactory", "writerFactory", "=", "Json", ".", "createWriterFactory", "(", "config", ")", ";", "JsonWriter", "streamWriter", "=", "writerFactory", ".", "createWriter", "(", "s", ")", ";", "streamWriter", ".", "write", "(", "builtJsonObject", ")", ";", "}", "catch", "(", "IllegalStateException", "ise", ")", "{", "// the reflective attempt to build the object failed.", "throw", "new", "IOException", "(", "\"Unable to build JSON for Object\"", ",", "ise", ")", ";", "}", "catch", "(", "JsonException", "e", ")", "{", "throw", "new", "IOException", "(", "\"Unable to build JSON for Object\"", ",", "e", ")", ";", "}", "}" ]
Convert a POJO into Serialized JSON form. @param o the POJO to serialize @param s the OutputStream to write to.. @throws IOException when there are problems creating the JSON.
[ "Convert", "a", "POJO", "into", "Serialized", "JSON", "form", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/client/DataModelSerializer.java#L327-L341
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/jdbc/PgCallableStatement.java
PgCallableStatement.checkIndex
private void checkIndex(int parameterIndex, boolean fetchingData) throws SQLException { """ Helper function for the getXXX calls to check isFunction and index == 1. @param parameterIndex index of getXXX (index) check to make sure is a function and index == 1 @param fetchingData fetching data """ if (!isFunction) { throw new PSQLException( GT.tr( "A CallableStatement was declared, but no call to registerOutParameter(1, <some type>) was made."), PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL); } if (fetchingData) { if (!returnTypeSet) { throw new PSQLException(GT.tr("No function outputs were registered."), PSQLState.OBJECT_NOT_IN_STATE); } if (callResult == null) { throw new PSQLException( GT.tr("Results cannot be retrieved from a CallableStatement before it is executed."), PSQLState.NO_DATA); } lastIndex = parameterIndex; } }
java
private void checkIndex(int parameterIndex, boolean fetchingData) throws SQLException { if (!isFunction) { throw new PSQLException( GT.tr( "A CallableStatement was declared, but no call to registerOutParameter(1, <some type>) was made."), PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL); } if (fetchingData) { if (!returnTypeSet) { throw new PSQLException(GT.tr("No function outputs were registered."), PSQLState.OBJECT_NOT_IN_STATE); } if (callResult == null) { throw new PSQLException( GT.tr("Results cannot be retrieved from a CallableStatement before it is executed."), PSQLState.NO_DATA); } lastIndex = parameterIndex; } }
[ "private", "void", "checkIndex", "(", "int", "parameterIndex", ",", "boolean", "fetchingData", ")", "throws", "SQLException", "{", "if", "(", "!", "isFunction", ")", "{", "throw", "new", "PSQLException", "(", "GT", ".", "tr", "(", "\"A CallableStatement was declared, but no call to registerOutParameter(1, <some type>) was made.\"", ")", ",", "PSQLState", ".", "STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL", ")", ";", "}", "if", "(", "fetchingData", ")", "{", "if", "(", "!", "returnTypeSet", ")", "{", "throw", "new", "PSQLException", "(", "GT", ".", "tr", "(", "\"No function outputs were registered.\"", ")", ",", "PSQLState", ".", "OBJECT_NOT_IN_STATE", ")", ";", "}", "if", "(", "callResult", "==", "null", ")", "{", "throw", "new", "PSQLException", "(", "GT", ".", "tr", "(", "\"Results cannot be retrieved from a CallableStatement before it is executed.\"", ")", ",", "PSQLState", ".", "NO_DATA", ")", ";", "}", "lastIndex", "=", "parameterIndex", ";", "}", "}" ]
Helper function for the getXXX calls to check isFunction and index == 1. @param parameterIndex index of getXXX (index) check to make sure is a function and index == 1 @param fetchingData fetching data
[ "Helper", "function", "for", "the", "getXXX", "calls", "to", "check", "isFunction", "and", "index", "==", "1", "." ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/PgCallableStatement.java#L403-L425
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/integration/Seam2Processor.java
Seam2Processor.getSeamIntResourceRoot
protected synchronized ResourceRoot getSeamIntResourceRoot() throws DeploymentUnitProcessingException { """ Lookup Seam integration resource loader. @return the Seam integration resource loader @throws DeploymentUnitProcessingException for any error """ try { if (seamIntResourceRoot == null) { final ModuleLoader moduleLoader = Module.getBootModuleLoader(); Module extModule = moduleLoader.loadModule(EXT_CONTENT_MODULE); URL url = extModule.getExportedResource(SEAM_INT_JAR); if (url == null) throw ServerLogger.ROOT_LOGGER.noSeamIntegrationJarPresent(extModule); File file = new File(url.toURI()); VirtualFile vf = VFS.getChild(file.toURI()); final Closeable mountHandle = VFS.mountZip(file, vf, TempFileProviderService.provider()); Service<Closeable> mountHandleService = new Service<Closeable>() { public void start(StartContext startContext) throws StartException { } public void stop(StopContext stopContext) { VFSUtils.safeClose(mountHandle); } public Closeable getValue() throws IllegalStateException, IllegalArgumentException { return mountHandle; } }; ServiceBuilder<Closeable> builder = serviceTarget.addService(ServiceName.JBOSS.append(SEAM_INT_JAR), mountHandleService); builder.setInitialMode(ServiceController.Mode.ACTIVE).install(); serviceTarget = null; // our cleanup service install work is done MountHandle dummy = MountHandle.create(null); // actual close is done by the MSC service above seamIntResourceRoot = new ResourceRoot(vf, dummy); } return seamIntResourceRoot; } catch (Exception e) { throw new DeploymentUnitProcessingException(e); } }
java
protected synchronized ResourceRoot getSeamIntResourceRoot() throws DeploymentUnitProcessingException { try { if (seamIntResourceRoot == null) { final ModuleLoader moduleLoader = Module.getBootModuleLoader(); Module extModule = moduleLoader.loadModule(EXT_CONTENT_MODULE); URL url = extModule.getExportedResource(SEAM_INT_JAR); if (url == null) throw ServerLogger.ROOT_LOGGER.noSeamIntegrationJarPresent(extModule); File file = new File(url.toURI()); VirtualFile vf = VFS.getChild(file.toURI()); final Closeable mountHandle = VFS.mountZip(file, vf, TempFileProviderService.provider()); Service<Closeable> mountHandleService = new Service<Closeable>() { public void start(StartContext startContext) throws StartException { } public void stop(StopContext stopContext) { VFSUtils.safeClose(mountHandle); } public Closeable getValue() throws IllegalStateException, IllegalArgumentException { return mountHandle; } }; ServiceBuilder<Closeable> builder = serviceTarget.addService(ServiceName.JBOSS.append(SEAM_INT_JAR), mountHandleService); builder.setInitialMode(ServiceController.Mode.ACTIVE).install(); serviceTarget = null; // our cleanup service install work is done MountHandle dummy = MountHandle.create(null); // actual close is done by the MSC service above seamIntResourceRoot = new ResourceRoot(vf, dummy); } return seamIntResourceRoot; } catch (Exception e) { throw new DeploymentUnitProcessingException(e); } }
[ "protected", "synchronized", "ResourceRoot", "getSeamIntResourceRoot", "(", ")", "throws", "DeploymentUnitProcessingException", "{", "try", "{", "if", "(", "seamIntResourceRoot", "==", "null", ")", "{", "final", "ModuleLoader", "moduleLoader", "=", "Module", ".", "getBootModuleLoader", "(", ")", ";", "Module", "extModule", "=", "moduleLoader", ".", "loadModule", "(", "EXT_CONTENT_MODULE", ")", ";", "URL", "url", "=", "extModule", ".", "getExportedResource", "(", "SEAM_INT_JAR", ")", ";", "if", "(", "url", "==", "null", ")", "throw", "ServerLogger", ".", "ROOT_LOGGER", ".", "noSeamIntegrationJarPresent", "(", "extModule", ")", ";", "File", "file", "=", "new", "File", "(", "url", ".", "toURI", "(", ")", ")", ";", "VirtualFile", "vf", "=", "VFS", ".", "getChild", "(", "file", ".", "toURI", "(", ")", ")", ";", "final", "Closeable", "mountHandle", "=", "VFS", ".", "mountZip", "(", "file", ",", "vf", ",", "TempFileProviderService", ".", "provider", "(", ")", ")", ";", "Service", "<", "Closeable", ">", "mountHandleService", "=", "new", "Service", "<", "Closeable", ">", "(", ")", "{", "public", "void", "start", "(", "StartContext", "startContext", ")", "throws", "StartException", "{", "}", "public", "void", "stop", "(", "StopContext", "stopContext", ")", "{", "VFSUtils", ".", "safeClose", "(", "mountHandle", ")", ";", "}", "public", "Closeable", "getValue", "(", ")", "throws", "IllegalStateException", ",", "IllegalArgumentException", "{", "return", "mountHandle", ";", "}", "}", ";", "ServiceBuilder", "<", "Closeable", ">", "builder", "=", "serviceTarget", ".", "addService", "(", "ServiceName", ".", "JBOSS", ".", "append", "(", "SEAM_INT_JAR", ")", ",", "mountHandleService", ")", ";", "builder", ".", "setInitialMode", "(", "ServiceController", ".", "Mode", ".", "ACTIVE", ")", ".", "install", "(", ")", ";", "serviceTarget", "=", "null", ";", "// our cleanup service install work is done", "MountHandle", "dummy", "=", "MountHandle", ".", "create", "(", "null", ")", ";", "// actual close is done by the MSC service above", "seamIntResourceRoot", "=", "new", "ResourceRoot", "(", "vf", ",", "dummy", ")", ";", "}", "return", "seamIntResourceRoot", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "DeploymentUnitProcessingException", "(", "e", ")", ";", "}", "}" ]
Lookup Seam integration resource loader. @return the Seam integration resource loader @throws DeploymentUnitProcessingException for any error
[ "Lookup", "Seam", "integration", "resource", "loader", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/integration/Seam2Processor.java#L93-L129
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/UserResources.java
UserResources.createPrincipalUser
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Description("Creates a user.") public PrincipalUserDto createPrincipalUser(@Context HttpServletRequest req, final PrincipalUserDto userDto) { """ Creates a user. @param req The HTTP request. @param userDto The user to create. @return The updated DTO for the created user. @throws WebApplicationException If an error occurs. """ PrincipalUser remoteUser = validateAndGetOwner(req, null); validateResourceAuthorization(req, remoteUser, remoteUser); if (userDto == null) { throw new WebApplicationException("Cannot create a null user.", Status.BAD_REQUEST); } PrincipalUser user = new PrincipalUser(remoteUser, userDto.getUserName(), userDto.getEmail()); copyProperties(user, userDto); user = _uService.updateUser(user); return PrincipalUserDto.transformToDto(user); }
java
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Description("Creates a user.") public PrincipalUserDto createPrincipalUser(@Context HttpServletRequest req, final PrincipalUserDto userDto) { PrincipalUser remoteUser = validateAndGetOwner(req, null); validateResourceAuthorization(req, remoteUser, remoteUser); if (userDto == null) { throw new WebApplicationException("Cannot create a null user.", Status.BAD_REQUEST); } PrincipalUser user = new PrincipalUser(remoteUser, userDto.getUserName(), userDto.getEmail()); copyProperties(user, userDto); user = _uService.updateUser(user); return PrincipalUserDto.transformToDto(user); }
[ "@", "POST", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Description", "(", "\"Creates a user.\"", ")", "public", "PrincipalUserDto", "createPrincipalUser", "(", "@", "Context", "HttpServletRequest", "req", ",", "final", "PrincipalUserDto", "userDto", ")", "{", "PrincipalUser", "remoteUser", "=", "validateAndGetOwner", "(", "req", ",", "null", ")", ";", "validateResourceAuthorization", "(", "req", ",", "remoteUser", ",", "remoteUser", ")", ";", "if", "(", "userDto", "==", "null", ")", "{", "throw", "new", "WebApplicationException", "(", "\"Cannot create a null user.\"", ",", "Status", ".", "BAD_REQUEST", ")", ";", "}", "PrincipalUser", "user", "=", "new", "PrincipalUser", "(", "remoteUser", ",", "userDto", ".", "getUserName", "(", ")", ",", "userDto", ".", "getEmail", "(", ")", ")", ";", "copyProperties", "(", "user", ",", "userDto", ")", ";", "user", "=", "_uService", ".", "updateUser", "(", "user", ")", ";", "return", "PrincipalUserDto", ".", "transformToDto", "(", "user", ")", ";", "}" ]
Creates a user. @param req The HTTP request. @param userDto The user to create. @return The updated DTO for the created user. @throws WebApplicationException If an error occurs.
[ "Creates", "a", "user", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/UserResources.java#L178-L195
adorsys/hbci4java-adorsys
src/main/java/org/kapott/hbci/sepa/SepaVersion.java
SepaVersion.choose
public static SepaVersion choose(String sepadesc, String sepadata) { """ Die Bank sendet in ihren Antworten sowohl den SEPA-Deskriptor als auch die SEPA-Daten (die XML-Datei) selbst. Diese Funktion ermittelt sowohl aus dem SEPA-Deskriptor als auch aus den SEPA-Daten die angegebene SEPA-Version und vergleicht beide. Stimmen sie nicht ueberein, wird eine Warnung ausgegeben. Die Funktion liefert anschliessend die zum Parsen passende Version zurueck. Falls sich die angegebenen Versionen unterscheiden, wird die in den XML-Daten angegebene Version zurueckgeliefert. Siehe https://www.willuhn.de/bugzilla/show_bug.cgi?id=1806 @param sepadesc die in der HBCI-Nachricht angegebene SEPA-Version. @param sepadata die eigentlichen XML-Daten. @return die zum Parsen zu verwendende SEPA-Version. NULL, wenn keinerlei Daten angegeben wurden. """ final boolean haveDesc = sepadesc != null && sepadesc.length() > 0; final boolean haveData = sepadata != null && sepadata.length() > 0; if (!haveDesc && !haveData) { log.warn("neither sepadesr nor sepa data given"); return null; } try { final SepaVersion versionDesc = haveDesc ? SepaVersion.byURN(sepadesc) : null; final SepaVersion versionData = haveData ? SepaVersion.autodetect(new ByteArrayInputStream(sepadata.getBytes(ENCODING))) : null; log.debug("sepa version given in sepadescr: " + versionDesc); log.debug("sepa version according to data: " + versionData); // Wir haben keine Version im Deskriptor, dann bleibt nur die aus den Daten if (versionDesc == null) return versionData; // Wir haben keine Version in den Daten, dann bleibt nur die im Deskriptor if (versionData == null) return versionDesc; // Wir geben noch eine Warnung aus, wenn unterschiedliche Versionen angegeben sind if (!versionDesc.equals(versionData)) log.warn("sepa version mismatch. sepadesc: " + versionDesc + " vs. data: " + versionData); // Wir geben priorisiert die Version aus den Daten zurueck, damit ist sicherer, dass die // Daten gelesen werden koennen return versionData; } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } return null; }
java
public static SepaVersion choose(String sepadesc, String sepadata) { final boolean haveDesc = sepadesc != null && sepadesc.length() > 0; final boolean haveData = sepadata != null && sepadata.length() > 0; if (!haveDesc && !haveData) { log.warn("neither sepadesr nor sepa data given"); return null; } try { final SepaVersion versionDesc = haveDesc ? SepaVersion.byURN(sepadesc) : null; final SepaVersion versionData = haveData ? SepaVersion.autodetect(new ByteArrayInputStream(sepadata.getBytes(ENCODING))) : null; log.debug("sepa version given in sepadescr: " + versionDesc); log.debug("sepa version according to data: " + versionData); // Wir haben keine Version im Deskriptor, dann bleibt nur die aus den Daten if (versionDesc == null) return versionData; // Wir haben keine Version in den Daten, dann bleibt nur die im Deskriptor if (versionData == null) return versionDesc; // Wir geben noch eine Warnung aus, wenn unterschiedliche Versionen angegeben sind if (!versionDesc.equals(versionData)) log.warn("sepa version mismatch. sepadesc: " + versionDesc + " vs. data: " + versionData); // Wir geben priorisiert die Version aus den Daten zurueck, damit ist sicherer, dass die // Daten gelesen werden koennen return versionData; } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } return null; }
[ "public", "static", "SepaVersion", "choose", "(", "String", "sepadesc", ",", "String", "sepadata", ")", "{", "final", "boolean", "haveDesc", "=", "sepadesc", "!=", "null", "&&", "sepadesc", ".", "length", "(", ")", ">", "0", ";", "final", "boolean", "haveData", "=", "sepadata", "!=", "null", "&&", "sepadata", ".", "length", "(", ")", ">", "0", ";", "if", "(", "!", "haveDesc", "&&", "!", "haveData", ")", "{", "log", ".", "warn", "(", "\"neither sepadesr nor sepa data given\"", ")", ";", "return", "null", ";", "}", "try", "{", "final", "SepaVersion", "versionDesc", "=", "haveDesc", "?", "SepaVersion", ".", "byURN", "(", "sepadesc", ")", ":", "null", ";", "final", "SepaVersion", "versionData", "=", "haveData", "?", "SepaVersion", ".", "autodetect", "(", "new", "ByteArrayInputStream", "(", "sepadata", ".", "getBytes", "(", "ENCODING", ")", ")", ")", ":", "null", ";", "log", ".", "debug", "(", "\"sepa version given in sepadescr: \"", "+", "versionDesc", ")", ";", "log", ".", "debug", "(", "\"sepa version according to data: \"", "+", "versionData", ")", ";", "// Wir haben keine Version im Deskriptor, dann bleibt nur die aus den Daten", "if", "(", "versionDesc", "==", "null", ")", "return", "versionData", ";", "// Wir haben keine Version in den Daten, dann bleibt nur die im Deskriptor", "if", "(", "versionData", "==", "null", ")", "return", "versionDesc", ";", "// Wir geben noch eine Warnung aus, wenn unterschiedliche Versionen angegeben sind", "if", "(", "!", "versionDesc", ".", "equals", "(", "versionData", ")", ")", "log", ".", "warn", "(", "\"sepa version mismatch. sepadesc: \"", "+", "versionDesc", "+", "\" vs. data: \"", "+", "versionData", ")", ";", "// Wir geben priorisiert die Version aus den Daten zurueck, damit ist sicherer, dass die", "// Daten gelesen werden koennen", "return", "versionData", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "log", ".", "error", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "return", "null", ";", "}" ]
Die Bank sendet in ihren Antworten sowohl den SEPA-Deskriptor als auch die SEPA-Daten (die XML-Datei) selbst. Diese Funktion ermittelt sowohl aus dem SEPA-Deskriptor als auch aus den SEPA-Daten die angegebene SEPA-Version und vergleicht beide. Stimmen sie nicht ueberein, wird eine Warnung ausgegeben. Die Funktion liefert anschliessend die zum Parsen passende Version zurueck. Falls sich die angegebenen Versionen unterscheiden, wird die in den XML-Daten angegebene Version zurueckgeliefert. Siehe https://www.willuhn.de/bugzilla/show_bug.cgi?id=1806 @param sepadesc die in der HBCI-Nachricht angegebene SEPA-Version. @param sepadata die eigentlichen XML-Daten. @return die zum Parsen zu verwendende SEPA-Version. NULL, wenn keinerlei Daten angegeben wurden.
[ "Die", "Bank", "sendet", "in", "ihren", "Antworten", "sowohl", "den", "SEPA", "-", "Deskriptor", "als", "auch", "die", "SEPA", "-", "Daten", "(", "die", "XML", "-", "Datei", ")", "selbst", ".", "Diese", "Funktion", "ermittelt", "sowohl", "aus", "dem", "SEPA", "-", "Deskriptor", "als", "auch", "aus", "den", "SEPA", "-", "Daten", "die", "angegebene", "SEPA", "-", "Version", "und", "vergleicht", "beide", ".", "Stimmen", "sie", "nicht", "ueberein", "wird", "eine", "Warnung", "ausgegeben", ".", "Die", "Funktion", "liefert", "anschliessend", "die", "zum", "Parsen", "passende", "Version", "zurueck", ".", "Falls", "sich", "die", "angegebenen", "Versionen", "unterscheiden", "wird", "die", "in", "den", "XML", "-", "Daten", "angegebene", "Version", "zurueckgeliefert", ".", "Siehe", "https", ":", "//", "www", ".", "willuhn", ".", "de", "/", "bugzilla", "/", "show_bug", ".", "cgi?id", "=", "1806" ]
train
https://github.com/adorsys/hbci4java-adorsys/blob/5e24f7e429d6b555e1d993196b4cf1adda6433cf/src/main/java/org/kapott/hbci/sepa/SepaVersion.java#L275-L311
Coveros/selenified
src/main/java/com/coveros/selenified/application/WaitFor.java
WaitFor.textPresent
public void textPresent(double seconds, String expectedText) { """ Waits up to the provided wait time for provided text(s) are on the current page. This information will be logged and recorded, with a screenshot for traceability and added debugging support. @param expectedText the expected text to be present @param seconds the number of seconds to wait """ double end = System.currentTimeMillis() + (seconds * 1000); while (!app.is().textPresent(expectedText) && System.currentTimeMillis() < end) ; double timeTook = Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000; checkTextPresent(expectedText, seconds, timeTook); }
java
public void textPresent(double seconds, String expectedText) { double end = System.currentTimeMillis() + (seconds * 1000); while (!app.is().textPresent(expectedText) && System.currentTimeMillis() < end) ; double timeTook = Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000; checkTextPresent(expectedText, seconds, timeTook); }
[ "public", "void", "textPresent", "(", "double", "seconds", ",", "String", "expectedText", ")", "{", "double", "end", "=", "System", ".", "currentTimeMillis", "(", ")", "+", "(", "seconds", "*", "1000", ")", ";", "while", "(", "!", "app", ".", "is", "(", ")", ".", "textPresent", "(", "expectedText", ")", "&&", "System", ".", "currentTimeMillis", "(", ")", "<", "end", ")", ";", "double", "timeTook", "=", "Math", ".", "min", "(", "(", "seconds", "*", "1000", ")", "-", "(", "end", "-", "System", ".", "currentTimeMillis", "(", ")", ")", ",", "seconds", "*", "1000", ")", "/", "1000", ";", "checkTextPresent", "(", "expectedText", ",", "seconds", ",", "timeTook", ")", ";", "}" ]
Waits up to the provided wait time for provided text(s) are on the current page. This information will be logged and recorded, with a screenshot for traceability and added debugging support. @param expectedText the expected text to be present @param seconds the number of seconds to wait
[ "Waits", "up", "to", "the", "provided", "wait", "time", "for", "provided", "text", "(", "s", ")", "are", "on", "the", "current", "page", ".", "This", "information", "will", "be", "logged", "and", "recorded", "with", "a", "screenshot", "for", "traceability", "and", "added", "debugging", "support", "." ]
train
https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/application/WaitFor.java#L664-L669
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/sms_server.java
sms_server.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ sms_server_responses result = (sms_server_responses) service.get_payload_formatter().string_to_resource(sms_server_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.sms_server_response_array); } sms_server[] result_sms_server = new sms_server[result.sms_server_response_array.length]; for(int i = 0; i < result.sms_server_response_array.length; i++) { result_sms_server[i] = result.sms_server_response_array[i].sms_server[0]; } return result_sms_server; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { sms_server_responses result = (sms_server_responses) service.get_payload_formatter().string_to_resource(sms_server_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.sms_server_response_array); } sms_server[] result_sms_server = new sms_server[result.sms_server_response_array.length]; for(int i = 0; i < result.sms_server_response_array.length; i++) { result_sms_server[i] = result.sms_server_response_array[i].sms_server[0]; } return result_sms_server; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "sms_server_responses", "result", "=", "(", "sms_server_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "sms_server_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "sms_server_response_array", ")", ";", "}", "sms_server", "[", "]", "result_sms_server", "=", "new", "sms_server", "[", "result", ".", "sms_server_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "sms_server_response_array", ".", "length", ";", "i", "++", ")", "{", "result_sms_server", "[", "i", "]", "=", "result", ".", "sms_server_response_array", "[", "i", "]", ".", "sms_server", "[", "0", "]", ";", "}", "return", "result_sms_server", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/sms_server.java#L683-L700
dkpro/dkpro-jwpl
de.tudarmstadt.ukp.wikipedia.api/src/main/java/de/tudarmstadt/ukp/wikipedia/api/CategoryGraph.java
CategoryGraph.getLCS
public Category getLCS(int categoryPageId1, int categoryPageId2) throws WikiApiException { """ Gets the lowest common subsumer (LCS) of two nodes. The LCS of two nodes is first node on the path to the root, that has both nodes as sons. Nodes that are not in the same connected component as the root node are defined to have no LCS. @param categoryPageId1 The pageid of the first category node. @param categoryPageId2 The pageid of the second category node. @return The lowest common subsumer of the two nodes, or null if there is no LCS. """ int lcsid = getLCSId(categoryPageId1, categoryPageId2); return lcsid>-1?wiki.getCategory(getLCSId(categoryPageId1, categoryPageId2)):null; }
java
public Category getLCS(int categoryPageId1, int categoryPageId2) throws WikiApiException { int lcsid = getLCSId(categoryPageId1, categoryPageId2); return lcsid>-1?wiki.getCategory(getLCSId(categoryPageId1, categoryPageId2)):null; }
[ "public", "Category", "getLCS", "(", "int", "categoryPageId1", ",", "int", "categoryPageId2", ")", "throws", "WikiApiException", "{", "int", "lcsid", "=", "getLCSId", "(", "categoryPageId1", ",", "categoryPageId2", ")", ";", "return", "lcsid", ">", "-", "1", "?", "wiki", ".", "getCategory", "(", "getLCSId", "(", "categoryPageId1", ",", "categoryPageId2", ")", ")", ":", "null", ";", "}" ]
Gets the lowest common subsumer (LCS) of two nodes. The LCS of two nodes is first node on the path to the root, that has both nodes as sons. Nodes that are not in the same connected component as the root node are defined to have no LCS. @param categoryPageId1 The pageid of the first category node. @param categoryPageId2 The pageid of the second category node. @return The lowest common subsumer of the two nodes, or null if there is no LCS.
[ "Gets", "the", "lowest", "common", "subsumer", "(", "LCS", ")", "of", "two", "nodes", ".", "The", "LCS", "of", "two", "nodes", "is", "first", "node", "on", "the", "path", "to", "the", "root", "that", "has", "both", "nodes", "as", "sons", ".", "Nodes", "that", "are", "not", "in", "the", "same", "connected", "component", "as", "the", "root", "node", "are", "defined", "to", "have", "no", "LCS", "." ]
train
https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.api/src/main/java/de/tudarmstadt/ukp/wikipedia/api/CategoryGraph.java#L465-L468
E7du/jfinal-ext3
src/main/java/com/jfinal/ext/kit/PageViewKit.java
PageViewKit.getHTMLPageView
public static String getHTMLPageView(String dir, String viewPath, String pageName) { """ 获取静态页面 @param dir 所在目录 @param viewPath view路径 @param pageName view名字 @return """ return getPageView(dir, viewPath, pageName, HTML); }
java
public static String getHTMLPageView(String dir, String viewPath, String pageName){ return getPageView(dir, viewPath, pageName, HTML); }
[ "public", "static", "String", "getHTMLPageView", "(", "String", "dir", ",", "String", "viewPath", ",", "String", "pageName", ")", "{", "return", "getPageView", "(", "dir", ",", "viewPath", ",", "pageName", ",", "HTML", ")", ";", "}" ]
获取静态页面 @param dir 所在目录 @param viewPath view路径 @param pageName view名字 @return
[ "获取静态页面" ]
train
https://github.com/E7du/jfinal-ext3/blob/8ffcbd150fd50c72852bb778bd427b5eb19254dc/src/main/java/com/jfinal/ext/kit/PageViewKit.java#L192-L194
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/util/Stats.java
Stats.nashsut
public static double nashsut(double[] prediction, double[] validation, double pow) { """ Calculates the efficiency between a test data set and a verification data set after Nash & Sutcliffe (1970). The efficiency is described as the proportion of the cumulated cubic deviation between both data sets and the cumulated cubic deviation between the verification data set and its mean value. @param prediction the simulation data set @param validation the validation (observed) data set @param pow the power for the deviation terms @return the calculated efficiency or -9999 if an error occurs """ int pre_size = prediction.length; int val_size = validation.length; int steps = 0; double sum_td = 0; double sum_vd = 0; /** checking if both data arrays have the same number of elements*/ if (pre_size != val_size) { System.err.println("Prediction data and validation data are not consistent!"); return -9999; } else { steps = pre_size; } /**summing up both data sets */ for (int i = 0; i < steps; i++) { sum_td = sum_td + prediction[i]; sum_vd = sum_vd + validation[i]; } /** calculating mean values for both data sets */ double mean_td = sum_td / steps; double mean_vd = sum_vd / steps; /** calculating mean pow deviations */ double td_vd = 0; double vd_mean = 0; for (int i = 0; i < steps; i++) { td_vd = td_vd + (Math.pow((Math.abs(validation[i] - prediction[i])), pow)); vd_mean = vd_mean + (Math.pow((Math.abs(validation[i] - mean_vd)), pow)); } /** calculating efficiency after Nash & Sutcliffe (1970) */ double efficiency = 1 - (td_vd / vd_mean); return efficiency; }
java
public static double nashsut(double[] prediction, double[] validation, double pow) { int pre_size = prediction.length; int val_size = validation.length; int steps = 0; double sum_td = 0; double sum_vd = 0; /** checking if both data arrays have the same number of elements*/ if (pre_size != val_size) { System.err.println("Prediction data and validation data are not consistent!"); return -9999; } else { steps = pre_size; } /**summing up both data sets */ for (int i = 0; i < steps; i++) { sum_td = sum_td + prediction[i]; sum_vd = sum_vd + validation[i]; } /** calculating mean values for both data sets */ double mean_td = sum_td / steps; double mean_vd = sum_vd / steps; /** calculating mean pow deviations */ double td_vd = 0; double vd_mean = 0; for (int i = 0; i < steps; i++) { td_vd = td_vd + (Math.pow((Math.abs(validation[i] - prediction[i])), pow)); vd_mean = vd_mean + (Math.pow((Math.abs(validation[i] - mean_vd)), pow)); } /** calculating efficiency after Nash & Sutcliffe (1970) */ double efficiency = 1 - (td_vd / vd_mean); return efficiency; }
[ "public", "static", "double", "nashsut", "(", "double", "[", "]", "prediction", ",", "double", "[", "]", "validation", ",", "double", "pow", ")", "{", "int", "pre_size", "=", "prediction", ".", "length", ";", "int", "val_size", "=", "validation", ".", "length", ";", "int", "steps", "=", "0", ";", "double", "sum_td", "=", "0", ";", "double", "sum_vd", "=", "0", ";", "/** checking if both data arrays have the same number of elements*/", "if", "(", "pre_size", "!=", "val_size", ")", "{", "System", ".", "err", ".", "println", "(", "\"Prediction data and validation data are not consistent!\"", ")", ";", "return", "-", "9999", ";", "}", "else", "{", "steps", "=", "pre_size", ";", "}", "/**summing up both data sets */", "for", "(", "int", "i", "=", "0", ";", "i", "<", "steps", ";", "i", "++", ")", "{", "sum_td", "=", "sum_td", "+", "prediction", "[", "i", "]", ";", "sum_vd", "=", "sum_vd", "+", "validation", "[", "i", "]", ";", "}", "/** calculating mean values for both data sets */", "double", "mean_td", "=", "sum_td", "/", "steps", ";", "double", "mean_vd", "=", "sum_vd", "/", "steps", ";", "/** calculating mean pow deviations */", "double", "td_vd", "=", "0", ";", "double", "vd_mean", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "steps", ";", "i", "++", ")", "{", "td_vd", "=", "td_vd", "+", "(", "Math", ".", "pow", "(", "(", "Math", ".", "abs", "(", "validation", "[", "i", "]", "-", "prediction", "[", "i", "]", ")", ")", ",", "pow", ")", ")", ";", "vd_mean", "=", "vd_mean", "+", "(", "Math", ".", "pow", "(", "(", "Math", ".", "abs", "(", "validation", "[", "i", "]", "-", "mean_vd", ")", ")", ",", "pow", ")", ")", ";", "}", "/** calculating efficiency after Nash & Sutcliffe (1970) */", "double", "efficiency", "=", "1", "-", "(", "td_vd", "/", "vd_mean", ")", ";", "return", "efficiency", ";", "}" ]
Calculates the efficiency between a test data set and a verification data set after Nash & Sutcliffe (1970). The efficiency is described as the proportion of the cumulated cubic deviation between both data sets and the cumulated cubic deviation between the verification data set and its mean value. @param prediction the simulation data set @param validation the validation (observed) data set @param pow the power for the deviation terms @return the calculated efficiency or -9999 if an error occurs
[ "Calculates", "the", "efficiency", "between", "a", "test", "data", "set", "and", "a", "verification", "data", "set", "after", "Nash", "&", "Sutcliffe", "(", "1970", ")", ".", "The", "efficiency", "is", "described", "as", "the", "proportion", "of", "the", "cumulated", "cubic", "deviation", "between", "both", "data", "sets", "and", "the", "cumulated", "cubic", "deviation", "between", "the", "verification", "data", "set", "and", "its", "mean", "value", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/util/Stats.java#L186-L223
looly/hutool
hutool-core/src/main/java/cn/hutool/core/lang/Assert.java
Assert.isAssignable
public static void isAssignable(Class<?> superType, Class<?> subType, String errorMsgTemplate, Object... params) throws IllegalArgumentException { """ 断言 {@code superType.isAssignableFrom(subType)} 是否为 {@code true}. <pre class="code"> Assert.isAssignable(Number.class, myClass); </pre> @param superType 需要检查的父类或接口 @param subType 需要检查的子类 @param errorMsgTemplate 异常时的消息模板 @param params 参数列表 @throws IllegalArgumentException 如果子类非继承父类,抛出此异常 """ notNull(superType, "Type to check against must not be null"); if (subType == null || !superType.isAssignableFrom(subType)) { throw new IllegalArgumentException(StrUtil.format(errorMsgTemplate, params)); } }
java
public static void isAssignable(Class<?> superType, Class<?> subType, String errorMsgTemplate, Object... params) throws IllegalArgumentException { notNull(superType, "Type to check against must not be null"); if (subType == null || !superType.isAssignableFrom(subType)) { throw new IllegalArgumentException(StrUtil.format(errorMsgTemplate, params)); } }
[ "public", "static", "void", "isAssignable", "(", "Class", "<", "?", ">", "superType", ",", "Class", "<", "?", ">", "subType", ",", "String", "errorMsgTemplate", ",", "Object", "...", "params", ")", "throws", "IllegalArgumentException", "{", "notNull", "(", "superType", ",", "\"Type to check against must not be null\"", ")", ";", "if", "(", "subType", "==", "null", "||", "!", "superType", ".", "isAssignableFrom", "(", "subType", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "StrUtil", ".", "format", "(", "errorMsgTemplate", ",", "params", ")", ")", ";", "}", "}" ]
断言 {@code superType.isAssignableFrom(subType)} 是否为 {@code true}. <pre class="code"> Assert.isAssignable(Number.class, myClass); </pre> @param superType 需要检查的父类或接口 @param subType 需要检查的子类 @param errorMsgTemplate 异常时的消息模板 @param params 参数列表 @throws IllegalArgumentException 如果子类非继承父类,抛出此异常
[ "断言", "{", "@code", "superType", ".", "isAssignableFrom", "(", "subType", ")", "}", "是否为", "{", "@code", "true", "}", "." ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/Assert.java#L485-L490
Impetus/Kundera
src/kundera-redis/src/main/java/com/impetus/client/redis/RedisClient.java
RedisClient.onDelete
private void onDelete(Object entity, Object pKey, Object connection) { """ On delete. @param entity the entity @param pKey the key @param connection the connection """ EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass()); AttributeWrapper wrapper = wrap(entityMetadata, entity); Set<byte[]> columnNames = wrapper.columns.keySet(); String rowKey = null; MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( entityMetadata.getPersistenceUnit()); if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())) { rowKey = KunderaCoreUtils.prepareCompositeKey(entityMetadata, pKey); } else { rowKey = PropertyAccessorHelper.getString(entity, (Field) entityMetadata.getIdAttribute().getJavaMember()); } for (byte[] name : columnNames) { if (resource != null && resource.isActive()) { ((Transaction) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey), PropertyAccessorFactory.STRING.fromBytes(String.class, name)); } else { ((Pipeline) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey), PropertyAccessorFactory.STRING.fromBytes(String.class, name)); } } // Delete relation values. deleteRelation(connection, entityMetadata, rowKey); // Delete inverted indexes. unIndex(connection, wrapper, rowKey); if (resource != null && resource.isActive()) { ((Transaction) connection).zrem( getHashKey(entityMetadata.getTableName(), ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), rowKey); } else { ((Pipeline) connection).zrem( getHashKey(entityMetadata.getTableName(), ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), rowKey); } KunderaCoreUtils.printQuery("Delete data from:" + entityMetadata.getTableName() + "for primary key: " + rowKey, showQuery); }
java
private void onDelete(Object entity, Object pKey, Object connection) { EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass()); AttributeWrapper wrapper = wrap(entityMetadata, entity); Set<byte[]> columnNames = wrapper.columns.keySet(); String rowKey = null; MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( entityMetadata.getPersistenceUnit()); if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())) { rowKey = KunderaCoreUtils.prepareCompositeKey(entityMetadata, pKey); } else { rowKey = PropertyAccessorHelper.getString(entity, (Field) entityMetadata.getIdAttribute().getJavaMember()); } for (byte[] name : columnNames) { if (resource != null && resource.isActive()) { ((Transaction) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey), PropertyAccessorFactory.STRING.fromBytes(String.class, name)); } else { ((Pipeline) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey), PropertyAccessorFactory.STRING.fromBytes(String.class, name)); } } // Delete relation values. deleteRelation(connection, entityMetadata, rowKey); // Delete inverted indexes. unIndex(connection, wrapper, rowKey); if (resource != null && resource.isActive()) { ((Transaction) connection).zrem( getHashKey(entityMetadata.getTableName(), ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), rowKey); } else { ((Pipeline) connection).zrem( getHashKey(entityMetadata.getTableName(), ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), rowKey); } KunderaCoreUtils.printQuery("Delete data from:" + entityMetadata.getTableName() + "for primary key: " + rowKey, showQuery); }
[ "private", "void", "onDelete", "(", "Object", "entity", ",", "Object", "pKey", ",", "Object", "connection", ")", "{", "EntityMetadata", "entityMetadata", "=", "KunderaMetadataManager", ".", "getEntityMetadata", "(", "kunderaMetadata", ",", "entity", ".", "getClass", "(", ")", ")", ";", "AttributeWrapper", "wrapper", "=", "wrap", "(", "entityMetadata", ",", "entity", ")", ";", "Set", "<", "byte", "[", "]", ">", "columnNames", "=", "wrapper", ".", "columns", ".", "keySet", "(", ")", ";", "String", "rowKey", "=", "null", ";", "MetamodelImpl", "metaModel", "=", "(", "MetamodelImpl", ")", "kunderaMetadata", ".", "getApplicationMetadata", "(", ")", ".", "getMetamodel", "(", "entityMetadata", ".", "getPersistenceUnit", "(", ")", ")", ";", "if", "(", "metaModel", ".", "isEmbeddable", "(", "entityMetadata", ".", "getIdAttribute", "(", ")", ".", "getBindableJavaType", "(", ")", ")", ")", "{", "rowKey", "=", "KunderaCoreUtils", ".", "prepareCompositeKey", "(", "entityMetadata", ",", "pKey", ")", ";", "}", "else", "{", "rowKey", "=", "PropertyAccessorHelper", ".", "getString", "(", "entity", ",", "(", "Field", ")", "entityMetadata", ".", "getIdAttribute", "(", ")", ".", "getJavaMember", "(", ")", ")", ";", "}", "for", "(", "byte", "[", "]", "name", ":", "columnNames", ")", "{", "if", "(", "resource", "!=", "null", "&&", "resource", ".", "isActive", "(", ")", ")", "{", "(", "(", "Transaction", ")", "connection", ")", ".", "hdel", "(", "getHashKey", "(", "entityMetadata", ".", "getTableName", "(", ")", ",", "rowKey", ")", ",", "PropertyAccessorFactory", ".", "STRING", ".", "fromBytes", "(", "String", ".", "class", ",", "name", ")", ")", ";", "}", "else", "{", "(", "(", "Pipeline", ")", "connection", ")", ".", "hdel", "(", "getHashKey", "(", "entityMetadata", ".", "getTableName", "(", ")", ",", "rowKey", ")", ",", "PropertyAccessorFactory", ".", "STRING", ".", "fromBytes", "(", "String", ".", "class", ",", "name", ")", ")", ";", "}", "}", "// Delete relation values.", "deleteRelation", "(", "connection", ",", "entityMetadata", ",", "rowKey", ")", ";", "// Delete inverted indexes.", "unIndex", "(", "connection", ",", "wrapper", ",", "rowKey", ")", ";", "if", "(", "resource", "!=", "null", "&&", "resource", ".", "isActive", "(", ")", ")", "{", "(", "(", "Transaction", ")", "connection", ")", ".", "zrem", "(", "getHashKey", "(", "entityMetadata", ".", "getTableName", "(", ")", ",", "(", "(", "AbstractAttribute", ")", "entityMetadata", ".", "getIdAttribute", "(", ")", ")", ".", "getJPAColumnName", "(", ")", ")", ",", "rowKey", ")", ";", "}", "else", "{", "(", "(", "Pipeline", ")", "connection", ")", ".", "zrem", "(", "getHashKey", "(", "entityMetadata", ".", "getTableName", "(", ")", ",", "(", "(", "AbstractAttribute", ")", "entityMetadata", ".", "getIdAttribute", "(", ")", ")", ".", "getJPAColumnName", "(", ")", ")", ",", "rowKey", ")", ";", "}", "KunderaCoreUtils", ".", "printQuery", "(", "\"Delete data from:\"", "+", "entityMetadata", ".", "getTableName", "(", ")", "+", "\"for primary key: \"", "+", "rowKey", ",", "showQuery", ")", ";", "}" ]
On delete. @param entity the entity @param pKey the key @param connection the connection
[ "On", "delete", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-redis/src/main/java/com/impetus/client/redis/RedisClient.java#L2162-L2222
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/File.java
File.toURI
public URI toURI() { """ Returns a Uniform Resource Identifier for this file. The URI is system dependent and may not be transferable between different operating / file systems. @return an URI for this file. """ String name = getAbsoluteName(); try { if (!name.startsWith("/")) { // start with sep. return new URI("file", null, "/" + name, null, null); } else if (name.startsWith("//")) { return new URI("file", "", name, null); // UNC path } return new URI("file", null, name, null, null); } catch (URISyntaxException e) { // this should never happen return null; } }
java
public URI toURI() { String name = getAbsoluteName(); try { if (!name.startsWith("/")) { // start with sep. return new URI("file", null, "/" + name, null, null); } else if (name.startsWith("//")) { return new URI("file", "", name, null); // UNC path } return new URI("file", null, name, null, null); } catch (URISyntaxException e) { // this should never happen return null; } }
[ "public", "URI", "toURI", "(", ")", "{", "String", "name", "=", "getAbsoluteName", "(", ")", ";", "try", "{", "if", "(", "!", "name", ".", "startsWith", "(", "\"/\"", ")", ")", "{", "// start with sep.", "return", "new", "URI", "(", "\"file\"", ",", "null", ",", "\"/\"", "+", "name", ",", "null", ",", "null", ")", ";", "}", "else", "if", "(", "name", ".", "startsWith", "(", "\"//\"", ")", ")", "{", "return", "new", "URI", "(", "\"file\"", ",", "\"\"", ",", "name", ",", "null", ")", ";", "// UNC path", "}", "return", "new", "URI", "(", "\"file\"", ",", "null", ",", "name", ",", "null", ",", "null", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "// this should never happen", "return", "null", ";", "}", "}" ]
Returns a Uniform Resource Identifier for this file. The URI is system dependent and may not be transferable between different operating / file systems. @return an URI for this file.
[ "Returns", "a", "Uniform", "Resource", "Identifier", "for", "this", "file", ".", "The", "URI", "is", "system", "dependent", "and", "may", "not", "be", "transferable", "between", "different", "operating", "/", "file", "systems", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/File.java#L1155-L1169
belaban/JGroups
src/org/jgroups/protocols/relay/Relayer.java
Relayer.start
public void start(List<RelayConfig.BridgeConfig> bridge_configs, String bridge_name, final String my_site_id) throws Throwable { """ Creates all bridges from site_config and connects them (joining the bridge clusters) @param bridge_configs A list of bridge configurations @param bridge_name The name of the local bridge channel, prefixed with '_'. @param my_site_id The ID of this site @throws Throwable """ if(done) { log.trace(relay.getLocalAddress() + ": will not start the Relayer as stop() has been called"); return; } try { for(RelayConfig.BridgeConfig bridge_config: bridge_configs) { Bridge bridge=new Bridge(bridge_config.createChannel(), bridge_config.getClusterName(), bridge_name, () -> new SiteUUID(UUID.randomUUID(), null, my_site_id)); bridges.add(bridge); } for(Bridge bridge: bridges) bridge.start(); } catch(Throwable t) { stop(); throw t; } finally { if(done) { log.trace(relay.getLocalAddress() + ": stop() was called while starting the relayer; stopping the relayer now"); stop(); } } }
java
public void start(List<RelayConfig.BridgeConfig> bridge_configs, String bridge_name, final String my_site_id) throws Throwable { if(done) { log.trace(relay.getLocalAddress() + ": will not start the Relayer as stop() has been called"); return; } try { for(RelayConfig.BridgeConfig bridge_config: bridge_configs) { Bridge bridge=new Bridge(bridge_config.createChannel(), bridge_config.getClusterName(), bridge_name, () -> new SiteUUID(UUID.randomUUID(), null, my_site_id)); bridges.add(bridge); } for(Bridge bridge: bridges) bridge.start(); } catch(Throwable t) { stop(); throw t; } finally { if(done) { log.trace(relay.getLocalAddress() + ": stop() was called while starting the relayer; stopping the relayer now"); stop(); } } }
[ "public", "void", "start", "(", "List", "<", "RelayConfig", ".", "BridgeConfig", ">", "bridge_configs", ",", "String", "bridge_name", ",", "final", "String", "my_site_id", ")", "throws", "Throwable", "{", "if", "(", "done", ")", "{", "log", ".", "trace", "(", "relay", ".", "getLocalAddress", "(", ")", "+", "\": will not start the Relayer as stop() has been called\"", ")", ";", "return", ";", "}", "try", "{", "for", "(", "RelayConfig", ".", "BridgeConfig", "bridge_config", ":", "bridge_configs", ")", "{", "Bridge", "bridge", "=", "new", "Bridge", "(", "bridge_config", ".", "createChannel", "(", ")", ",", "bridge_config", ".", "getClusterName", "(", ")", ",", "bridge_name", ",", "(", ")", "->", "new", "SiteUUID", "(", "UUID", ".", "randomUUID", "(", ")", ",", "null", ",", "my_site_id", ")", ")", ";", "bridges", ".", "add", "(", "bridge", ")", ";", "}", "for", "(", "Bridge", "bridge", ":", "bridges", ")", "bridge", ".", "start", "(", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "stop", "(", ")", ";", "throw", "t", ";", "}", "finally", "{", "if", "(", "done", ")", "{", "log", ".", "trace", "(", "relay", ".", "getLocalAddress", "(", ")", "+", "\": stop() was called while starting the relayer; stopping the relayer now\"", ")", ";", "stop", "(", ")", ";", "}", "}", "}" ]
Creates all bridges from site_config and connects them (joining the bridge clusters) @param bridge_configs A list of bridge configurations @param bridge_name The name of the local bridge channel, prefixed with '_'. @param my_site_id The ID of this site @throws Throwable
[ "Creates", "all", "bridges", "from", "site_config", "and", "connects", "them", "(", "joining", "the", "bridge", "clusters", ")" ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/protocols/relay/Relayer.java#L67-L92
googleapis/google-cloud-java
google-cloud-clients/google-cloud-securitycenter/src/main/java/com/google/cloud/securitycenter/v1/SecurityCenterClient.java
SecurityCenterClient.setFindingState
public final Finding setFindingState(FindingName name, Finding.State state, Timestamp startTime) { """ Updates the state of a finding. <p>Sample code: <pre><code> try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { FindingName name = FindingName.of("[ORGANIZATION]", "[SOURCE]", "[FINDING]"); Finding.State state = Finding.State.STATE_UNSPECIFIED; Timestamp startTime = Timestamp.newBuilder().build(); Finding response = securityCenterClient.setFindingState(name, state, startTime); } </code></pre> @param name The relative resource name of the finding. See: https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/123/sources/456/finding/789". @param state The desired State of the finding. @param startTime The time at which the updated state takes effect. @throws com.google.api.gax.rpc.ApiException if the remote call fails """ SetFindingStateRequest request = SetFindingStateRequest.newBuilder() .setName(name == null ? null : name.toString()) .setState(state) .setStartTime(startTime) .build(); return setFindingState(request); }
java
public final Finding setFindingState(FindingName name, Finding.State state, Timestamp startTime) { SetFindingStateRequest request = SetFindingStateRequest.newBuilder() .setName(name == null ? null : name.toString()) .setState(state) .setStartTime(startTime) .build(); return setFindingState(request); }
[ "public", "final", "Finding", "setFindingState", "(", "FindingName", "name", ",", "Finding", ".", "State", "state", ",", "Timestamp", "startTime", ")", "{", "SetFindingStateRequest", "request", "=", "SetFindingStateRequest", ".", "newBuilder", "(", ")", ".", "setName", "(", "name", "==", "null", "?", "null", ":", "name", ".", "toString", "(", ")", ")", ".", "setState", "(", "state", ")", ".", "setStartTime", "(", "startTime", ")", ".", "build", "(", ")", ";", "return", "setFindingState", "(", "request", ")", ";", "}" ]
Updates the state of a finding. <p>Sample code: <pre><code> try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { FindingName name = FindingName.of("[ORGANIZATION]", "[SOURCE]", "[FINDING]"); Finding.State state = Finding.State.STATE_UNSPECIFIED; Timestamp startTime = Timestamp.newBuilder().build(); Finding response = securityCenterClient.setFindingState(name, state, startTime); } </code></pre> @param name The relative resource name of the finding. See: https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/123/sources/456/finding/789". @param state The desired State of the finding. @param startTime The time at which the updated state takes effect. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Updates", "the", "state", "of", "a", "finding", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-securitycenter/src/main/java/com/google/cloud/securitycenter/v1/SecurityCenterClient.java#L1420-L1429