repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
201
func_name
stringlengths
4
126
whole_func_string
stringlengths
75
3.57k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.57k
func_code_tokens
listlengths
21
599
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
square/jna-gmp
jnagmp/src/main/java/com/squareup/jnagmp/Gmp.java
Gmp.modInverse
public static BigInteger modInverse(BigInteger val, BigInteger modulus) { if (modulus.signum() <= 0) { throw new ArithmeticException("modulus must be positive"); } return INSTANCE.get().modInverseImpl(val, modulus); }
java
public static BigInteger modInverse(BigInteger val, BigInteger modulus) { if (modulus.signum() <= 0) { throw new ArithmeticException("modulus must be positive"); } return INSTANCE.get().modInverseImpl(val, modulus); }
[ "public", "static", "BigInteger", "modInverse", "(", "BigInteger", "val", ",", "BigInteger", "modulus", ")", "{", "if", "(", "modulus", ".", "signum", "(", ")", "<=", "0", ")", "{", "throw", "new", "ArithmeticException", "(", "\"modulus must be positive\"", ")...
Calculate val^-1 % modulus. @param val must be positive @param modulus the modulus @return val^-1 % modulus @throws ArithmeticException if modulus is non-positive or val is not invertible
[ "Calculate", "val^", "-", "1", "%", "modulus", "." ]
train
https://github.com/square/jna-gmp/blob/192d26d97d6773bc3c68ccfa97450f4257d54838/jnagmp/src/main/java/com/squareup/jnagmp/Gmp.java#L150-L155
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/TimeSeriesUtils.java
TimeSeriesUtils.reverseTimeSeriesMask
public static INDArray reverseTimeSeriesMask(INDArray mask, LayerWorkspaceMgr workspaceMgr, ArrayType arrayType){ if(mask == null){ return null; } if(mask.rank() == 3){ //Should normally not be used - but handle the per-output masking case return reverseTimeSeries(mask, workspaceMgr, arrayType); } else if(mask.rank() != 2){ throw new IllegalArgumentException("Invalid mask rank: must be rank 2 or 3. Got rank " + mask.rank() + " with shape " + Arrays.toString(mask.shape())); } // FIXME: int cast int[] idxs = new int[(int) mask.size(1)]; int j=0; for( int i=idxs.length-1; i>=0; i--){ idxs[j++] = i; } INDArray ret = workspaceMgr.createUninitialized(arrayType, mask.dataType(), new long[]{mask.size(0), idxs.length}, 'f'); return Nd4j.pullRows(mask, ret, 0, idxs); /* //Assume input mask is 2d: [minibatch, tsLength] INDArray out = Nd4j.createUninitialized(mask.shape(), 'f'); CustomOp op = DynamicCustomOp.builder("reverse") .addIntegerArguments(new int[]{1}) .addInputs(mask) .addOutputs(out) .callInplace(false) .build(); Nd4j.getExecutioner().exec(op); return out; */ }
java
public static INDArray reverseTimeSeriesMask(INDArray mask, LayerWorkspaceMgr workspaceMgr, ArrayType arrayType){ if(mask == null){ return null; } if(mask.rank() == 3){ //Should normally not be used - but handle the per-output masking case return reverseTimeSeries(mask, workspaceMgr, arrayType); } else if(mask.rank() != 2){ throw new IllegalArgumentException("Invalid mask rank: must be rank 2 or 3. Got rank " + mask.rank() + " with shape " + Arrays.toString(mask.shape())); } // FIXME: int cast int[] idxs = new int[(int) mask.size(1)]; int j=0; for( int i=idxs.length-1; i>=0; i--){ idxs[j++] = i; } INDArray ret = workspaceMgr.createUninitialized(arrayType, mask.dataType(), new long[]{mask.size(0), idxs.length}, 'f'); return Nd4j.pullRows(mask, ret, 0, idxs); /* //Assume input mask is 2d: [minibatch, tsLength] INDArray out = Nd4j.createUninitialized(mask.shape(), 'f'); CustomOp op = DynamicCustomOp.builder("reverse") .addIntegerArguments(new int[]{1}) .addInputs(mask) .addOutputs(out) .callInplace(false) .build(); Nd4j.getExecutioner().exec(op); return out; */ }
[ "public", "static", "INDArray", "reverseTimeSeriesMask", "(", "INDArray", "mask", ",", "LayerWorkspaceMgr", "workspaceMgr", ",", "ArrayType", "arrayType", ")", "{", "if", "(", "mask", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "mask", "."...
Reverse a (per time step) time series mask, with shape [minibatch, timeSeriesLength] @param mask Mask to reverse along time dimension @return Mask after reversing
[ "Reverse", "a", "(", "per", "time", "step", ")", "time", "series", "mask", "with", "shape", "[", "minibatch", "timeSeriesLength", "]" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/TimeSeriesUtils.java#L310-L345
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/api/DeploymentInfo.java
DeploymentInfo.addPreCompressedResourceEncoding
public DeploymentInfo addPreCompressedResourceEncoding(String encoding, String extension) { preCompressedResources.put(encoding, extension); return this; }
java
public DeploymentInfo addPreCompressedResourceEncoding(String encoding, String extension) { preCompressedResources.put(encoding, extension); return this; }
[ "public", "DeploymentInfo", "addPreCompressedResourceEncoding", "(", "String", "encoding", ",", "String", "extension", ")", "{", "preCompressedResources", ".", "put", "(", "encoding", ",", "extension", ")", ";", "return", "this", ";", "}" ]
Adds a pre compressed resource encoding and maps it to a file extension @param encoding The content encoding @param extension The file extension @return this builder
[ "Adds", "a", "pre", "compressed", "resource", "encoding", "and", "maps", "it", "to", "a", "file", "extension" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/api/DeploymentInfo.java#L1342-L1345
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/hash/MurmurHash3Adaptor.java
MurmurHash3Adaptor.asInt
public static int asInt(final String datum, final int n) { if ((datum == null) || datum.isEmpty()) { throw new SketchesArgumentException("Input is null or empty."); } final byte[] data = datum.getBytes(UTF_8); return asInteger(toLongArray(data), n); //data is byte[] }
java
public static int asInt(final String datum, final int n) { if ((datum == null) || datum.isEmpty()) { throw new SketchesArgumentException("Input is null or empty."); } final byte[] data = datum.getBytes(UTF_8); return asInteger(toLongArray(data), n); //data is byte[] }
[ "public", "static", "int", "asInt", "(", "final", "String", "datum", ",", "final", "int", "n", ")", "{", "if", "(", "(", "datum", "==", "null", ")", "||", "datum", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "SketchesArgumentException", "(", ...
Returns a deterministic uniform random integer between zero (inclusive) and n (exclusive) given the input datum. @param datum the given String. @param n The upper exclusive bound of the integers produced. Must be &gt; 1. @return deterministic uniform random integer
[ "Returns", "a", "deterministic", "uniform", "random", "integer", "between", "zero", "(", "inclusive", ")", "and", "n", "(", "exclusive", ")", "given", "the", "input", "datum", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hash/MurmurHash3Adaptor.java#L305-L311
agmip/ace-lookup
src/main/java/org/agmip/ace/util/AcePathfinderUtil.java
AcePathfinderUtil.buildPath
private static void buildPath(HashMap m, String p) { boolean isEvent = false; if(p.contains("@")) { String[] components = p.split("@"); int cl = components.length; buildNestedBuckets(m, components[0]); if(cl == 2) { if(p.contains("!")) isEvent = true; HashMap pointer = traverseToPoint(m, components[0]); String d; if(isEvent) { String[] temp = components[1].split("!"); d = temp[0]; } else { d = components[1]; } if( ! pointer.containsKey(d) ) pointer.put(d, new ArrayList()); } } }
java
private static void buildPath(HashMap m, String p) { boolean isEvent = false; if(p.contains("@")) { String[] components = p.split("@"); int cl = components.length; buildNestedBuckets(m, components[0]); if(cl == 2) { if(p.contains("!")) isEvent = true; HashMap pointer = traverseToPoint(m, components[0]); String d; if(isEvent) { String[] temp = components[1].split("!"); d = temp[0]; } else { d = components[1]; } if( ! pointer.containsKey(d) ) pointer.put(d, new ArrayList()); } } }
[ "private", "static", "void", "buildPath", "(", "HashMap", "m", ",", "String", "p", ")", "{", "boolean", "isEvent", "=", "false", ";", "if", "(", "p", ".", "contains", "(", "\"@\"", ")", ")", "{", "String", "[", "]", "components", "=", "p", ".", "sp...
Creates a nested path, if not already present in the map. This does not support multipath definitions. Please split prior to sending the path to this function. @param m The map to create the path inside of. @param p The full path to create.
[ "Creates", "a", "nested", "path", "if", "not", "already", "present", "in", "the", "map", ".", "This", "does", "not", "support", "multipath", "definitions", ".", "Please", "split", "prior", "to", "sending", "the", "path", "to", "this", "function", "." ]
train
https://github.com/agmip/ace-lookup/blob/d8224a231cb8c01729e63010916a2a85517ce4c1/src/main/java/org/agmip/ace/util/AcePathfinderUtil.java#L233-L253
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/edit/ST_MultiplyZ.java
ST_MultiplyZ.multiplyZ
public static Geometry multiplyZ(Geometry geometry, double z) throws SQLException { if(geometry == null){ return null; } geometry.apply(new MultiplyZCoordinateSequenceFilter(z)); return geometry; }
java
public static Geometry multiplyZ(Geometry geometry, double z) throws SQLException { if(geometry == null){ return null; } geometry.apply(new MultiplyZCoordinateSequenceFilter(z)); return geometry; }
[ "public", "static", "Geometry", "multiplyZ", "(", "Geometry", "geometry", ",", "double", "z", ")", "throws", "SQLException", "{", "if", "(", "geometry", "==", "null", ")", "{", "return", "null", ";", "}", "geometry", ".", "apply", "(", "new", "MultiplyZCoo...
Multiply the z values of the geometry by another double value. NaN values are not updated. @param geometry @param z @return @throws java.sql.SQLException
[ "Multiply", "the", "z", "values", "of", "the", "geometry", "by", "another", "double", "value", ".", "NaN", "values", "are", "not", "updated", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/edit/ST_MultiplyZ.java#L56-L62
tvesalainen/util
util/src/main/java/org/vesalainen/bean/BeanHelper.java
BeanHelper.defaultFactory
public static final <T> T defaultFactory(Class<T> cls, String hint) { try { return cls.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { throw new IllegalArgumentException(ex); } }
java
public static final <T> T defaultFactory(Class<T> cls, String hint) { try { return cls.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { throw new IllegalArgumentException(ex); } }
[ "public", "static", "final", "<", "T", ">", "T", "defaultFactory", "(", "Class", "<", "T", ">", "cls", ",", "String", "hint", ")", "{", "try", "{", "return", "cls", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "InstantiationException", "|", ...
Default object factory that calls newInstance method. Checked exceptions are wrapped in IllegalArgumentException. @param <T> @param cls Target class @param hint Hint for factory @return
[ "Default", "object", "factory", "that", "calls", "newInstance", "method", ".", "Checked", "exceptions", "are", "wrapped", "in", "IllegalArgumentException", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/bean/BeanHelper.java#L416-L426
netty/netty
codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java
ByteToMessageDecoder.fireChannelRead
static void fireChannelRead(ChannelHandlerContext ctx, List<Object> msgs, int numElements) { if (msgs instanceof CodecOutputList) { fireChannelRead(ctx, (CodecOutputList) msgs, numElements); } else { for (int i = 0; i < numElements; i++) { ctx.fireChannelRead(msgs.get(i)); } } }
java
static void fireChannelRead(ChannelHandlerContext ctx, List<Object> msgs, int numElements) { if (msgs instanceof CodecOutputList) { fireChannelRead(ctx, (CodecOutputList) msgs, numElements); } else { for (int i = 0; i < numElements; i++) { ctx.fireChannelRead(msgs.get(i)); } } }
[ "static", "void", "fireChannelRead", "(", "ChannelHandlerContext", "ctx", ",", "List", "<", "Object", ">", "msgs", ",", "int", "numElements", ")", "{", "if", "(", "msgs", "instanceof", "CodecOutputList", ")", "{", "fireChannelRead", "(", "ctx", ",", "(", "Co...
Get {@code numElements} out of the {@link List} and forward these through the pipeline.
[ "Get", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java#L308-L316
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ModuleSummaryBuilder.java
ModuleSummaryBuilder.getInstance
public static ModuleSummaryBuilder getInstance(Context context, ModuleElement mdle, ModuleSummaryWriter moduleWriter) { return new ModuleSummaryBuilder(context, mdle, moduleWriter); }
java
public static ModuleSummaryBuilder getInstance(Context context, ModuleElement mdle, ModuleSummaryWriter moduleWriter) { return new ModuleSummaryBuilder(context, mdle, moduleWriter); }
[ "public", "static", "ModuleSummaryBuilder", "getInstance", "(", "Context", "context", ",", "ModuleElement", "mdle", ",", "ModuleSummaryWriter", "moduleWriter", ")", "{", "return", "new", "ModuleSummaryBuilder", "(", "context", ",", "mdle", ",", "moduleWriter", ")", ...
Construct a new ModuleSummaryBuilder. @param context the build context. @param mdle the module being documented. @param moduleWriter the doclet specific writer that will output the result. @return an instance of a ModuleSummaryBuilder.
[ "Construct", "a", "new", "ModuleSummaryBuilder", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ModuleSummaryBuilder.java#L99-L102
ysc/word
src/main/java/org/apdplat/word/corpus/Evaluation.java
Evaluation.generateDataset
public static int generateDataset(String file, String test, String standard){ int textCharCount=0; try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8")); BufferedWriter testWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(test),"utf-8")); BufferedWriter standardWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(standard),"utf-8"))){ String line; int duplicateCount=0; Set<String> set = new HashSet<>(); while( (line = reader.readLine()) != null ){ //不把空格当做标点符号 List<String> list = Punctuation.seg(line, false, ' '); for(String item : list){ item = item.trim(); //忽略空行和长度为一的行 if("".equals(item) || item.length()==1){ continue; } //忽略重复的内容 if(set.contains(item)){ duplicateCount++; continue; } set.add(item); String testItem = item.replaceAll(" ", ""); textCharCount += testItem.length(); testWriter.write(testItem+"\n"); standardWriter.write(item+"\n"); } } LOGGER.info("重复行数为:"+duplicateCount); } catch (IOException ex) { LOGGER.error("生成测试数据集和标准数据集失败:", ex); } return textCharCount; }
java
public static int generateDataset(String file, String test, String standard){ int textCharCount=0; try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8")); BufferedWriter testWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(test),"utf-8")); BufferedWriter standardWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(standard),"utf-8"))){ String line; int duplicateCount=0; Set<String> set = new HashSet<>(); while( (line = reader.readLine()) != null ){ //不把空格当做标点符号 List<String> list = Punctuation.seg(line, false, ' '); for(String item : list){ item = item.trim(); //忽略空行和长度为一的行 if("".equals(item) || item.length()==1){ continue; } //忽略重复的内容 if(set.contains(item)){ duplicateCount++; continue; } set.add(item); String testItem = item.replaceAll(" ", ""); textCharCount += testItem.length(); testWriter.write(testItem+"\n"); standardWriter.write(item+"\n"); } } LOGGER.info("重复行数为:"+duplicateCount); } catch (IOException ex) { LOGGER.error("生成测试数据集和标准数据集失败:", ex); } return textCharCount; }
[ "public", "static", "int", "generateDataset", "(", "String", "file", ",", "String", "test", ",", "String", "standard", ")", "{", "int", "textCharCount", "=", "0", ";", "try", "(", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputSt...
生成测试数据集和标准数据集 @param file 已分词文本,词之间空格分隔 @param test 生成测试数据集文件路径 @param standard 生成标准数据集文件路径 @return 测试数据集字符数
[ "生成测试数据集和标准数据集" ]
train
https://github.com/ysc/word/blob/5e45607f4e97207f55d1e3bc561abda6b34f7c54/src/main/java/org/apdplat/word/corpus/Evaluation.java#L113-L148
cverges/expect4j
src/main/java/expect4j/ExpectUtils.java
ExpectUtils.SSH
public static Expect4j SSH(String hostname, String username, String password, int port) throws Exception { logger.debug("Creating SSH session with " + hostname + ":" + port + " as " + username); JSch jsch = new JSch(); //jsch.setKnownHosts("/home/foo/.ssh/known_hosts"); final Session session = jsch.getSession(username, hostname, port); if (password != null) { logger.trace("Setting the Jsch password to the one provided (not shown)"); session.setPassword(password); } java.util.Hashtable<String, String> config = new java.util.Hashtable<>(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setDaemonThread(true); session.connect(3 * 1000); // making a connection with timeout. ChannelShell channel = (ChannelShell) session.openChannel("shell"); //channel.setInputStream(System.in); //channel.setOutputStream(System.out); channel.setPtyType("vt102"); //channel.setEnv("LANG", "ja_JP.eucJP"); Expect4j expect = new Expect4j(channel.getInputStream(), channel.getOutputStream()) { public void close() { super.close(); session.disconnect(); } }; channel.connect(5 * 1000); return expect; }
java
public static Expect4j SSH(String hostname, String username, String password, int port) throws Exception { logger.debug("Creating SSH session with " + hostname + ":" + port + " as " + username); JSch jsch = new JSch(); //jsch.setKnownHosts("/home/foo/.ssh/known_hosts"); final Session session = jsch.getSession(username, hostname, port); if (password != null) { logger.trace("Setting the Jsch password to the one provided (not shown)"); session.setPassword(password); } java.util.Hashtable<String, String> config = new java.util.Hashtable<>(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setDaemonThread(true); session.connect(3 * 1000); // making a connection with timeout. ChannelShell channel = (ChannelShell) session.openChannel("shell"); //channel.setInputStream(System.in); //channel.setOutputStream(System.out); channel.setPtyType("vt102"); //channel.setEnv("LANG", "ja_JP.eucJP"); Expect4j expect = new Expect4j(channel.getInputStream(), channel.getOutputStream()) { public void close() { super.close(); session.disconnect(); } }; channel.connect(5 * 1000); return expect; }
[ "public", "static", "Expect4j", "SSH", "(", "String", "hostname", ",", "String", "username", ",", "String", "password", ",", "int", "port", ")", "throws", "Exception", "{", "logger", ".", "debug", "(", "\"Creating SSH session with \"", "+", "hostname", "+", "\...
Creates an SSH session to the given server on a custom TCP port using the provided credentials. This is equivalent to Expect's <code>spawn ssh $hostname</code>. @param hostname the DNS or IP address of the remote server @param username the account name to use when authenticating @param password the account password to use when authenticating @param port the TCP port for the SSH service @return the controlling Expect4j instance @throws Exception on a variety of errors
[ "Creates", "an", "SSH", "session", "to", "the", "given", "server", "on", "a", "custom", "TCP", "port", "using", "the", "provided", "credentials", ".", "This", "is", "equivalent", "to", "Expect", "s", "<code", ">", "spawn", "ssh", "$hostname<", "/", "code",...
train
https://github.com/cverges/expect4j/blob/97b1da9b7bd231344cd7b7ce26d14caf8bb16cd6/src/main/java/expect4j/ExpectUtils.java#L180-L218
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/AbstractApi.java
AbstractApi.addFormParam
protected void addFormParam(Form formData, String name, Object value) throws IllegalArgumentException { addFormParam(formData, name, value, false); }
java
protected void addFormParam(Form formData, String name, Object value) throws IllegalArgumentException { addFormParam(formData, name, value, false); }
[ "protected", "void", "addFormParam", "(", "Form", "formData", ",", "String", "name", ",", "Object", "value", ")", "throws", "IllegalArgumentException", "{", "addFormParam", "(", "formData", ",", "name", ",", "value", ",", "false", ")", ";", "}" ]
Convenience method for adding query and form parameters to a get() or post() call. @param formData the Form containing the name/value pairs @param name the name of the field/attribute to add @param value the value of the field/attribute to add
[ "Convenience", "method", "for", "adding", "query", "and", "form", "parameters", "to", "a", "get", "()", "or", "post", "()", "call", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/AbstractApi.java#L541-L543
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/exception/fault/FaultFormatTextDecorator.java
FaultFormatTextDecorator.getText
@Override public String getText() { if(this.target == null) return null; try { //Check if load of template needed if((this.template == null || this.template.length() == 0) && this.templateName != null) { try { this.template = Text.loadTemplate(templateName); } catch(Exception e) { throw new SetupException("Cannot load template:"+templateName,e); } } Map<Object,Object> faultMap = JavaBean.toMap(this.target); if(this.argumentTextDecorator != null) { this.argumentTextDecorator.setTarget(this.target.getArgument()); faultMap.put(this.argumentKeyName, this.argumentTextDecorator.getText()); } return Text.format(this.template, faultMap); } catch (FormatException e) { throw new FormatFaultException(this.template, e); } }
java
@Override public String getText() { if(this.target == null) return null; try { //Check if load of template needed if((this.template == null || this.template.length() == 0) && this.templateName != null) { try { this.template = Text.loadTemplate(templateName); } catch(Exception e) { throw new SetupException("Cannot load template:"+templateName,e); } } Map<Object,Object> faultMap = JavaBean.toMap(this.target); if(this.argumentTextDecorator != null) { this.argumentTextDecorator.setTarget(this.target.getArgument()); faultMap.put(this.argumentKeyName, this.argumentTextDecorator.getText()); } return Text.format(this.template, faultMap); } catch (FormatException e) { throw new FormatFaultException(this.template, e); } }
[ "@", "Override", "public", "String", "getText", "(", ")", "{", "if", "(", "this", ".", "target", "==", "null", ")", "return", "null", ";", "try", "{", "//Check if load of template needed", "if", "(", "(", "this", ".", "template", "==", "null", "||", "thi...
Converts the target fault into a formatted text. @see nyla.solutions.core.data.Textable#getText()
[ "Converts", "the", "target", "fault", "into", "a", "formatted", "text", "." ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/exception/fault/FaultFormatTextDecorator.java#L40-L80
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/view/ChocoViews.java
ChocoViews.resolveDependencies
public static List<ChocoView> resolveDependencies(Model mo, List<ChocoView> views, Collection<String> base) throws SchedulerException { Set<String> done = new HashSet<>(base); List<ChocoView> remaining = new ArrayList<>(views); List<ChocoView> solved = new ArrayList<>(); while (!remaining.isEmpty()) { ListIterator<ChocoView> ite = remaining.listIterator(); boolean blocked = true; while (ite.hasNext()) { ChocoView s = ite.next(); if (done.containsAll(s.getDependencies())) { ite.remove(); done.add(s.getIdentifier()); solved.add(s); blocked = false; } } if (blocked) { throw new SchedulerModelingException(mo, "Missing dependencies or cyclic dependencies prevent from using: " + remaining); } } return solved; }
java
public static List<ChocoView> resolveDependencies(Model mo, List<ChocoView> views, Collection<String> base) throws SchedulerException { Set<String> done = new HashSet<>(base); List<ChocoView> remaining = new ArrayList<>(views); List<ChocoView> solved = new ArrayList<>(); while (!remaining.isEmpty()) { ListIterator<ChocoView> ite = remaining.listIterator(); boolean blocked = true; while (ite.hasNext()) { ChocoView s = ite.next(); if (done.containsAll(s.getDependencies())) { ite.remove(); done.add(s.getIdentifier()); solved.add(s); blocked = false; } } if (blocked) { throw new SchedulerModelingException(mo, "Missing dependencies or cyclic dependencies prevent from using: " + remaining); } } return solved; }
[ "public", "static", "List", "<", "ChocoView", ">", "resolveDependencies", "(", "Model", "mo", ",", "List", "<", "ChocoView", ">", "views", ",", "Collection", "<", "String", ">", "base", ")", "throws", "SchedulerException", "{", "Set", "<", "String", ">", "...
Flatten the views while considering their dependencies. Operations over the views that respect the iteration order, satisfies the dependencies. @param mo the model @param views the associated solver views @return the list of views, dependency-free @throws SchedulerException if there is a cyclic dependency
[ "Flatten", "the", "views", "while", "considering", "their", "dependencies", ".", "Operations", "over", "the", "views", "that", "respect", "the", "iteration", "order", "satisfies", "the", "dependencies", "." ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/view/ChocoViews.java#L52-L73
lessthanoptimal/ejml
main/ejml-core/src/org/ejml/ops/ReadMatrixCsv.java
ReadMatrixCsv.readCDRM
public CMatrixRMaj readCDRM(int numRows, int numCols) throws IOException { CMatrixRMaj A = new CMatrixRMaj(numRows,numCols); int wordsCol = numCols*2; for( int i = 0; i < numRows; i++ ) { List<String> words = extractWords(); if( words == null ) throw new IOException("Too few rows found. expected "+numRows+" actual "+i); if( words.size() != wordsCol ) throw new IOException("Unexpected number of words in column. Found "+words.size()+" expected "+wordsCol); for( int j = 0; j < wordsCol; j += 2 ) { float real = Float.parseFloat(words.get(j)); float imaginary = Float.parseFloat(words.get(j+1)); A.set(i, j, real, imaginary); } } return A; }
java
public CMatrixRMaj readCDRM(int numRows, int numCols) throws IOException { CMatrixRMaj A = new CMatrixRMaj(numRows,numCols); int wordsCol = numCols*2; for( int i = 0; i < numRows; i++ ) { List<String> words = extractWords(); if( words == null ) throw new IOException("Too few rows found. expected "+numRows+" actual "+i); if( words.size() != wordsCol ) throw new IOException("Unexpected number of words in column. Found "+words.size()+" expected "+wordsCol); for( int j = 0; j < wordsCol; j += 2 ) { float real = Float.parseFloat(words.get(j)); float imaginary = Float.parseFloat(words.get(j+1)); A.set(i, j, real, imaginary); } } return A; }
[ "public", "CMatrixRMaj", "readCDRM", "(", "int", "numRows", ",", "int", "numCols", ")", "throws", "IOException", "{", "CMatrixRMaj", "A", "=", "new", "CMatrixRMaj", "(", "numRows", ",", "numCols", ")", ";", "int", "wordsCol", "=", "numCols", "*", "2", ";",...
Reads in a {@link CMatrixRMaj} from the IO stream where the user specifies the matrix dimensions. @param numRows Number of rows in the matrix @param numCols Number of columns in the matrix @return CMatrixRMaj @throws IOException
[ "Reads", "in", "a", "{", "@link", "CMatrixRMaj", "}", "from", "the", "IO", "stream", "where", "the", "user", "specifies", "the", "matrix", "dimensions", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-core/src/org/ejml/ops/ReadMatrixCsv.java#L216-L239
gallandarakhneorg/afc
advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/coordinate/GISCoordinates.java
GISCoordinates.L93_EL2
@Pure public static Point2d L93_EL2(double x, double y) { final Point2d ntfLambdaPhi = NTFLambert_NTFLambdaPhi(x, y, LAMBERT_93_N, LAMBERT_93_C, LAMBERT_93_XS, LAMBERT_93_YS); return NTFLambdaPhi_NTFLambert( ntfLambdaPhi.getX(), ntfLambdaPhi.getY(), LAMBERT_2E_N, LAMBERT_2E_C, LAMBERT_2E_XS, LAMBERT_2E_YS); }
java
@Pure public static Point2d L93_EL2(double x, double y) { final Point2d ntfLambdaPhi = NTFLambert_NTFLambdaPhi(x, y, LAMBERT_93_N, LAMBERT_93_C, LAMBERT_93_XS, LAMBERT_93_YS); return NTFLambdaPhi_NTFLambert( ntfLambdaPhi.getX(), ntfLambdaPhi.getY(), LAMBERT_2E_N, LAMBERT_2E_C, LAMBERT_2E_XS, LAMBERT_2E_YS); }
[ "@", "Pure", "public", "static", "Point2d", "L93_EL2", "(", "double", "x", ",", "double", "y", ")", "{", "final", "Point2d", "ntfLambdaPhi", "=", "NTFLambert_NTFLambdaPhi", "(", "x", ",", "y", ",", "LAMBERT_93_N", ",", "LAMBERT_93_C", ",", "LAMBERT_93_XS", "...
This function convert France Lambert 93 coordinate to extended France Lambert II coordinate. @param x is the coordinate in France Lambert 93 @param y is the coordinate in France Lambert 93 @return the extended France Lambert II coordinate.
[ "This", "function", "convert", "France", "Lambert", "93", "coordinate", "to", "extended", "France", "Lambert", "II", "coordinate", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/coordinate/GISCoordinates.java#L823-L836
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/error/AbstractErrorMetric.java
AbstractErrorMetric.considerEstimatedPreference
public static double considerEstimatedPreference(final ErrorStrategy errorStrategy, final double recValue) { boolean consider = true; double v = recValue; switch (errorStrategy) { default: case CONSIDER_EVERYTHING: break; case NOT_CONSIDER_NAN: consider = !Double.isNaN(recValue); break; case CONSIDER_NAN_AS_0: if (Double.isNaN(recValue)) { v = 0.0; } break; case CONSIDER_NAN_AS_1: if (Double.isNaN(recValue)) { v = 1.0; } break; case CONSIDER_NAN_AS_3: if (Double.isNaN(recValue)) { v = 3.0; } break; } if (consider) { return v; } else { return Double.NaN; } }
java
public static double considerEstimatedPreference(final ErrorStrategy errorStrategy, final double recValue) { boolean consider = true; double v = recValue; switch (errorStrategy) { default: case CONSIDER_EVERYTHING: break; case NOT_CONSIDER_NAN: consider = !Double.isNaN(recValue); break; case CONSIDER_NAN_AS_0: if (Double.isNaN(recValue)) { v = 0.0; } break; case CONSIDER_NAN_AS_1: if (Double.isNaN(recValue)) { v = 1.0; } break; case CONSIDER_NAN_AS_3: if (Double.isNaN(recValue)) { v = 3.0; } break; } if (consider) { return v; } else { return Double.NaN; } }
[ "public", "static", "double", "considerEstimatedPreference", "(", "final", "ErrorStrategy", "errorStrategy", ",", "final", "double", "recValue", ")", "{", "boolean", "consider", "=", "true", ";", "double", "v", "=", "recValue", ";", "switch", "(", "errorStrategy",...
Method that returns an estimated preference according to a given value and an error strategy. @param errorStrategy the error strategy @param recValue the predicted value by the recommender @return an estimated preference according to the provided strategy
[ "Method", "that", "returns", "an", "estimated", "preference", "according", "to", "a", "given", "value", "and", "an", "error", "strategy", "." ]
train
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/error/AbstractErrorMetric.java#L159-L190
agapsys/embedded-servlet-container
src/main/java/com/agapsys/jee/ServletContainer.java
ServletContainer.registerFilter
public SC registerFilter(Class<? extends Filter> filterClass, String urlPattern) { __throwIfInitialized(); List<Class<? extends Filter>> filterList = filterMap.get(urlPattern); if (filterList == null) { filterList = new LinkedList<>(); filterMap.put(urlPattern, filterList); } if (!filterList.contains(filterClass)) { filterList.add(filterClass); } return (SC) this; }
java
public SC registerFilter(Class<? extends Filter> filterClass, String urlPattern) { __throwIfInitialized(); List<Class<? extends Filter>> filterList = filterMap.get(urlPattern); if (filterList == null) { filterList = new LinkedList<>(); filterMap.put(urlPattern, filterList); } if (!filterList.contains(filterClass)) { filterList.add(filterClass); } return (SC) this; }
[ "public", "SC", "registerFilter", "(", "Class", "<", "?", "extends", "Filter", ">", "filterClass", ",", "String", "urlPattern", ")", "{", "__throwIfInitialized", "(", ")", ";", "List", "<", "Class", "<", "?", "extends", "Filter", ">", ">", "filterList", "=...
Registers a filter. @param filterClass class to be registered. @param urlPattern url pattern to be associated with given class. @return this
[ "Registers", "a", "filter", "." ]
train
https://github.com/agapsys/embedded-servlet-container/blob/28314a2600ad8550ed2c901d8e35d86583c26bb0/src/main/java/com/agapsys/jee/ServletContainer.java#L293-L308
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/flow/DenseFlowPyramidBase.java
DenseFlowPyramidBase.interpolateFlowScale
protected void interpolateFlowScale(GrayF32 prev, GrayF32 curr) { interp.setImage(prev); float scaleX = (float)prev.width/(float)curr.width; float scaleY = (float)prev.height/(float)curr.height; float scale = (float)prev.width/(float)curr.width; int indexCurr = 0; for( int y = 0; y < curr.height; y++ ) { float yy = y*scaleY; for( int x = 0; x < curr.width; x++ ) { float xx = x*scaleX; if( interp.isInFastBounds(xx,yy)) { curr.data[indexCurr++] = interp.get_fast(x * scaleX, y * scaleY) / scale; } else { curr.data[indexCurr++] = interp.get(x * scaleX, y * scaleY) / scale; } } } }
java
protected void interpolateFlowScale(GrayF32 prev, GrayF32 curr) { interp.setImage(prev); float scaleX = (float)prev.width/(float)curr.width; float scaleY = (float)prev.height/(float)curr.height; float scale = (float)prev.width/(float)curr.width; int indexCurr = 0; for( int y = 0; y < curr.height; y++ ) { float yy = y*scaleY; for( int x = 0; x < curr.width; x++ ) { float xx = x*scaleX; if( interp.isInFastBounds(xx,yy)) { curr.data[indexCurr++] = interp.get_fast(x * scaleX, y * scaleY) / scale; } else { curr.data[indexCurr++] = interp.get(x * scaleX, y * scaleY) / scale; } } } }
[ "protected", "void", "interpolateFlowScale", "(", "GrayF32", "prev", ",", "GrayF32", "curr", ")", "{", "interp", ".", "setImage", "(", "prev", ")", ";", "float", "scaleX", "=", "(", "float", ")", "prev", ".", "width", "/", "(", "float", ")", "curr", "....
Takes the flow from the previous lower resolution layer and uses it to initialize the flow in the current layer. Adjusts for change in image scale.
[ "Takes", "the", "flow", "from", "the", "previous", "lower", "resolution", "layer", "and", "uses", "it", "to", "initialize", "the", "flow", "in", "the", "current", "layer", ".", "Adjusts", "for", "change", "in", "image", "scale", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/flow/DenseFlowPyramidBase.java#L96-L116
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/table/ClassUtils.java
ClassUtils.getWriteMethod
public static final Method getWriteMethod(Class<?> clazz, String propertyName, Class<?> propertyType) { String propertyNameCapitalized = capitalize(propertyName); try { return clazz.getMethod("set" + propertyNameCapitalized, new Class[]{propertyType}); } catch (Exception e) { return null; } }
java
public static final Method getWriteMethod(Class<?> clazz, String propertyName, Class<?> propertyType) { String propertyNameCapitalized = capitalize(propertyName); try { return clazz.getMethod("set" + propertyNameCapitalized, new Class[]{propertyType}); } catch (Exception e) { return null; } }
[ "public", "static", "final", "Method", "getWriteMethod", "(", "Class", "<", "?", ">", "clazz", ",", "String", "propertyName", ",", "Class", "<", "?", ">", "propertyType", ")", "{", "String", "propertyNameCapitalized", "=", "capitalize", "(", "propertyName", ")...
Lookup the setter method for the given property. @param clazz type which contains the property. @param propertyName name of the property. @param propertyType type of the property. @return a Method with write-access for the property.
[ "Lookup", "the", "setter", "method", "for", "the", "given", "property", "." ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/table/ClassUtils.java#L99-L110
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/util/FontUtils.java
FontUtils.drawLeft
public static void drawLeft(Font font, String s, int x, int y) { drawString(font, s, Alignment.LEFT, x, y, 0, Color.white); }
java
public static void drawLeft(Font font, String s, int x, int y) { drawString(font, s, Alignment.LEFT, x, y, 0, Color.white); }
[ "public", "static", "void", "drawLeft", "(", "Font", "font", ",", "String", "s", ",", "int", "x", ",", "int", "y", ")", "{", "drawString", "(", "font", ",", "s", ",", "Alignment", ".", "LEFT", ",", "x", ",", "y", ",", "0", ",", "Color", ".", "w...
Draw text left justified @param font The font to draw with @param s The string to draw @param x The x location to draw at @param y The y location to draw at
[ "Draw", "text", "left", "justified" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/util/FontUtils.java#L38-L40
beihaifeiwu/dolphin
dolphin-common/src/main/java/com/freetmp/common/annotation/OrderUtils.java
OrderUtils.getOrder
public static Integer getOrder(Class<?> type, Integer defaultOrder) { Order order = AnnotationUtils.findAnnotation(type, Order.class); if (order != null) { return order.value(); } Integer priorityOrder = getPriority(type); if (priorityOrder != null) { return priorityOrder; } return defaultOrder; }
java
public static Integer getOrder(Class<?> type, Integer defaultOrder) { Order order = AnnotationUtils.findAnnotation(type, Order.class); if (order != null) { return order.value(); } Integer priorityOrder = getPriority(type); if (priorityOrder != null) { return priorityOrder; } return defaultOrder; }
[ "public", "static", "Integer", "getOrder", "(", "Class", "<", "?", ">", "type", ",", "Integer", "defaultOrder", ")", "{", "Order", "order", "=", "AnnotationUtils", ".", "findAnnotation", "(", "type", ",", "Order", ".", "class", ")", ";", "if", "(", "orde...
Return the order on the specified {@code type}, or the specified default value if none can be found. <p>Take care of {@link Order @Order} and {@code @javax.annotation.Priority}. @param type the type to handle @return the priority value, or the specified default order if none can be found
[ "Return", "the", "order", "on", "the", "specified", "{" ]
train
https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/annotation/OrderUtils.java#L67-L77
lucee/Lucee
core/src/main/java/lucee/runtime/type/scope/session/SessionMemory.java
SessionMemory.getInstance
public static Session getInstance(PageContext pc, RefBoolean isNew, Log log) { isNew.setValue(true); return new SessionMemory(pc, log); }
java
public static Session getInstance(PageContext pc, RefBoolean isNew, Log log) { isNew.setValue(true); return new SessionMemory(pc, log); }
[ "public", "static", "Session", "getInstance", "(", "PageContext", "pc", ",", "RefBoolean", "isNew", ",", "Log", "log", ")", "{", "isNew", ".", "setValue", "(", "true", ")", ";", "return", "new", "SessionMemory", "(", "pc", ",", "log", ")", ";", "}" ]
load a new instance of the class @param pc @param isNew @return
[ "load", "a", "new", "instance", "of", "the", "class" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/type/scope/session/SessionMemory.java#L62-L65
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/cfg/ProcessEngineConfigurationImpl.java
ProcessEngineConfigurationImpl.ensurePrefixAndSchemaFitToegether
protected void ensurePrefixAndSchemaFitToegether(String prefix, String schema) { if (schema == null) { return; } else if (prefix == null || (prefix != null && !prefix.startsWith(schema + "."))) { throw new ProcessEngineException("When setting a schema the prefix has to be schema + '.'. Received schema: " + schema + " prefix: " + prefix); } }
java
protected void ensurePrefixAndSchemaFitToegether(String prefix, String schema) { if (schema == null) { return; } else if (prefix == null || (prefix != null && !prefix.startsWith(schema + "."))) { throw new ProcessEngineException("When setting a schema the prefix has to be schema + '.'. Received schema: " + schema + " prefix: " + prefix); } }
[ "protected", "void", "ensurePrefixAndSchemaFitToegether", "(", "String", "prefix", ",", "String", "schema", ")", "{", "if", "(", "schema", "==", "null", ")", "{", "return", ";", "}", "else", "if", "(", "prefix", "==", "null", "||", "(", "prefix", "!=", "...
When providing a schema and a prefix the prefix has to be the schema ending with a dot.
[ "When", "providing", "a", "schema", "and", "a", "prefix", "the", "prefix", "has", "to", "be", "the", "schema", "ending", "with", "a", "dot", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/cfg/ProcessEngineConfigurationImpl.java#L1677-L1683
xiancloud/xian
xian-zookeeper/xian-curator/xian-curator-framework/src/main/java/org/apache/curator/framework/CuratorFrameworkFactory.java
CuratorFrameworkFactory.newClient
public static CuratorFramework newClient(String connectString, RetryPolicy retryPolicy) { return newClient(connectString, DEFAULT_SESSION_TIMEOUT_MS, DEFAULT_CONNECTION_TIMEOUT_MS, retryPolicy); }
java
public static CuratorFramework newClient(String connectString, RetryPolicy retryPolicy) { return newClient(connectString, DEFAULT_SESSION_TIMEOUT_MS, DEFAULT_CONNECTION_TIMEOUT_MS, retryPolicy); }
[ "public", "static", "CuratorFramework", "newClient", "(", "String", "connectString", ",", "RetryPolicy", "retryPolicy", ")", "{", "return", "newClient", "(", "connectString", ",", "DEFAULT_SESSION_TIMEOUT_MS", ",", "DEFAULT_CONNECTION_TIMEOUT_MS", ",", "retryPolicy", ")",...
Create a new client with default session timeout and default connection timeout @param connectString list of servers to connect to @param retryPolicy retry policy to use @return client
[ "Create", "a", "new", "client", "with", "default", "session", "timeout", "and", "default", "connection", "timeout" ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-zookeeper/xian-curator/xian-curator-framework/src/main/java/org/apache/curator/framework/CuratorFrameworkFactory.java#L79-L82
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.beginPause
public void beginPause(String resourceGroupName, String serverName, String databaseName) { beginPauseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).toBlocking().single().body(); }
java
public void beginPause(String resourceGroupName, String serverName, String databaseName) { beginPauseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).toBlocking().single().body(); }
[ "public", "void", "beginPause", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "databaseName", ")", "{", "beginPauseWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "databaseName", ")", ".", "toBlocking", "(...
Pauses a data warehouse. @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 databaseName The name of the data warehouse to pause. @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
[ "Pauses", "a", "data", "warehouse", "." ]
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#L244-L246
zsoltk/overpasser
library/src/main/java/hu/supercluster/overpasser/library/query/OverpassFilterQuery.java
OverpassFilterQuery.tagRegexNot
public OverpassFilterQuery tagRegexNot(String name, String value) { builder.regexDoesntMatch(name, value); return this; }
java
public OverpassFilterQuery tagRegexNot(String name, String value) { builder.regexDoesntMatch(name, value); return this; }
[ "public", "OverpassFilterQuery", "tagRegexNot", "(", "String", "name", ",", "String", "value", ")", "{", "builder", ".", "regexDoesntMatch", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Adds a <i>["name"!~value]</i> filter tag to the current query. @param name the filter name @param value the filter value @return the current query object
[ "Adds", "a", "<i", ">", "[", "name", "!~value", "]", "<", "/", "i", ">", "filter", "tag", "to", "the", "current", "query", "." ]
train
https://github.com/zsoltk/overpasser/blob/0464d3844e75c5f9393d2458d3a3aedf3e40f30d/library/src/main/java/hu/supercluster/overpasser/library/query/OverpassFilterQuery.java#L205-L209
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/Request.java
Request.newStatusUpdateRequest
public static Request newStatusUpdateRequest(Session session, String message, Callback callback) { return newStatusUpdateRequest(session, message, (String)null, null, callback); }
java
public static Request newStatusUpdateRequest(Session session, String message, Callback callback) { return newStatusUpdateRequest(session, message, (String)null, null, callback); }
[ "public", "static", "Request", "newStatusUpdateRequest", "(", "Session", "session", ",", "String", "message", ",", "Callback", "callback", ")", "{", "return", "newStatusUpdateRequest", "(", "session", ",", "message", ",", "(", "String", ")", "null", ",", "null",...
Creates a new Request configured to post a status update to a user's feed. @param session the Session to use, or null; if non-null, the session must be in an opened state @param message the text of the status update @param callback a callback that will be called when the request is completed to handle success or error conditions @return a Request that is ready to execute
[ "Creates", "a", "new", "Request", "configured", "to", "post", "a", "status", "update", "to", "a", "user", "s", "feed", "." ]
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L440-L442
WASdev/ci.ant
src/main/java/net/wasdev/wlp/ant/AbstractTask.java
AbstractTask.findStringInFile
protected String findStringInFile(String regexp, File fileToSearch) throws Exception { String foundString = null; List<String> matches = findStringsInFileCommon(regexp, true, -1, fileToSearch); if (matches != null && !matches.isEmpty()) { foundString = matches.get(0); } return foundString; }
java
protected String findStringInFile(String regexp, File fileToSearch) throws Exception { String foundString = null; List<String> matches = findStringsInFileCommon(regexp, true, -1, fileToSearch); if (matches != null && !matches.isEmpty()) { foundString = matches.get(0); } return foundString; }
[ "protected", "String", "findStringInFile", "(", "String", "regexp", ",", "File", "fileToSearch", ")", "throws", "Exception", "{", "String", "foundString", "=", "null", ";", "List", "<", "String", ">", "matches", "=", "findStringsInFileCommon", "(", "regexp", ","...
Searches the given file for the given regular expression. @param regexp a regular expression (or just a text snippet) to search for @param fileToSearch the file to search @return The first line which includes the pattern, or null if the pattern isn't found or if the file doesn't exist @throws Exception
[ "Searches", "the", "given", "file", "for", "the", "given", "regular", "expression", "." ]
train
https://github.com/WASdev/ci.ant/blob/13edd5c9111b98e12f74c0be83f9180285e6e40c/src/main/java/net/wasdev/wlp/ant/AbstractTask.java#L336-L346
citrusframework/citrus
modules/citrus-jms/src/main/java/com/consol/citrus/jms/actions/PurgeJmsQueuesAction.java
PurgeJmsQueuesAction.purgeDestination
private void purgeDestination(Destination destination, Session session, String destinationName) throws JMSException { if (log.isDebugEnabled()) { log.debug("Try to purge destination " + destinationName); } int messagesPurged = 0; MessageConsumer messageConsumer = session.createConsumer(destination); try { javax.jms.Message message; do { message = (receiveTimeout >= 0) ? messageConsumer.receive(receiveTimeout) : messageConsumer.receive(); if (message != null) { log.debug("Removed message from destination " + destinationName); messagesPurged++; try { Thread.sleep(sleepTime); } catch (InterruptedException e) { log.warn("Interrupted during wait", e); } } } while (message != null); if (log.isDebugEnabled()) { log.debug("Purged " + messagesPurged + " messages from destination"); } } finally { JmsUtils.closeMessageConsumer(messageConsumer); } }
java
private void purgeDestination(Destination destination, Session session, String destinationName) throws JMSException { if (log.isDebugEnabled()) { log.debug("Try to purge destination " + destinationName); } int messagesPurged = 0; MessageConsumer messageConsumer = session.createConsumer(destination); try { javax.jms.Message message; do { message = (receiveTimeout >= 0) ? messageConsumer.receive(receiveTimeout) : messageConsumer.receive(); if (message != null) { log.debug("Removed message from destination " + destinationName); messagesPurged++; try { Thread.sleep(sleepTime); } catch (InterruptedException e) { log.warn("Interrupted during wait", e); } } } while (message != null); if (log.isDebugEnabled()) { log.debug("Purged " + messagesPurged + " messages from destination"); } } finally { JmsUtils.closeMessageConsumer(messageConsumer); } }
[ "private", "void", "purgeDestination", "(", "Destination", "destination", ",", "Session", "session", ",", "String", "destinationName", ")", "throws", "JMSException", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", ...
Purge destination by receiving all available messages. @param destination @param session @param destinationName @throws JMSException
[ "Purge", "destination", "by", "receiving", "all", "available", "messages", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jms/src/main/java/com/consol/citrus/jms/actions/PurgeJmsQueuesAction.java#L128-L158
JOML-CI/JOML
src/org/joml/Quaterniond.java
Quaterniond.lookAlong
public Quaterniond lookAlong(double dirX, double dirY, double dirZ, double upX, double upY, double upZ, Quaterniond dest) { // Normalize direction double invDirLength = 1.0 / Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); double dirnX = -dirX * invDirLength; double dirnY = -dirY * invDirLength; double dirnZ = -dirZ * invDirLength; // left = up x dir double leftX, leftY, leftZ; leftX = upY * dirnZ - upZ * dirnY; leftY = upZ * dirnX - upX * dirnZ; leftZ = upX * dirnY - upY * dirnX; // normalize left double invLeftLength = 1.0 / Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLength; leftY *= invLeftLength; leftZ *= invLeftLength; // up = direction x left double upnX = dirnY * leftZ - dirnZ * leftY; double upnY = dirnZ * leftX - dirnX * leftZ; double upnZ = dirnX * leftY - dirnY * leftX; /* Convert orthonormal basis vectors to quaternion */ double x, y, z, w; double t; double tr = leftX + upnY + dirnZ; if (tr >= 0.0) { t = Math.sqrt(tr + 1.0); w = t * 0.5; t = 0.5 / t; x = (dirnY - upnZ) * t; y = (leftZ - dirnX) * t; z = (upnX - leftY) * t; } else { if (leftX > upnY && leftX > dirnZ) { t = Math.sqrt(1.0 + leftX - upnY - dirnZ); x = t * 0.5; t = 0.5 / t; y = (leftY + upnX) * t; z = (dirnX + leftZ) * t; w = (dirnY - upnZ) * t; } else if (upnY > dirnZ) { t = Math.sqrt(1.0 + upnY - leftX - dirnZ); y = t * 0.5; t = 0.5 / t; x = (leftY + upnX) * t; z = (upnZ + dirnY) * t; w = (leftZ - dirnX) * t; } else { t = Math.sqrt(1.0 + dirnZ - leftX - upnY); z = t * 0.5; t = 0.5 / t; x = (dirnX + leftZ) * t; y = (upnZ + dirnY) * t; w = (upnX - leftY) * t; } } /* Multiply */ dest.set(this.w * x + this.x * w + this.y * z - this.z * y, this.w * y - this.x * z + this.y * w + this.z * x, this.w * z + this.x * y - this.y * x + this.z * w, this.w * w - this.x * x - this.y * y - this.z * z); return dest; }
java
public Quaterniond lookAlong(double dirX, double dirY, double dirZ, double upX, double upY, double upZ, Quaterniond dest) { // Normalize direction double invDirLength = 1.0 / Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); double dirnX = -dirX * invDirLength; double dirnY = -dirY * invDirLength; double dirnZ = -dirZ * invDirLength; // left = up x dir double leftX, leftY, leftZ; leftX = upY * dirnZ - upZ * dirnY; leftY = upZ * dirnX - upX * dirnZ; leftZ = upX * dirnY - upY * dirnX; // normalize left double invLeftLength = 1.0 / Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLength; leftY *= invLeftLength; leftZ *= invLeftLength; // up = direction x left double upnX = dirnY * leftZ - dirnZ * leftY; double upnY = dirnZ * leftX - dirnX * leftZ; double upnZ = dirnX * leftY - dirnY * leftX; /* Convert orthonormal basis vectors to quaternion */ double x, y, z, w; double t; double tr = leftX + upnY + dirnZ; if (tr >= 0.0) { t = Math.sqrt(tr + 1.0); w = t * 0.5; t = 0.5 / t; x = (dirnY - upnZ) * t; y = (leftZ - dirnX) * t; z = (upnX - leftY) * t; } else { if (leftX > upnY && leftX > dirnZ) { t = Math.sqrt(1.0 + leftX - upnY - dirnZ); x = t * 0.5; t = 0.5 / t; y = (leftY + upnX) * t; z = (dirnX + leftZ) * t; w = (dirnY - upnZ) * t; } else if (upnY > dirnZ) { t = Math.sqrt(1.0 + upnY - leftX - dirnZ); y = t * 0.5; t = 0.5 / t; x = (leftY + upnX) * t; z = (upnZ + dirnY) * t; w = (leftZ - dirnX) * t; } else { t = Math.sqrt(1.0 + dirnZ - leftX - upnY); z = t * 0.5; t = 0.5 / t; x = (dirnX + leftZ) * t; y = (upnZ + dirnY) * t; w = (upnX - leftY) * t; } } /* Multiply */ dest.set(this.w * x + this.x * w + this.y * z - this.z * y, this.w * y - this.x * z + this.y * w + this.z * x, this.w * z + this.x * y - this.y * x + this.z * w, this.w * w - this.x * x - this.y * y - this.z * z); return dest; }
[ "public", "Quaterniond", "lookAlong", "(", "double", "dirX", ",", "double", "dirY", ",", "double", "dirZ", ",", "double", "upX", ",", "double", "upY", ",", "double", "upZ", ",", "Quaterniond", "dest", ")", "{", "// Normalize direction", "double", "invDirLength...
/* (non-Javadoc) @see org.joml.Quaterniondc#lookAlong(double, double, double, double, double, double, org.joml.Quaterniond)
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaterniond.java#L1712-L1774
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/ThrottlerCalculator.java
ThrottlerCalculator.getThrottlingDelay
DelayResult getThrottlingDelay() { // These delays are not additive. There's no benefit to adding a batching delay on top of a throttling delay, since // a throttling delay will have increased batching as a side effect. int maxDelay = 0; boolean maximum = false; for (Throttler t : this.throttlers) { int delay = t.getDelayMillis(); if (delay >= MAX_DELAY_MILLIS) { // This throttler introduced the maximum delay. No need to search more. maxDelay = MAX_DELAY_MILLIS; maximum = true; break; } maxDelay = Math.max(maxDelay, delay); } return new DelayResult(maxDelay, maximum); }
java
DelayResult getThrottlingDelay() { // These delays are not additive. There's no benefit to adding a batching delay on top of a throttling delay, since // a throttling delay will have increased batching as a side effect. int maxDelay = 0; boolean maximum = false; for (Throttler t : this.throttlers) { int delay = t.getDelayMillis(); if (delay >= MAX_DELAY_MILLIS) { // This throttler introduced the maximum delay. No need to search more. maxDelay = MAX_DELAY_MILLIS; maximum = true; break; } maxDelay = Math.max(maxDelay, delay); } return new DelayResult(maxDelay, maximum); }
[ "DelayResult", "getThrottlingDelay", "(", ")", "{", "// These delays are not additive. There's no benefit to adding a batching delay on top of a throttling delay, since", "// a throttling delay will have increased batching as a side effect.", "int", "maxDelay", "=", "0", ";", "boolean", "m...
Calculates the amount of time needed to delay based on the configured throttlers. The computed result is not additive, as there is no benefit to adding delays from various Throttle Calculators together. For example, a cache throttling delay will have increased batching as a side effect, so there's no need to include the batching one as well. @return A DelayResult representing the computed delay. This delay is the maximum delay as calculated by the internal throttlers.
[ "Calculates", "the", "amount", "of", "time", "needed", "to", "delay", "based", "on", "the", "configured", "throttlers", ".", "The", "computed", "result", "is", "not", "additive", "as", "there", "is", "no", "benefit", "to", "adding", "delays", "from", "variou...
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/ThrottlerCalculator.java#L91-L109
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/util/ShapeGenerator.java
ShapeGenerator.createScrollButtonTogetherIncrease
public Shape createScrollButtonTogetherIncrease(int x, int y, int w, int h) { return createRectangle(x, y, w, h); }
java
public Shape createScrollButtonTogetherIncrease(int x, int y, int w, int h) { return createRectangle(x, y, w, h); }
[ "public", "Shape", "createScrollButtonTogetherIncrease", "(", "int", "x", ",", "int", "y", ",", "int", "w", ",", "int", "h", ")", "{", "return", "createRectangle", "(", "x", ",", "y", ",", "w", ",", "h", ")", ";", "}" ]
Return a path for a scroll bar increase button. This is used when the buttons are placed together at one end of the scroll bar. @param x the X coordinate of the upper-left corner of the button @param y the Y coordinate of the upper-left corner of the button @param w the width of the button @param h the height of the button @return a path representing the shape.
[ "Return", "a", "path", "for", "a", "scroll", "bar", "increase", "button", ".", "This", "is", "used", "when", "the", "buttons", "are", "placed", "together", "at", "one", "end", "of", "the", "scroll", "bar", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/util/ShapeGenerator.java#L712-L714
Ordinastie/MalisisCore
src/main/java/net/malisis/core/block/component/ColorComponent.java
ColorComponent.getColor
public static EnumDyeColor getColor(IBlockAccess world, BlockPos pos) { return world != null && pos != null ? getColor(world.getBlockState(pos)) : EnumDyeColor.WHITE; }
java
public static EnumDyeColor getColor(IBlockAccess world, BlockPos pos) { return world != null && pos != null ? getColor(world.getBlockState(pos)) : EnumDyeColor.WHITE; }
[ "public", "static", "EnumDyeColor", "getColor", "(", "IBlockAccess", "world", ",", "BlockPos", "pos", ")", "{", "return", "world", "!=", "null", "&&", "pos", "!=", "null", "?", "getColor", "(", "world", ".", "getBlockState", "(", "pos", ")", ")", ":", "E...
Gets the {@link EnumDyeColor color} for the {@link Block} at world coords. @param world the world @param pos the pos @return the EnumDyeColor, null if the block is not {@link ColorComponent}
[ "Gets", "the", "{", "@link", "EnumDyeColor", "color", "}", "for", "the", "{", "@link", "Block", "}", "at", "world", "coords", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/block/component/ColorComponent.java#L203-L206
datastax/java-driver
query-builder/src/main/java/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.java
SchemaBuilder.dropAggregate
@NonNull public static Drop dropAggregate( @Nullable CqlIdentifier keyspace, @NonNull CqlIdentifier aggregateName) { return new DefaultDrop(keyspace, aggregateName, "AGGREGATE"); }
java
@NonNull public static Drop dropAggregate( @Nullable CqlIdentifier keyspace, @NonNull CqlIdentifier aggregateName) { return new DefaultDrop(keyspace, aggregateName, "AGGREGATE"); }
[ "@", "NonNull", "public", "static", "Drop", "dropAggregate", "(", "@", "Nullable", "CqlIdentifier", "keyspace", ",", "@", "NonNull", "CqlIdentifier", "aggregateName", ")", "{", "return", "new", "DefaultDrop", "(", "keyspace", ",", "aggregateName", ",", "\"AGGREGAT...
Starts an DROP AGGREGATE query for the given aggregate name for the given keyspace name.
[ "Starts", "an", "DROP", "AGGREGATE", "query", "for", "the", "given", "aggregate", "name", "for", "the", "given", "keyspace", "name", "." ]
train
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/query-builder/src/main/java/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.java#L589-L593
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Scroller.java
Scroller.scrollView
public boolean scrollView(final View view, int direction){ if(view == null){ return false; } int height = view.getHeight(); height--; int scrollTo = -1; if (direction == DOWN) { scrollTo = height; } else if (direction == UP) { scrollTo = -height; } int originalY = view.getScrollY(); final int scrollAmount = scrollTo; inst.runOnMainSync(new Runnable(){ public void run(){ view.scrollBy(0, scrollAmount); } }); if (originalY == view.getScrollY()) { return false; } else{ return true; } }
java
public boolean scrollView(final View view, int direction){ if(view == null){ return false; } int height = view.getHeight(); height--; int scrollTo = -1; if (direction == DOWN) { scrollTo = height; } else if (direction == UP) { scrollTo = -height; } int originalY = view.getScrollY(); final int scrollAmount = scrollTo; inst.runOnMainSync(new Runnable(){ public void run(){ view.scrollBy(0, scrollAmount); } }); if (originalY == view.getScrollY()) { return false; } else{ return true; } }
[ "public", "boolean", "scrollView", "(", "final", "View", "view", ",", "int", "direction", ")", "{", "if", "(", "view", "==", "null", ")", "{", "return", "false", ";", "}", "int", "height", "=", "view", ".", "getHeight", "(", ")", ";", "height", "--",...
Scrolls a ScrollView. @param direction the direction to be scrolled @return {@code true} if scrolling occurred, false if it did not
[ "Scrolls", "a", "ScrollView", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Scroller.java#L105-L136
pressgang-ccms/PressGangCCMSContentSpecProcessor
src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecParser.java
ContentSpecParser.parseFilesMetaData
protected FileList parseFilesMetaData(final ParserData parserData, final String value, final int lineNumber, final String line) throws ParsingException { int startingPos = StringUtilities.indexOf(value, '['); if (startingPos != -1) { final List<File> files = new LinkedList<File>(); final HashMap<ParserType, String[]> variables = getLineVariables(parserData, value, lineNumber, '[', ']', ',', true); final String[] vars = variables.get(ParserType.NONE); // Loop over each file found and parse it for (final String var : vars) { final File file = parseFileMetaData(var, lineNumber); if (file != null) { files.add(file); } } return new FileList(CommonConstants.CS_FILE_TITLE, files, lineNumber); } else { throw new ParsingException(format(ProcessorConstants.ERROR_INVALID_FILES_MSG, lineNumber, line)); } }
java
protected FileList parseFilesMetaData(final ParserData parserData, final String value, final int lineNumber, final String line) throws ParsingException { int startingPos = StringUtilities.indexOf(value, '['); if (startingPos != -1) { final List<File> files = new LinkedList<File>(); final HashMap<ParserType, String[]> variables = getLineVariables(parserData, value, lineNumber, '[', ']', ',', true); final String[] vars = variables.get(ParserType.NONE); // Loop over each file found and parse it for (final String var : vars) { final File file = parseFileMetaData(var, lineNumber); if (file != null) { files.add(file); } } return new FileList(CommonConstants.CS_FILE_TITLE, files, lineNumber); } else { throw new ParsingException(format(ProcessorConstants.ERROR_INVALID_FILES_MSG, lineNumber, line)); } }
[ "protected", "FileList", "parseFilesMetaData", "(", "final", "ParserData", "parserData", ",", "final", "String", "value", ",", "final", "int", "lineNumber", ",", "final", "String", "line", ")", "throws", "ParsingException", "{", "int", "startingPos", "=", "StringU...
Parse an "Additional Files" metadata component into a List of {@link org.jboss.pressgang.ccms.contentspec.File} objects. @param parserData @param value The value of the key value pair @param lineNumber The line number of the additional files key @param line The full line of the key value pair @return A list of parsed File objects. @throws ParsingException Thrown if an error occurs during parsing.
[ "Parse", "an", "Additional", "Files", "metadata", "component", "into", "a", "List", "of", "{", "@link", "org", ".", "jboss", ".", "pressgang", ".", "ccms", ".", "contentspec", ".", "File", "}", "objects", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpecProcessor/blob/85ffac047c4ede0f972364ab1f03f7d61a4de5f1/src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecParser.java#L858-L878
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/date/GosuDateUtil.java
GosuDateUtil.addMonths
public static Date addMonths(Date date, int iMonths) { Calendar dateTime = dateToCalendar(date); dateTime.add(Calendar.MONTH, iMonths); return dateTime.getTime(); }
java
public static Date addMonths(Date date, int iMonths) { Calendar dateTime = dateToCalendar(date); dateTime.add(Calendar.MONTH, iMonths); return dateTime.getTime(); }
[ "public", "static", "Date", "addMonths", "(", "Date", "date", ",", "int", "iMonths", ")", "{", "Calendar", "dateTime", "=", "dateToCalendar", "(", "date", ")", ";", "dateTime", ".", "add", "(", "Calendar", ".", "MONTH", ",", "iMonths", ")", ";", "return"...
Adds the specified (signed) amount of months to the given date. For example, to subtract 5 months from the current date, you can achieve it by calling: <code>addMonths(Date, -5)</code>. @param date The time. @param iMonths The amount of months to add. @return A new date with the months added.
[ "Adds", "the", "specified", "(", "signed", ")", "amount", "of", "months", "to", "the", "given", "date", ".", "For", "example", "to", "subtract", "5", "months", "from", "the", "current", "date", "you", "can", "achieve", "it", "by", "calling", ":", "<code"...
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/date/GosuDateUtil.java#L109-L113
Azure/azure-sdk-for-java
compute/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/compute/v2018_04_01/implementation/DisksInner.java
DisksInner.beginGrantAccessAsync
public Observable<AccessUriInner> beginGrantAccessAsync(String resourceGroupName, String diskName, GrantAccessData grantAccessData) { return beginGrantAccessWithServiceResponseAsync(resourceGroupName, diskName, grantAccessData).map(new Func1<ServiceResponse<AccessUriInner>, AccessUriInner>() { @Override public AccessUriInner call(ServiceResponse<AccessUriInner> response) { return response.body(); } }); }
java
public Observable<AccessUriInner> beginGrantAccessAsync(String resourceGroupName, String diskName, GrantAccessData grantAccessData) { return beginGrantAccessWithServiceResponseAsync(resourceGroupName, diskName, grantAccessData).map(new Func1<ServiceResponse<AccessUriInner>, AccessUriInner>() { @Override public AccessUriInner call(ServiceResponse<AccessUriInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "AccessUriInner", ">", "beginGrantAccessAsync", "(", "String", "resourceGroupName", ",", "String", "diskName", ",", "GrantAccessData", "grantAccessData", ")", "{", "return", "beginGrantAccessWithServiceResponseAsync", "(", "resourceGroupName", "...
Grants access to a disk. @param resourceGroupName The name of the resource group. @param diskName The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported characters for the name are a-z, A-Z, 0-9 and _. The maximum name length is 80 characters. @param grantAccessData Access data object supplied in the body of the get disk access operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the AccessUriInner object
[ "Grants", "access", "to", "a", "disk", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/compute/v2018_04_01/implementation/DisksInner.java#L1055-L1062
networknt/light-rest-4j
openapi-validator/src/main/java/com/networknt/openapi/ResponseValidator.java
ResponseValidator.getOpenApiOperation
private OpenApiOperation getOpenApiOperation(String uri, String httpMethod) throws URISyntaxException { String uriWithoutQuery = new URI(uri).getPath(); NormalisedPath requestPath = new ApiNormalisedPath(uriWithoutQuery); Optional<NormalisedPath> maybeApiPath = OpenApiHelper.findMatchingApiPath(requestPath); if (!maybeApiPath.isPresent()) { return null; } final NormalisedPath openApiPathString = maybeApiPath.get(); final Path path = OpenApiHelper.openApi3.getPath(openApiPathString.original()); final Operation operation = path.getOperation(httpMethod); return new OpenApiOperation(openApiPathString, path, httpMethod, operation); }
java
private OpenApiOperation getOpenApiOperation(String uri, String httpMethod) throws URISyntaxException { String uriWithoutQuery = new URI(uri).getPath(); NormalisedPath requestPath = new ApiNormalisedPath(uriWithoutQuery); Optional<NormalisedPath> maybeApiPath = OpenApiHelper.findMatchingApiPath(requestPath); if (!maybeApiPath.isPresent()) { return null; } final NormalisedPath openApiPathString = maybeApiPath.get(); final Path path = OpenApiHelper.openApi3.getPath(openApiPathString.original()); final Operation operation = path.getOperation(httpMethod); return new OpenApiOperation(openApiPathString, path, httpMethod, operation); }
[ "private", "OpenApiOperation", "getOpenApiOperation", "(", "String", "uri", ",", "String", "httpMethod", ")", "throws", "URISyntaxException", "{", "String", "uriWithoutQuery", "=", "new", "URI", "(", "uri", ")", ".", "getPath", "(", ")", ";", "NormalisedPath", "...
locate operation based on uri and httpMethod @param uri original uri of the request @param httpMethod http method of the request @return OpenApiOperation the wrapper of an api operation
[ "locate", "operation", "based", "on", "uri", "and", "httpMethod" ]
train
https://github.com/networknt/light-rest-4j/blob/06b15128e6101351e617284a636ef5d632e6b1fe/openapi-validator/src/main/java/com/networknt/openapi/ResponseValidator.java#L173-L186
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/MinimizeEnergyPrune.java
MinimizeEnergyPrune.energyRemoveCorner
protected double energyRemoveCorner( int removed , GrowQueue_I32 corners ) { double total = 0; int cornerA = CircularIndex.addOffset(removed, -1 , corners.size()); int cornerB = CircularIndex.addOffset(removed, 1 , corners.size()); total += computeSegmentEnergy(corners, cornerA, cornerB); if( cornerA > cornerB ) { for (int i = cornerB; i < cornerA; i++) total += energySegment[i]; } else { for (int i = 0; i < cornerA; i++) { total += energySegment[i]; } for (int i = cornerB; i < corners.size(); i++) { total += energySegment[i]; } } return total; }
java
protected double energyRemoveCorner( int removed , GrowQueue_I32 corners ) { double total = 0; int cornerA = CircularIndex.addOffset(removed, -1 , corners.size()); int cornerB = CircularIndex.addOffset(removed, 1 , corners.size()); total += computeSegmentEnergy(corners, cornerA, cornerB); if( cornerA > cornerB ) { for (int i = cornerB; i < cornerA; i++) total += energySegment[i]; } else { for (int i = 0; i < cornerA; i++) { total += energySegment[i]; } for (int i = cornerB; i < corners.size(); i++) { total += energySegment[i]; } } return total; }
[ "protected", "double", "energyRemoveCorner", "(", "int", "removed", ",", "GrowQueue_I32", "corners", ")", "{", "double", "total", "=", "0", ";", "int", "cornerA", "=", "CircularIndex", ".", "addOffset", "(", "removed", ",", "-", "1", ",", "corners", ".", "...
Returns the total energy after removing a corner @param removed index of the corner that is being removed @param corners list of corner indexes
[ "Returns", "the", "total", "energy", "after", "removing", "a", "corner" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/MinimizeEnergyPrune.java#L184-L205
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/core/model/Properties.java
Properties.putMapEntry
public <K, V> void putMapEntry(PropertyMapKey<K, V> property, K key, V value) { Map<K, V> map = get(property); if (!property.allowsOverwrite() && map.containsKey(key)) { throw new ProcessEngineException("Cannot overwrite property key " + key + ". Key already exists"); } map.put(key, value); if (!contains(property)) { set(property, map); } }
java
public <K, V> void putMapEntry(PropertyMapKey<K, V> property, K key, V value) { Map<K, V> map = get(property); if (!property.allowsOverwrite() && map.containsKey(key)) { throw new ProcessEngineException("Cannot overwrite property key " + key + ". Key already exists"); } map.put(key, value); if (!contains(property)) { set(property, map); } }
[ "public", "<", "K", ",", "V", ">", "void", "putMapEntry", "(", "PropertyMapKey", "<", "K", ",", "V", ">", "property", ",", "K", "key", ",", "V", "value", ")", "{", "Map", "<", "K", ",", "V", ">", "map", "=", "get", "(", "property", ")", ";", ...
Insert the value to the map to which the specified property key is mapped. If this properties contains no mapping for the property key, the value insert to a new map witch is associate the the specified property key. @param <K> the type of keys maintained by the map @param <V> the type of mapped values @param property the property key whose associated list is to be added @param value the value to be appended to list
[ "Insert", "the", "value", "to", "the", "map", "to", "which", "the", "specified", "property", "key", "is", "mapped", ".", "If", "this", "properties", "contains", "no", "mapping", "for", "the", "property", "key", "the", "value", "insert", "to", "a", "new", ...
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/core/model/Properties.java#L183-L195
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/earth/ST_GeometryShadow.java
ST_GeometryShadow.shadowLine
private static Geometry shadowLine(LineString lineString, double[] shadowOffset, GeometryFactory factory, boolean doUnion) { Coordinate[] coords = lineString.getCoordinates(); Collection<Polygon> shadows = new ArrayList<Polygon>(); createShadowPolygons(shadows, coords, shadowOffset, factory); if (!doUnion) { return factory.buildGeometry(shadows); } else { if (!shadows.isEmpty()) { CascadedPolygonUnion union = new CascadedPolygonUnion(shadows); Geometry result = union.union(); result.apply(new UpdateZCoordinateSequenceFilter(0, 1)); return result; } return null; } }
java
private static Geometry shadowLine(LineString lineString, double[] shadowOffset, GeometryFactory factory, boolean doUnion) { Coordinate[] coords = lineString.getCoordinates(); Collection<Polygon> shadows = new ArrayList<Polygon>(); createShadowPolygons(shadows, coords, shadowOffset, factory); if (!doUnion) { return factory.buildGeometry(shadows); } else { if (!shadows.isEmpty()) { CascadedPolygonUnion union = new CascadedPolygonUnion(shadows); Geometry result = union.union(); result.apply(new UpdateZCoordinateSequenceFilter(0, 1)); return result; } return null; } }
[ "private", "static", "Geometry", "shadowLine", "(", "LineString", "lineString", ",", "double", "[", "]", "shadowOffset", ",", "GeometryFactory", "factory", ",", "boolean", "doUnion", ")", "{", "Coordinate", "[", "]", "coords", "=", "lineString", ".", "getCoordin...
Compute the shadow for a linestring @param lineString the input linestring @param shadowOffset computed according the sun position and the height of the geometry @return
[ "Compute", "the", "shadow", "for", "a", "linestring" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/earth/ST_GeometryShadow.java#L133-L148
couchbase/CouchbaseMock
src/main/java/com/couchbase/mock/CouchbaseMock.java
CouchbaseMock.createDefaultConfig
private static BucketConfiguration createDefaultConfig(String hostname, int numNodes, int bucketStartPort, int numVBuckets, int numReplicas) { BucketConfiguration defaultConfig = new BucketConfiguration(); defaultConfig.type = BucketType.COUCHBASE; defaultConfig.hostname = hostname; defaultConfig.numNodes = numNodes; if (numReplicas > -1) { defaultConfig.numReplicas = numReplicas; } defaultConfig.bucketStartPort = bucketStartPort; defaultConfig.numVBuckets = numVBuckets; return defaultConfig; }
java
private static BucketConfiguration createDefaultConfig(String hostname, int numNodes, int bucketStartPort, int numVBuckets, int numReplicas) { BucketConfiguration defaultConfig = new BucketConfiguration(); defaultConfig.type = BucketType.COUCHBASE; defaultConfig.hostname = hostname; defaultConfig.numNodes = numNodes; if (numReplicas > -1) { defaultConfig.numReplicas = numReplicas; } defaultConfig.bucketStartPort = bucketStartPort; defaultConfig.numVBuckets = numVBuckets; return defaultConfig; }
[ "private", "static", "BucketConfiguration", "createDefaultConfig", "(", "String", "hostname", ",", "int", "numNodes", ",", "int", "bucketStartPort", ",", "int", "numVBuckets", ",", "int", "numReplicas", ")", "{", "BucketConfiguration", "defaultConfig", "=", "new", "...
Initializes the default configuration from the command line parameters. This is present in order to allow the super constructor to be the first statement
[ "Initializes", "the", "default", "configuration", "from", "the", "command", "line", "parameters", ".", "This", "is", "present", "in", "order", "to", "allow", "the", "super", "constructor", "to", "be", "the", "first", "statement" ]
train
https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/CouchbaseMock.java#L215-L227
trellis-ldp/trellis
components/constraint-rules/src/main/java/org/trellisldp/constraint/LdpConstraints.java
LdpConstraints.propertyFilter
private static boolean propertyFilter(final Triple t, final IRI ixnModel) { return typeMap.getOrDefault(ixnModel, LdpConstraints::basicConstraints).test(t); }
java
private static boolean propertyFilter(final Triple t, final IRI ixnModel) { return typeMap.getOrDefault(ixnModel, LdpConstraints::basicConstraints).test(t); }
[ "private", "static", "boolean", "propertyFilter", "(", "final", "Triple", "t", ",", "final", "IRI", "ixnModel", ")", "{", "return", "typeMap", ".", "getOrDefault", "(", "ixnModel", ",", "LdpConstraints", "::", "basicConstraints", ")", ".", "test", "(", "t", ...
Ensure that any LDP properties are appropriate for the interaction model
[ "Ensure", "that", "any", "LDP", "properties", "are", "appropriate", "for", "the", "interaction", "model" ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/components/constraint-rules/src/main/java/org/trellisldp/constraint/LdpConstraints.java#L121-L123
networknt/light-4j
client/src/main/java/com/networknt/client/ssl/APINameChecker.java
APINameChecker.verifyAndThrow
public static void verifyAndThrow(final String name, final X509Certificate cert) throws CertificateException{ if (!verify(name, cert)) { throw new CertificateException("No name matching " + name + " found"); } }
java
public static void verifyAndThrow(final String name, final X509Certificate cert) throws CertificateException{ if (!verify(name, cert)) { throw new CertificateException("No name matching " + name + " found"); } }
[ "public", "static", "void", "verifyAndThrow", "(", "final", "String", "name", ",", "final", "X509Certificate", "cert", ")", "throws", "CertificateException", "{", "if", "(", "!", "verify", "(", "name", ",", "cert", ")", ")", "{", "throw", "new", "Certificate...
Perform server identify check using given name and throw CertificateException if the check fails. @param name @param cert @throws CertificateException
[ "Perform", "server", "identify", "check", "using", "given", "name", "and", "throw", "CertificateException", "if", "the", "check", "fails", "." ]
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/client/src/main/java/com/networknt/client/ssl/APINameChecker.java#L54-L58
cfg4j/cfg4j
cfg4j-core/src/main/java/org/cfg4j/source/files/FilesConfigurationSource.java
FilesConfigurationSource.getConfiguration
@Override public Properties getConfiguration(Environment environment) { Properties properties = new Properties(); Path rootPath; if (environment.getName().trim().isEmpty()) { rootPath = Paths.get(System.getProperty("user.home")); } else { rootPath = Paths.get(environment.getName()); } if (!rootPath.toFile().exists()) { throw new MissingEnvironmentException("Directory doesn't exist: " + rootPath); } List<Path> paths = new ArrayList<>(); for (Path path : configFilesProvider.getConfigFiles()) { paths.add(rootPath.resolve(path)); } for (Path path : paths) { try (InputStream input = new FileInputStream(path.toFile())) { PropertiesProvider provider = propertiesProviderSelector.getProvider(path.getFileName().toString()); properties.putAll(provider.getProperties(input)); } catch (IOException e) { throw new IllegalStateException("Unable to load properties from file: " + path, e); } } return properties; }
java
@Override public Properties getConfiguration(Environment environment) { Properties properties = new Properties(); Path rootPath; if (environment.getName().trim().isEmpty()) { rootPath = Paths.get(System.getProperty("user.home")); } else { rootPath = Paths.get(environment.getName()); } if (!rootPath.toFile().exists()) { throw new MissingEnvironmentException("Directory doesn't exist: " + rootPath); } List<Path> paths = new ArrayList<>(); for (Path path : configFilesProvider.getConfigFiles()) { paths.add(rootPath.resolve(path)); } for (Path path : paths) { try (InputStream input = new FileInputStream(path.toFile())) { PropertiesProvider provider = propertiesProviderSelector.getProvider(path.getFileName().toString()); properties.putAll(provider.getProperties(input)); } catch (IOException e) { throw new IllegalStateException("Unable to load properties from file: " + path, e); } } return properties; }
[ "@", "Override", "public", "Properties", "getConfiguration", "(", "Environment", "environment", ")", "{", "Properties", "properties", "=", "new", "Properties", "(", ")", ";", "Path", "rootPath", ";", "if", "(", "environment", ".", "getName", "(", ")", ".", "...
Get configuration set for a given {@code environment} from this source in a form of {@link Properties}. {@link Environment} name is prepended to all file paths from {@link ConfigFilesProvider} to form an absolute configuration file path. If environment name is empty paths are treated as relative to the user's home directory location. @param environment environment to use @return configuration set for {@code environment} @throws MissingEnvironmentException when requested environment couldn't be found @throws IllegalStateException when unable to fetch configuration
[ "Get", "configuration", "set", "for", "a", "given", "{", "@code", "environment", "}", "from", "this", "source", "in", "a", "form", "of", "{", "@link", "Properties", "}", ".", "{", "@link", "Environment", "}", "name", "is", "prepended", "to", "all", "file...
train
https://github.com/cfg4j/cfg4j/blob/47d4f63e5fc820c62631e557adc34a29d8ab396d/cfg4j-core/src/main/java/org/cfg4j/source/files/FilesConfigurationSource.java#L98-L130
mgormley/pacaya
src/main/java/edu/jhu/pacaya/gm/data/bayesnet/BayesNetReader.java
BayesNetReader.readBnAsFg
public FactorGraph readBnAsFg(InputStream networkIs, InputStream cpdIs) throws IOException { // Read network file. BufferedReader networkReader = new BufferedReader(new InputStreamReader(networkIs)); // -- read the number of variables. int numVars = Integer.parseInt(networkReader.readLine().trim()); varMap = new HashMap<String,Var>(); VarSet allVars = new VarSet(); for (int i = 0; i < numVars; i++) { Var var = parseVar(networkReader.readLine()); allVars.add(var); varMap.put(var.getName(), var); } assert (allVars.size() == numVars); // -- read the dependencies between variables. // ....or not... networkReader.close(); // Read CPD file. BufferedReader cpdReader = new BufferedReader(new InputStreamReader(cpdIs)); factorMap = new LinkedHashMap<VarSet, ExplicitFactor>(); String line; while ((line = cpdReader.readLine()) != null) { // Parse out the variable configuration. VarConfig config = new VarConfig(); String[] assns = whitespaceOrComma.split(line); for (int i=0; i<assns.length-1; i++) { String assn = assns[i]; String[] va = equals.split(assn); assert(va.length == 2); String varName = va[0]; String stateName = va[1]; config.put(varMap.get(varName), stateName); } // The double is the last value on the line. double value = Double.parseDouble(assns[assns.length-1]); // Factor graphs store the log value. value = FastMath.log(value); // Get the factor for this configuration, creating a new one if necessary. VarSet vars = config.getVars(); ExplicitFactor f = factorMap.get(vars); if (f == null) { f = new ExplicitFactor(vars); } // Set the value in the factor. f.setValue(config.getConfigIndex(), value); factorMap.put(vars, f); } cpdReader.close(); // Create the factor graph. FactorGraph fg = new FactorGraph(); for (ExplicitFactor f : factorMap.values()) { fg.addFactor(f); } return fg; }
java
public FactorGraph readBnAsFg(InputStream networkIs, InputStream cpdIs) throws IOException { // Read network file. BufferedReader networkReader = new BufferedReader(new InputStreamReader(networkIs)); // -- read the number of variables. int numVars = Integer.parseInt(networkReader.readLine().trim()); varMap = new HashMap<String,Var>(); VarSet allVars = new VarSet(); for (int i = 0; i < numVars; i++) { Var var = parseVar(networkReader.readLine()); allVars.add(var); varMap.put(var.getName(), var); } assert (allVars.size() == numVars); // -- read the dependencies between variables. // ....or not... networkReader.close(); // Read CPD file. BufferedReader cpdReader = new BufferedReader(new InputStreamReader(cpdIs)); factorMap = new LinkedHashMap<VarSet, ExplicitFactor>(); String line; while ((line = cpdReader.readLine()) != null) { // Parse out the variable configuration. VarConfig config = new VarConfig(); String[] assns = whitespaceOrComma.split(line); for (int i=0; i<assns.length-1; i++) { String assn = assns[i]; String[] va = equals.split(assn); assert(va.length == 2); String varName = va[0]; String stateName = va[1]; config.put(varMap.get(varName), stateName); } // The double is the last value on the line. double value = Double.parseDouble(assns[assns.length-1]); // Factor graphs store the log value. value = FastMath.log(value); // Get the factor for this configuration, creating a new one if necessary. VarSet vars = config.getVars(); ExplicitFactor f = factorMap.get(vars); if (f == null) { f = new ExplicitFactor(vars); } // Set the value in the factor. f.setValue(config.getConfigIndex(), value); factorMap.put(vars, f); } cpdReader.close(); // Create the factor graph. FactorGraph fg = new FactorGraph(); for (ExplicitFactor f : factorMap.values()) { fg.addFactor(f); } return fg; }
[ "public", "FactorGraph", "readBnAsFg", "(", "InputStream", "networkIs", ",", "InputStream", "cpdIs", ")", "throws", "IOException", "{", "// Read network file.", "BufferedReader", "networkReader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "netwo...
Reads a Bayesian Network from a network InputStream and a CPD InputStream, and returns a factor graph representation of it.
[ "Reads", "a", "Bayesian", "Network", "from", "a", "network", "InputStream", "and", "a", "CPD", "InputStream", "and", "returns", "a", "factor", "graph", "representation", "of", "it", "." ]
train
https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/gm/data/bayesnet/BayesNetReader.java#L50-L110
line/armeria
core/src/main/java/com/linecorp/armeria/common/logging/LoggingDecoratorBuilder.java
LoggingDecoratorBuilder.contentSanitizer
public T contentSanitizer(Function<Object, ?> contentSanitizer) { requireNonNull(contentSanitizer, "contentSanitizer"); requestContentSanitizer(contentSanitizer); responseContentSanitizer(contentSanitizer); return self(); }
java
public T contentSanitizer(Function<Object, ?> contentSanitizer) { requireNonNull(contentSanitizer, "contentSanitizer"); requestContentSanitizer(contentSanitizer); responseContentSanitizer(contentSanitizer); return self(); }
[ "public", "T", "contentSanitizer", "(", "Function", "<", "Object", ",", "?", ">", "contentSanitizer", ")", "{", "requireNonNull", "(", "contentSanitizer", ",", "\"contentSanitizer\"", ")", ";", "requestContentSanitizer", "(", "contentSanitizer", ")", ";", "responseC...
Sets the {@link Function} to use to sanitize request and response content before logging. It is common to have the {@link Function} that removes sensitive content, such as an GPS location query and an address, before logging. If unset, will use {@link Function#identity()}. This method is a shortcut of: <pre>{@code builder.requestContentSanitizer(contentSanitizer); builder.responseContentSanitizer(contentSanitizer); }</pre> @see #requestContentSanitizer(Function) @see #responseContentSanitizer(Function)
[ "Sets", "the", "{", "@link", "Function", "}", "to", "use", "to", "sanitize", "request", "and", "response", "content", "before", "logging", ".", "It", "is", "common", "to", "have", "the", "{", "@link", "Function", "}", "that", "removes", "sensitive", "conte...
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/common/logging/LoggingDecoratorBuilder.java#L243-L248
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/activity_status.java
activity_status.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { activity_status_responses result = (activity_status_responses) service.get_payload_formatter().string_to_resource(activity_status_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.activity_status_response_array); } activity_status[] result_activity_status = new activity_status[result.activity_status_response_array.length]; for(int i = 0; i < result.activity_status_response_array.length; i++) { result_activity_status[i] = result.activity_status_response_array[i].activity_status[0]; } return result_activity_status; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { activity_status_responses result = (activity_status_responses) service.get_payload_formatter().string_to_resource(activity_status_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.activity_status_response_array); } activity_status[] result_activity_status = new activity_status[result.activity_status_response_array.length]; for(int i = 0; i < result.activity_status_response_array.length; i++) { result_activity_status[i] = result.activity_status_response_array[i].activity_status[0]; } return result_activity_status; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "activity_status_responses", "result", "=", "(", "activity_status_responses", ")", "service", ".", "get_payloa...
<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/activity_status.java#L281-L298
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/data/WaveformFinder.java
WaveformFinder.requestWaveformDetailFrom
public WaveformDetail requestWaveformDetailFrom(final DataReference dataReference) { ensureRunning(); for (WaveformDetail cached : detailHotCache.values()) { if (cached.dataReference.equals(dataReference)) { // Found a hot cue hit, use it. return cached; } } return requestDetailInternal(dataReference, false); }
java
public WaveformDetail requestWaveformDetailFrom(final DataReference dataReference) { ensureRunning(); for (WaveformDetail cached : detailHotCache.values()) { if (cached.dataReference.equals(dataReference)) { // Found a hot cue hit, use it. return cached; } } return requestDetailInternal(dataReference, false); }
[ "public", "WaveformDetail", "requestWaveformDetailFrom", "(", "final", "DataReference", "dataReference", ")", "{", "ensureRunning", "(", ")", ";", "for", "(", "WaveformDetail", "cached", ":", "detailHotCache", ".", "values", "(", ")", ")", "{", "if", "(", "cache...
Ask the specified player for the specified waveform detail from the specified media slot, first checking if we have a cached copy. @param dataReference uniquely identifies the desired waveform detail @return the waveform detail, if it was found, or {@code null} @throws IllegalStateException if the WaveformFinder is not running
[ "Ask", "the", "specified", "player", "for", "the", "specified", "waveform", "detail", "from", "the", "specified", "media", "slot", "first", "checking", "if", "we", "have", "a", "cached", "copy", "." ]
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/WaveformFinder.java#L563-L571
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/process/PTBLexer.java
PTBLexer.getNext
private Object getNext(String txt, String originalText) { if (invertible) { String str = prevWordAfter.toString(); prevWordAfter.setLength(0); CoreLabel word = (CoreLabel) tokenFactory.makeToken(txt, yychar, yylength()); word.set(OriginalTextAnnotation.class, originalText); word.set(BeforeAnnotation.class, str); prevWord.set(AfterAnnotation.class, str); prevWord = word; return word; } else { return tokenFactory.makeToken(txt, yychar, yylength()); } }
java
private Object getNext(String txt, String originalText) { if (invertible) { String str = prevWordAfter.toString(); prevWordAfter.setLength(0); CoreLabel word = (CoreLabel) tokenFactory.makeToken(txt, yychar, yylength()); word.set(OriginalTextAnnotation.class, originalText); word.set(BeforeAnnotation.class, str); prevWord.set(AfterAnnotation.class, str); prevWord = word; return word; } else { return tokenFactory.makeToken(txt, yychar, yylength()); } }
[ "private", "Object", "getNext", "(", "String", "txt", ",", "String", "originalText", ")", "{", "if", "(", "invertible", ")", "{", "String", "str", "=", "prevWordAfter", ".", "toString", "(", ")", ";", "prevWordAfter", ".", "setLength", "(", "0", ")", ";"...
Make the next token. @param txt What the token should be @param originalText The original String that got transformed into txt
[ "Make", "the", "next", "token", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/process/PTBLexer.java#L10618-L10631
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java
VirtualNetworkGatewaysInner.beginGeneratevpnclientpackage
public String beginGeneratevpnclientpackage(String resourceGroupName, String virtualNetworkGatewayName, VpnClientParameters parameters) { return beginGeneratevpnclientpackageWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, parameters).toBlocking().single().body(); }
java
public String beginGeneratevpnclientpackage(String resourceGroupName, String virtualNetworkGatewayName, VpnClientParameters parameters) { return beginGeneratevpnclientpackageWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, parameters).toBlocking().single().body(); }
[ "public", "String", "beginGeneratevpnclientpackage", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayName", ",", "VpnClientParameters", "parameters", ")", "{", "return", "beginGeneratevpnclientpackageWithServiceResponseAsync", "(", "resourceGroupName", ",...
Generates VPN client package for P2S client of the virtual network gateway in the specified resource group. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param parameters Parameters supplied to the generate virtual network gateway VPN client package operation. @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 String object if successful.
[ "Generates", "VPN", "client", "package", "for", "P2S", "client", "of", "the", "virtual", "network", "gateway", "in", "the", "specified", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L1540-L1542
EdwardRaff/JSAT
JSAT/src/jsat/math/Complex.java
Complex.cMul
public static void cMul(double a, double b, double c, double d, double[] results) { results[0] = a*c-b*d; results[1] = b*c+a*d; }
java
public static void cMul(double a, double b, double c, double d, double[] results) { results[0] = a*c-b*d; results[1] = b*c+a*d; }
[ "public", "static", "void", "cMul", "(", "double", "a", ",", "double", "b", ",", "double", "c", ",", "double", "d", ",", "double", "[", "]", "results", ")", "{", "results", "[", "0", "]", "=", "a", "*", "c", "-", "b", "*", "d", ";", "results", ...
Performs a complex multiplication @param a the real part of the first number @param b the imaginary part of the first number @param c the real part of the second number @param d the imaginary part of the second number @param results an array to store the real and imaginary results in. First index is the real, 2nd is the imaginary.
[ "Performs", "a", "complex", "multiplication" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/math/Complex.java#L145-L149
feroult/yawp
yawp-core/src/main/java/io/yawp/commons/utils/ResourceFinder.java
ResourceFinder.mapAvailableStrings
public Map<String, String> mapAvailableStrings(String uri) throws IOException { resourcesNotLoaded.clear(); Map<String, String> strings = new HashMap<>(); Map<String, URL> resourcesMap = getResourcesMap(uri); for (Iterator iterator = resourcesMap.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); URL url = (URL) entry.getValue(); try { String value = readContents(url); strings.put(name, value); } catch (IOException notAvailable) { resourcesNotLoaded.add(url.toExternalForm()); } } return strings; }
java
public Map<String, String> mapAvailableStrings(String uri) throws IOException { resourcesNotLoaded.clear(); Map<String, String> strings = new HashMap<>(); Map<String, URL> resourcesMap = getResourcesMap(uri); for (Iterator iterator = resourcesMap.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); URL url = (URL) entry.getValue(); try { String value = readContents(url); strings.put(name, value); } catch (IOException notAvailable) { resourcesNotLoaded.add(url.toExternalForm()); } } return strings; }
[ "public", "Map", "<", "String", ",", "String", ">", "mapAvailableStrings", "(", "String", "uri", ")", "throws", "IOException", "{", "resourcesNotLoaded", ".", "clear", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "strings", "=", "new", "HashMap...
Reads the contents of all non-directory URLs immediately under the specified location and returns them in a map keyed by the file name. <p/> Individual URLs that cannot be read are skipped and added to the list of 'resourcesNotLoaded' <p/> Example classpath: <p/> META-INF/serializables/one META-INF/serializables/two # not readable META-INF/serializables/three META-INF/serializables/four/foo.txt <p/> ResourceFinder finder = new ResourceFinder("META-INF/"); Map map = finder.mapAvailableStrings("serializables"); map.contains("one"); // true map.contains("two"); // false map.contains("three"); // true map.contains("four"); // false @param uri @return a list of the content of each resource URL found @throws IOException if classLoader.getResources throws an exception
[ "Reads", "the", "contents", "of", "all", "non", "-", "directory", "URLs", "immediately", "under", "the", "specified", "location", "and", "returns", "them", "in", "a", "map", "keyed", "by", "the", "file", "name", ".", "<p", "/", ">", "Individual", "URLs", ...
train
https://github.com/feroult/yawp/blob/b90deb905edd3fdb3009a5525e310cd17ead7f3d/yawp-core/src/main/java/io/yawp/commons/utils/ResourceFinder.java#L273-L289
gallandarakhneorg/afc
core/vmutils/src/main/java/org/arakhne/afc/vmutil/VMCommandLine.java
VMCommandLine.saveVMParameters
@Inline(value = "VMCommandLine.saveVMParameters((($1) != null) ? ($1).getCanonicalName() : null, ($2))", imported = {VMCommandLine.class}, statementExpression = true) public static void saveVMParameters(Class<?> classToLaunch, String... parameters) { saveVMParameters( (classToLaunch != null) ? classToLaunch.getCanonicalName() : null, parameters); }
java
@Inline(value = "VMCommandLine.saveVMParameters((($1) != null) ? ($1).getCanonicalName() : null, ($2))", imported = {VMCommandLine.class}, statementExpression = true) public static void saveVMParameters(Class<?> classToLaunch, String... parameters) { saveVMParameters( (classToLaunch != null) ? classToLaunch.getCanonicalName() : null, parameters); }
[ "@", "Inline", "(", "value", "=", "\"VMCommandLine.saveVMParameters((($1) != null) ? ($1).getCanonicalName() : null, ($2))\"", ",", "imported", "=", "{", "VMCommandLine", ".", "class", "}", ",", "statementExpression", "=", "true", ")", "public", "static", "void", "saveVMP...
Save parameters that permit to relaunch a VM with {@link #relaunchVM()}. @param classToLaunch is the class which contains a <code>main</code>. @param parameters is the parameters to pass to the <code>main</code>.
[ "Save", "parameters", "that", "permit", "to", "relaunch", "a", "VM", "with", "{", "@link", "#relaunchVM", "()", "}", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/vmutils/src/main/java/org/arakhne/afc/vmutil/VMCommandLine.java#L309-L316
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/Matchers.java
Matchers.hasArgumentWithValue
public static Matcher<AnnotationTree> hasArgumentWithValue( String argumentName, Matcher<ExpressionTree> valueMatcher) { return new AnnotationHasArgumentWithValue(argumentName, valueMatcher); }
java
public static Matcher<AnnotationTree> hasArgumentWithValue( String argumentName, Matcher<ExpressionTree> valueMatcher) { return new AnnotationHasArgumentWithValue(argumentName, valueMatcher); }
[ "public", "static", "Matcher", "<", "AnnotationTree", ">", "hasArgumentWithValue", "(", "String", "argumentName", ",", "Matcher", "<", "ExpressionTree", ">", "valueMatcher", ")", "{", "return", "new", "AnnotationHasArgumentWithValue", "(", "argumentName", ",", "valueM...
Matches an Annotation AST node if the argument to the annotation with the given name has a value which matches the given matcher. For example, {@code hasArgumentWithValue("value", stringLiteral("one"))} matches {@code @Thing("one")} or {@code @Thing({"one", "two"})} or {@code @Thing(value = "one")}
[ "Matches", "an", "Annotation", "AST", "node", "if", "the", "argument", "to", "the", "annotation", "with", "the", "given", "name", "has", "a", "value", "which", "matches", "the", "given", "matcher", ".", "For", "example", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L717-L720
Ardesco/selenium-standalone-server-plugin
src/main/java/com/lazerycode/selenium/download/DownloadHandler.java
DownloadHandler.downloadFile
protected File downloadFile(DriverDetails driverDetails, boolean shouldWeCheckFileHash) throws MojoExecutionException, IOException, URISyntaxException { URL remoteFileLocation = driverDetails.fileLocation; final String filename = FilenameUtils.getName(remoteFileLocation.getFile()); for (int retryAttempts = 1; retryAttempts <= this.fileDownloadRetryAttempts; retryAttempts++) { File downloadedFile = fileDownloader.attemptToDownload(remoteFileLocation); if (null != downloadedFile) { if (!shouldWeCheckFileHash || checkFileHash(downloadedFile, driverDetails.hash, driverDetails.hashType)) { LOG.info("Archive file '" + downloadedFile.getName() + "' is valid : true"); return downloadedFile; } else { LOG.info("Archive file '" + downloadedFile.getName() + "' is valid : false"); } } LOG.info("Problem downloading '" + filename + "'... "); if (retryAttempts < this.fileDownloadRetryAttempts) { LOG.info("Retry attempt " + (retryAttempts) + " for '" + filename + "'"); } } throw new MojoExecutionException("Unable to successfully download '" + filename + "'!"); }
java
protected File downloadFile(DriverDetails driverDetails, boolean shouldWeCheckFileHash) throws MojoExecutionException, IOException, URISyntaxException { URL remoteFileLocation = driverDetails.fileLocation; final String filename = FilenameUtils.getName(remoteFileLocation.getFile()); for (int retryAttempts = 1; retryAttempts <= this.fileDownloadRetryAttempts; retryAttempts++) { File downloadedFile = fileDownloader.attemptToDownload(remoteFileLocation); if (null != downloadedFile) { if (!shouldWeCheckFileHash || checkFileHash(downloadedFile, driverDetails.hash, driverDetails.hashType)) { LOG.info("Archive file '" + downloadedFile.getName() + "' is valid : true"); return downloadedFile; } else { LOG.info("Archive file '" + downloadedFile.getName() + "' is valid : false"); } } LOG.info("Problem downloading '" + filename + "'... "); if (retryAttempts < this.fileDownloadRetryAttempts) { LOG.info("Retry attempt " + (retryAttempts) + " for '" + filename + "'"); } } throw new MojoExecutionException("Unable to successfully download '" + filename + "'!"); }
[ "protected", "File", "downloadFile", "(", "DriverDetails", "driverDetails", ",", "boolean", "shouldWeCheckFileHash", ")", "throws", "MojoExecutionException", ",", "IOException", ",", "URISyntaxException", "{", "URL", "remoteFileLocation", "=", "driverDetails", ".", "fileL...
Perform the file download @param driverDetails Driver details extracted from Repositorymap.xml @param shouldWeCheckFileHash true if file hash should be checked @return File @throws MojoExecutionException Unable to download file @throws IOException Error writing to file system @throws URISyntaxException Invalid URI
[ "Perform", "the", "file", "download" ]
train
https://github.com/Ardesco/selenium-standalone-server-plugin/blob/e0ecfad426c1a28115cab60def84731d7a4d7e6f/src/main/java/com/lazerycode/selenium/download/DownloadHandler.java#L61-L83
dlemmermann/CalendarFX
CalendarFXRecurrence/src/main/java/com/google/ical/util/DTBuilder.java
DTBuilder.toDateTime
public DateTimeValue toDateTime() { normalize(); return new DateTimeValueImpl(year, month, day, hour, minute, second); }
java
public DateTimeValue toDateTime() { normalize(); return new DateTimeValueImpl(year, month, day, hour, minute, second); }
[ "public", "DateTimeValue", "toDateTime", "(", ")", "{", "normalize", "(", ")", ";", "return", "new", "DateTimeValueImpl", "(", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", ")", ";", "}" ]
produces a normalized date time, using zero for the time fields if none were provided. @return not null
[ "produces", "a", "normalized", "date", "time", "using", "zero", "for", "the", "time", "fields", "if", "none", "were", "provided", "." ]
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXRecurrence/src/main/java/com/google/ical/util/DTBuilder.java#L83-L86
lisicnu/droidUtil
src/main/java/com/github/lisicnu/libDroid/helper/BitmapCacheLoader.java
BitmapCacheLoader.loadFile
public Bitmap loadFile(String fileName, String tmpDirectory, ImageCallBack imageCallBack, boolean canRemove) { return loadFile(fileName, tmpDirectory, imageCallBack, canRemove, -1, -1); }
java
public Bitmap loadFile(String fileName, String tmpDirectory, ImageCallBack imageCallBack, boolean canRemove) { return loadFile(fileName, tmpDirectory, imageCallBack, canRemove, -1, -1); }
[ "public", "Bitmap", "loadFile", "(", "String", "fileName", ",", "String", "tmpDirectory", ",", "ImageCallBack", "imageCallBack", ",", "boolean", "canRemove", ")", "{", "return", "loadFile", "(", "fileName", ",", "tmpDirectory", ",", "imageCallBack", ",", "canRemov...
Load Steps:<br/> 1. load from caches. <br/> 2. if file not exist in caches, then load it from local storage.<br/> 3. if local storage not exist, then load it from temporary directory.<br/> 4. if file not exist in temporary directory. then download it.<br/> 5. after download, then callback will be added.<br/> @param fileName file name , local or URL 可以是带路径名, 也可以不带路径名. 当带路径名时, 先去查找指定目录.. 然后再找傳入的臨時目錄. @param tmpDirectory 临时目录, 下载之后的保存目录. 默认路径: mnt/sdcard/cache @param imageCallBack 下载完成时的毁掉 @param canRemove 是否可以移除. 当等待的个数超过最大下载数目时, 当前条目是否可以清除. @return the bitmap loaded. if from network, this will return null, return the result from callback
[ "Load", "Steps", ":", "<br", "/", ">", "1", ".", "load", "from", "caches", ".", "<br", "/", ">", "2", ".", "if", "file", "not", "exist", "in", "caches", "then", "load", "it", "from", "local", "storage", ".", "<br", "/", ">", "3", ".", "if", "lo...
train
https://github.com/lisicnu/droidUtil/blob/e4d6cf3e3f60e5efb5a75672607ded94d1725519/src/main/java/com/github/lisicnu/libDroid/helper/BitmapCacheLoader.java#L162-L166
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/publickey/PublicKeySubsystem.java
PublicKeySubsystem.associateCommand
public void associateCommand(SshPublicKey key, String command) throws SshException, PublicKeySubsystemException { try { Packet msg = createPacket(); msg.writeString("command"); msg.writeString(key.getAlgorithm()); msg.writeBinaryString(key.getEncoded()); msg.writeString(command); sendMessage(msg); readStatusResponse(); } catch (IOException ex) { throw new SshException(ex); } }
java
public void associateCommand(SshPublicKey key, String command) throws SshException, PublicKeySubsystemException { try { Packet msg = createPacket(); msg.writeString("command"); msg.writeString(key.getAlgorithm()); msg.writeBinaryString(key.getEncoded()); msg.writeString(command); sendMessage(msg); readStatusResponse(); } catch (IOException ex) { throw new SshException(ex); } }
[ "public", "void", "associateCommand", "(", "SshPublicKey", "key", ",", "String", "command", ")", "throws", "SshException", ",", "PublicKeySubsystemException", "{", "try", "{", "Packet", "msg", "=", "createPacket", "(", ")", ";", "msg", ".", "writeString", "(", ...
Associate a command with an accepted public key. The request will fail if the public key is not currently in the users acceptable list. Also some server implementations may choose not to support this feature. @param key @param command @throws SshException @throws PublicKeyStatusException
[ "Associate", "a", "command", "with", "an", "accepted", "public", "key", ".", "The", "request", "will", "fail", "if", "the", "public", "key", "is", "not", "currently", "in", "the", "users", "acceptable", "list", ".", "Also", "some", "server", "implementations...
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/publickey/PublicKeySubsystem.java#L216-L235
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/util/CellFinder.java
CellFinder.query
public static CellFinder query(final Sheet sheet, final String label, final Configuration config) { return new CellFinder(sheet, label, config); }
java
public static CellFinder query(final Sheet sheet, final String label, final Configuration config) { return new CellFinder(sheet, label, config); }
[ "public", "static", "CellFinder", "query", "(", "final", "Sheet", "sheet", ",", "final", "String", "label", ",", "final", "Configuration", "config", ")", "{", "return", "new", "CellFinder", "(", "sheet", ",", "label", ",", "config", ")", ";", "}" ]
検索する際の条件を組み立てる @param sheet 検索対象のシート @param label 検索するセルのラベル @param config システム設定。 設定値 {@link Configuration#isNormalizeLabelText()}、{@link Configuration#isRegexLabelText()}の値によって、 検索する際にラベルを正規化、または正規表現により一致するかで判定を行う。
[ "検索する際の条件を組み立てる" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/util/CellFinder.java#L63-L65
drinkjava2/jBeanBox
jbeanbox/src/main/java/com/github/drinkjava2/jbeanbox/BeanBox.java
BeanBox.addBeanAop
public synchronized BeanBox addBeanAop(Object aop, String methodNameRegex) { checkOrCreateMethodAopRules(); aopRules.add(new Object[] { BeanBoxUtils.checkAOP(aop), methodNameRegex }); return this; }
java
public synchronized BeanBox addBeanAop(Object aop, String methodNameRegex) { checkOrCreateMethodAopRules(); aopRules.add(new Object[] { BeanBoxUtils.checkAOP(aop), methodNameRegex }); return this; }
[ "public", "synchronized", "BeanBox", "addBeanAop", "(", "Object", "aop", ",", "String", "methodNameRegex", ")", "{", "checkOrCreateMethodAopRules", "(", ")", ";", "aopRules", ".", "add", "(", "new", "Object", "[", "]", "{", "BeanBoxUtils", ".", "checkAOP", "("...
Add an AOP to Bean @param aop An AOP alliance interceptor class or instance @param methodNameRegex @return
[ "Add", "an", "AOP", "to", "Bean" ]
train
https://github.com/drinkjava2/jBeanBox/blob/01c216599ffa2e5f2d9c01df2adaad0f45567c04/jbeanbox/src/main/java/com/github/drinkjava2/jbeanbox/BeanBox.java#L267-L271
walkmod/walkmod-core
src/main/java/org/walkmod/WalkModFacade.java
WalkModFacade.removeChains
public void removeChains(List<String> chains, boolean recursive) throws Exception { long startTime = System.currentTimeMillis(); Exception exception = null; if (cfg.exists()) { userDir = new File(System.getProperty("user.dir")).getAbsolutePath(); System.setProperty("user.dir", options.getExecutionDirectory().getAbsolutePath()); try { ConfigurationManager manager = new ConfigurationManager(cfg, false); manager.getProjectConfigurationProvider().removeChains(chains, recursive); } catch (Exception e) { exception = e; } finally { System.setProperty("user.dir", userDir); updateMsg(startTime, exception); } } }
java
public void removeChains(List<String> chains, boolean recursive) throws Exception { long startTime = System.currentTimeMillis(); Exception exception = null; if (cfg.exists()) { userDir = new File(System.getProperty("user.dir")).getAbsolutePath(); System.setProperty("user.dir", options.getExecutionDirectory().getAbsolutePath()); try { ConfigurationManager manager = new ConfigurationManager(cfg, false); manager.getProjectConfigurationProvider().removeChains(chains, recursive); } catch (Exception e) { exception = e; } finally { System.setProperty("user.dir", userDir); updateMsg(startTime, exception); } } }
[ "public", "void", "removeChains", "(", "List", "<", "String", ">", "chains", ",", "boolean", "recursive", ")", "throws", "Exception", "{", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "Exception", "exception", "=", "null", ";"...
Removes the chains from the Walkmod config file. @param chains Chain names to remove @param recursive If it necessary to remove the chains from all the submodules. @throws Exception If the walkmod configuration file can't be read.
[ "Removes", "the", "chains", "from", "the", "Walkmod", "config", "file", "." ]
train
https://github.com/walkmod/walkmod-core/blob/fa79b836894fa00ca4b3e2bd26326a44b778f46f/src/main/java/org/walkmod/WalkModFacade.java#L956-L974
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/journal/helpers/ParameterHelper.java
ParameterHelper.parseParametersForSizeLimit
public static long parseParametersForSizeLimit(Map<String, String> parameters) throws JournalException { String sizeString = getOptionalStringParameter(parameters, PARAMETER_JOURNAL_FILE_SIZE_LIMIT, DEFAULT_SIZE_LIMIT); Pattern p = Pattern.compile("([0-9]+)([KMG]?)"); Matcher m = p.matcher(sizeString); if (!m.matches()) { throw new JournalException("Parameter '" + PARAMETER_JOURNAL_FILE_SIZE_LIMIT + "' must be an integer number of bytes, " + "optionally followed by 'K', 'M', or 'G', " + "or a 0 to indicate no size limit"); } long size = Long.parseLong(m.group(1)); String factor = m.group(2); if ("K".equals(factor)) { size *= 1024; } else if ("M".equals(factor)) { size *= 1024 * 1024; } else if ("G".equals(factor)) { size *= 1024 * 1024 * 1024; } return size; }
java
public static long parseParametersForSizeLimit(Map<String, String> parameters) throws JournalException { String sizeString = getOptionalStringParameter(parameters, PARAMETER_JOURNAL_FILE_SIZE_LIMIT, DEFAULT_SIZE_LIMIT); Pattern p = Pattern.compile("([0-9]+)([KMG]?)"); Matcher m = p.matcher(sizeString); if (!m.matches()) { throw new JournalException("Parameter '" + PARAMETER_JOURNAL_FILE_SIZE_LIMIT + "' must be an integer number of bytes, " + "optionally followed by 'K', 'M', or 'G', " + "or a 0 to indicate no size limit"); } long size = Long.parseLong(m.group(1)); String factor = m.group(2); if ("K".equals(factor)) { size *= 1024; } else if ("M".equals(factor)) { size *= 1024 * 1024; } else if ("G".equals(factor)) { size *= 1024 * 1024 * 1024; } return size; }
[ "public", "static", "long", "parseParametersForSizeLimit", "(", "Map", "<", "String", ",", "String", ">", "parameters", ")", "throws", "JournalException", "{", "String", "sizeString", "=", "getOptionalStringParameter", "(", "parameters", ",", "PARAMETER_JOURNAL_FILE_SIZ...
Get the size limit parameter (or let it default), and convert it to bytes.
[ "Get", "the", "size", "limit", "parameter", "(", "or", "let", "it", "default", ")", "and", "convert", "it", "to", "bytes", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/helpers/ParameterHelper.java#L129-L154
micronaut-projects/micronaut-core
core/src/main/java/io/micronaut/core/reflect/GenericTypeUtils.java
GenericTypeUtils.resolveInterfaceTypeArgument
public static Optional<Class> resolveInterfaceTypeArgument(Class type, Class interfaceType) { Type[] genericInterfaces = type.getGenericInterfaces(); for (Type genericInterface : genericInterfaces) { if (genericInterface instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) genericInterface; if (pt.getRawType() == interfaceType) { return resolveSingleTypeArgument(genericInterface); } } } Class superClass = type.getSuperclass(); if (superClass != null && superClass != Object.class) { return resolveInterfaceTypeArgument(superClass, interfaceType); } return Optional.empty(); }
java
public static Optional<Class> resolveInterfaceTypeArgument(Class type, Class interfaceType) { Type[] genericInterfaces = type.getGenericInterfaces(); for (Type genericInterface : genericInterfaces) { if (genericInterface instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) genericInterface; if (pt.getRawType() == interfaceType) { return resolveSingleTypeArgument(genericInterface); } } } Class superClass = type.getSuperclass(); if (superClass != null && superClass != Object.class) { return resolveInterfaceTypeArgument(superClass, interfaceType); } return Optional.empty(); }
[ "public", "static", "Optional", "<", "Class", ">", "resolveInterfaceTypeArgument", "(", "Class", "type", ",", "Class", "interfaceType", ")", "{", "Type", "[", "]", "genericInterfaces", "=", "type", ".", "getGenericInterfaces", "(", ")", ";", "for", "(", "Type"...
Resolves a single type argument from the given interface of the given class. Also searches superclasses. @param type The type to resolve from @param interfaceType The interface to resolve for @return The class or null
[ "Resolves", "a", "single", "type", "argument", "from", "the", "given", "interface", "of", "the", "given", "class", ".", "Also", "searches", "superclasses", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/core/src/main/java/io/micronaut/core/reflect/GenericTypeUtils.java#L147-L162
alkacon/opencms-core
src/org/opencms/workplace/CmsWorkplace.java
CmsWorkplace.buttonBarStartTab
public String buttonBarStartTab(int leftPixel, int rightPixel) { StringBuffer result = new StringBuffer(512); result.append(buttonBarLineSpacer(leftPixel)); result.append("<td><span class=\"starttab\"><span style=\"width:1px; height:1px\"></span></span></td>\n"); result.append(buttonBarLineSpacer(rightPixel)); return result.toString(); }
java
public String buttonBarStartTab(int leftPixel, int rightPixel) { StringBuffer result = new StringBuffer(512); result.append(buttonBarLineSpacer(leftPixel)); result.append("<td><span class=\"starttab\"><span style=\"width:1px; height:1px\"></span></span></td>\n"); result.append(buttonBarLineSpacer(rightPixel)); return result.toString(); }
[ "public", "String", "buttonBarStartTab", "(", "int", "leftPixel", ",", "int", "rightPixel", ")", "{", "StringBuffer", "result", "=", "new", "StringBuffer", "(", "512", ")", ";", "result", ".", "append", "(", "buttonBarLineSpacer", "(", "leftPixel", ")", ")", ...
Generates a button bar starter tab.<p> @param leftPixel the amount of pixel left to the starter @param rightPixel the amount of pixel right to the starter @return a button bar starter tab
[ "Generates", "a", "button", "bar", "starter", "tab", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsWorkplace.java#L1418-L1425
DV8FromTheWorld/JDA
src/main/java/net/dv8tion/jda/core/requests/restaction/GuildAction.java
GuildAction.newChannel
@CheckReturnValue public ChannelData newChannel(ChannelType type, String name) { ChannelData data = new ChannelData(type, name); addChannel(data); return data; }
java
@CheckReturnValue public ChannelData newChannel(ChannelType type, String name) { ChannelData data = new ChannelData(type, name); addChannel(data); return data; }
[ "@", "CheckReturnValue", "public", "ChannelData", "newChannel", "(", "ChannelType", "type", ",", "String", "name", ")", "{", "ChannelData", "data", "=", "new", "ChannelData", "(", "type", ",", "name", ")", ";", "addChannel", "(", "data", ")", ";", "return", ...
Creates a new {@link net.dv8tion.jda.core.requests.restaction.GuildAction.ChannelData ChannelData} instance and adds it to this GuildAction. @param type The {@link net.dv8tion.jda.core.entities.ChannelType ChannelType} of the resulting Channel <br>This may be of type {@link net.dv8tion.jda.core.entities.ChannelType#TEXT TEXT} or {@link net.dv8tion.jda.core.entities.ChannelType#VOICE VOICE}! @param name The name of the channel. This must be alphanumeric with underscores for type TEXT @throws java.lang.IllegalArgumentException <ul> <li>If provided with an invalid ChannelType</li> <li>If the provided name is {@code null} or blank</li> <li>If the provided name is not between 2-100 characters long</li> <li>If the type is TEXT and the provided name is not alphanumeric with underscores</li> </ul> @return The new ChannelData instance
[ "Creates", "a", "new", "{", "@link", "net", ".", "dv8tion", ".", "jda", ".", "core", ".", "requests", ".", "restaction", ".", "GuildAction", ".", "ChannelData", "ChannelData", "}", "instance", "and", "adds", "it", "to", "this", "GuildAction", "." ]
train
https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/requests/restaction/GuildAction.java#L277-L283
jferard/fastods
fastods/src/main/java/com/github/jferard/fastods/style/TableCellStyleBuilder.java
TableCellStyleBuilder.borderAll
public TableCellStyleBuilder borderAll(final Length size, final Color borderColor, final BorderAttribute.Style style) { final BorderAttribute bs = new BorderAttribute(size, borderColor, style); this.bordersBuilder.all(bs); return this; }
java
public TableCellStyleBuilder borderAll(final Length size, final Color borderColor, final BorderAttribute.Style style) { final BorderAttribute bs = new BorderAttribute(size, borderColor, style); this.bordersBuilder.all(bs); return this; }
[ "public", "TableCellStyleBuilder", "borderAll", "(", "final", "Length", "size", ",", "final", "Color", "borderColor", ",", "final", "BorderAttribute", ".", "Style", "style", ")", "{", "final", "BorderAttribute", "bs", "=", "new", "BorderAttribute", "(", "size", ...
Add a border style for all the borders of this cell. @param size the size of the line @param borderColor the color to be used in format #rrggbb e.g. '#ff0000' for a red border @param style the style of the border line, either BorderAttribute.BORDER_SOLID or BorderAttribute.BORDER_DOUBLE @return this for fluent style
[ "Add", "a", "border", "style", "for", "all", "the", "borders", "of", "this", "cell", "." ]
train
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/style/TableCellStyleBuilder.java#L98-L103
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/collision/TileCollidableModel.java
TileCollidableModel.onCollided
private void onCollided(CollisionResult result, CollisionCategory category) { for (final TileCollidableListener listener : listeners) { listener.notifyTileCollided(result, category); } }
java
private void onCollided(CollisionResult result, CollisionCategory category) { for (final TileCollidableListener listener : listeners) { listener.notifyTileCollided(result, category); } }
[ "private", "void", "onCollided", "(", "CollisionResult", "result", ",", "CollisionCategory", "category", ")", "{", "for", "(", "final", "TileCollidableListener", "listener", ":", "listeners", ")", "{", "listener", ".", "notifyTileCollided", "(", "result", ",", "ca...
Called when a collision occurred on a specified axis. @param result The result reference. @param category The collision category reference.
[ "Called", "when", "a", "collision", "occurred", "on", "a", "specified", "axis", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/collision/TileCollidableModel.java#L114-L120
bitcoinj/bitcoinj
tools/src/main/java/org/bitcoinj/tools/WalletTool.java
WalletTool.parseLockTimeStr
private static long parseLockTimeStr(String lockTimeStr) throws ParseException { if (lockTimeStr.indexOf("/") != -1) { SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd", Locale.US); Date date = format.parse(lockTimeStr); return date.getTime() / 1000; } return Long.parseLong(lockTimeStr); }
java
private static long parseLockTimeStr(String lockTimeStr) throws ParseException { if (lockTimeStr.indexOf("/") != -1) { SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd", Locale.US); Date date = format.parse(lockTimeStr); return date.getTime() / 1000; } return Long.parseLong(lockTimeStr); }
[ "private", "static", "long", "parseLockTimeStr", "(", "String", "lockTimeStr", ")", "throws", "ParseException", "{", "if", "(", "lockTimeStr", ".", "indexOf", "(", "\"/\"", ")", "!=", "-", "1", ")", "{", "SimpleDateFormat", "format", "=", "new", "SimpleDateFor...
Parses the string either as a whole number of blocks, or if it contains slashes as a YYYY/MM/DD format date and returns the lock time in wire format.
[ "Parses", "the", "string", "either", "as", "a", "whole", "number", "of", "blocks", "or", "if", "it", "contains", "slashes", "as", "a", "YYYY", "/", "MM", "/", "DD", "format", "date", "and", "returns", "the", "lock", "time", "in", "wire", "format", "." ...
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/tools/src/main/java/org/bitcoinj/tools/WalletTool.java#L1064-L1071
powermock/powermock
powermock-reflect/src/main/java/org/powermock/reflect/Whitebox.java
Whitebox.setInternalState
public static void setInternalState(Object object, String fieldName, Object value, Class<?> where) { WhiteboxImpl.setInternalState(object, fieldName, value, where); }
java
public static void setInternalState(Object object, String fieldName, Object value, Class<?> where) { WhiteboxImpl.setInternalState(object, fieldName, value, where); }
[ "public", "static", "void", "setInternalState", "(", "Object", "object", ",", "String", "fieldName", ",", "Object", "value", ",", "Class", "<", "?", ">", "where", ")", "{", "WhiteboxImpl", ".", "setInternalState", "(", "object", ",", "fieldName", ",", "value...
Set the value of a field using reflection. Use this method when you need to specify in which class the field is declared. This might be useful when you have mocked the instance you are trying to modify. @param object the object to modify @param fieldName the name of the field @param value the new value of the field @param where the class in the hierarchy where the field is defined
[ "Set", "the", "value", "of", "a", "field", "using", "reflection", ".", "Use", "this", "method", "when", "you", "need", "to", "specify", "in", "which", "class", "the", "field", "is", "declared", ".", "This", "might", "be", "useful", "when", "you", "have",...
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/Whitebox.java#L240-L242
sebastiangraf/jSCSI
bundles/target/src/main/java/org/jscsi/target/settings/SettingsNegotiator.java
SettingsNegotiator.getEntry
static final Entry getEntry (final String key, final Collection<Entry> entries) { for (Entry e : entries) if (e.matchKey(key)) return e; return null; }
java
static final Entry getEntry (final String key, final Collection<Entry> entries) { for (Entry e : entries) if (e.matchKey(key)) return e; return null; }
[ "static", "final", "Entry", "getEntry", "(", "final", "String", "key", ",", "final", "Collection", "<", "Entry", ">", "entries", ")", "{", "for", "(", "Entry", "e", ":", "entries", ")", "if", "(", "e", ".", "matchKey", "(", "key", ")", ")", "return",...
Returns the first {@link Entry} in the specified {@link Collection} for which {@link Entry#matchKey(String)} returns <code>true</code>. @param key the key String identifying the {@link Entry} @param entries a {@link Collection} of {@link Entry} objects. @return a matching {@link Entry} or null, if no such {@link Entry} exists
[ "Returns", "the", "first", "{", "@link", "Entry", "}", "in", "the", "specified", "{", "@link", "Collection", "}", "for", "which", "{", "@link", "Entry#matchKey", "(", "String", ")", "}", "returns", "<code", ">", "true<", "/", "code", ">", "." ]
train
https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/target/src/main/java/org/jscsi/target/settings/SettingsNegotiator.java#L43-L47
jbundle/jbundle
thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java
BaseApplet.popBrowserHistory
public void popBrowserHistory(int quanityToPop, boolean bCommandHandledByJava, String browserTitle) { if (this.getBrowserManager() != null) this.getBrowserManager().popBrowserHistory(quanityToPop, bCommandHandledByJava, this.getStatusText(Constants.INFORMATION)); // Let browser know about the new screen }
java
public void popBrowserHistory(int quanityToPop, boolean bCommandHandledByJava, String browserTitle) { if (this.getBrowserManager() != null) this.getBrowserManager().popBrowserHistory(quanityToPop, bCommandHandledByJava, this.getStatusText(Constants.INFORMATION)); // Let browser know about the new screen }
[ "public", "void", "popBrowserHistory", "(", "int", "quanityToPop", ",", "boolean", "bCommandHandledByJava", ",", "String", "browserTitle", ")", "{", "if", "(", "this", ".", "getBrowserManager", "(", ")", "!=", "null", ")", "this", ".", "getBrowserManager", "(", ...
Pop commands off the browser stack. @param quanityToPop The number of commands to pop off the stack @param bCommandHandledByJava If I say false, the browser will do a 'back', otherwise, it just pops to top command(s)
[ "Pop", "commands", "off", "the", "browser", "stack", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java#L1279-L1283
RogerParkinson/madura-objects-parent
madura-rules/src/main/java/nz/co/senanque/rulesparser/ParsePackage.java
ParsePackage.processRule
private AbstractRule processRule(RulesTextProvider textProvider) { log.debug("processRule"); int start = textProvider.getPos(); Rule rule = new Rule(); LoadCommonRuleData(rule,textProvider); textProvider.addTOCElement(null, rule.getDescription(), start, textProvider.getPos(), TYPE_RULE); exactOrError("{",textProvider); if (!exact("if",textProvider)) throw new ParserException("expected 'if' in a rule: ",textProvider); // Condition Expression condition = processCondition(textProvider); rule.addCondition(condition); exactOrError("{",textProvider); while (!exact("}",textProvider)) { Expression action = processAction(textProvider); exact(";",textProvider); rule.addAction(action); } exact("}",textProvider); return rule; }
java
private AbstractRule processRule(RulesTextProvider textProvider) { log.debug("processRule"); int start = textProvider.getPos(); Rule rule = new Rule(); LoadCommonRuleData(rule,textProvider); textProvider.addTOCElement(null, rule.getDescription(), start, textProvider.getPos(), TYPE_RULE); exactOrError("{",textProvider); if (!exact("if",textProvider)) throw new ParserException("expected 'if' in a rule: ",textProvider); // Condition Expression condition = processCondition(textProvider); rule.addCondition(condition); exactOrError("{",textProvider); while (!exact("}",textProvider)) { Expression action = processAction(textProvider); exact(";",textProvider); rule.addAction(action); } exact("}",textProvider); return rule; }
[ "private", "AbstractRule", "processRule", "(", "RulesTextProvider", "textProvider", ")", "{", "log", ".", "debug", "(", "\"processRule\"", ")", ";", "int", "start", "=", "textProvider", ".", "getPos", "(", ")", ";", "Rule", "rule", "=", "new", "Rule", "(", ...
Method processRule. Parse the rule. Rules have an if/then structure with conditions and actions @return Rule @throws ParserException
[ "Method", "processRule", ".", "Parse", "the", "rule", ".", "Rules", "have", "an", "if", "/", "then", "structure", "with", "conditions", "and", "actions" ]
train
https://github.com/RogerParkinson/madura-objects-parent/blob/9b5385dd0437611f0ce8506f63646e018d06fb8e/madura-rules/src/main/java/nz/co/senanque/rulesparser/ParsePackage.java#L242-L266
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/ClusterHeartbeatManager.java
ClusterHeartbeatManager.sendHeartbeat
private void sendHeartbeat(Member target) { if (target == null) { return; } try { MembersViewMetadata membersViewMetadata = clusterService.getMembershipManager().createLocalMembersViewMetadata(); Operation op = new HeartbeatOp(membersViewMetadata, target.getUuid(), clusterClock.getClusterTime()); op.setCallerUuid(clusterService.getThisUuid()); node.nodeEngine.getOperationService().send(op, target.getAddress()); } catch (Exception e) { if (logger.isFineEnabled()) { logger.fine(format("Error while sending heartbeat -> %s[%s]", e.getClass().getName(), e.getMessage())); } } }
java
private void sendHeartbeat(Member target) { if (target == null) { return; } try { MembersViewMetadata membersViewMetadata = clusterService.getMembershipManager().createLocalMembersViewMetadata(); Operation op = new HeartbeatOp(membersViewMetadata, target.getUuid(), clusterClock.getClusterTime()); op.setCallerUuid(clusterService.getThisUuid()); node.nodeEngine.getOperationService().send(op, target.getAddress()); } catch (Exception e) { if (logger.isFineEnabled()) { logger.fine(format("Error while sending heartbeat -> %s[%s]", e.getClass().getName(), e.getMessage())); } } }
[ "private", "void", "sendHeartbeat", "(", "Member", "target", ")", "{", "if", "(", "target", "==", "null", ")", "{", "return", ";", "}", "try", "{", "MembersViewMetadata", "membersViewMetadata", "=", "clusterService", ".", "getMembershipManager", "(", ")", ".",...
Send a {@link HeartbeatOp} to the {@code target} @param target target Member
[ "Send", "a", "{" ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/ClusterHeartbeatManager.java#L614-L628
apache/incubator-gobblin
gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanClient.java
AzkabanClient.handleResponse
protected static Map<String, String> handleResponse(HttpResponse response) throws IOException { int code = response.getStatusLine().getStatusCode(); if (code != HttpStatus.SC_CREATED && code != HttpStatus.SC_OK) { log.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); throw new AzkabanClientException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } // Get response in string HttpEntity entity = null; String jsonResponseString; try { entity = response.getEntity(); jsonResponseString = IOUtils.toString(entity.getContent(), "UTF-8"); log.info("Response string: " + jsonResponseString); } catch (Exception e) { throw new AzkabanClientException("Cannot convert response to a string", e); } finally { if (entity != null) { EntityUtils.consume(entity); } } return AzkabanClient.parseResponse(jsonResponseString); }
java
protected static Map<String, String> handleResponse(HttpResponse response) throws IOException { int code = response.getStatusLine().getStatusCode(); if (code != HttpStatus.SC_CREATED && code != HttpStatus.SC_OK) { log.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); throw new AzkabanClientException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } // Get response in string HttpEntity entity = null; String jsonResponseString; try { entity = response.getEntity(); jsonResponseString = IOUtils.toString(entity.getContent(), "UTF-8"); log.info("Response string: " + jsonResponseString); } catch (Exception e) { throw new AzkabanClientException("Cannot convert response to a string", e); } finally { if (entity != null) { EntityUtils.consume(entity); } } return AzkabanClient.parseResponse(jsonResponseString); }
[ "protected", "static", "Map", "<", "String", ",", "String", ">", "handleResponse", "(", "HttpResponse", "response", ")", "throws", "IOException", "{", "int", "code", "=", "response", ".", "getStatusLine", "(", ")", ".", "getStatusCode", "(", ")", ";", "if", ...
Convert a {@link HttpResponse} to a <string, string> map. Put protected modifier here so it is visible to {@link AzkabanAjaxAPIClient}. @param response An http response returned by {@link org.apache.http.client.HttpClient} execution. This should be JSON string. @return A map composed by the first level of KV pair of json object
[ "Convert", "a", "{", "@link", "HttpResponse", "}", "to", "a", "<string", "string", ">", "map", ".", "Put", "protected", "modifier", "here", "so", "it", "is", "visible", "to", "{", "@link", "AzkabanAjaxAPIClient", "}", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanClient.java#L206-L230
centic9/commons-dost
src/main/java/org/dstadler/commons/svn/SVNCommands.java
SVNCommands.getBranchLogStream
public static InputStream getBranchLogStream(String[] branches, long startRevision, long endRevision, String baseUrl, String user, String pwd) throws IOException { CommandLine cmdLine = getCommandLineForXMLLog(user, pwd); cmdLine.addArgument(startRevision + ":" + (endRevision != -1 ? endRevision : "HEAD")); // use HEAD if no valid endRevision given (= -1) cmdLine.addArgument(baseUrl + branches[0]); return ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000); }
java
public static InputStream getBranchLogStream(String[] branches, long startRevision, long endRevision, String baseUrl, String user, String pwd) throws IOException { CommandLine cmdLine = getCommandLineForXMLLog(user, pwd); cmdLine.addArgument(startRevision + ":" + (endRevision != -1 ? endRevision : "HEAD")); // use HEAD if no valid endRevision given (= -1) cmdLine.addArgument(baseUrl + branches[0]); return ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000); }
[ "public", "static", "InputStream", "getBranchLogStream", "(", "String", "[", "]", "branches", ",", "long", "startRevision", ",", "long", "endRevision", ",", "String", "baseUrl", ",", "String", "user", ",", "String", "pwd", ")", "throws", "IOException", "{", "C...
Retrieve the XML-log of changes on the given branch, starting with the given revision up to HEAD. This method returns an {@link InputStream} that can be used to read and process the XML data without storing the complete result. This is useful when you are potentially reading many revisions and thus need to avoid being limited in memory or disk. @param branches The list of branches to fetch logs for, currently only the first entry is used! @param startRevision The SVN revision to use as starting point for the log-entries. @param endRevision The SVN revision to use as end point for the log-entries. In case <code>endRevision</code> is <code>-1</code>, HEAD revision is being used @param baseUrl The SVN url to connect to @param user The SVN user or null if the default user from the machine should be used @param pwd The SVN password or null if the default user from the machine should be used @return A stream that can be used to read the XML data, should be closed by the caller @return An InputStream which provides the XML-log response @throws IOException Execution of the SVN sub-process failed or the sub-process returned a exit value indicating a failure
[ "Retrieve", "the", "XML", "-", "log", "of", "changes", "on", "the", "given", "branch", "starting", "with", "the", "given", "revision", "up", "to", "HEAD", ".", "This", "method", "returns", "an", "{", "@link", "InputStream", "}", "that", "can", "be", "use...
train
https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/svn/SVNCommands.java#L167-L173
jfinal/jfinal
src/main/java/com/jfinal/plugin/redis/Cache.java
Cache.zrank
public Long zrank(Object key, Object member) { Jedis jedis = getJedis(); try { return jedis.zrank(keyToBytes(key), valueToBytes(member)); } finally {close(jedis);} }
java
public Long zrank(Object key, Object member) { Jedis jedis = getJedis(); try { return jedis.zrank(keyToBytes(key), valueToBytes(member)); } finally {close(jedis);} }
[ "public", "Long", "zrank", "(", "Object", "key", ",", "Object", "member", ")", "{", "Jedis", "jedis", "=", "getJedis", "(", ")", ";", "try", "{", "return", "jedis", ".", "zrank", "(", "keyToBytes", "(", "key", ")", ",", "valueToBytes", "(", "member", ...
返回有序集 key 中成员 member 的排名。其中有序集成员按 score 值递增(从小到大)顺序排列。 排名以 0 为底,也就是说, score 值最小的成员排名为 0 。 使用 ZREVRANK 命令可以获得成员按 score 值递减(从大到小)排列的排名。
[ "返回有序集", "key", "中成员", "member", "的排名。其中有序集成员按", "score", "值递增", "(", "从小到大", ")", "顺序排列。", "排名以", "0", "为底,也就是说,", "score", "值最小的成员排名为", "0", "。", "使用", "ZREVRANK", "命令可以获得成员按", "score", "值递减", "(", "从大到小", ")", "排列的排名。" ]
train
https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/redis/Cache.java#L1106-L1112
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/util/CmsClientStringUtil.java
CmsClientStringUtil.getStackTrace
public static String getStackTrace(Throwable t, String separator) { Throwable cause = t; String result = ""; while (cause != null) { result += getStackTraceAsString(cause.getStackTrace(), separator); cause = cause.getCause(); } return result; }
java
public static String getStackTrace(Throwable t, String separator) { Throwable cause = t; String result = ""; while (cause != null) { result += getStackTraceAsString(cause.getStackTrace(), separator); cause = cause.getCause(); } return result; }
[ "public", "static", "String", "getStackTrace", "(", "Throwable", "t", ",", "String", "separator", ")", "{", "Throwable", "cause", "=", "t", ";", "String", "result", "=", "\"\"", ";", "while", "(", "cause", "!=", "null", ")", "{", "result", "+=", "getStac...
Returns the stack trace of the Throwable as a string.<p> @param t the Throwable for which the stack trace should be returned @param separator the separator between the lines of the stack trace @return a string representing a stack trace
[ "Returns", "the", "stack", "trace", "of", "the", "Throwable", "as", "a", "string", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/CmsClientStringUtil.java#L100-L109
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/shape/Shape.java
Shape.createShapeInformation
public static DataBuffer createShapeInformation(int[] shape, int[] stride, long offset, int elementWiseStride, char order) { if (shape.length != stride.length) throw new IllegalStateException("Shape and stride must be the same length"); int rank = shape.length; int shapeBuffer[] = new int[rank * 2 + 4]; shapeBuffer[0] = rank; int count = 1; for (int e = 0; e < shape.length; e++) shapeBuffer[count++] = shape[e]; for (int e = 0; e < stride.length; e++) shapeBuffer[count++] = stride[e]; shapeBuffer[count++] = (int) offset; shapeBuffer[count++] = elementWiseStride; shapeBuffer[count] = (int) order; DataBuffer ret = Nd4j.createBufferDetached(shapeBuffer); ret.setConstant(true); return ret; }
java
public static DataBuffer createShapeInformation(int[] shape, int[] stride, long offset, int elementWiseStride, char order) { if (shape.length != stride.length) throw new IllegalStateException("Shape and stride must be the same length"); int rank = shape.length; int shapeBuffer[] = new int[rank * 2 + 4]; shapeBuffer[0] = rank; int count = 1; for (int e = 0; e < shape.length; e++) shapeBuffer[count++] = shape[e]; for (int e = 0; e < stride.length; e++) shapeBuffer[count++] = stride[e]; shapeBuffer[count++] = (int) offset; shapeBuffer[count++] = elementWiseStride; shapeBuffer[count] = (int) order; DataBuffer ret = Nd4j.createBufferDetached(shapeBuffer); ret.setConstant(true); return ret; }
[ "public", "static", "DataBuffer", "createShapeInformation", "(", "int", "[", "]", "shape", ",", "int", "[", "]", "stride", ",", "long", "offset", ",", "int", "elementWiseStride", ",", "char", "order", ")", "{", "if", "(", "shape", ".", "length", "!=", "s...
Creates the shape information buffer given the shape,stride @param shape the shape for the buffer @param stride the stride for the buffer @param offset the offset for the buffer @param elementWiseStride the element wise stride for the buffer @param order the order for the buffer @return the shape information buffer given the parameters
[ "Creates", "the", "shape", "information", "buffer", "given", "the", "shape", "stride" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/shape/Shape.java#L3170-L3192
gallandarakhneorg/afc
advanced/bootique/bootique-log4j/src/main/java/org/arakhne/afc/bootique/log4j/modules/Log4jIntegrationModule.java
Log4jIntegrationModule.provideRootLogger
@SuppressWarnings("static-method") @Singleton @Provides public Logger provideRootLogger(ConfigurationFactory configFactory, Provider<Log4jIntegrationConfig> config) { final Logger root = Logger.getRootLogger(); // Reroute JUL SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); final Log4jIntegrationConfig cfg = config.get(); if (!cfg.getUseLog4jConfig()) { cfg.configureLogger(root); } return root; }
java
@SuppressWarnings("static-method") @Singleton @Provides public Logger provideRootLogger(ConfigurationFactory configFactory, Provider<Log4jIntegrationConfig> config) { final Logger root = Logger.getRootLogger(); // Reroute JUL SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); final Log4jIntegrationConfig cfg = config.get(); if (!cfg.getUseLog4jConfig()) { cfg.configureLogger(root); } return root; }
[ "@", "SuppressWarnings", "(", "\"static-method\"", ")", "@", "Singleton", "@", "Provides", "public", "Logger", "provideRootLogger", "(", "ConfigurationFactory", "configFactory", ",", "Provider", "<", "Log4jIntegrationConfig", ">", "config", ")", "{", "final", "Logger"...
Provide the root logger. @param configFactory the factory of configurations. @param config the logger configuration. @return the root logger.
[ "Provide", "the", "root", "logger", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/bootique/bootique-log4j/src/main/java/org/arakhne/afc/bootique/log4j/modules/Log4jIntegrationModule.java#L89-L102
stapler/stapler
core/src/main/java/org/kohsuke/stapler/lang/KlassNavigator.java
KlassNavigator.getArrayElement
public Object getArrayElement(Object o, int index) throws IndexOutOfBoundsException { if (o instanceof List) return ((List)o).get(index); return Array.get(o,index); }
java
public Object getArrayElement(Object o, int index) throws IndexOutOfBoundsException { if (o instanceof List) return ((List)o).get(index); return Array.get(o,index); }
[ "public", "Object", "getArrayElement", "(", "Object", "o", ",", "int", "index", ")", "throws", "IndexOutOfBoundsException", "{", "if", "(", "o", "instanceof", "List", ")", "return", "(", "(", "List", ")", "o", ")", ".", "get", "(", "index", ")", ";", "...
Given an instance for which the type reported {@code isArray()==true}, obtains the element of the specified index. @see #isArray(Object)
[ "Given", "an", "instance", "for", "which", "the", "type", "reported", "{" ]
train
https://github.com/stapler/stapler/blob/11ad5af185e062fb46e01bf9fbed66f3ebf2a8f7/core/src/main/java/org/kohsuke/stapler/lang/KlassNavigator.java#L120-L124
teatrove/teatrove
trove/src/main/java/org/teatrove/trove/util/PropertyMap.java
PropertyMap.getBoolean
public boolean getBoolean(String key, boolean def) { String value = getString(key); if (value == null) { return def; } else { return "true".equalsIgnoreCase(value); } }
java
public boolean getBoolean(String key, boolean def) { String value = getString(key); if (value == null) { return def; } else { return "true".equalsIgnoreCase(value); } }
[ "public", "boolean", "getBoolean", "(", "String", "key", ",", "boolean", "def", ")", "{", "String", "value", "=", "getString", "(", "key", ")", ";", "if", "(", "value", "==", "null", ")", "{", "return", "def", ";", "}", "else", "{", "return", "\"true...
Returns the default value if the given key isn't in this PropertyMap or if the the value isn't equal to "true", ignoring case. @param key Key of property to read @param def Default value
[ "Returns", "the", "default", "value", "if", "the", "given", "key", "isn", "t", "in", "this", "PropertyMap", "or", "if", "the", "the", "value", "isn", "t", "equal", "to", "true", "ignoring", "case", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/util/PropertyMap.java#L400-L408
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/service/warden/WardenNotifier.java
WardenNotifier.addAnnotationSuspendedUser
protected void addAnnotationSuspendedUser(NotificationContext context, SubSystem subSystem) { Alert alert = context.getAlert(); PrincipalUser wardenUser = getWardenUser(alert.getName()); Metric metric = null; Map<Long, Double> datapoints = new HashMap<>(); metric = new Metric(Counter.WARDEN_TRIGGERS.getScope(), Counter.WARDEN_TRIGGERS.getMetric()); metric.setTag("user", wardenUser.getUserName()); datapoints.put(context.getTriggerFiredTime(), 1.0); metric.setDatapoints(datapoints); _tsdbService.putMetrics(Arrays.asList(new Metric[] { metric })); Annotation annotation = new Annotation(ANNOTATION_SOURCE, wardenUser.getUserName(), ANNOTATION_TYPE, Counter.WARDEN_TRIGGERS.getScope(), Counter.WARDEN_TRIGGERS.getMetric(), context.getTriggerFiredTime()); Map<String, String> fields = new TreeMap<>(); fields.put("Suspended from subsystem", subSystem.toString()); fields.put("Alert Name", alert.getName()); fields.put("Notification Name", context.getNotification().getName()); fields.put("Trigger Name", context.getTrigger().getName()); annotation.setFields(fields); _annotationService.updateAnnotation(alert.getOwner(), annotation); }
java
protected void addAnnotationSuspendedUser(NotificationContext context, SubSystem subSystem) { Alert alert = context.getAlert(); PrincipalUser wardenUser = getWardenUser(alert.getName()); Metric metric = null; Map<Long, Double> datapoints = new HashMap<>(); metric = new Metric(Counter.WARDEN_TRIGGERS.getScope(), Counter.WARDEN_TRIGGERS.getMetric()); metric.setTag("user", wardenUser.getUserName()); datapoints.put(context.getTriggerFiredTime(), 1.0); metric.setDatapoints(datapoints); _tsdbService.putMetrics(Arrays.asList(new Metric[] { metric })); Annotation annotation = new Annotation(ANNOTATION_SOURCE, wardenUser.getUserName(), ANNOTATION_TYPE, Counter.WARDEN_TRIGGERS.getScope(), Counter.WARDEN_TRIGGERS.getMetric(), context.getTriggerFiredTime()); Map<String, String> fields = new TreeMap<>(); fields.put("Suspended from subsystem", subSystem.toString()); fields.put("Alert Name", alert.getName()); fields.put("Notification Name", context.getNotification().getName()); fields.put("Trigger Name", context.getTrigger().getName()); annotation.setFields(fields); _annotationService.updateAnnotation(alert.getOwner(), annotation); }
[ "protected", "void", "addAnnotationSuspendedUser", "(", "NotificationContext", "context", ",", "SubSystem", "subSystem", ")", "{", "Alert", "alert", "=", "context", ".", "getAlert", "(", ")", ";", "PrincipalUser", "wardenUser", "=", "getWardenUser", "(", "alert", ...
Add annotation for user suspension to the <tt>triggers.warden</tt> metric.. @param context The notification context. Cannot be null. @param subSystem The subsystem for which the user is being suspended. Cannot be null.
[ "Add", "annotation", "for", "user", "suspension", "to", "the", "<tt", ">", "triggers", ".", "warden<", "/", "tt", ">", "metric", ".." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/warden/WardenNotifier.java#L146-L169
seancfoley/IPAddress
IPAddress/src/inet.ipaddr/inet/ipaddr/format/validate/ParsedAddressGrouping.java
ParsedAddressGrouping.getNetworkPrefixLength
public static Integer getNetworkPrefixLength(int bitsPerSegment, int segmentPrefixLength, int segmentIndex) { int increment = (bitsPerSegment == 8) ? segmentIndex << 3 : ((bitsPerSegment == 16) ? segmentIndex << 4 : segmentIndex * bitsPerSegment); return increment + segmentPrefixLength; }
java
public static Integer getNetworkPrefixLength(int bitsPerSegment, int segmentPrefixLength, int segmentIndex) { int increment = (bitsPerSegment == 8) ? segmentIndex << 3 : ((bitsPerSegment == 16) ? segmentIndex << 4 : segmentIndex * bitsPerSegment); return increment + segmentPrefixLength; }
[ "public", "static", "Integer", "getNetworkPrefixLength", "(", "int", "bitsPerSegment", ",", "int", "segmentPrefixLength", ",", "int", "segmentIndex", ")", "{", "int", "increment", "=", "(", "bitsPerSegment", "==", "8", ")", "?", "segmentIndex", "<<", "3", ":", ...
Translates a non-null segment prefix length into an address prefix length. When calling this for the first segment with a non-null prefix length, this gives the overall prefix length. <p> Across an address prefixes are: IPv6: (null):...:(null):(1 to 16):(0):...:(0) or IPv4: ...(null).(1 to 8).(0)...
[ "Translates", "a", "non", "-", "null", "segment", "prefix", "length", "into", "an", "address", "prefix", "length", ".", "When", "calling", "this", "for", "the", "first", "segment", "with", "a", "non", "-", "null", "prefix", "length", "this", "gives", "the"...
train
https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/format/validate/ParsedAddressGrouping.java#L101-L104
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/sampling/ClusterSampling.java
ClusterSampling.xbarVariance
public static double xbarVariance(TransposeDataCollection sampleDataCollection, int populationM, double Nbar) { double xbarVariance = 0.0; int sampleM = sampleDataCollection.size(); double mean = mean(sampleDataCollection); for(Map.Entry<Object, FlatDataCollection> entry : sampleDataCollection.entrySet()) { double sum = 0.0; Iterator<Double> it = entry.getValue().iteratorDouble(); while(it.hasNext()) { sum+=(it.next() - mean); } xbarVariance+= sum*sum/(sampleM-1); } xbarVariance *= (populationM-sampleM)/(populationM*sampleM*Nbar*Nbar); return xbarVariance; }
java
public static double xbarVariance(TransposeDataCollection sampleDataCollection, int populationM, double Nbar) { double xbarVariance = 0.0; int sampleM = sampleDataCollection.size(); double mean = mean(sampleDataCollection); for(Map.Entry<Object, FlatDataCollection> entry : sampleDataCollection.entrySet()) { double sum = 0.0; Iterator<Double> it = entry.getValue().iteratorDouble(); while(it.hasNext()) { sum+=(it.next() - mean); } xbarVariance+= sum*sum/(sampleM-1); } xbarVariance *= (populationM-sampleM)/(populationM*sampleM*Nbar*Nbar); return xbarVariance; }
[ "public", "static", "double", "xbarVariance", "(", "TransposeDataCollection", "sampleDataCollection", ",", "int", "populationM", ",", "double", "Nbar", ")", "{", "double", "xbarVariance", "=", "0.0", ";", "int", "sampleM", "=", "sampleDataCollection", ".", "size", ...
Calculates Variance for Xbar @param sampleDataCollection @param populationM @param Nbar @return
[ "Calculates", "Variance", "for", "Xbar" ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/sampling/ClusterSampling.java#L103-L122
rhuss/jolokia
agent/jvm/src/main/java/org/jolokia/jvmagent/security/KeyStoreUtil.java
KeyStoreUtil.updateWithServerPems
public static void updateWithServerPems(KeyStore pKeyStore, File pServerCert, File pServerKey, String pKeyAlgo, char[] pPassword) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException { InputStream is = new FileInputStream(pServerCert); try { CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is); byte[] keyBytes = decodePem(pServerKey); PrivateKey privateKey; KeyFactory keyFactory = KeyFactory.getInstance(pKeyAlgo); try { // First let's try PKCS8 privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); } catch (InvalidKeySpecException e) { // Otherwise try PKCS1 RSAPrivateCrtKeySpec keySpec = PKCS1Util.decodePKCS1(keyBytes); privateKey = keyFactory.generatePrivate(keySpec); } String alias = cert.getSubjectX500Principal().getName(); pKeyStore.setKeyEntry(alias, privateKey, pPassword, new Certificate[]{cert}); } finally { is.close(); } }
java
public static void updateWithServerPems(KeyStore pKeyStore, File pServerCert, File pServerKey, String pKeyAlgo, char[] pPassword) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException { InputStream is = new FileInputStream(pServerCert); try { CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is); byte[] keyBytes = decodePem(pServerKey); PrivateKey privateKey; KeyFactory keyFactory = KeyFactory.getInstance(pKeyAlgo); try { // First let's try PKCS8 privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); } catch (InvalidKeySpecException e) { // Otherwise try PKCS1 RSAPrivateCrtKeySpec keySpec = PKCS1Util.decodePKCS1(keyBytes); privateKey = keyFactory.generatePrivate(keySpec); } String alias = cert.getSubjectX500Principal().getName(); pKeyStore.setKeyEntry(alias, privateKey, pPassword, new Certificate[]{cert}); } finally { is.close(); } }
[ "public", "static", "void", "updateWithServerPems", "(", "KeyStore", "pKeyStore", ",", "File", "pServerCert", ",", "File", "pServerKey", ",", "String", "pKeyAlgo", ",", "char", "[", "]", "pPassword", ")", "throws", "IOException", ",", "CertificateException", ",", ...
Update a key store with the keys found in a server PEM and its key file. @param pKeyStore keystore to update @param pServerCert server certificate @param pServerKey server key @param pKeyAlgo algorithm used in the keystore (e.g. "RSA") @param pPassword password to use for the key file. must not be null, use <code>char[0]</code> for an empty password.
[ "Update", "a", "key", "store", "with", "the", "keys", "found", "in", "a", "server", "PEM", "and", "its", "key", "file", "." ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/jvm/src/main/java/org/jolokia/jvmagent/security/KeyStoreUtil.java#L79-L104
apiman/apiman
manager/api/gateway/src/main/java/io/apiman/manager/api/gateway/rest/GatewayClient.java
GatewayClient.parseStackTrace
protected static StackTraceElement[] parseStackTrace(String stacktrace) { try (BufferedReader reader = new BufferedReader(new StringReader(stacktrace))) { List<StackTraceElement> elements = new ArrayList<>(); String line; // Example lines: // \tat io.apiman.gateway.engine.es.ESRegistry$1.completed(ESRegistry.java:79) // \tat org.apache.http.impl.nio.client.InternalIODispatch.onInputReady(InternalIODispatch.java:81)\r\n while ( (line = reader.readLine()) != null) { if (line.startsWith("\tat ")) { //$NON-NLS-1$ int openParenIdx = line.indexOf('('); int closeParenIdx = line.indexOf(')'); String classAndMethod = line.substring(4, openParenIdx); String fileAndLineNum = line.substring(openParenIdx + 1, closeParenIdx); String className = classAndMethod.substring(0, classAndMethod.lastIndexOf('.')); String methodName = classAndMethod.substring(classAndMethod.lastIndexOf('.') + 1); String [] split = fileAndLineNum.split(":"); //$NON-NLS-1$ if (split.length == 1) { elements.add(new StackTraceElement(className, methodName, fileAndLineNum, -1)); } else { String fileName = split[0]; String lineNum = split[1]; elements.add(new StackTraceElement(className, methodName, fileName, new Integer(lineNum))); } } } return elements.toArray(new StackTraceElement[elements.size()]); } catch (Exception e) { e.printStackTrace(); return null; } }
java
protected static StackTraceElement[] parseStackTrace(String stacktrace) { try (BufferedReader reader = new BufferedReader(new StringReader(stacktrace))) { List<StackTraceElement> elements = new ArrayList<>(); String line; // Example lines: // \tat io.apiman.gateway.engine.es.ESRegistry$1.completed(ESRegistry.java:79) // \tat org.apache.http.impl.nio.client.InternalIODispatch.onInputReady(InternalIODispatch.java:81)\r\n while ( (line = reader.readLine()) != null) { if (line.startsWith("\tat ")) { //$NON-NLS-1$ int openParenIdx = line.indexOf('('); int closeParenIdx = line.indexOf(')'); String classAndMethod = line.substring(4, openParenIdx); String fileAndLineNum = line.substring(openParenIdx + 1, closeParenIdx); String className = classAndMethod.substring(0, classAndMethod.lastIndexOf('.')); String methodName = classAndMethod.substring(classAndMethod.lastIndexOf('.') + 1); String [] split = fileAndLineNum.split(":"); //$NON-NLS-1$ if (split.length == 1) { elements.add(new StackTraceElement(className, methodName, fileAndLineNum, -1)); } else { String fileName = split[0]; String lineNum = split[1]; elements.add(new StackTraceElement(className, methodName, fileName, new Integer(lineNum))); } } } return elements.toArray(new StackTraceElement[elements.size()]); } catch (Exception e) { e.printStackTrace(); return null; } }
[ "protected", "static", "StackTraceElement", "[", "]", "parseStackTrace", "(", "String", "stacktrace", ")", "{", "try", "(", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "StringReader", "(", "stacktrace", ")", ")", ")", "{", "List", "<"...
Parses a stack trace from the given string. @param stacktrace
[ "Parses", "a", "stack", "trace", "from", "the", "given", "string", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/gateway/src/main/java/io/apiman/manager/api/gateway/rest/GatewayClient.java#L309-L339
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/util/FtpFileUtil.java
FtpFileUtil.executeCommandOnFTPServer
public static String executeCommandOnFTPServer(String hostName, Integer port, String userName, String password, String command, String commandArgs) { String result = null; if (StringUtils.isNotBlank(command)) { FTPClient ftpClient = new FTPClient(); String errorMessage = "Unable to connect and execute %s command with argumments '%s' for FTP server '%s'."; try { connectAndLoginOnFTPServer(ftpClient, hostName, port, userName, password); // execute command if (StringUtils.isBlank(commandArgs)) { ftpClient.sendCommand(command); } else { ftpClient.sendCommand(command, commandArgs); } validatResponse(ftpClient); result = ftpClient.getReplyString(); } catch (IOException ex) { throw new RuntimeException(String.format(errorMessage, command, commandArgs, hostName), ex); } finally { disconnectAndLogoutFromFTPServer(ftpClient, hostName); } } return result; }
java
public static String executeCommandOnFTPServer(String hostName, Integer port, String userName, String password, String command, String commandArgs) { String result = null; if (StringUtils.isNotBlank(command)) { FTPClient ftpClient = new FTPClient(); String errorMessage = "Unable to connect and execute %s command with argumments '%s' for FTP server '%s'."; try { connectAndLoginOnFTPServer(ftpClient, hostName, port, userName, password); // execute command if (StringUtils.isBlank(commandArgs)) { ftpClient.sendCommand(command); } else { ftpClient.sendCommand(command, commandArgs); } validatResponse(ftpClient); result = ftpClient.getReplyString(); } catch (IOException ex) { throw new RuntimeException(String.format(errorMessage, command, commandArgs, hostName), ex); } finally { disconnectAndLogoutFromFTPServer(ftpClient, hostName); } } return result; }
[ "public", "static", "String", "executeCommandOnFTPServer", "(", "String", "hostName", ",", "Integer", "port", ",", "String", "userName", ",", "String", "password", ",", "String", "command", ",", "String", "commandArgs", ")", "{", "String", "result", "=", "null",...
Execute command with supplied arguments on the FTP server. @param hostName the FTP server host name to connect @param port the port to connect @param userName the user name @param password the password @param command the command to execute. @param commandArgs the command argument(s), if any. @return reply string from FTP server after the command has been executed. @throws RuntimeException in case any exception has been thrown.
[ "Execute", "command", "with", "supplied", "arguments", "on", "the", "FTP", "server", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/FtpFileUtil.java#L55-L82
apache/incubator-druid
extensions-core/parquet-extensions/src/main/java/org/apache/druid/data/input/parquet/simple/ParquetGroupConverter.java
ParquetGroupConverter.convertPrimitiveField
@Nullable private static Object convertPrimitiveField(Group g, int fieldIndex, boolean binaryAsString) { PrimitiveType pt = (PrimitiveType) g.getType().getFields().get(fieldIndex); if (pt.isRepetition(Type.Repetition.REPEATED) && g.getFieldRepetitionCount(fieldIndex) > 1) { List<Object> vals = new ArrayList<>(); for (int i = 0; i < g.getFieldRepetitionCount(fieldIndex); i++) { vals.add(convertPrimitiveField(g, fieldIndex, i, binaryAsString)); } return vals; } return convertPrimitiveField(g, fieldIndex, 0, binaryAsString); }
java
@Nullable private static Object convertPrimitiveField(Group g, int fieldIndex, boolean binaryAsString) { PrimitiveType pt = (PrimitiveType) g.getType().getFields().get(fieldIndex); if (pt.isRepetition(Type.Repetition.REPEATED) && g.getFieldRepetitionCount(fieldIndex) > 1) { List<Object> vals = new ArrayList<>(); for (int i = 0; i < g.getFieldRepetitionCount(fieldIndex); i++) { vals.add(convertPrimitiveField(g, fieldIndex, i, binaryAsString)); } return vals; } return convertPrimitiveField(g, fieldIndex, 0, binaryAsString); }
[ "@", "Nullable", "private", "static", "Object", "convertPrimitiveField", "(", "Group", "g", ",", "int", "fieldIndex", ",", "boolean", "binaryAsString", ")", "{", "PrimitiveType", "pt", "=", "(", "PrimitiveType", ")", "g", ".", "getType", "(", ")", ".", "getF...
Convert a primitive group field to a "ingestion friendly" java object @return "ingestion ready" java object, or null
[ "Convert", "a", "primitive", "group", "field", "to", "a", "ingestion", "friendly", "java", "object" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/parquet-extensions/src/main/java/org/apache/druid/data/input/parquet/simple/ParquetGroupConverter.java#L246-L258
btc-ag/redg
redg-runtime/src/main/java/com/btc/redg/runtime/dummy/DefaultDummyFactory.java
DefaultDummyFactory.createNewDummy
private <T extends RedGEntity> T createNewDummy(AbstractRedG redG, Class<T> dummyClass) { Constructor constructor = Arrays.stream(dummyClass.getDeclaredConstructors()) .filter(this::isDummyRedGEntityConstructor) .findFirst().orElseThrow(() -> new DummyCreationException("Could not find a fitting constructor")); Object[] parameter = new Object[constructor.getParameterCount()]; parameter[0] = redG; for (int i = 1; i < constructor.getParameterCount(); i++) { parameter[i] = getDummy(redG, constructor.getParameterTypes()[i]); } try { constructor.setAccessible(true); T obj = dummyClass.cast(constructor.newInstance(parameter)); redG.addEntity(obj); return obj; } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new DummyCreationException("Instantiation of the dummy failed", e); } }
java
private <T extends RedGEntity> T createNewDummy(AbstractRedG redG, Class<T> dummyClass) { Constructor constructor = Arrays.stream(dummyClass.getDeclaredConstructors()) .filter(this::isDummyRedGEntityConstructor) .findFirst().orElseThrow(() -> new DummyCreationException("Could not find a fitting constructor")); Object[] parameter = new Object[constructor.getParameterCount()]; parameter[0] = redG; for (int i = 1; i < constructor.getParameterCount(); i++) { parameter[i] = getDummy(redG, constructor.getParameterTypes()[i]); } try { constructor.setAccessible(true); T obj = dummyClass.cast(constructor.newInstance(parameter)); redG.addEntity(obj); return obj; } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new DummyCreationException("Instantiation of the dummy failed", e); } }
[ "private", "<", "T", "extends", "RedGEntity", ">", "T", "createNewDummy", "(", "AbstractRedG", "redG", ",", "Class", "<", "T", ">", "dummyClass", ")", "{", "Constructor", "constructor", "=", "Arrays", ".", "stream", "(", "dummyClass", ".", "getDeclaredConstruc...
Creates a new dummy entity of the required type. Required non null foreign keys will be taken from the {@link #getDummy(AbstractRedG, Class)} method and will be created if necessary as well. If the creation fails for some reason, a {@link DummyCreationException} will be thrown. @param redG The redG instance @param dummyClass The class specifying the wanted entity type @param <T> The wanted entity type @return A new dummy entity of the required type. It has already been added to the redG object and can be used immediately. @throws DummyCreationException If no fitting constructor is found or instantiation fails
[ "Creates", "a", "new", "dummy", "entity", "of", "the", "required", "type", ".", "Required", "non", "null", "foreign", "keys", "will", "be", "taken", "from", "the", "{", "@link", "#getDummy", "(", "AbstractRedG", "Class", ")", "}", "method", "and", "will", ...
train
https://github.com/btc-ag/redg/blob/416a68639d002512cabfebff09afd2e1909e27df/redg-runtime/src/main/java/com/btc/redg/runtime/dummy/DefaultDummyFactory.java#L78-L96
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java
NetworkInterfacesInner.createOrUpdateAsync
public Observable<NetworkInterfaceInner> createOrUpdateAsync(String resourceGroupName, String networkInterfaceName, NetworkInterfaceInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, networkInterfaceName, parameters).map(new Func1<ServiceResponse<NetworkInterfaceInner>, NetworkInterfaceInner>() { @Override public NetworkInterfaceInner call(ServiceResponse<NetworkInterfaceInner> response) { return response.body(); } }); }
java
public Observable<NetworkInterfaceInner> createOrUpdateAsync(String resourceGroupName, String networkInterfaceName, NetworkInterfaceInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, networkInterfaceName, parameters).map(new Func1<ServiceResponse<NetworkInterfaceInner>, NetworkInterfaceInner>() { @Override public NetworkInterfaceInner call(ServiceResponse<NetworkInterfaceInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "NetworkInterfaceInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "networkInterfaceName", ",", "NetworkInterfaceInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourc...
Creates or updates a network interface. @param resourceGroupName The name of the resource group. @param networkInterfaceName The name of the network interface. @param parameters Parameters supplied to the create or update network interface operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Creates", "or", "updates", "a", "network", "interface", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java#L520-L527
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/instance/NodeShutdownHelper.java
NodeShutdownHelper.shutdownNodeByFiringEvents
public static void shutdownNodeByFiringEvents(Node node, boolean terminate) { final HazelcastInstanceImpl hazelcastInstance = node.hazelcastInstance; final LifecycleServiceImpl lifecycleService = hazelcastInstance.getLifecycleService(); lifecycleService.fireLifecycleEvent(LifecycleEvent.LifecycleState.SHUTTING_DOWN); node.shutdown(terminate); lifecycleService.fireLifecycleEvent(LifecycleEvent.LifecycleState.SHUTDOWN); }
java
public static void shutdownNodeByFiringEvents(Node node, boolean terminate) { final HazelcastInstanceImpl hazelcastInstance = node.hazelcastInstance; final LifecycleServiceImpl lifecycleService = hazelcastInstance.getLifecycleService(); lifecycleService.fireLifecycleEvent(LifecycleEvent.LifecycleState.SHUTTING_DOWN); node.shutdown(terminate); lifecycleService.fireLifecycleEvent(LifecycleEvent.LifecycleState.SHUTDOWN); }
[ "public", "static", "void", "shutdownNodeByFiringEvents", "(", "Node", "node", ",", "boolean", "terminate", ")", "{", "final", "HazelcastInstanceImpl", "hazelcastInstance", "=", "node", ".", "hazelcastInstance", ";", "final", "LifecycleServiceImpl", "lifecycleService", ...
Shutdowns a node by firing lifecycle events. Do not call this method for every node shutdown scenario since {@link com.hazelcast.core.LifecycleListener}s will end up more than one {@link com.hazelcast.core.LifecycleEvent.LifecycleState#SHUTTING_DOWN} or {@link com.hazelcast.core.LifecycleEvent.LifecycleState#SHUTDOWN} events. @param node Node to shutdown. @param terminate <code>false</code> for graceful shutdown, <code>true</code> for terminate (un-graceful shutdown)
[ "Shutdowns", "a", "node", "by", "firing", "lifecycle", "events", ".", "Do", "not", "call", "this", "method", "for", "every", "node", "shutdown", "scenario", "since", "{", "@link", "com", ".", "hazelcast", ".", "core", ".", "LifecycleListener", "}", "s", "w...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/instance/NodeShutdownHelper.java#L40-L46
lightblueseas/swing-components
src/main/java/de/alpharogroup/swing/components/factories/JComponentFactory.java
JComponentFactory.newSplashScreen
public static SplashScreen newSplashScreen(final String image, final String text) { final SplashScreen splashscreen = new SplashScreen(image, text); return splashscreen; }
java
public static SplashScreen newSplashScreen(final String image, final String text) { final SplashScreen splashscreen = new SplashScreen(image, text); return splashscreen; }
[ "public", "static", "SplashScreen", "newSplashScreen", "(", "final", "String", "image", ",", "final", "String", "text", ")", "{", "final", "SplashScreen", "splashscreen", "=", "new", "SplashScreen", "(", "image", ",", "text", ")", ";", "return", "splashscreen", ...
Factory method for create a {@link SplashScreen}. @param image the image @param text the text @return the new {@link SplashScreen}.
[ "Factory", "method", "for", "create", "a", "{", "@link", "SplashScreen", "}", "." ]
train
https://github.com/lightblueseas/swing-components/blob/4045e85cabd8f0ce985cbfff134c3c9873930c79/src/main/java/de/alpharogroup/swing/components/factories/JComponentFactory.java#L298-L302
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/ToStream.java
ToStream.startDTD
public void startDTD(String name, String publicId, String systemId) throws org.xml.sax.SAXException { setDoctypeSystem(systemId); setDoctypePublic(publicId); m_elemContext.m_elementName = name; m_inDoctype = true; }
java
public void startDTD(String name, String publicId, String systemId) throws org.xml.sax.SAXException { setDoctypeSystem(systemId); setDoctypePublic(publicId); m_elemContext.m_elementName = name; m_inDoctype = true; }
[ "public", "void", "startDTD", "(", "String", "name", ",", "String", "publicId", ",", "String", "systemId", ")", "throws", "org", ".", "xml", ".", "sax", ".", "SAXException", "{", "setDoctypeSystem", "(", "systemId", ")", ";", "setDoctypePublic", "(", "public...
Report the start of DTD declarations, if any. Any declarations are assumed to be in the internal subset unless otherwise indicated. @param name The document type name. @param publicId The declared public identifier for the external DTD subset, or null if none was declared. @param systemId The declared system identifier for the external DTD subset, or null if none was declared. @throws org.xml.sax.SAXException The application may raise an exception. @see #endDTD @see #startEntity
[ "Report", "the", "start", "of", "DTD", "declarations", "if", "any", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/ToStream.java#L2666-L2674
luuuis/jcalendar
src/main/java/com/toedter/components/JSpinField.java
JSpinField.setValue
protected void setValue(int newValue, boolean updateTextField, boolean firePropertyChange) { int oldValue = value; if (newValue < min) { value = min; } else if (newValue > max) { value = max; } else { value = newValue; } if (updateTextField) { textField.setText(Integer.toString(value)); textField.setForeground(Color.black); } if (firePropertyChange) { firePropertyChange("value", oldValue, value); } }
java
protected void setValue(int newValue, boolean updateTextField, boolean firePropertyChange) { int oldValue = value; if (newValue < min) { value = min; } else if (newValue > max) { value = max; } else { value = newValue; } if (updateTextField) { textField.setText(Integer.toString(value)); textField.setForeground(Color.black); } if (firePropertyChange) { firePropertyChange("value", oldValue, value); } }
[ "protected", "void", "setValue", "(", "int", "newValue", ",", "boolean", "updateTextField", ",", "boolean", "firePropertyChange", ")", "{", "int", "oldValue", "=", "value", ";", "if", "(", "newValue", "<", "min", ")", "{", "value", "=", "min", ";", "}", ...
Sets the value attribute of the JSpinField object. @param newValue The new value @param updateTextField true if text field should be updated
[ "Sets", "the", "value", "attribute", "of", "the", "JSpinField", "object", "." ]
train
https://github.com/luuuis/jcalendar/blob/442e5bc319d92dee93400e6180ca74a5b6bd7775/src/main/java/com/toedter/components/JSpinField.java#L147-L165
KyoriPowered/lunar
src/main/java/net/kyori/lunar/collection/MoreTables.java
MoreTables.computeIfAbsent
public static <R, C, V> /* @Nullable */ V computeIfAbsent(final @NonNull Table<R, C, V> table, final @Nullable R rowKey, final @Nullable C columnKey, final @NonNull BiFunction<? super R, ? super C, ? extends V> valueFunction) { /* @Nullable */ V value = table.get(rowKey, columnKey); if(value == null) { value = valueFunction.apply(rowKey, columnKey); table.put(rowKey, columnKey, value); } return value; }
java
public static <R, C, V> /* @Nullable */ V computeIfAbsent(final @NonNull Table<R, C, V> table, final @Nullable R rowKey, final @Nullable C columnKey, final @NonNull BiFunction<? super R, ? super C, ? extends V> valueFunction) { /* @Nullable */ V value = table.get(rowKey, columnKey); if(value == null) { value = valueFunction.apply(rowKey, columnKey); table.put(rowKey, columnKey, value); } return value; }
[ "public", "static", "<", "R", ",", "C", ",", "V", ">", "/* @Nullable */", "V", "computeIfAbsent", "(", "final", "@", "NonNull", "Table", "<", "R", ",", "C", ",", "V", ">", "table", ",", "final", "@", "Nullable", "R", "rowKey", ",", "final", "@", "N...
Gets the value of {@code rowKey} and {@code columnKey} from {@code table}, or computes the value using {@code valueFunction} and inserts it into the table. @param table the table @param rowKey the row key @param columnKey the column key @param valueFunction the value function @param <R> the row type @param <C> the column type @param <V> the value type @return the value
[ "Gets", "the", "value", "of", "{", "@code", "rowKey", "}", "and", "{", "@code", "columnKey", "}", "from", "{", "@code", "table", "}", "or", "computes", "the", "value", "using", "{", "@code", "valueFunction", "}", "and", "inserts", "it", "into", "the", ...
train
https://github.com/KyoriPowered/lunar/blob/6856747d9034a2fe0c8d0a8a0150986797732b5c/src/main/java/net/kyori/lunar/collection/MoreTables.java#L56-L63
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/requeststate/NameService.java
NameService.getMap
public Map getMap(String name, boolean create) { if (name == null) throw new IllegalStateException("name must not be null"); if (_nameMap == null) return null; TrackingObject to = (TrackingObject) _nameMap.get(name); // The object wasn't found if (to == null) return null; // If the object has been reclaimed, then we remove the named object from the map. WeakReference wr = to.getWeakINameable(); INameable o = (INameable) wr.get(); if (o == null) { synchronized (_nameMap) { _nameMap.remove(name); } return null; } if (create) return to; return to.isMapCreated() ? to : null; }
java
public Map getMap(String name, boolean create) { if (name == null) throw new IllegalStateException("name must not be null"); if (_nameMap == null) return null; TrackingObject to = (TrackingObject) _nameMap.get(name); // The object wasn't found if (to == null) return null; // If the object has been reclaimed, then we remove the named object from the map. WeakReference wr = to.getWeakINameable(); INameable o = (INameable) wr.get(); if (o == null) { synchronized (_nameMap) { _nameMap.remove(name); } return null; } if (create) return to; return to.isMapCreated() ? to : null; }
[ "public", "Map", "getMap", "(", "String", "name", ",", "boolean", "create", ")", "{", "if", "(", "name", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"name must not be null\"", ")", ";", "if", "(", "_nameMap", "==", "null", ")", "retu...
This method will return the state map associated with the Nameable object if the object has been stored in the <code>NameService</code> and something has been stored into the <code>Map</code>. Otherwise this will return null indicating that the map is empty. If the <code>create</code> parameter is true, we will always return the <code>Map</code> object. @param name The name of the object to return the named object. This must not be null. @param create This will create the map if necessary. @return A Map Object for the named object. This will return null if nothing has been stored in the map and <code>create</code> is false.
[ "This", "method", "will", "return", "the", "state", "map", "associated", "with", "the", "Nameable", "object", "if", "the", "object", "has", "been", "stored", "in", "the", "<code", ">", "NameService<", "/", "code", ">", "and", "something", "has", "been", "s...
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/requeststate/NameService.java#L243-L267
sarl/sarl
contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyExpressionGenerator.java
PyExpressionGenerator._generate
protected XExpression _generate(XFeatureCall call, IAppendable it, IExtraLanguageGeneratorContext context) { appendReturnIfExpectedReturnedExpression(it, context); newFeatureCallGenerator(context, it).generate(call); return call; }
java
protected XExpression _generate(XFeatureCall call, IAppendable it, IExtraLanguageGeneratorContext context) { appendReturnIfExpectedReturnedExpression(it, context); newFeatureCallGenerator(context, it).generate(call); return call; }
[ "protected", "XExpression", "_generate", "(", "XFeatureCall", "call", ",", "IAppendable", "it", ",", "IExtraLanguageGeneratorContext", "context", ")", "{", "appendReturnIfExpectedReturnedExpression", "(", "it", ",", "context", ")", ";", "newFeatureCallGenerator", "(", "...
Generate the given object. @param call the feature call. @param it the target for the generated content. @param context the context. @return the feature call.
[ "Generate", "the", "given", "object", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyExpressionGenerator.java#L497-L501