repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/AgreementsInner.java
AgreementsInner.getAsync
public Observable<IntegrationAccountAgreementInner> getAsync(String resourceGroupName, String integrationAccountName, String agreementName) { return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, agreementName).map(new Func1<ServiceResponse<IntegrationAccountAgreementInner>, IntegrationAccountAgreementInner>() { @Override public IntegrationAccountAgreementInner call(ServiceResponse<IntegrationAccountAgreementInner> response) { return response.body(); } }); }
java
public Observable<IntegrationAccountAgreementInner> getAsync(String resourceGroupName, String integrationAccountName, String agreementName) { return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, agreementName).map(new Func1<ServiceResponse<IntegrationAccountAgreementInner>, IntegrationAccountAgreementInner>() { @Override public IntegrationAccountAgreementInner call(ServiceResponse<IntegrationAccountAgreementInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "IntegrationAccountAgreementInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "integrationAccountName", ",", "String", "agreementName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", ...
Gets an integration account agreement. @param resourceGroupName The resource group name. @param integrationAccountName The integration account name. @param agreementName The integration account agreement name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the IntegrationAccountAgreementInner object
[ "Gets", "an", "integration", "account", "agreement", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/AgreementsInner.java#L381-L388
hazelcast/hazelcast
hazelcast-client/src/main/java/com/hazelcast/client/config/ClientConfig.java
ClientConfig.setFlakeIdGeneratorConfigMap
public ClientConfig setFlakeIdGeneratorConfigMap(Map<String, ClientFlakeIdGeneratorConfig> map) { Preconditions.isNotNull(map, "flakeIdGeneratorConfigMap"); flakeIdGeneratorConfigMap.clear(); flakeIdGeneratorConfigMap.putAll(map); for (Entry<String, ClientFlakeIdGeneratorConfig> entry : map.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
java
public ClientConfig setFlakeIdGeneratorConfigMap(Map<String, ClientFlakeIdGeneratorConfig> map) { Preconditions.isNotNull(map, "flakeIdGeneratorConfigMap"); flakeIdGeneratorConfigMap.clear(); flakeIdGeneratorConfigMap.putAll(map); for (Entry<String, ClientFlakeIdGeneratorConfig> entry : map.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
[ "public", "ClientConfig", "setFlakeIdGeneratorConfigMap", "(", "Map", "<", "String", ",", "ClientFlakeIdGeneratorConfig", ">", "map", ")", "{", "Preconditions", ".", "isNotNull", "(", "map", ",", "\"flakeIdGeneratorConfigMap\"", ")", ";", "flakeIdGeneratorConfigMap", "....
Sets the map of {@link FlakeIdGenerator} configurations, mapped by config name. The config name may be a pattern with which the configuration will be obtained in the future. @param map the FlakeIdGenerator configuration map to set @return this config instance
[ "Sets", "the", "map", "of", "{", "@link", "FlakeIdGenerator", "}", "configurations", "mapped", "by", "config", "name", ".", "The", "config", "name", "may", "be", "a", "pattern", "with", "which", "the", "configuration", "will", "be", "obtained", "in", "the", ...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast-client/src/main/java/com/hazelcast/client/config/ClientConfig.java#L505-L513
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/api/GroupsMembersApi.java
GroupsMembersApi.getList
public Members getList(String groupId, EnumSet<JinxConstants.MemberType> memberTypes, int perPage, int page) throws JinxException { JinxUtils.validateParams(groupId); Map<String, String> params = new TreeMap<String, String>(); params.put("method", "flickr.groups.members.getList"); params.put("group_id", groupId); if (memberTypes != null) { StringBuilder sb = new StringBuilder(); for (JinxConstants.MemberType type : memberTypes) { sb.append(JinxUtils.memberTypeToMemberTypeId(type)).append(','); } params.put("membertypes", sb.deleteCharAt(sb.length() - 1).toString()); } if (perPage > 0) { params.put("per_page", Integer.toString(perPage)); } if (page > 0) { params.put("page", Integer.toString(page)); } return jinx.flickrGet(params, Members.class); }
java
public Members getList(String groupId, EnumSet<JinxConstants.MemberType> memberTypes, int perPage, int page) throws JinxException { JinxUtils.validateParams(groupId); Map<String, String> params = new TreeMap<String, String>(); params.put("method", "flickr.groups.members.getList"); params.put("group_id", groupId); if (memberTypes != null) { StringBuilder sb = new StringBuilder(); for (JinxConstants.MemberType type : memberTypes) { sb.append(JinxUtils.memberTypeToMemberTypeId(type)).append(','); } params.put("membertypes", sb.deleteCharAt(sb.length() - 1).toString()); } if (perPage > 0) { params.put("per_page", Integer.toString(perPage)); } if (page > 0) { params.put("page", Integer.toString(page)); } return jinx.flickrGet(params, Members.class); }
[ "public", "Members", "getList", "(", "String", "groupId", ",", "EnumSet", "<", "JinxConstants", ".", "MemberType", ">", "memberTypes", ",", "int", "perPage", ",", "int", "page", ")", "throws", "JinxException", "{", "JinxUtils", ".", "validateParams", "(", "gro...
<br> Get a list of the members of a group. The call must be signed on behalf of a Flickr member, and the ability to see the group membership will be determined by the Flickr member's group privileges. <br> This method requires authentication with 'read' permission. @param groupId (Required) Return a list of members for this group. The group must be viewable by the Flickr member on whose behalf the API call is made. @param memberTypes (Optional) Return only these member types. If null, return all member types. (Returning super rare member type "1: narwhal" isn't supported by this API method) @param perPage number of members to return per page. If this argument is less than 1, it defaults to 100. The maximum allowed value is 500. @param page page of results to return. If this argument is less than 1, it defaults to 1. @return members object containing metadata and a list of members. @throws JinxException if required parameters are null or empty, or if there are any errors. @see <a href="https://www.flickr.com/services/api/flickr.groups.members.getList.html">flickr.groups.members.getList</a>
[ "<br", ">", "Get", "a", "list", "of", "the", "members", "of", "a", "group", ".", "The", "call", "must", "be", "signed", "on", "behalf", "of", "a", "Flickr", "member", "and", "the", "ability", "to", "see", "the", "group", "membership", "will", "be", "...
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/GroupsMembersApi.java#L59-L78
aalmiray/Json-lib
src/main/java/net/sf/json/JsonConfig.java
JsonConfig.unregisterJsonValueProcessor
public void unregisterJsonValueProcessor( Class beanClass, String key ) { if( beanClass != null && key != null ) { beanKeyMap.remove( beanClass, key ); } }
java
public void unregisterJsonValueProcessor( Class beanClass, String key ) { if( beanClass != null && key != null ) { beanKeyMap.remove( beanClass, key ); } }
[ "public", "void", "unregisterJsonValueProcessor", "(", "Class", "beanClass", ",", "String", "key", ")", "{", "if", "(", "beanClass", "!=", "null", "&&", "key", "!=", "null", ")", "{", "beanKeyMap", ".", "remove", "(", "beanClass", ",", "key", ")", ";", "...
Removes a JsonValueProcessor.<br> [Java -&gt; JSON] @param beanClass the class to which the property may belong @param key the name of the property which may belong to the target class
[ "Removes", "a", "JsonValueProcessor", ".", "<br", ">", "[", "Java", "-", "&gt", ";", "JSON", "]" ]
train
https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/JsonConfig.java#L1378-L1382
looly/hutool
hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java
DateUtil.truncate
public static DateTime truncate(Date date, DateField dateField) { return new DateTime(truncate(calendar(date), dateField)); }
java
public static DateTime truncate(Date date, DateField dateField) { return new DateTime(truncate(calendar(date), dateField)); }
[ "public", "static", "DateTime", "truncate", "(", "Date", "date", ",", "DateField", "dateField", ")", "{", "return", "new", "DateTime", "(", "truncate", "(", "calendar", "(", "date", ")", ",", "dateField", ")", ")", ";", "}" ]
修改日期为某个时间字段起始时间 @param date {@link Date} @param dateField 时间字段 @return {@link DateTime} @since 4.5.7
[ "修改日期为某个时间字段起始时间" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java#L755-L757
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/journal/EventJournalReadOperation.java
EventJournalReadOperation.clampToBounds
private long clampToBounds(EventJournal<J> journal, int partitionId, long requestedSequence) { final long oldestSequence = journal.oldestSequence(namespace, partitionId); final long newestSequence = journal.newestSequence(namespace, partitionId); // fast forward if late and no store is configured if (requestedSequence < oldestSequence && !journal.isPersistenceEnabled(namespace, partitionId)) { return oldestSequence; } // jump back if too far in future if (requestedSequence > newestSequence + 1) { return newestSequence + 1; } return requestedSequence; }
java
private long clampToBounds(EventJournal<J> journal, int partitionId, long requestedSequence) { final long oldestSequence = journal.oldestSequence(namespace, partitionId); final long newestSequence = journal.newestSequence(namespace, partitionId); // fast forward if late and no store is configured if (requestedSequence < oldestSequence && !journal.isPersistenceEnabled(namespace, partitionId)) { return oldestSequence; } // jump back if too far in future if (requestedSequence > newestSequence + 1) { return newestSequence + 1; } return requestedSequence; }
[ "private", "long", "clampToBounds", "(", "EventJournal", "<", "J", ">", "journal", ",", "int", "partitionId", ",", "long", "requestedSequence", ")", "{", "final", "long", "oldestSequence", "=", "journal", ".", "oldestSequence", "(", "namespace", ",", "partitionI...
Checks if the provided {@code requestedSequence} is within bounds of the oldest and newest sequence in the event journal. If the {@code requestedSequence} is too old or too new, it will return the current oldest or newest journal sequence. This method can be used for a loss-tolerant reader when trying to avoid a {@link com.hazelcast.ringbuffer.StaleSequenceException}. @param journal the event journal @param partitionId the partition ID to read @param requestedSequence the requested sequence to read @return the bounded journal sequence
[ "Checks", "if", "the", "provided", "{", "@code", "requestedSequence", "}", "is", "within", "bounds", "of", "the", "oldest", "and", "newest", "sequence", "in", "the", "event", "journal", ".", "If", "the", "{", "@code", "requestedSequence", "}", "is", "too", ...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/journal/EventJournalReadOperation.java#L201-L215
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/line/ConnectLinesGrid.java
ConnectLinesGrid.findBestCompatible
private int findBestCompatible( LineSegment2D_F32 target , List<LineSegment2D_F32> candidates , int start ) { int bestIndex = -1; double bestDistance = Double.MAX_VALUE; int bestFarthest = 0; float targetAngle = UtilAngle.atanSafe(target.slopeY(),target.slopeX()); float cos = (float)Math.cos(targetAngle); float sin = (float)Math.sin(targetAngle); for( int i = start; i < candidates.size(); i++ ) { LineSegment2D_F32 c = candidates.get(i); float angle = UtilAngle.atanSafe(c.slopeY(),c.slopeX()); // see if the two lines have the same slope if( UtilAngle.distHalf(targetAngle,angle) > lineSlopeAngleTol ) continue; // see the distance the two lines are apart and if it could be the best line closestFarthestPoints(target, c); // two closest end points Point2D_F32 pt0 = closestIndex < 2 ? target.a : target.b; Point2D_F32 pt1 = (closestIndex %2) == 0 ? c.a : c.b; float xx = pt1.x-pt0.x; float yy = pt1.y-pt0.y; float distX = Math.abs(cos*xx - sin*yy); float distY = Math.abs(cos*yy + sin*xx); if( distX >= bestDistance || distX > parallelTol || distY > tangentTol ) continue; // check the angle of the combined line pt0 = farthestIndex < 2 ? target.a : target.b; pt1 = (farthestIndex %2) == 0 ? c.a : c.b; float angleCombined = UtilAngle.atanSafe(pt1.y-pt0.y,pt1.x-pt0.x); if( UtilAngle.distHalf(targetAngle,angleCombined) <= lineSlopeAngleTol ) { bestDistance = distX; bestIndex = i; bestFarthest = farthestIndex; } } if( bestDistance < parallelTol) { farthestIndex = bestFarthest; return bestIndex; } return -1; }
java
private int findBestCompatible( LineSegment2D_F32 target , List<LineSegment2D_F32> candidates , int start ) { int bestIndex = -1; double bestDistance = Double.MAX_VALUE; int bestFarthest = 0; float targetAngle = UtilAngle.atanSafe(target.slopeY(),target.slopeX()); float cos = (float)Math.cos(targetAngle); float sin = (float)Math.sin(targetAngle); for( int i = start; i < candidates.size(); i++ ) { LineSegment2D_F32 c = candidates.get(i); float angle = UtilAngle.atanSafe(c.slopeY(),c.slopeX()); // see if the two lines have the same slope if( UtilAngle.distHalf(targetAngle,angle) > lineSlopeAngleTol ) continue; // see the distance the two lines are apart and if it could be the best line closestFarthestPoints(target, c); // two closest end points Point2D_F32 pt0 = closestIndex < 2 ? target.a : target.b; Point2D_F32 pt1 = (closestIndex %2) == 0 ? c.a : c.b; float xx = pt1.x-pt0.x; float yy = pt1.y-pt0.y; float distX = Math.abs(cos*xx - sin*yy); float distY = Math.abs(cos*yy + sin*xx); if( distX >= bestDistance || distX > parallelTol || distY > tangentTol ) continue; // check the angle of the combined line pt0 = farthestIndex < 2 ? target.a : target.b; pt1 = (farthestIndex %2) == 0 ? c.a : c.b; float angleCombined = UtilAngle.atanSafe(pt1.y-pt0.y,pt1.x-pt0.x); if( UtilAngle.distHalf(targetAngle,angleCombined) <= lineSlopeAngleTol ) { bestDistance = distX; bestIndex = i; bestFarthest = farthestIndex; } } if( bestDistance < parallelTol) { farthestIndex = bestFarthest; return bestIndex; } return -1; }
[ "private", "int", "findBestCompatible", "(", "LineSegment2D_F32", "target", ",", "List", "<", "LineSegment2D_F32", ">", "candidates", ",", "int", "start", ")", "{", "int", "bestIndex", "=", "-", "1", ";", "double", "bestDistance", "=", "Double", ".", "MAX_VALU...
Searches for a line in the list which the target is compatible with and can be connected to. @param target Line being connected to. @param candidates List of candidate lines. @param start First index in the candidate list it should start searching at. @return Index of the candidate it can connect to. -1 if there is no match.
[ "Searches", "for", "a", "line", "in", "the", "list", "which", "the", "target", "is", "compatible", "with", "and", "can", "be", "connected", "to", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/line/ConnectLinesGrid.java#L207-L263
SeleniumHQ/fluent-selenium
java/src/main/java/org/seleniumhq/selenium/fluent/FluentSelect.java
FluentSelect.selectByIndex
public FluentSelect selectByIndex(final int index) { executeAndWrapReThrowIfNeeded(new SelectByIndex(index), Context.singular(context, "selectByIndex", null, index), true); return new FluentSelect(super.delegate, currentElement.getFound(), this.context, monitor, booleanInsteadOfNotFoundException); }
java
public FluentSelect selectByIndex(final int index) { executeAndWrapReThrowIfNeeded(new SelectByIndex(index), Context.singular(context, "selectByIndex", null, index), true); return new FluentSelect(super.delegate, currentElement.getFound(), this.context, monitor, booleanInsteadOfNotFoundException); }
[ "public", "FluentSelect", "selectByIndex", "(", "final", "int", "index", ")", "{", "executeAndWrapReThrowIfNeeded", "(", "new", "SelectByIndex", "(", "index", ")", ",", "Context", ".", "singular", "(", "context", ",", "\"selectByIndex\"", ",", "null", ",", "inde...
Select the option at the given index. This is done by examing the "index" attribute of an element, and not merely by counting. @param index The option at this index will be selected
[ "Select", "the", "option", "at", "the", "given", "index", ".", "This", "is", "done", "by", "examing", "the", "index", "attribute", "of", "an", "element", "and", "not", "merely", "by", "counting", "." ]
train
https://github.com/SeleniumHQ/fluent-selenium/blob/fcb171471a7d1abb2800bcbca21b3ae3e6c12472/java/src/main/java/org/seleniumhq/selenium/fluent/FluentSelect.java#L99-L102
mygreen/excel-cellformatter
src/main/java/com/github/mygreen/cellformatter/POICellFormatter.java
POICellFormatter.format
public CellFormatResult format(final Cell cell, final Locale locale) { if(cell == null) { return createBlankCellResult(); } final Locale runtimeLocale = locale != null ? locale : Locale.getDefault(); switch(cell.getCellTypeEnum()) { case BLANK: if(isConsiderMergedCell()) { // 結合しているセルの場合、左上のセル以外に値が設定されている場合がある。 return getMergedCellValue(cell, runtimeLocale); } else { return createBlankCellResult(); } case BOOLEAN: return getCellValue(cell, runtimeLocale); case STRING: return getCellValue(cell, runtimeLocale); case NUMERIC: return getCellValue(cell, runtimeLocale); case FORMULA: return getFormulaCellValue(cell, runtimeLocale); case ERROR: return getErrorCellValue(cell, runtimeLocale); default: final CellFormatResult result = new CellFormatResult(); result.setCellType(FormatCellType.Unknown); result.setText(""); return result; } }
java
public CellFormatResult format(final Cell cell, final Locale locale) { if(cell == null) { return createBlankCellResult(); } final Locale runtimeLocale = locale != null ? locale : Locale.getDefault(); switch(cell.getCellTypeEnum()) { case BLANK: if(isConsiderMergedCell()) { // 結合しているセルの場合、左上のセル以外に値が設定されている場合がある。 return getMergedCellValue(cell, runtimeLocale); } else { return createBlankCellResult(); } case BOOLEAN: return getCellValue(cell, runtimeLocale); case STRING: return getCellValue(cell, runtimeLocale); case NUMERIC: return getCellValue(cell, runtimeLocale); case FORMULA: return getFormulaCellValue(cell, runtimeLocale); case ERROR: return getErrorCellValue(cell, runtimeLocale); default: final CellFormatResult result = new CellFormatResult(); result.setCellType(FormatCellType.Unknown); result.setText(""); return result; } }
[ "public", "CellFormatResult", "format", "(", "final", "Cell", "cell", ",", "final", "Locale", "locale", ")", "{", "if", "(", "cell", "==", "null", ")", "{", "return", "createBlankCellResult", "(", ")", ";", "}", "final", "Locale", "runtimeLocale", "=", "lo...
ロケールを指定してセルの値を取得する @since 0.3 @param cell フォーマット対象のセル @param locale locale フォーマットしたロケール。nullでも可能。 ロケールに依存する場合、指定したロケールにより自動的に切り替わります。 @return フォーマット結果。cellがnullの場合、空セルとして値を返す。
[ "ロケールを指定してセルの値を取得する" ]
train
https://github.com/mygreen/excel-cellformatter/blob/e802af273d49889500591e03799c9262cbf29185/src/main/java/com/github/mygreen/cellformatter/POICellFormatter.java#L127-L165
azkaban/azkaban
azkaban-exec-server/src/main/java/azkaban/dag/DagBuilder.java
DagBuilder.createNode
public Node createNode(final String name, final NodeProcessor nodeProcessor) { checkIsBuilt(); if (this.nameToNodeMap.get(name) != null) { throw new DagException(String.format("Node names in %s need to be unique. The name " + "(%s) already exists.", this, name)); } final Node node = new Node(name, nodeProcessor, this.dag); this.nameToNodeMap.put(name, node); return node; }
java
public Node createNode(final String name, final NodeProcessor nodeProcessor) { checkIsBuilt(); if (this.nameToNodeMap.get(name) != null) { throw new DagException(String.format("Node names in %s need to be unique. The name " + "(%s) already exists.", this, name)); } final Node node = new Node(name, nodeProcessor, this.dag); this.nameToNodeMap.put(name, node); return node; }
[ "public", "Node", "createNode", "(", "final", "String", "name", ",", "final", "NodeProcessor", "nodeProcessor", ")", "{", "checkIsBuilt", "(", ")", ";", "if", "(", "this", ".", "nameToNodeMap", ".", "get", "(", "name", ")", "!=", "null", ")", "{", "throw...
Creates a new node and adds it to the DagBuilder. @param name name of the node @param nodeProcessor node processor associated with this node @return a new node @throws DagException if the name is not unique in the DAG.
[ "Creates", "a", "new", "node", "and", "adds", "it", "to", "the", "DagBuilder", "." ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-exec-server/src/main/java/azkaban/dag/DagBuilder.java#L65-L76
beangle/beangle3
commons/core/src/main/java/org/beangle/commons/lang/Strings.java
Strings.isEqualSeq
public static boolean isEqualSeq(final String first, final String second, final String delimiter) { if (isNotEmpty(first) && isNotEmpty(second)) { String[] firstWords = split(first, delimiter); Set<String> firstSet = CollectUtils.newHashSet(); for (int i = 0; i < firstWords.length; i++) { firstSet.add(firstWords[i]); } String[] secondWords = split(second, delimiter); Set<String> secondSet = CollectUtils.newHashSet(); for (int i = 0; i < secondWords.length; i++) { secondSet.add(secondWords[i]); } return firstSet.equals(secondSet); } else { return isEmpty(first) & isEmpty(second); } }
java
public static boolean isEqualSeq(final String first, final String second, final String delimiter) { if (isNotEmpty(first) && isNotEmpty(second)) { String[] firstWords = split(first, delimiter); Set<String> firstSet = CollectUtils.newHashSet(); for (int i = 0; i < firstWords.length; i++) { firstSet.add(firstWords[i]); } String[] secondWords = split(second, delimiter); Set<String> secondSet = CollectUtils.newHashSet(); for (int i = 0; i < secondWords.length; i++) { secondSet.add(secondWords[i]); } return firstSet.equals(secondSet); } else { return isEmpty(first) & isEmpty(second); } }
[ "public", "static", "boolean", "isEqualSeq", "(", "final", "String", "first", ",", "final", "String", "second", ",", "final", "String", "delimiter", ")", "{", "if", "(", "isNotEmpty", "(", "first", ")", "&&", "isNotEmpty", "(", "second", ")", ")", "{", "...
判断两个","逗号相隔的字符串中的单词是否完全等同. @param first a {@link java.lang.String} object. @param second a {@link java.lang.String} object. @param delimiter a {@link java.lang.String} object. @return a boolean.
[ "判断两个", "逗号相隔的字符串中的单词是否完全等同", "." ]
train
https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/lang/Strings.java#L357-L373
facebookarchive/swift
swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java
ThriftCodecByteCodeGenerator.constructStructInstance
private LocalVariableDefinition constructStructInstance(MethodDefinition read, Map<Short, LocalVariableDefinition> structData) { LocalVariableDefinition instance = read.addLocalVariable(structType, "instance"); // create the new instance (or builder) if (metadata.getBuilderClass() == null) { read.newObject(structType).dup(); } else { read.newObject(metadata.getBuilderClass()).dup(); } // invoke constructor ThriftConstructorInjection constructor = metadata.getConstructorInjection().get(); // push parameters on stack for (ThriftParameterInjection parameter : constructor.getParameters()) { read.loadVariable(structData.get(parameter.getId())); } // invoke constructor read.invokeConstructor(constructor.getConstructor()) .storeVariable(instance); return instance; }
java
private LocalVariableDefinition constructStructInstance(MethodDefinition read, Map<Short, LocalVariableDefinition> structData) { LocalVariableDefinition instance = read.addLocalVariable(structType, "instance"); // create the new instance (or builder) if (metadata.getBuilderClass() == null) { read.newObject(structType).dup(); } else { read.newObject(metadata.getBuilderClass()).dup(); } // invoke constructor ThriftConstructorInjection constructor = metadata.getConstructorInjection().get(); // push parameters on stack for (ThriftParameterInjection parameter : constructor.getParameters()) { read.loadVariable(structData.get(parameter.getId())); } // invoke constructor read.invokeConstructor(constructor.getConstructor()) .storeVariable(instance); return instance; }
[ "private", "LocalVariableDefinition", "constructStructInstance", "(", "MethodDefinition", "read", ",", "Map", "<", "Short", ",", "LocalVariableDefinition", ">", "structData", ")", "{", "LocalVariableDefinition", "instance", "=", "read", ".", "addLocalVariable", "(", "st...
Defines the code to construct the struct (or builder) instance and stores it in a local variable.
[ "Defines", "the", "code", "to", "construct", "the", "struct", "(", "or", "builder", ")", "instance", "and", "stores", "it", "in", "a", "local", "variable", "." ]
train
https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L425-L447
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java
ReviewsImpl.getVideoFramesAsync
public Observable<Frames> getVideoFramesAsync(String teamName, String reviewId, GetVideoFramesOptionalParameter getVideoFramesOptionalParameter) { return getVideoFramesWithServiceResponseAsync(teamName, reviewId, getVideoFramesOptionalParameter).map(new Func1<ServiceResponse<Frames>, Frames>() { @Override public Frames call(ServiceResponse<Frames> response) { return response.body(); } }); }
java
public Observable<Frames> getVideoFramesAsync(String teamName, String reviewId, GetVideoFramesOptionalParameter getVideoFramesOptionalParameter) { return getVideoFramesWithServiceResponseAsync(teamName, reviewId, getVideoFramesOptionalParameter).map(new Func1<ServiceResponse<Frames>, Frames>() { @Override public Frames call(ServiceResponse<Frames> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Frames", ">", "getVideoFramesAsync", "(", "String", "teamName", ",", "String", "reviewId", ",", "GetVideoFramesOptionalParameter", "getVideoFramesOptionalParameter", ")", "{", "return", "getVideoFramesWithServiceResponseAsync", "(", "teamName", ...
The reviews created would show up for Reviewers on your team. As Reviewers complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) on the specified CallBackEndpoint. &lt;h3&gt;CallBack Schemas &lt;/h3&gt; &lt;h4&gt;Review Completion CallBack Sample&lt;/h4&gt; &lt;p&gt; {&lt;br/&gt; "ReviewId": "&lt;Review Id&gt;",&lt;br/&gt; "ModifiedOn": "2016-10-11T22:36:32.9934851Z",&lt;br/&gt; "ModifiedBy": "&lt;Name of the Reviewer&gt;",&lt;br/&gt; "CallBackType": "Review",&lt;br/&gt; "ContentId": "&lt;The ContentId that was specified input&gt;",&lt;br/&gt; "Metadata": {&lt;br/&gt; "adultscore": "0.xxx",&lt;br/&gt; "a": "False",&lt;br/&gt; "racyscore": "0.xxx",&lt;br/&gt; "r": "True"&lt;br/&gt; },&lt;br/&gt; "ReviewerResultTags": {&lt;br/&gt; "a": "False",&lt;br/&gt; "r": "True"&lt;br/&gt; }&lt;br/&gt; }&lt;br/&gt; &lt;/p&gt;. @param teamName Your team name. @param reviewId Id of the review. @param getVideoFramesOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the Frames object
[ "The", "reviews", "created", "would", "show", "up", "for", "Reviewers", "on", "your", "team", ".", "As", "Reviewers", "complete", "reviewing", "results", "of", "the", "Review", "would", "be", "POSTED", "(", "i", ".", "e", ".", "HTTP", "POST", ")", "on", ...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java#L1411-L1418
XiaoMi/chronos
chronos-server/src/main/java/com/xiaomi/infra/chronos/zookeeper/FailoverWatcher.java
FailoverWatcher.connectZooKeeper
protected void connectZooKeeper() throws IOException { LOG.info("Connecting ZooKeeper " + zkQuorum); for (int i = 0; i <= connectRetryTimes; i++) { try { zooKeeper = new ZooKeeper(zkQuorum, sessionTimeout, this); break; } catch (IOException e) { if (i == connectRetryTimes) { throw new IOException("Can't connect ZooKeeper after retrying", e); } LOG.error("Exception to connect ZooKeeper, retry " + (i + 1) + " times"); } } }
java
protected void connectZooKeeper() throws IOException { LOG.info("Connecting ZooKeeper " + zkQuorum); for (int i = 0; i <= connectRetryTimes; i++) { try { zooKeeper = new ZooKeeper(zkQuorum, sessionTimeout, this); break; } catch (IOException e) { if (i == connectRetryTimes) { throw new IOException("Can't connect ZooKeeper after retrying", e); } LOG.error("Exception to connect ZooKeeper, retry " + (i + 1) + " times"); } } }
[ "protected", "void", "connectZooKeeper", "(", ")", "throws", "IOException", "{", "LOG", ".", "info", "(", "\"Connecting ZooKeeper \"", "+", "zkQuorum", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "connectRetryTimes", ";", "i", "++", ")", ...
Connect with ZooKeeper with retries. @throws IOException when error to construct ZooKeeper object after retrying
[ "Connect", "with", "ZooKeeper", "with", "retries", "." ]
train
https://github.com/XiaoMi/chronos/blob/92e4a30c98947e87aba47ea88c944a56505a4ec0/chronos-server/src/main/java/com/xiaomi/infra/chronos/zookeeper/FailoverWatcher.java#L94-L108
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/description/type/TypeVariableToken.java
TypeVariableToken.of
public static TypeVariableToken of(TypeDescription.Generic typeVariable, ElementMatcher<? super TypeDescription> matcher) { return new TypeVariableToken(typeVariable.getSymbol(), typeVariable.getUpperBounds().accept(new TypeDescription.Generic.Visitor.Substitutor.ForDetachment(matcher)), typeVariable.getDeclaredAnnotations()); }
java
public static TypeVariableToken of(TypeDescription.Generic typeVariable, ElementMatcher<? super TypeDescription> matcher) { return new TypeVariableToken(typeVariable.getSymbol(), typeVariable.getUpperBounds().accept(new TypeDescription.Generic.Visitor.Substitutor.ForDetachment(matcher)), typeVariable.getDeclaredAnnotations()); }
[ "public", "static", "TypeVariableToken", "of", "(", "TypeDescription", ".", "Generic", "typeVariable", ",", "ElementMatcher", "<", "?", "super", "TypeDescription", ">", "matcher", ")", "{", "return", "new", "TypeVariableToken", "(", "typeVariable", ".", "getSymbol",...
Transforms a type variable into a type variable token with its bounds detached. @param typeVariable A type variable in its attached state. @param matcher A matcher that identifies types to detach from the upper bound types. @return A token representing the detached type variable.
[ "Transforms", "a", "type", "variable", "into", "a", "type", "variable", "token", "with", "its", "bounds", "detached", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/description/type/TypeVariableToken.java#L76-L80
alkacon/opencms-core
src-gwt/org/opencms/ade/sitemap/client/hoverbar/CmsSitemapHoverbar.java
CmsSitemapHoverbar.installOn
public static CmsSitemapHoverbar installOn( CmsSitemapController controller, CmsTreeItem treeItem, Collection<Widget> buttons) { CmsSitemapHoverbar hoverbar = new CmsSitemapHoverbar(controller, buttons); installHoverbar(hoverbar, treeItem.getListItemWidget()); return hoverbar; }
java
public static CmsSitemapHoverbar installOn( CmsSitemapController controller, CmsTreeItem treeItem, Collection<Widget> buttons) { CmsSitemapHoverbar hoverbar = new CmsSitemapHoverbar(controller, buttons); installHoverbar(hoverbar, treeItem.getListItemWidget()); return hoverbar; }
[ "public", "static", "CmsSitemapHoverbar", "installOn", "(", "CmsSitemapController", "controller", ",", "CmsTreeItem", "treeItem", ",", "Collection", "<", "Widget", ">", "buttons", ")", "{", "CmsSitemapHoverbar", "hoverbar", "=", "new", "CmsSitemapHoverbar", "(", "cont...
Installs a hover bar for the given item widget.<p> @param controller the controller @param treeItem the item to hover @param buttons the buttons @return the hover bar instance
[ "Installs", "a", "hover", "bar", "for", "the", "given", "item", "widget", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/hoverbar/CmsSitemapHoverbar.java#L233-L241
EdwardRaff/JSAT
JSAT/src/jsat/text/HashedTextDataLoader.java
HashedTextDataLoader.addOriginalDocument
protected int addOriginalDocument(String text) { if(noMoreAdding) throw new RuntimeException("Initial data set has been finalized"); StringBuilder localWorkSpace = workSpace.get(); List<String> localStorageSpace = storageSpace.get(); Map<String, Integer> localWordCounts = wordCounts.get(); if(localWorkSpace == null) { localWorkSpace = new StringBuilder(); localStorageSpace = new ArrayList<String>(); localWordCounts = new LinkedHashMap<String, Integer>(); workSpace.set(localWorkSpace); storageSpace.set(localStorageSpace); wordCounts.set(localWordCounts); } localWorkSpace.setLength(0); localStorageSpace.clear(); tokenizer.tokenize(text, localWorkSpace, localStorageSpace); for(String word : localStorageSpace) { Integer count = localWordCounts.get(word); if(count == null) localWordCounts.put(word, 1); else localWordCounts.put(word, count+1); } SparseVector vec = new SparseVector(dimensionSize, localWordCounts.size()); for(Iterator<Entry<String, Integer>> iter = localWordCounts.entrySet().iterator(); iter.hasNext();) { Entry<String, Integer> entry = iter.next(); String word = entry.getKey(); //XXX This code generates a hashcode and then computes the absolute value of that hashcode. If the hashcode is Integer.MIN_VALUE, then the result will be negative as well (since Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE). int index = Math.abs(word.hashCode()) % dimensionSize; vec.set(index, entry.getValue()); termDocumentFrequencys.addAndGet(index, entry.getValue()); iter.remove(); } synchronized(vectors) { vectors.add(vec); return documents++; } }
java
protected int addOriginalDocument(String text) { if(noMoreAdding) throw new RuntimeException("Initial data set has been finalized"); StringBuilder localWorkSpace = workSpace.get(); List<String> localStorageSpace = storageSpace.get(); Map<String, Integer> localWordCounts = wordCounts.get(); if(localWorkSpace == null) { localWorkSpace = new StringBuilder(); localStorageSpace = new ArrayList<String>(); localWordCounts = new LinkedHashMap<String, Integer>(); workSpace.set(localWorkSpace); storageSpace.set(localStorageSpace); wordCounts.set(localWordCounts); } localWorkSpace.setLength(0); localStorageSpace.clear(); tokenizer.tokenize(text, localWorkSpace, localStorageSpace); for(String word : localStorageSpace) { Integer count = localWordCounts.get(word); if(count == null) localWordCounts.put(word, 1); else localWordCounts.put(word, count+1); } SparseVector vec = new SparseVector(dimensionSize, localWordCounts.size()); for(Iterator<Entry<String, Integer>> iter = localWordCounts.entrySet().iterator(); iter.hasNext();) { Entry<String, Integer> entry = iter.next(); String word = entry.getKey(); //XXX This code generates a hashcode and then computes the absolute value of that hashcode. If the hashcode is Integer.MIN_VALUE, then the result will be negative as well (since Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE). int index = Math.abs(word.hashCode()) % dimensionSize; vec.set(index, entry.getValue()); termDocumentFrequencys.addAndGet(index, entry.getValue()); iter.remove(); } synchronized(vectors) { vectors.add(vec); return documents++; } }
[ "protected", "int", "addOriginalDocument", "(", "String", "text", ")", "{", "if", "(", "noMoreAdding", ")", "throw", "new", "RuntimeException", "(", "\"Initial data set has been finalized\"", ")", ";", "StringBuilder", "localWorkSpace", "=", "workSpace", ".", "get", ...
To be called by the {@link #initialLoad() } method. It will take in the text and add a new document vector to the data set. Once all text documents have been loaded, this method should never be called again. <br> This method is thread safe. @param text the text of the document to add @return the index of the created document for the given text. Starts from zero and counts up.
[ "To", "be", "called", "by", "the", "{", "@link", "#initialLoad", "()", "}", "method", ".", "It", "will", "take", "in", "the", "text", "and", "add", "a", "new", "document", "vector", "to", "the", "data", "set", ".", "Once", "all", "text", "documents", ...
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/text/HashedTextDataLoader.java#L116-L165
m-m-m/util
gwt/src/main/java/net/sf/mmm/util/pojo/descriptor/impl/rebind/PojoDescriptorGenerator.java
PojoDescriptorGenerator.generateConstructor
protected void generateConstructor(SourceWriter sourceWriter, String simpleName, JClassType inputType, PojoDescriptor<?> pojoDescriptor, GeneratorContext context) { generateSourcePublicConstructorDeclaration(sourceWriter, simpleName); sourceWriter.print("super(new "); sourceWriter.print(SimpleGenericTypeLimited.class.getSimpleName()); sourceWriter.print("("); sourceWriter.print(inputType.getName()); sourceWriter.print(".class), "); sourceWriter.print(AbstractPojoDescriptorBuilderLimited.class.getSimpleName()); sourceWriter.println(".getInstance());"); // local variable for property descriptor sourceWriter.print(PojoPropertyDescriptorImpl.class.getSimpleName()); sourceWriter.println(" propertyDescriptor;"); JClassType superType = getConfiguration().getSupportedSuperType(inputType, context.getTypeOracle()); StatefulPropertyGenerator state = new StatefulPropertyGenerator(sourceWriter, superType); for (PojoPropertyDescriptor propertyDescriptor : pojoDescriptor.getPropertyDescriptors()) { state.generatePropertyDescriptorBlock(propertyDescriptor); } generateSourceCloseBlock(sourceWriter); }
java
protected void generateConstructor(SourceWriter sourceWriter, String simpleName, JClassType inputType, PojoDescriptor<?> pojoDescriptor, GeneratorContext context) { generateSourcePublicConstructorDeclaration(sourceWriter, simpleName); sourceWriter.print("super(new "); sourceWriter.print(SimpleGenericTypeLimited.class.getSimpleName()); sourceWriter.print("("); sourceWriter.print(inputType.getName()); sourceWriter.print(".class), "); sourceWriter.print(AbstractPojoDescriptorBuilderLimited.class.getSimpleName()); sourceWriter.println(".getInstance());"); // local variable for property descriptor sourceWriter.print(PojoPropertyDescriptorImpl.class.getSimpleName()); sourceWriter.println(" propertyDescriptor;"); JClassType superType = getConfiguration().getSupportedSuperType(inputType, context.getTypeOracle()); StatefulPropertyGenerator state = new StatefulPropertyGenerator(sourceWriter, superType); for (PojoPropertyDescriptor propertyDescriptor : pojoDescriptor.getPropertyDescriptors()) { state.generatePropertyDescriptorBlock(propertyDescriptor); } generateSourceCloseBlock(sourceWriter); }
[ "protected", "void", "generateConstructor", "(", "SourceWriter", "sourceWriter", ",", "String", "simpleName", ",", "JClassType", "inputType", ",", "PojoDescriptor", "<", "?", ">", "pojoDescriptor", ",", "GeneratorContext", "context", ")", "{", "generateSourcePublicConst...
Generates the constructor of the {@link Class} to generate. @param sourceWriter is the {@link SourceWriter} where to {@link SourceWriter#print(String) write} the source code to. @param simpleName is the {@link Class#getSimpleName() simple name} of the {@link Class} to generate. @param inputType is the {@link JClassType} reflecting the input-type that triggered the generation via {@link com.google.gwt.core.client.GWT#create(Class)}. @param pojoDescriptor is the {@link PojoDescriptor}. @param context is the {@link GeneratorContext}.
[ "Generates", "the", "constructor", "of", "the", "{", "@link", "Class", "}", "to", "generate", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/gwt/src/main/java/net/sf/mmm/util/pojo/descriptor/impl/rebind/PojoDescriptorGenerator.java#L127-L150
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/ApplicationSession.java
ApplicationSession.updateSchema
public boolean updateSchema(String text, ContentType contentType) { Utils.require(text != null && text.length() > 0, "text"); Utils.require(contentType != null, "contentType"); try { // Send a PUT request to "/_applications/{application}". byte[] body = Utils.toBytes(text); StringBuilder uri = new StringBuilder("/_applications/"); uri.append(Utils.urlEncode(m_appDef.getAppName())); RESTResponse response = m_restClient.sendRequest(HttpMethod.PUT, uri.toString(), contentType, body); m_logger.debug("updateSchema() response: {}", response.toString()); throwIfErrorResponse(response); return true; } catch (Exception e) { throw new RuntimeException(e); } }
java
public boolean updateSchema(String text, ContentType contentType) { Utils.require(text != null && text.length() > 0, "text"); Utils.require(contentType != null, "contentType"); try { // Send a PUT request to "/_applications/{application}". byte[] body = Utils.toBytes(text); StringBuilder uri = new StringBuilder("/_applications/"); uri.append(Utils.urlEncode(m_appDef.getAppName())); RESTResponse response = m_restClient.sendRequest(HttpMethod.PUT, uri.toString(), contentType, body); m_logger.debug("updateSchema() response: {}", response.toString()); throwIfErrorResponse(response); return true; } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "boolean", "updateSchema", "(", "String", "text", ",", "ContentType", "contentType", ")", "{", "Utils", ".", "require", "(", "text", "!=", "null", "&&", "text", ".", "length", "(", ")", ">", "0", ",", "\"text\"", ")", ";", "Utils", ".", "requ...
Update the schema for this session's application with the given definition. The text must be formatted in XML or JSON, as defined by the given content type. True is returned if the update was successful. An exception is thrown if an error occurred. @param text Text of updated schema definition. @param contentType Format of text. Must be {@link ContentType#APPLICATION_JSON} or {@link ContentType#TEXT_XML}. @return True if the schema update was successful.
[ "Update", "the", "schema", "for", "this", "session", "s", "application", "with", "the", "given", "definition", ".", "The", "text", "must", "be", "formatted", "in", "XML", "or", "JSON", "as", "defined", "by", "the", "given", "content", "type", ".", "True", ...
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/ApplicationSession.java#L135-L152
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java
ValueEnforcer.isBetweenInclusive
public static BigInteger isBetweenInclusive (final BigInteger aValue, final String sName, @Nonnull final BigInteger aLowerBoundInclusive, @Nonnull final BigInteger aUpperBoundInclusive) { if (isEnabled ()) return isBetweenInclusive (aValue, () -> sName, aLowerBoundInclusive, aUpperBoundInclusive); return aValue; }
java
public static BigInteger isBetweenInclusive (final BigInteger aValue, final String sName, @Nonnull final BigInteger aLowerBoundInclusive, @Nonnull final BigInteger aUpperBoundInclusive) { if (isEnabled ()) return isBetweenInclusive (aValue, () -> sName, aLowerBoundInclusive, aUpperBoundInclusive); return aValue; }
[ "public", "static", "BigInteger", "isBetweenInclusive", "(", "final", "BigInteger", "aValue", ",", "final", "String", "sName", ",", "@", "Nonnull", "final", "BigInteger", "aLowerBoundInclusive", ",", "@", "Nonnull", "final", "BigInteger", "aUpperBoundInclusive", ")", ...
Check if <code>nValue &ge; nLowerBoundInclusive &amp;&amp; nValue &le; nUpperBoundInclusive</code> @param aValue Value @param sName Name @param aLowerBoundInclusive Lower bound @param aUpperBoundInclusive Upper bound @return The value
[ "Check", "if", "<code", ">", "nValue", "&ge", ";", "nLowerBoundInclusive", "&amp", ";", "&amp", ";", "nValue", "&le", ";", "nUpperBoundInclusive<", "/", "code", ">" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L2616-L2624
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/tableset/DistributedTableSerializer.java
DistributedTableSerializer.loadFromNode
private Set<Long> loadFromNode(String path, OutputStream out) throws KeeperException.NoNodeException { try { // Get the cached representation of this table byte[] data = _curator.getData().forPath(path); DataInputStream in = new DataInputStream(new ByteArrayInputStream(data)); int uuidCountOrExceptionCode = in.readInt(); // A negative first integer indicates an exception condition. if (uuidCountOrExceptionCode < 0) { String exceptionJson = new String(data, 4, data.length - 4, Charsets.UTF_8); switch (uuidCountOrExceptionCode) { case UNKNOWN_TABLE: throw JsonHelper.fromJson(exceptionJson, UnknownTableException.class); case DROPPED_TABLE: throw JsonHelper.fromJson(exceptionJson, DroppedTableException.class); } } // Load the UUIDs for this table Set<Long> uuids = Sets.newHashSet(); for (int i=0; i < uuidCountOrExceptionCode; i++) { uuids.add(in.readLong()); } // Copy the remaining bytes as the content ByteStreams.copy(in, out); return uuids; } catch (Throwable t) { Throwables.propagateIfInstanceOf(t, KeeperException.NoNodeException.class); throw Throwables.propagate(t); } }
java
private Set<Long> loadFromNode(String path, OutputStream out) throws KeeperException.NoNodeException { try { // Get the cached representation of this table byte[] data = _curator.getData().forPath(path); DataInputStream in = new DataInputStream(new ByteArrayInputStream(data)); int uuidCountOrExceptionCode = in.readInt(); // A negative first integer indicates an exception condition. if (uuidCountOrExceptionCode < 0) { String exceptionJson = new String(data, 4, data.length - 4, Charsets.UTF_8); switch (uuidCountOrExceptionCode) { case UNKNOWN_TABLE: throw JsonHelper.fromJson(exceptionJson, UnknownTableException.class); case DROPPED_TABLE: throw JsonHelper.fromJson(exceptionJson, DroppedTableException.class); } } // Load the UUIDs for this table Set<Long> uuids = Sets.newHashSet(); for (int i=0; i < uuidCountOrExceptionCode; i++) { uuids.add(in.readLong()); } // Copy the remaining bytes as the content ByteStreams.copy(in, out); return uuids; } catch (Throwable t) { Throwables.propagateIfInstanceOf(t, KeeperException.NoNodeException.class); throw Throwables.propagate(t); } }
[ "private", "Set", "<", "Long", ">", "loadFromNode", "(", "String", "path", ",", "OutputStream", "out", ")", "throws", "KeeperException", ".", "NoNodeException", "{", "try", "{", "// Get the cached representation of this table", "byte", "[", "]", "data", "=", "_cur...
Loads the table data from the path and writes it to the output stream. Returns the set of UUIDs associated with the table, just like {@link #loadAndSerialize(long, java.io.OutputStream)}.
[ "Loads", "the", "table", "data", "from", "the", "path", "and", "writes", "it", "to", "the", "output", "stream", ".", "Returns", "the", "set", "of", "UUIDs", "associated", "with", "the", "table", "just", "like", "{" ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/tableset/DistributedTableSerializer.java#L119-L151
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/layout/ColumnLayout.java
ColumnLayout.setAlignment
public void setAlignment(final int col, final Alignment alignment) { columnAlignments[col] = alignment == null ? Alignment.LEFT : alignment; }
java
public void setAlignment(final int col, final Alignment alignment) { columnAlignments[col] = alignment == null ? Alignment.LEFT : alignment; }
[ "public", "void", "setAlignment", "(", "final", "int", "col", ",", "final", "Alignment", "alignment", ")", "{", "columnAlignments", "[", "col", "]", "=", "alignment", "==", "null", "?", "Alignment", ".", "LEFT", ":", "alignment", ";", "}" ]
Sets the alignment of the given column. An IndexOutOfBoundsException will be thrown if col is out of bounds. @param col the index of the column to set the alignment of. @param alignment the alignment to set.
[ "Sets", "the", "alignment", "of", "the", "given", "column", ".", "An", "IndexOutOfBoundsException", "will", "be", "thrown", "if", "col", "is", "out", "of", "bounds", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/layout/ColumnLayout.java#L188-L190
google/closure-compiler
src/com/google/javascript/jscomp/JSModuleGraph.java
JSModuleGraph.dependsOn
public boolean dependsOn(JSModule src, JSModule m) { return src != m && selfPlusTransitiveDeps[src.getIndex()].get(m.getIndex()); }
java
public boolean dependsOn(JSModule src, JSModule m) { return src != m && selfPlusTransitiveDeps[src.getIndex()].get(m.getIndex()); }
[ "public", "boolean", "dependsOn", "(", "JSModule", "src", ",", "JSModule", "m", ")", "{", "return", "src", "!=", "m", "&&", "selfPlusTransitiveDeps", "[", "src", ".", "getIndex", "(", ")", "]", ".", "get", "(", "m", ".", "getIndex", "(", ")", ")", ";...
Determines whether this module depends on a given module. Note that a module never depends on itself, as that dependency would be cyclic.
[ "Determines", "whether", "this", "module", "depends", "on", "a", "given", "module", ".", "Note", "that", "a", "module", "never", "depends", "on", "itself", "as", "that", "dependency", "would", "be", "cyclic", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JSModuleGraph.java#L339-L341
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/command/support/AbstractCommand.java
AbstractCommand.getButtonManager
private CommandFaceButtonManager getButtonManager(String faceDescriptorId) { if (this.faceButtonManagers == null) { this.faceButtonManagers = new AbstractCachingMapDecorator() { protected Object create(Object key) { return new CommandFaceButtonManager(AbstractCommand.this, (String) key); } }; } CommandFaceButtonManager m = (CommandFaceButtonManager) this.faceButtonManagers.get(faceDescriptorId); return m; }
java
private CommandFaceButtonManager getButtonManager(String faceDescriptorId) { if (this.faceButtonManagers == null) { this.faceButtonManagers = new AbstractCachingMapDecorator() { protected Object create(Object key) { return new CommandFaceButtonManager(AbstractCommand.this, (String) key); } }; } CommandFaceButtonManager m = (CommandFaceButtonManager) this.faceButtonManagers.get(faceDescriptorId); return m; }
[ "private", "CommandFaceButtonManager", "getButtonManager", "(", "String", "faceDescriptorId", ")", "{", "if", "(", "this", ".", "faceButtonManagers", "==", "null", ")", "{", "this", ".", "faceButtonManagers", "=", "new", "AbstractCachingMapDecorator", "(", ")", "{",...
Returns the {@link CommandFaceButtonManager} for the given faceDescriptorId. @param faceDescriptorId id of the {@link CommandFaceDescriptor}. @return the {@link CommandFaceButtonManager} managing buttons configured with the {@link CommandFaceDescriptor}.
[ "Returns", "the", "{", "@link", "CommandFaceButtonManager", "}", "for", "the", "given", "faceDescriptorId", "." ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/command/support/AbstractCommand.java#L945-L955
sematext/ActionGenerator
ag-player-solr/src/main/java/com/sematext/ag/solr/util/XMLUtils.java
XMLUtils.getSolrAddDocument
public static String getSolrAddDocument(Map<String, String> values) { StringBuilder builder = new StringBuilder(); builder.append("<add><doc>"); for (Map.Entry<String, String> pair : values.entrySet()) { XMLUtils.addSolrField(builder, pair); } builder.append("</doc></add>"); return builder.toString(); }
java
public static String getSolrAddDocument(Map<String, String> values) { StringBuilder builder = new StringBuilder(); builder.append("<add><doc>"); for (Map.Entry<String, String> pair : values.entrySet()) { XMLUtils.addSolrField(builder, pair); } builder.append("</doc></add>"); return builder.toString(); }
[ "public", "static", "String", "getSolrAddDocument", "(", "Map", "<", "String", ",", "String", ">", "values", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "builder", ".", "append", "(", "\"<add><doc>\"", ")", ";", "for", ...
Returns Apache Solr add command. @param values values to include @return XML as String
[ "Returns", "Apache", "Solr", "add", "command", "." ]
train
https://github.com/sematext/ActionGenerator/blob/10f4a3e680f20d7d151f5d40e6758aeb072d474f/ag-player-solr/src/main/java/com/sematext/ag/solr/util/XMLUtils.java#L37-L45
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/JobsInner.java
JobsInner.getOutput
public InputStream getOutput(String resourceGroupName, String automationAccountName, String jobId) { return getOutputWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId).toBlocking().single().body(); }
java
public InputStream getOutput(String resourceGroupName, String automationAccountName, String jobId) { return getOutputWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId).toBlocking().single().body(); }
[ "public", "InputStream", "getOutput", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "jobId", ")", "{", "return", "getOutputWithServiceResponseAsync", "(", "resourceGroupName", ",", "automationAccountName", ",", "jobId", ")", ...
Retrieve the job output identified by job id. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param jobId The job id. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the InputStream object if successful.
[ "Retrieve", "the", "job", "output", "identified", "by", "job", "id", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/JobsInner.java#L119-L121
structurizr/java
structurizr-core/src/com/structurizr/model/Container.java
Container.addComponent
public Component addComponent(String name, String type, String description, String technology) { return getModel().addComponentOfType(this, name, type, description, technology); }
java
public Component addComponent(String name, String type, String description, String technology) { return getModel().addComponentOfType(this, name, type, description, technology); }
[ "public", "Component", "addComponent", "(", "String", "name", ",", "String", "type", ",", "String", "description", ",", "String", "technology", ")", "{", "return", "getModel", "(", ")", ".", "addComponentOfType", "(", "this", ",", "name", ",", "type", ",", ...
Adds a component to this container. @param name the name of the component @param type a String describing the fully qualified name of the primary type of the component @param description a description of the component @param technology the technology of the component @return the resulting Component instance @throws IllegalArgumentException if the component name is null or empty, or a component with the same name already exists
[ "Adds", "a", "component", "to", "this", "container", "." ]
train
https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/model/Container.java#L113-L115
beanshell/beanshell
src/main/java/bsh/BSHBinaryExpression.java
BSHBinaryExpression.getVariableAtNode
private Variable getVariableAtNode(int index, CallStack callstack) throws UtilEvalError { Node nameNode = null; if (jjtGetChild(index).jjtGetNumChildren() > 0 && (nameNode = jjtGetChild(index).jjtGetChild(0)) instanceof BSHAmbiguousName) return callstack.top().getVariableImpl( ((BSHAmbiguousName) nameNode).text, true); return null; }
java
private Variable getVariableAtNode(int index, CallStack callstack) throws UtilEvalError { Node nameNode = null; if (jjtGetChild(index).jjtGetNumChildren() > 0 && (nameNode = jjtGetChild(index).jjtGetChild(0)) instanceof BSHAmbiguousName) return callstack.top().getVariableImpl( ((BSHAmbiguousName) nameNode).text, true); return null; }
[ "private", "Variable", "getVariableAtNode", "(", "int", "index", ",", "CallStack", "callstack", ")", "throws", "UtilEvalError", "{", "Node", "nameNode", "=", "null", ";", "if", "(", "jjtGetChild", "(", "index", ")", ".", "jjtGetNumChildren", "(", ")", ">", "...
Get Variable for value at specified index. @param index 0 for lhs val1 else 1 @param callstack the evaluation call stack @return the variable in call stack name space for the ambiguous node text @throws UtilEvalError thrown by getVariableImpl.
[ "Get", "Variable", "for", "value", "at", "specified", "index", "." ]
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/BSHBinaryExpression.java#L133-L141
ag-gipp/MathMLTools
mathml-utils/src/main/java/com/formulasearchengine/mathmltools/nativetools/CommandExecutor.java
CommandExecutor.exec
public NativeResponse exec(long timeout, TimeUnit unit, Level logLevel) { return internalexec(timeout, unit, logLevel); }
java
public NativeResponse exec(long timeout, TimeUnit unit, Level logLevel) { return internalexec(timeout, unit, logLevel); }
[ "public", "NativeResponse", "exec", "(", "long", "timeout", ",", "TimeUnit", "unit", ",", "Level", "logLevel", ")", "{", "return", "internalexec", "(", "timeout", ",", "unit", ",", "logLevel", ")", ";", "}" ]
Combination of everything before. @param timeout a @param unit a @param logLevel a @return a
[ "Combination", "of", "everything", "before", "." ]
train
https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-utils/src/main/java/com/formulasearchengine/mathmltools/nativetools/CommandExecutor.java#L186-L188
nohana/Amalgam
amalgam/src/main/java/com/amalgam/os/BundleUtils.java
BundleUtils.optCharSequence
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) public static CharSequence optCharSequence(@Nullable Bundle bundle, @Nullable String key, @Nullable CharSequence fallback) { if (bundle == null) { return fallback; } return bundle.getCharSequence(key, fallback); }
java
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) public static CharSequence optCharSequence(@Nullable Bundle bundle, @Nullable String key, @Nullable CharSequence fallback) { if (bundle == null) { return fallback; } return bundle.getCharSequence(key, fallback); }
[ "@", "TargetApi", "(", "Build", ".", "VERSION_CODES", ".", "HONEYCOMB_MR1", ")", "public", "static", "CharSequence", "optCharSequence", "(", "@", "Nullable", "Bundle", "bundle", ",", "@", "Nullable", "String", "key", ",", "@", "Nullable", "CharSequence", "fallba...
Returns a optional {@link CharSequence} value. In other words, returns the value mapped by key if it exists and is a {@link CharSequence}. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns a fallback value. @param bundle a bundle. If the bundle is null, this method will return a fallback value. @param key a key for the value. @param fallback fallback value. @return a {@link CharSequence} value if exists, fallback value otherwise. @see android.os.Bundle#getCharSequence(String, CharSequence)
[ "Returns", "a", "optional", "{" ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L343-L349
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/event/MapEventPublisherImpl.java
MapEventPublisherImpl.publishWanEvent
protected void publishWanEvent(String mapName, ReplicationEventObject event) { MapContainer mapContainer = mapServiceContext.getMapContainer(mapName); WanReplicationPublisher wanReplicationPublisher = mapContainer.getWanReplicationPublisher(); if (isOwnedPartition(event.getKey())) { wanReplicationPublisher.publishReplicationEvent(SERVICE_NAME, event); } else { wanReplicationPublisher.publishReplicationEventBackup(SERVICE_NAME, event); } }
java
protected void publishWanEvent(String mapName, ReplicationEventObject event) { MapContainer mapContainer = mapServiceContext.getMapContainer(mapName); WanReplicationPublisher wanReplicationPublisher = mapContainer.getWanReplicationPublisher(); if (isOwnedPartition(event.getKey())) { wanReplicationPublisher.publishReplicationEvent(SERVICE_NAME, event); } else { wanReplicationPublisher.publishReplicationEventBackup(SERVICE_NAME, event); } }
[ "protected", "void", "publishWanEvent", "(", "String", "mapName", ",", "ReplicationEventObject", "event", ")", "{", "MapContainer", "mapContainer", "=", "mapServiceContext", ".", "getMapContainer", "(", "mapName", ")", ";", "WanReplicationPublisher", "wanReplicationPublis...
Publishes the {@code event} to the {@link WanReplicationPublisher} configured for this map. @param mapName the map name @param event the event
[ "Publishes", "the", "{", "@code", "event", "}", "to", "the", "{", "@link", "WanReplicationPublisher", "}", "configured", "for", "this", "map", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/event/MapEventPublisherImpl.java#L122-L130
WiQuery/wiquery
wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/slider/AjaxSlider.java
AjaxSlider.setAjaxStartEvent
public void setAjaxStartEvent(ISliderAjaxEvent ajaxStartEvent) { this.ajaxEvents.put(SliderAjaxEvent.ajaxStartEvent, ajaxStartEvent); setSlideEvent(new SliderAjaxJsScopeUiEvent(this, SliderAjaxEvent.ajaxStartEvent)); }
java
public void setAjaxStartEvent(ISliderAjaxEvent ajaxStartEvent) { this.ajaxEvents.put(SliderAjaxEvent.ajaxStartEvent, ajaxStartEvent); setSlideEvent(new SliderAjaxJsScopeUiEvent(this, SliderAjaxEvent.ajaxStartEvent)); }
[ "public", "void", "setAjaxStartEvent", "(", "ISliderAjaxEvent", "ajaxStartEvent", ")", "{", "this", ".", "ajaxEvents", ".", "put", "(", "SliderAjaxEvent", ".", "ajaxStartEvent", ",", "ajaxStartEvent", ")", ";", "setSlideEvent", "(", "new", "SliderAjaxJsScopeUiEvent", ...
Sets the call-back for the AJAX Start Event. @param ajaxStartEvent The ISliderAjaxEvent.
[ "Sets", "the", "call", "-", "back", "for", "the", "AJAX", "Start", "Event", "." ]
train
https://github.com/WiQuery/wiquery/blob/1b8d60c7a3c37b90fd68c9cd0ff97178fcbcbb08/wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/slider/AjaxSlider.java#L318-L322
fnklabs/draenei
src/main/java/com/fnklabs/draenei/orm/CacheableDataProvider.java
CacheableDataProvider.executeOnEntry
public <ReturnValue> ReturnValue executeOnEntry(@NotNull Entry entry, @NotNull CacheEntryProcessor<Long, Entry, ReturnValue> entryProcessor) { long key = buildHashCode(entry); if (!cache.containsKey(key)) { List<Object> primaryKeys = getPrimaryKeys(entry); List<Entry> entries = super.fetch(primaryKeys); Optional<Entry> first = entries.stream().findFirst(); if (first.isPresent()) { cache.putIfAbsent(key, first.get()); } } return cache.invoke(key, entryProcessor); }
java
public <ReturnValue> ReturnValue executeOnEntry(@NotNull Entry entry, @NotNull CacheEntryProcessor<Long, Entry, ReturnValue> entryProcessor) { long key = buildHashCode(entry); if (!cache.containsKey(key)) { List<Object> primaryKeys = getPrimaryKeys(entry); List<Entry> entries = super.fetch(primaryKeys); Optional<Entry> first = entries.stream().findFirst(); if (first.isPresent()) { cache.putIfAbsent(key, first.get()); } } return cache.invoke(key, entryProcessor); }
[ "public", "<", "ReturnValue", ">", "ReturnValue", "executeOnEntry", "(", "@", "NotNull", "Entry", "entry", ",", "@", "NotNull", "CacheEntryProcessor", "<", "Long", ",", "Entry", ",", "ReturnValue", ">", "entryProcessor", ")", "{", "long", "key", "=", "buildHas...
Execute entry processor on entry cache @param entry Entry on which will be executed entry processor @param entryProcessor Entry processor that must be executed @param <ReturnValue> ClassType @return Return value from entry processor
[ "Execute", "entry", "processor", "on", "entry", "cache" ]
train
https://github.com/fnklabs/draenei/blob/0a8cac54f1f635be3e2950375a23291d38453ae8/src/main/java/com/fnklabs/draenei/orm/CacheableDataProvider.java#L130-L146
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/SerializableSaltedHasher.java
SerializableSaltedHasher.hashObjWithSalt
HashCode hashObjWithSalt(T object, int moreSalt) { Hasher hashInst = hasher.newHasher(); hashInst.putObject(object, funnel); hashInst.putLong(seedNSalt); hashInst.putInt(moreSalt); return hashInst.hash(); }
java
HashCode hashObjWithSalt(T object, int moreSalt) { Hasher hashInst = hasher.newHasher(); hashInst.putObject(object, funnel); hashInst.putLong(seedNSalt); hashInst.putInt(moreSalt); return hashInst.hash(); }
[ "HashCode", "hashObjWithSalt", "(", "T", "object", ",", "int", "moreSalt", ")", "{", "Hasher", "hashInst", "=", "hasher", ".", "newHasher", "(", ")", ";", "hashInst", ".", "putObject", "(", "object", ",", "funnel", ")", ";", "hashInst", ".", "putLong", "...
hashes the object with an additional salt. For purpose of the cuckoo filter, this is used when the hash generated for an item is all zeros. All zeros is the same as an empty bucket, so obviously it's not a valid tag.
[ "hashes", "the", "object", "with", "an", "additional", "salt", ".", "For", "purpose", "of", "the", "cuckoo", "filter", "this", "is", "used", "when", "the", "hash", "generated", "for", "an", "item", "is", "all", "zeros", ".", "All", "zeros", "is", "the", ...
train
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/SerializableSaltedHasher.java#L121-L127
protostuff/protostuff
protostuff-json/src/main/java/io/protostuff/JsonIOUtil.java
JsonIOUtil.parseListFrom
public static <T> List<T> parseListFrom(InputStream in, Schema<T> schema, boolean numeric, LinkedBuffer buffer) throws IOException { final IOContext context = new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(), in, false); final JsonParser parser = newJsonParser(in, buffer.buffer, 0, 0, false, context); try { return parseListFrom(parser, schema, numeric); } finally { parser.close(); } }
java
public static <T> List<T> parseListFrom(InputStream in, Schema<T> schema, boolean numeric, LinkedBuffer buffer) throws IOException { final IOContext context = new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(), in, false); final JsonParser parser = newJsonParser(in, buffer.buffer, 0, 0, false, context); try { return parseListFrom(parser, schema, numeric); } finally { parser.close(); } }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "parseListFrom", "(", "InputStream", "in", ",", "Schema", "<", "T", ">", "schema", ",", "boolean", "numeric", ",", "LinkedBuffer", "buffer", ")", "throws", "IOException", "{", "final", "IOContext", ...
Parses the {@code messages} from the stream using the given {@code schema}. <p> The {@link LinkedBuffer}'s internal byte array will be used when reading the message.
[ "Parses", "the", "{" ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-json/src/main/java/io/protostuff/JsonIOUtil.java#L587-L601
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java
DatumWriterGenerator.getEncodeMethod
private Method getEncodeMethod(TypeToken<?> outputType, Schema schema) { String key = String.format("%s%s", normalizeTypeName(outputType), schema.getSchemaHash()); Method method = encodeMethods.get(key); if (method != null) { return method; } // Generate the encode method (value, encoder, schema, set) TypeToken<?> callOutputType = getCallTypeToken(outputType, schema); String methodName = String.format("encode%s", key); method = getMethod(void.class, methodName, callOutputType.getRawType(), Encoder.class, Schema.class, Set.class); // Put the method into map first before generating the body in order to support recursive data type. encodeMethods.put(key, method); String methodSignature = Signatures.getMethodSignature(method, new TypeToken[]{ callOutputType, null, null, new TypeToken<Set<Object>>() { }}); GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PRIVATE, method, methodSignature, new Type[]{Type.getType(IOException.class)}, classWriter); generateEncodeBody(mg, schema, outputType, 0, 1, 2, 3); mg.returnValue(); mg.endMethod(); return method; }
java
private Method getEncodeMethod(TypeToken<?> outputType, Schema schema) { String key = String.format("%s%s", normalizeTypeName(outputType), schema.getSchemaHash()); Method method = encodeMethods.get(key); if (method != null) { return method; } // Generate the encode method (value, encoder, schema, set) TypeToken<?> callOutputType = getCallTypeToken(outputType, schema); String methodName = String.format("encode%s", key); method = getMethod(void.class, methodName, callOutputType.getRawType(), Encoder.class, Schema.class, Set.class); // Put the method into map first before generating the body in order to support recursive data type. encodeMethods.put(key, method); String methodSignature = Signatures.getMethodSignature(method, new TypeToken[]{ callOutputType, null, null, new TypeToken<Set<Object>>() { }}); GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PRIVATE, method, methodSignature, new Type[]{Type.getType(IOException.class)}, classWriter); generateEncodeBody(mg, schema, outputType, 0, 1, 2, 3); mg.returnValue(); mg.endMethod(); return method; }
[ "private", "Method", "getEncodeMethod", "(", "TypeToken", "<", "?", ">", "outputType", ",", "Schema", "schema", ")", "{", "String", "key", "=", "String", ".", "format", "(", "\"%s%s\"", ",", "normalizeTypeName", "(", "outputType", ")", ",", "schema", ".", ...
Returns the encode method for the given type and schema. The same method will be returned if the same type and schema has been passed to the method before. @param outputType Type information of the data type for output @param schema Schema to use for output. @return A method for encoding the given output type and schema.
[ "Returns", "the", "encode", "method", "for", "the", "given", "type", "and", "schema", ".", "The", "same", "method", "will", "be", "returned", "if", "the", "same", "type", "and", "schema", "has", "been", "passed", "to", "the", "method", "before", "." ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java#L285-L312
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/XPathContext.java
XPathContext.getDTMXRTreeFrag
public DTMXRTreeFrag getDTMXRTreeFrag(int dtmIdentity){ if(m_DTMXRTreeFrags == null){ m_DTMXRTreeFrags = new HashMap(); } if(m_DTMXRTreeFrags.containsKey(new Integer(dtmIdentity))){ return (DTMXRTreeFrag)m_DTMXRTreeFrags.get(new Integer(dtmIdentity)); }else{ final DTMXRTreeFrag frag = new DTMXRTreeFrag(dtmIdentity,this); m_DTMXRTreeFrags.put(new Integer(dtmIdentity),frag); return frag ; } }
java
public DTMXRTreeFrag getDTMXRTreeFrag(int dtmIdentity){ if(m_DTMXRTreeFrags == null){ m_DTMXRTreeFrags = new HashMap(); } if(m_DTMXRTreeFrags.containsKey(new Integer(dtmIdentity))){ return (DTMXRTreeFrag)m_DTMXRTreeFrags.get(new Integer(dtmIdentity)); }else{ final DTMXRTreeFrag frag = new DTMXRTreeFrag(dtmIdentity,this); m_DTMXRTreeFrags.put(new Integer(dtmIdentity),frag); return frag ; } }
[ "public", "DTMXRTreeFrag", "getDTMXRTreeFrag", "(", "int", "dtmIdentity", ")", "{", "if", "(", "m_DTMXRTreeFrags", "==", "null", ")", "{", "m_DTMXRTreeFrags", "=", "new", "HashMap", "(", ")", ";", "}", "if", "(", "m_DTMXRTreeFrags", ".", "containsKey", "(", ...
Gets DTMXRTreeFrag object if one has already been created. Creates new DTMXRTreeFrag object and adds to m_DTMXRTreeFrags HashMap, otherwise. @param dtmIdentity @return DTMXRTreeFrag
[ "Gets", "DTMXRTreeFrag", "object", "if", "one", "has", "already", "been", "created", ".", "Creates", "new", "DTMXRTreeFrag", "object", "and", "adds", "to", "m_DTMXRTreeFrags", "HashMap", "otherwise", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/XPathContext.java#L1322-L1334
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/extension/related/dublin/DublinCoreMetadata.java
DublinCoreMetadata.hasColumn
public static boolean hasColumn(UserTable<?> table, DublinCoreType type) { boolean hasColumn = table.hasColumn(type.getName()); if (!hasColumn) { for (String synonym : type.getSynonyms()) { hasColumn = table.hasColumn(synonym); if (hasColumn) { break; } } } return hasColumn; }
java
public static boolean hasColumn(UserTable<?> table, DublinCoreType type) { boolean hasColumn = table.hasColumn(type.getName()); if (!hasColumn) { for (String synonym : type.getSynonyms()) { hasColumn = table.hasColumn(synonym); if (hasColumn) { break; } } } return hasColumn; }
[ "public", "static", "boolean", "hasColumn", "(", "UserTable", "<", "?", ">", "table", ",", "DublinCoreType", "type", ")", "{", "boolean", "hasColumn", "=", "table", ".", "hasColumn", "(", "type", ".", "getName", "(", ")", ")", ";", "if", "(", "!", "has...
Check if the table has a column for the Dublin Core Type term @param table user table @param type Dublin Core Type @return true if has column
[ "Check", "if", "the", "table", "has", "a", "column", "for", "the", "Dublin", "Core", "Type", "term" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/extension/related/dublin/DublinCoreMetadata.java#L24-L38
VoltDB/voltdb
src/frontend/org/voltdb/jdbc/JDBC4ExecutionFuture.java
JDBC4ExecutionFuture.get
@Override public ClientResponse get() throws InterruptedException, ExecutionException { try { return get(this.timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException to) { this.status.compareAndSet(STATUS_RUNNING, STATUS_TIMEOUT); throw new ExecutionException(to); } }
java
@Override public ClientResponse get() throws InterruptedException, ExecutionException { try { return get(this.timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException to) { this.status.compareAndSet(STATUS_RUNNING, STATUS_TIMEOUT); throw new ExecutionException(to); } }
[ "@", "Override", "public", "ClientResponse", "get", "(", ")", "throws", "InterruptedException", ",", "ExecutionException", "{", "try", "{", "return", "get", "(", "this", ".", "timeout", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "}", "catch", "(", "Time...
Waits if necessary for the computation to complete, and then retrieves its result. @return the computed result. @throws CancellationException if the computation was cancelled. @throws ExecutionException if the computation threw an exception. @throws InterruptedException if the current thread was interrupted while waiting.
[ "Waits", "if", "necessary", "for", "the", "computation", "to", "complete", "and", "then", "retrieves", "its", "result", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4ExecutionFuture.java#L96-L104
JodaOrg/joda-time
src/main/java/org/joda/time/Duration.java
Duration.withDurationAdded
public Duration withDurationAdded(ReadableDuration durationToAdd, int scalar) { if (durationToAdd == null || scalar == 0) { return this; } return withDurationAdded(durationToAdd.getMillis(), scalar); }
java
public Duration withDurationAdded(ReadableDuration durationToAdd, int scalar) { if (durationToAdd == null || scalar == 0) { return this; } return withDurationAdded(durationToAdd.getMillis(), scalar); }
[ "public", "Duration", "withDurationAdded", "(", "ReadableDuration", "durationToAdd", ",", "int", "scalar", ")", "{", "if", "(", "durationToAdd", "==", "null", "||", "scalar", "==", "0", ")", "{", "return", "this", ";", "}", "return", "withDurationAdded", "(", ...
Returns a new duration with this length plus that specified multiplied by the scalar. This instance is immutable and is not altered. <p> If the addition is zero, this instance is returned. @param durationToAdd the duration to add to this one, null means zero @param scalar the amount of times to add, such as -1 to subtract once @return the new duration instance
[ "Returns", "a", "new", "duration", "with", "this", "length", "plus", "that", "specified", "multiplied", "by", "the", "scalar", ".", "This", "instance", "is", "immutable", "and", "is", "not", "altered", ".", "<p", ">", "If", "the", "addition", "is", "zero",...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/Duration.java#L409-L414
Bearded-Hen/Android-Bootstrap
AndroidBootstrap/src/main/java/com/beardedhen/androidbootstrap/BootstrapDrawableFactory.java
BootstrapDrawableFactory.bootstrapButton
static Drawable bootstrapButton(Context context, BootstrapBrand brand, int strokeWidth, int cornerRadius, ViewGroupPosition position, boolean showOutline, boolean rounded) { GradientDrawable defaultGd = new GradientDrawable(); GradientDrawable activeGd = new GradientDrawable(); GradientDrawable disabledGd = new GradientDrawable(); defaultGd.setColor(showOutline ? Color.TRANSPARENT : brand.defaultFill(context)); activeGd.setColor(showOutline ? brand.activeFill(context) : brand.activeFill(context)); disabledGd.setColor(showOutline ? Color.TRANSPARENT : brand.disabledFill(context)); defaultGd.setStroke(strokeWidth, brand.defaultEdge(context)); activeGd.setStroke(strokeWidth, brand.activeEdge(context)); disabledGd.setStroke(strokeWidth, brand.disabledEdge(context)); if (showOutline && brand instanceof DefaultBootstrapBrand) { DefaultBootstrapBrand db = (DefaultBootstrapBrand) brand; if (db == DefaultBootstrapBrand.SECONDARY) { int color = ColorUtils.resolveColor(R.color.bootstrap_brand_secondary_border, context); defaultGd.setStroke(strokeWidth, color); activeGd.setStroke(strokeWidth, color); disabledGd.setStroke(strokeWidth, color); } } setupDrawableCorners(position, rounded, cornerRadius, defaultGd, activeGd, disabledGd); return setupStateDrawable(position, strokeWidth, defaultGd, activeGd, disabledGd); }
java
static Drawable bootstrapButton(Context context, BootstrapBrand brand, int strokeWidth, int cornerRadius, ViewGroupPosition position, boolean showOutline, boolean rounded) { GradientDrawable defaultGd = new GradientDrawable(); GradientDrawable activeGd = new GradientDrawable(); GradientDrawable disabledGd = new GradientDrawable(); defaultGd.setColor(showOutline ? Color.TRANSPARENT : brand.defaultFill(context)); activeGd.setColor(showOutline ? brand.activeFill(context) : brand.activeFill(context)); disabledGd.setColor(showOutline ? Color.TRANSPARENT : brand.disabledFill(context)); defaultGd.setStroke(strokeWidth, brand.defaultEdge(context)); activeGd.setStroke(strokeWidth, brand.activeEdge(context)); disabledGd.setStroke(strokeWidth, brand.disabledEdge(context)); if (showOutline && brand instanceof DefaultBootstrapBrand) { DefaultBootstrapBrand db = (DefaultBootstrapBrand) brand; if (db == DefaultBootstrapBrand.SECONDARY) { int color = ColorUtils.resolveColor(R.color.bootstrap_brand_secondary_border, context); defaultGd.setStroke(strokeWidth, color); activeGd.setStroke(strokeWidth, color); disabledGd.setStroke(strokeWidth, color); } } setupDrawableCorners(position, rounded, cornerRadius, defaultGd, activeGd, disabledGd); return setupStateDrawable(position, strokeWidth, defaultGd, activeGd, disabledGd); }
[ "static", "Drawable", "bootstrapButton", "(", "Context", "context", ",", "BootstrapBrand", "brand", ",", "int", "strokeWidth", ",", "int", "cornerRadius", ",", "ViewGroupPosition", "position", ",", "boolean", "showOutline", ",", "boolean", "rounded", ")", "{", "Gr...
Generates a background drawable for a Bootstrap Button @param context the current context @param brand the bootstrap brand @param strokeWidth the stroke width in px @param cornerRadius the corner radius in px @param position the position of the button in its parent view @param showOutline whether the button should be outlined @param rounded whether the corners should be rounded @return a background drawable for the BootstrapButton
[ "Generates", "a", "background", "drawable", "for", "a", "Bootstrap", "Button" ]
train
https://github.com/Bearded-Hen/Android-Bootstrap/blob/b3d62cc1847e26d420c53c92665a4fe1e6ee7ecf/AndroidBootstrap/src/main/java/com/beardedhen/androidbootstrap/BootstrapDrawableFactory.java#L45-L79
buschmais/jqa-javaee6-plugin
src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/XmlDescriptorHelper.java
XmlDescriptorHelper.createDisplayName
public static DisplayNameDescriptor createDisplayName(DisplayNameType displayNameType, Store store) { DisplayNameDescriptor displayNameDescriptor = store.create(DisplayNameDescriptor.class); displayNameDescriptor.setLang(displayNameType.getLang()); displayNameDescriptor.setValue(displayNameType.getValue()); return displayNameDescriptor; }
java
public static DisplayNameDescriptor createDisplayName(DisplayNameType displayNameType, Store store) { DisplayNameDescriptor displayNameDescriptor = store.create(DisplayNameDescriptor.class); displayNameDescriptor.setLang(displayNameType.getLang()); displayNameDescriptor.setValue(displayNameType.getValue()); return displayNameDescriptor; }
[ "public", "static", "DisplayNameDescriptor", "createDisplayName", "(", "DisplayNameType", "displayNameType", ",", "Store", "store", ")", "{", "DisplayNameDescriptor", "displayNameDescriptor", "=", "store", ".", "create", "(", "DisplayNameDescriptor", ".", "class", ")", ...
Create a display name descriptor. @param displayNameType The XML display name type. @param store The store. @return The display name descriptor.
[ "Create", "a", "display", "name", "descriptor", "." ]
train
https://github.com/buschmais/jqa-javaee6-plugin/blob/f5776604d9255206807e5aca90b8767bde494e14/src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/XmlDescriptorHelper.java#L61-L66
m-m-m/util
value/src/main/java/net/sf/mmm/util/value/impl/ComposedValueConverterImpl.java
ComposedValueConverterImpl.isApplicable
protected boolean isApplicable(ValueConverter<?, ?> converter, GenericType<?> targetType) { Class<?> expectedTargetClass = targetType.getRetrievalClass(); if (expectedTargetClass.isArray()) { expectedTargetClass = expectedTargetClass.getComponentType(); } return isApplicable(converter.getTargetType(), expectedTargetClass); }
java
protected boolean isApplicable(ValueConverter<?, ?> converter, GenericType<?> targetType) { Class<?> expectedTargetClass = targetType.getRetrievalClass(); if (expectedTargetClass.isArray()) { expectedTargetClass = expectedTargetClass.getComponentType(); } return isApplicable(converter.getTargetType(), expectedTargetClass); }
[ "protected", "boolean", "isApplicable", "(", "ValueConverter", "<", "?", ",", "?", ">", "converter", ",", "GenericType", "<", "?", ">", "targetType", ")", "{", "Class", "<", "?", ">", "expectedTargetClass", "=", "targetType", ".", "getRetrievalClass", "(", "...
This method determines if the given {@code converter} is applicable for the given {@code targetType}. @see ValueConverter#getTargetType() @param converter is the {@link ValueConverter} to check. @param targetType is the {@link GenericType} to match with {@link ValueConverter#getTargetType()}. @return {@code true} if the given {@code converter} is applicable, {@code false} otherwise.
[ "This", "method", "determines", "if", "the", "given", "{", "@code", "converter", "}", "is", "applicable", "for", "the", "given", "{", "@code", "targetType", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/value/src/main/java/net/sf/mmm/util/value/impl/ComposedValueConverterImpl.java#L220-L227
lightblueseas/file-worker
src/main/java/de/alpharogroup/file/read/ReadFileExtensions.java
ReadFileExtensions.inputStream2String
public static String inputStream2String(final InputStream inputStream, final Charset encoding) throws IOException { return ReadFileExtensions.reader2String(new InputStreamReader(inputStream, encoding)); }
java
public static String inputStream2String(final InputStream inputStream, final Charset encoding) throws IOException { return ReadFileExtensions.reader2String(new InputStreamReader(inputStream, encoding)); }
[ "public", "static", "String", "inputStream2String", "(", "final", "InputStream", "inputStream", ",", "final", "Charset", "encoding", ")", "throws", "IOException", "{", "return", "ReadFileExtensions", ".", "reader2String", "(", "new", "InputStreamReader", "(", "inputSt...
The Method inputStream2String() reads the data from the InputStream into a String. @param inputStream The InputStream from where we read. @param encoding the encoding @return The String that we read from the InputStream. @throws IOException Signals that an I/O exception has occurred.
[ "The", "Method", "inputStream2String", "()", "reads", "the", "data", "from", "the", "InputStream", "into", "a", "String", "." ]
train
https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/read/ReadFileExtensions.java#L99-L103
IanGClifton/AndroidFloatLabel
FloatLabel/src/com/iangclifton/android/floatlabel/FloatLabel.java
FloatLabel.setText
public void setText(CharSequence text, TextView.BufferType type) { mEditText.setText(text, type); }
java
public void setText(CharSequence text, TextView.BufferType type) { mEditText.setText(text, type); }
[ "public", "void", "setText", "(", "CharSequence", "text", ",", "TextView", ".", "BufferType", "type", ")", "{", "mEditText", ".", "setText", "(", "text", ",", "type", ")", ";", "}" ]
Sets the EditText's text with label animation @param text CharSequence to set @param type TextView.BufferType
[ "Sets", "the", "EditText", "s", "text", "with", "label", "animation" ]
train
https://github.com/IanGClifton/AndroidFloatLabel/blob/b0a39c26f010f17d5f3648331e9784a41e025c0d/FloatLabel/src/com/iangclifton/android/floatlabel/FloatLabel.java#L270-L272
skuzzle/semantic-version
src/it/java/de/skuzzle/semantic/VersionRegEx.java
VersionRegEx.max
public static VersionRegEx max(VersionRegEx v1, VersionRegEx v2) { require(v1 != null, "v1 is null"); require(v2 != null, "v2 is null"); return compare(v1, v2, false) < 0 ? v2 : v1; }
java
public static VersionRegEx max(VersionRegEx v1, VersionRegEx v2) { require(v1 != null, "v1 is null"); require(v2 != null, "v2 is null"); return compare(v1, v2, false) < 0 ? v2 : v1; }
[ "public", "static", "VersionRegEx", "max", "(", "VersionRegEx", "v1", ",", "VersionRegEx", "v2", ")", "{", "require", "(", "v1", "!=", "null", ",", "\"v1 is null\"", ")", ";", "require", "(", "v2", "!=", "null", ",", "\"v2 is null\"", ")", ";", "return", ...
Returns the greater of the two given versions by comparing them using their natural ordering. If both versions are equal, then the first argument is returned. @param v1 The first version. @param v2 The second version. @return The greater version. @throws IllegalArgumentException If either argument is <code>null</code>. @since 0.4.0
[ "Returns", "the", "greater", "of", "the", "two", "given", "versions", "by", "comparing", "them", "using", "their", "natural", "ordering", ".", "If", "both", "versions", "are", "equal", "then", "the", "first", "argument", "is", "returned", "." ]
train
https://github.com/skuzzle/semantic-version/blob/2ddb66fb80244cd7f67c77ed5f8072d1132ad933/src/it/java/de/skuzzle/semantic/VersionRegEx.java#L228-L234
elki-project/elki
elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/strings/LevenshteinDistanceFunction.java
LevenshteinDistanceFunction.prefixLen
private static int prefixLen(String o1, String o2) { final int l1 = o1.length(), l2 = o2.length(), l = l1 < l2 ? l1 : l2; int prefix = 0; while(prefix < l && (o1.charAt(prefix) == o2.charAt(prefix))) { prefix++; } return prefix; }
java
private static int prefixLen(String o1, String o2) { final int l1 = o1.length(), l2 = o2.length(), l = l1 < l2 ? l1 : l2; int prefix = 0; while(prefix < l && (o1.charAt(prefix) == o2.charAt(prefix))) { prefix++; } return prefix; }
[ "private", "static", "int", "prefixLen", "(", "String", "o1", ",", "String", "o2", ")", "{", "final", "int", "l1", "=", "o1", ".", "length", "(", ")", ",", "l2", "=", "o2", ".", "length", "(", ")", ",", "l", "=", "l1", "<", "l2", "?", "l1", "...
Compute the length of the prefix. @param o1 First string @param o2 Second string @return Prefix length
[ "Compute", "the", "length", "of", "the", "prefix", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/strings/LevenshteinDistanceFunction.java#L115-L122
srikalyc/Sql4D
Sql4Ddriver/src/main/java/com/yahoo/sql4d/sql4ddriver/Joiner4Bean.java
Joiner4Bean.mapPkToRow
private Tuple2<Object, T> mapPkToRow(String timestamp, JSONObject jsonRow, List<String> joinFields) { Object joinValue = null; T rowValues = null; try { rowValues = rowMapper.newInstance(); rowValues.getClass().getMethod("setTimestamp", String.class).invoke(rowValues, timestamp); for (Object key : jsonRow.keySet()) { String colValue = key.toString(); Util.applyKVToBean(rowValues, colValue, jsonRow.get(colValue)); if (joinFields.contains(colValue)) { joinValue = (joinValue == null)?jsonRow.get(colValue):(joinValue + "\u0001" + jsonRow.get(colValue)); } } if (joinFields.contains("timestamp")) {// Join field could contain timestamp(timestamp can be out of the actual data JSON, so we try this way) joinValue = (joinValue == null)?timestamp:(joinValue + "\u0001" + timestamp); } } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(Joiner4Bean.class.getName()).log(Level.SEVERE, null, ex); } return new Tuple2<>(joinValue, rowValues); }
java
private Tuple2<Object, T> mapPkToRow(String timestamp, JSONObject jsonRow, List<String> joinFields) { Object joinValue = null; T rowValues = null; try { rowValues = rowMapper.newInstance(); rowValues.getClass().getMethod("setTimestamp", String.class).invoke(rowValues, timestamp); for (Object key : jsonRow.keySet()) { String colValue = key.toString(); Util.applyKVToBean(rowValues, colValue, jsonRow.get(colValue)); if (joinFields.contains(colValue)) { joinValue = (joinValue == null)?jsonRow.get(colValue):(joinValue + "\u0001" + jsonRow.get(colValue)); } } if (joinFields.contains("timestamp")) {// Join field could contain timestamp(timestamp can be out of the actual data JSON, so we try this way) joinValue = (joinValue == null)?timestamp:(joinValue + "\u0001" + timestamp); } } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(Joiner4Bean.class.getName()).log(Level.SEVERE, null, ex); } return new Tuple2<>(joinValue, rowValues); }
[ "private", "Tuple2", "<", "Object", ",", "T", ">", "mapPkToRow", "(", "String", "timestamp", ",", "JSONObject", "jsonRow", ",", "List", "<", "String", ">", "joinFields", ")", "{", "Object", "joinValue", "=", "null", ";", "T", "rowValues", "=", "null", ";...
Extract fields(k,v) from json k = primary field(s), i.e could be composite key as well. v = all fields . The first field is always timestamp. @param timestamp @param jsonRow @param joinFields @return
[ "Extract", "fields", "(", "k", "v", ")", "from", "json", "k", "=", "primary", "field", "(", "s", ")", "i", ".", "e", "could", "be", "composite", "key", "as", "well", ".", "v", "=", "all", "fields", ".", "The", "first", "field", "is", "always", "t...
train
https://github.com/srikalyc/Sql4D/blob/2c052fe60ead5a16277c798a3440de7d4f6f24f6/Sql4Ddriver/src/main/java/com/yahoo/sql4d/sql4ddriver/Joiner4Bean.java#L112-L132
JOML-CI/JOML
src/org/joml/Matrix4d.java
Matrix4d.setOrtho
public Matrix4d setOrtho(double left, double right, double bottom, double top, double zNear, double zFar, boolean zZeroToOne) { if ((properties & PROPERTY_IDENTITY) == 0) _identity(); m00 = 2.0 / (right - left); m11 = 2.0 / (top - bottom); m22 = (zZeroToOne ? 1.0 : 2.0) / (zNear - zFar); m30 = (right + left) / (left - right); m31 = (top + bottom) / (bottom - top); m32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar); properties = PROPERTY_AFFINE; return this; }
java
public Matrix4d setOrtho(double left, double right, double bottom, double top, double zNear, double zFar, boolean zZeroToOne) { if ((properties & PROPERTY_IDENTITY) == 0) _identity(); m00 = 2.0 / (right - left); m11 = 2.0 / (top - bottom); m22 = (zZeroToOne ? 1.0 : 2.0) / (zNear - zFar); m30 = (right + left) / (left - right); m31 = (top + bottom) / (bottom - top); m32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar); properties = PROPERTY_AFFINE; return this; }
[ "public", "Matrix4d", "setOrtho", "(", "double", "left", ",", "double", "right", ",", "double", "bottom", ",", "double", "top", ",", "double", "zNear", ",", "double", "zFar", ",", "boolean", "zZeroToOne", ")", "{", "if", "(", "(", "properties", "&", "PRO...
Set this matrix to be an orthographic projection transformation for a right-handed coordinate system using the given NDC z range. <p> In order to apply the orthographic projection to an already existing transformation, use {@link #ortho(double, double, double, double, double, double, boolean) ortho()}. <p> Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> @see #ortho(double, double, double, double, double, double, boolean) @param left the distance from the center to the left frustum edge @param right the distance from the center to the right frustum edge @param bottom the distance from the center to the bottom frustum edge @param top the distance from the center to the top frustum edge @param zNear near clipping plane distance @param zFar far clipping plane distance @param zZeroToOne whether to use Vulkan's and Direct3D's NDC z range of <code>[0..+1]</code> when <code>true</code> or whether to use OpenGL's NDC z range of <code>[-1..+1]</code> when <code>false</code> @return this
[ "Set", "this", "matrix", "to", "be", "an", "orthographic", "projection", "transformation", "for", "a", "right", "-", "handed", "coordinate", "system", "using", "the", "given", "NDC", "z", "range", ".", "<p", ">", "In", "order", "to", "apply", "the", "ortho...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L9944-L9955
h2oai/h2o-3
h2o-genmodel/src/main/java/hex/genmodel/AbstractMojoWriter.java
AbstractMojoWriter.writeln
protected final void writeln(String s, boolean escapeNewlines) { assert tmpfile != null : "No text file is currently being written"; tmpfile.append(escapeNewlines ? StringEscapeUtils.escapeNewlines(s) : s); tmpfile.append('\n'); }
java
protected final void writeln(String s, boolean escapeNewlines) { assert tmpfile != null : "No text file is currently being written"; tmpfile.append(escapeNewlines ? StringEscapeUtils.escapeNewlines(s) : s); tmpfile.append('\n'); }
[ "protected", "final", "void", "writeln", "(", "String", "s", ",", "boolean", "escapeNewlines", ")", "{", "assert", "tmpfile", "!=", "null", ":", "\"No text file is currently being written\"", ";", "tmpfile", ".", "append", "(", "escapeNewlines", "?", "StringEscapeUt...
Write a single line of text to a previously opened text file, escape new line characters if enabled.
[ "Write", "a", "single", "line", "of", "text", "to", "a", "previously", "opened", "text", "file", "escape", "new", "line", "characters", "if", "enabled", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-genmodel/src/main/java/hex/genmodel/AbstractMojoWriter.java#L102-L106
ltearno/hexa.tools
hexa.binding/src/main/java/fr/lteconsulting/hexa/databinding/properties/PropertyValues.java
PropertyValues.setValue
boolean setValue( Object object, String propertyName, Object value ) { Clazz<?> s = ClassInfo.Clazz( object.getClass() ); if( Property.class == getPropertyType( s, propertyName ) ) { Property<Object> property = getPropertyImpl( object, propertyName ); if( property != null ) { property.setValue( value ); return true; } return false; } return setPropertyImpl( s, object, propertyName, value ); }
java
boolean setValue( Object object, String propertyName, Object value ) { Clazz<?> s = ClassInfo.Clazz( object.getClass() ); if( Property.class == getPropertyType( s, propertyName ) ) { Property<Object> property = getPropertyImpl( object, propertyName ); if( property != null ) { property.setValue( value ); return true; } return false; } return setPropertyImpl( s, object, propertyName, value ); }
[ "boolean", "setValue", "(", "Object", "object", ",", "String", "propertyName", ",", "Object", "value", ")", "{", "Clazz", "<", "?", ">", "s", "=", "ClassInfo", ".", "Clazz", "(", "object", ".", "getClass", "(", ")", ")", ";", "if", "(", "Property", "...
Sets a value on an object's property @param object the object on which the property is set @param propertyName the name of the property value to be set @param value the new value of the property
[ "Sets", "a", "value", "on", "an", "object", "s", "property" ]
train
https://github.com/ltearno/hexa.tools/blob/604c804901b1bb13fe10b3823cc4a639f8993363/hexa.binding/src/main/java/fr/lteconsulting/hexa/databinding/properties/PropertyValues.java#L187-L204
Alluxio/alluxio
integration/fuse/src/main/java/alluxio/fuse/AlluxioFuseFileSystem.java
AlluxioFuseFileSystem.truncate
@Override public int truncate(String path, long size) { LOG.error("Truncate is not supported {}", path); return -ErrorCodes.EOPNOTSUPP(); }
java
@Override public int truncate(String path, long size) { LOG.error("Truncate is not supported {}", path); return -ErrorCodes.EOPNOTSUPP(); }
[ "@", "Override", "public", "int", "truncate", "(", "String", "path", ",", "long", "size", ")", "{", "LOG", ".", "error", "(", "\"Truncate is not supported {}\"", ",", "path", ")", ";", "return", "-", "ErrorCodes", ".", "EOPNOTSUPP", "(", ")", ";", "}" ]
Changes the size of a file. This operation would not succeed because of Alluxio's write-once model.
[ "Changes", "the", "size", "of", "a", "file", ".", "This", "operation", "would", "not", "succeed", "because", "of", "Alluxio", "s", "write", "-", "once", "model", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/fuse/src/main/java/alluxio/fuse/AlluxioFuseFileSystem.java#L639-L643
landawn/AbacusUtil
src/com/landawn/abacus/util/Iterables.java
Iterables.orderedPermutations
public static <E extends Comparable<? super E>> Collection<List<E>> orderedPermutations(Collection<E> elements) { return orderedPermutations(elements, Comparators.naturalOrder()); }
java
public static <E extends Comparable<? super E>> Collection<List<E>> orderedPermutations(Collection<E> elements) { return orderedPermutations(elements, Comparators.naturalOrder()); }
[ "public", "static", "<", "E", "extends", "Comparable", "<", "?", "super", "E", ">", ">", "Collection", "<", "List", "<", "E", ">", ">", "orderedPermutations", "(", "Collection", "<", "E", ">", "elements", ")", "{", "return", "orderedPermutations", "(", "...
Note: copy from Google Guava under Apache License v2. <br /> Returns a {@link Collection} of all the permutations of the specified {@link Iterable}. <p><i>Notes:</i> This is an implementation of the algorithm for Lexicographical Permutations Generation, described in Knuth's "The Art of Computer Programming", Volume 4, Chapter 7, Section 7.2.1.2. The iteration order follows the lexicographical order. This means that the first permutation will be in ascending order, and the last will be in descending order. <p>Duplicate elements are considered equal. For example, the list [1, 1] will have only one permutation, instead of two. This is why the elements have to implement {@link Comparable}. <p>An empty iterable has only one permutation, which is an empty list. <p>This method is equivalent to {@code Collections2.orderedPermutations(list, Ordering.natural())}. @param elements the original iterable whose elements have to be permuted. @return an immutable {@link Collection} containing all the different permutations of the original iterable. @throws NullPointerException if the specified iterable is null or has any null elements.
[ "Note", ":", "copy", "from", "Google", "Guava", "under", "Apache", "License", "v2", ".", "<br", "/", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Iterables.java#L669-L671
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/Matchers.java
Matchers.methodNameStartsWith
public static Matcher<MethodTree> methodNameStartsWith(final String prefix) { return new Matcher<MethodTree>() { @Override public boolean matches(MethodTree methodTree, VisitorState state) { return methodTree.getName().toString().startsWith(prefix); } }; }
java
public static Matcher<MethodTree> methodNameStartsWith(final String prefix) { return new Matcher<MethodTree>() { @Override public boolean matches(MethodTree methodTree, VisitorState state) { return methodTree.getName().toString().startsWith(prefix); } }; }
[ "public", "static", "Matcher", "<", "MethodTree", ">", "methodNameStartsWith", "(", "final", "String", "prefix", ")", "{", "return", "new", "Matcher", "<", "MethodTree", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "MethodTree", ...
Match a method declaration that starts with a given string. @param prefix The prefix.
[ "Match", "a", "method", "declaration", "that", "starts", "with", "a", "given", "string", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L932-L939
actframework/actframework
src/main/java/act/app/ActionContext.java
ActionContext.loginAndRedirectBack
public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) { login(userIdentifier); RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl); }
java
public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) { login(userIdentifier); RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl); }
[ "public", "void", "loginAndRedirectBack", "(", "Object", "userIdentifier", ",", "String", "defaultLandingUrl", ")", "{", "login", "(", "userIdentifier", ")", ";", "RedirectToLoginUrl", ".", "redirectToOriginalUrl", "(", "this", ",", "defaultLandingUrl", ")", ";", "}...
Login the user and redirect back to original URL. If no original URL found then redirect to `defaultLandingUrl`. @param userIdentifier the user identifier, could be either userId or username @param defaultLandingUrl the URL to be redirected if original URL not found
[ "Login", "the", "user", "and", "redirect", "back", "to", "original", "URL", ".", "If", "no", "original", "URL", "found", "then", "redirect", "to", "defaultLandingUrl", "." ]
train
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/app/ActionContext.java#L1293-L1296
Netflix/eureka
eureka-core/src/main/java/com/netflix/eureka/cluster/PeerEurekaNode.java
PeerEurekaNode.statusUpdate
public void statusUpdate(final String asgName, final ASGStatus newStatus) { long expiryTime = System.currentTimeMillis() + maxProcessingDelayMs; nonBatchingDispatcher.process( asgName, new AsgReplicationTask(targetHost, Action.StatusUpdate, asgName, newStatus) { public EurekaHttpResponse<?> execute() { return replicationClient.statusUpdate(asgName, newStatus); } }, expiryTime ); }
java
public void statusUpdate(final String asgName, final ASGStatus newStatus) { long expiryTime = System.currentTimeMillis() + maxProcessingDelayMs; nonBatchingDispatcher.process( asgName, new AsgReplicationTask(targetHost, Action.StatusUpdate, asgName, newStatus) { public EurekaHttpResponse<?> execute() { return replicationClient.statusUpdate(asgName, newStatus); } }, expiryTime ); }
[ "public", "void", "statusUpdate", "(", "final", "String", "asgName", ",", "final", "ASGStatus", "newStatus", ")", "{", "long", "expiryTime", "=", "System", ".", "currentTimeMillis", "(", ")", "+", "maxProcessingDelayMs", ";", "nonBatchingDispatcher", ".", "process...
Send the status information of of the ASG represented by the instance. <p> ASG (Autoscaling group) names are available for instances in AWS and the ASG information is used for determining if the instance should be registered as {@link InstanceStatus#DOWN} or {@link InstanceStatus#UP}. @param asgName the asg name if any of this instance. @param newStatus the new status of the ASG.
[ "Send", "the", "status", "information", "of", "of", "the", "ASG", "represented", "by", "the", "instance", "." ]
train
https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-core/src/main/java/com/netflix/eureka/cluster/PeerEurekaNode.java#L243-L254
facebookarchive/hadoop-20
src/core/org/apache/hadoop/io/retry/RetryPolicies.java
RetryPolicies.exponentialBackoffRetry
public static final RetryPolicy exponentialBackoffRetry( int maxRetries, long sleepTime, TimeUnit timeUnit) { return new ExponentialBackoffRetry(maxRetries, sleepTime, timeUnit); }
java
public static final RetryPolicy exponentialBackoffRetry( int maxRetries, long sleepTime, TimeUnit timeUnit) { return new ExponentialBackoffRetry(maxRetries, sleepTime, timeUnit); }
[ "public", "static", "final", "RetryPolicy", "exponentialBackoffRetry", "(", "int", "maxRetries", ",", "long", "sleepTime", ",", "TimeUnit", "timeUnit", ")", "{", "return", "new", "ExponentialBackoffRetry", "(", "maxRetries", ",", "sleepTime", ",", "timeUnit", ")", ...
<p> Keep trying a limited number of times, waiting a growing amount of time between attempts, and then fail by re-throwing the exception. The time between attempts is <code>sleepTime</code> mutliplied by a random number in the range of [0, 2 to the number of retries) </p>
[ "<p", ">", "Keep", "trying", "a", "limited", "number", "of", "times", "waiting", "a", "growing", "amount", "of", "time", "between", "attempts", "and", "then", "fail", "by", "re", "-", "throwing", "the", "exception", ".", "The", "time", "between", "attempts...
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/io/retry/RetryPolicies.java#L98-L101
alkacon/opencms-core
src/org/opencms/ui/error/CmsErrorUI.java
CmsErrorUI.setErrorAttributes
private static void setErrorAttributes(CmsObject cms, Throwable throwable, HttpServletRequest request) { String errorUri = CmsFlexController.getThrowableResourceUri(request); if (errorUri == null) { errorUri = cms.getRequestContext().getUri(); } // try to get the exception root cause Throwable cause = CmsFlexController.getThrowable(request); if (cause == null) { cause = throwable; } request.getSession().setAttribute(THROWABLE, cause); request.getSession().setAttribute(PATH, errorUri); }
java
private static void setErrorAttributes(CmsObject cms, Throwable throwable, HttpServletRequest request) { String errorUri = CmsFlexController.getThrowableResourceUri(request); if (errorUri == null) { errorUri = cms.getRequestContext().getUri(); } // try to get the exception root cause Throwable cause = CmsFlexController.getThrowable(request); if (cause == null) { cause = throwable; } request.getSession().setAttribute(THROWABLE, cause); request.getSession().setAttribute(PATH, errorUri); }
[ "private", "static", "void", "setErrorAttributes", "(", "CmsObject", "cms", ",", "Throwable", "throwable", ",", "HttpServletRequest", "request", ")", "{", "String", "errorUri", "=", "CmsFlexController", ".", "getThrowableResourceUri", "(", "request", ")", ";", "if",...
Sets the error attributes to the current session.<p> @param cms the cms context @param throwable the throwable @param request the current request
[ "Sets", "the", "error", "attributes", "to", "the", "current", "session", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/error/CmsErrorUI.java#L131-L146
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/RuntimeModelIo.java
RuntimeModelIo.writeInstances
public static void writeInstances( File targetFile, Collection<Instance> rootInstances ) throws IOException { FileDefinition def = new FromInstances().buildFileDefinition( rootInstances, targetFile, false, true ); ParsingModelIo.saveRelationsFile( def, false, "\n" ); }
java
public static void writeInstances( File targetFile, Collection<Instance> rootInstances ) throws IOException { FileDefinition def = new FromInstances().buildFileDefinition( rootInstances, targetFile, false, true ); ParsingModelIo.saveRelationsFile( def, false, "\n" ); }
[ "public", "static", "void", "writeInstances", "(", "File", "targetFile", ",", "Collection", "<", "Instance", ">", "rootInstances", ")", "throws", "IOException", "{", "FileDefinition", "def", "=", "new", "FromInstances", "(", ")", ".", "buildFileDefinition", "(", ...
Writes all the instances into a file. @param targetFile the file to save @param rootInstances the root instances (not null) @throws IOException if something went wrong
[ "Writes", "all", "the", "instances", "into", "a", "file", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/RuntimeModelIo.java#L484-L488
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/images/ImageGenerator.java
ImageGenerator.drawImage
public BufferedImage drawImage( ReferencedEnvelope ref, int imageWidth, int imageHeight, double buffer ) { checkMapContent(); if (buffer > 0.0) ref.expandBy(buffer, buffer); Rectangle2D refRect = new Rectangle2D.Double(ref.getMinX(), ref.getMinY(), ref.getWidth(), ref.getHeight()); Rectangle2D imageRect = new Rectangle2D.Double(0, 0, imageWidth, imageHeight); GeometryUtilities.scaleToRatio(imageRect, refRect, false); ReferencedEnvelope newRef = new ReferencedEnvelope(refRect, ref.getCoordinateReferenceSystem()); Rectangle imageBounds = new Rectangle(0, 0, imageWidth, imageHeight); BufferedImage dumpImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = dumpImage.createGraphics(); g2d.fillRect(0, 0, imageWidth, imageHeight); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); synchronized (renderer) { renderer.paint(g2d, imageBounds, newRef); } return dumpImage; }
java
public BufferedImage drawImage( ReferencedEnvelope ref, int imageWidth, int imageHeight, double buffer ) { checkMapContent(); if (buffer > 0.0) ref.expandBy(buffer, buffer); Rectangle2D refRect = new Rectangle2D.Double(ref.getMinX(), ref.getMinY(), ref.getWidth(), ref.getHeight()); Rectangle2D imageRect = new Rectangle2D.Double(0, 0, imageWidth, imageHeight); GeometryUtilities.scaleToRatio(imageRect, refRect, false); ReferencedEnvelope newRef = new ReferencedEnvelope(refRect, ref.getCoordinateReferenceSystem()); Rectangle imageBounds = new Rectangle(0, 0, imageWidth, imageHeight); BufferedImage dumpImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = dumpImage.createGraphics(); g2d.fillRect(0, 0, imageWidth, imageHeight); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); synchronized (renderer) { renderer.paint(g2d, imageBounds, newRef); } return dumpImage; }
[ "public", "BufferedImage", "drawImage", "(", "ReferencedEnvelope", "ref", ",", "int", "imageWidth", ",", "int", "imageHeight", ",", "double", "buffer", ")", "{", "checkMapContent", "(", ")", ";", "if", "(", "buffer", ">", "0.0", ")", "ref", ".", "expandBy", ...
Draw the map on an image. @param bounds the area of interest. @param imageWidth the width of the image to produce. @param imageHeight the height of the image to produce. @param buffer the buffer to add around the map bounds in map units. @return the image.
[ "Draw", "the", "map", "on", "an", "image", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/images/ImageGenerator.java#L452-L476
wildfly/wildfly-core
domain-management/src/main/java/org/jboss/as/domain/management/security/adduser/PropertyFileFinder.java
PropertyFileFinder.validatePermissions
private void validatePermissions(final File dirPath, final File file) { // Check execute and read permissions for parent dirPath if( !dirPath.canExecute() || !dirPath.canRead() ) { validFilePermissions = false; filePermissionsProblemPath = dirPath.getAbsolutePath(); return; } // Check read and write permissions for properties file if( !file.canRead() || !file.canWrite() ) { validFilePermissions = false; filePermissionsProblemPath = dirPath.getAbsolutePath(); } }
java
private void validatePermissions(final File dirPath, final File file) { // Check execute and read permissions for parent dirPath if( !dirPath.canExecute() || !dirPath.canRead() ) { validFilePermissions = false; filePermissionsProblemPath = dirPath.getAbsolutePath(); return; } // Check read and write permissions for properties file if( !file.canRead() || !file.canWrite() ) { validFilePermissions = false; filePermissionsProblemPath = dirPath.getAbsolutePath(); } }
[ "private", "void", "validatePermissions", "(", "final", "File", "dirPath", ",", "final", "File", "file", ")", "{", "// Check execute and read permissions for parent dirPath", "if", "(", "!", "dirPath", ".", "canExecute", "(", ")", "||", "!", "dirPath", ".", "canRe...
This method performs a series of permissions checks given a directory and properties file path. 1 - Check whether the parent directory dirPath has proper execute and read permissions 2 - Check whether properties file path is readable and writable If either of the permissions checks fail, update validFilePermissions and filePermissionsProblemPath appropriately.
[ "This", "method", "performs", "a", "series", "of", "permissions", "checks", "given", "a", "directory", "and", "properties", "file", "path", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/domain-management/src/main/java/org/jboss/as/domain/management/security/adduser/PropertyFileFinder.java#L293-L308
UrielCh/ovh-java-sdk
ovh-java-sdk-emailpro/src/main/java/net/minidev/ovh/api/ApiOvhEmailpro.java
ApiOvhEmailpro.service_externalContact_externalEmailAddress_PUT
public void service_externalContact_externalEmailAddress_PUT(String service, String externalEmailAddress, OvhExternalContact body) throws IOException { String qPath = "/email/pro/{service}/externalContact/{externalEmailAddress}"; StringBuilder sb = path(qPath, service, externalEmailAddress); exec(qPath, "PUT", sb.toString(), body); }
java
public void service_externalContact_externalEmailAddress_PUT(String service, String externalEmailAddress, OvhExternalContact body) throws IOException { String qPath = "/email/pro/{service}/externalContact/{externalEmailAddress}"; StringBuilder sb = path(qPath, service, externalEmailAddress); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "service_externalContact_externalEmailAddress_PUT", "(", "String", "service", ",", "String", "externalEmailAddress", ",", "OvhExternalContact", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/pro/{service}/externalContact/{external...
Alter this object properties REST: PUT /email/pro/{service}/externalContact/{externalEmailAddress} @param body [required] New object properties @param service [required] The internal name of your pro organization @param externalEmailAddress [required] Contact email API beta
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailpro/src/main/java/net/minidev/ovh/api/ApiOvhEmailpro.java#L93-L97
adamfisk/littleshoot-util
src/main/java/org/littleshoot/util/xml/XPathUtils.java
XPathUtils.newXPath
public static XPathUtils newXPath(final InputStream is) throws SAXException, IOException { final XPathFactory xpfactory = XPathFactory.newInstance(); final XPath xPath = xpfactory.newXPath(); final Document doc = XmlUtils.toDoc(is); return new XPathUtils(xPath, doc); }
java
public static XPathUtils newXPath(final InputStream is) throws SAXException, IOException { final XPathFactory xpfactory = XPathFactory.newInstance(); final XPath xPath = xpfactory.newXPath(); final Document doc = XmlUtils.toDoc(is); return new XPathUtils(xPath, doc); }
[ "public", "static", "XPathUtils", "newXPath", "(", "final", "InputStream", "is", ")", "throws", "SAXException", ",", "IOException", "{", "final", "XPathFactory", "xpfactory", "=", "XPathFactory", ".", "newInstance", "(", ")", ";", "final", "XPath", "xPath", "=",...
Creates a new {@link XPathUtils} instance. @param is The {@link InputStream} with XML data. @return A new {@link XPathUtils} instance. @throws SAXException If there's a SAX error in the XML. @throws IOException If there's an IO error reading the stream.
[ "Creates", "a", "new", "{", "@link", "XPathUtils", "}", "instance", "." ]
train
https://github.com/adamfisk/littleshoot-util/blob/3c0dc4955116b3382d6b0575d2f164b7508a4f73/src/main/java/org/littleshoot/util/xml/XPathUtils.java#L102-L108
jenkinsci/jenkins
core/src/main/java/hudson/model/AbstractModelObject.java
AbstractModelObject.requirePOST
@Deprecated protected final void requirePOST() throws ServletException { StaplerRequest req = Stapler.getCurrentRequest(); if (req==null) return; // invoked outside the context of servlet String method = req.getMethod(); if(!method.equalsIgnoreCase("POST")) throw new ServletException("Must be POST, Can't be "+method); }
java
@Deprecated protected final void requirePOST() throws ServletException { StaplerRequest req = Stapler.getCurrentRequest(); if (req==null) return; // invoked outside the context of servlet String method = req.getMethod(); if(!method.equalsIgnoreCase("POST")) throw new ServletException("Must be POST, Can't be "+method); }
[ "@", "Deprecated", "protected", "final", "void", "requirePOST", "(", ")", "throws", "ServletException", "{", "StaplerRequest", "req", "=", "Stapler", ".", "getCurrentRequest", "(", ")", ";", "if", "(", "req", "==", "null", ")", "return", ";", "// invoked outsi...
Convenience method to verify that the current request is a POST request. @deprecated Use {@link RequirePOST} on your method.
[ "Convenience", "method", "to", "verify", "that", "the", "current", "request", "is", "a", "POST", "request", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/AbstractModelObject.java#L84-L91
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/metrics/MetricsStore.java
MetricsStore.putWorkerMetrics
public void putWorkerMetrics(String hostname, List<Metric> metrics) { if (metrics.isEmpty()) { return; } synchronized (mWorkerMetrics) { mWorkerMetrics.removeByField(ID_INDEX, getFullInstanceId(hostname, null)); for (Metric metric : metrics) { if (metric.getHostname() == null) { continue; // ignore metrics whose hostname is null } mWorkerMetrics.add(metric); } } }
java
public void putWorkerMetrics(String hostname, List<Metric> metrics) { if (metrics.isEmpty()) { return; } synchronized (mWorkerMetrics) { mWorkerMetrics.removeByField(ID_INDEX, getFullInstanceId(hostname, null)); for (Metric metric : metrics) { if (metric.getHostname() == null) { continue; // ignore metrics whose hostname is null } mWorkerMetrics.add(metric); } } }
[ "public", "void", "putWorkerMetrics", "(", "String", "hostname", ",", "List", "<", "Metric", ">", "metrics", ")", "{", "if", "(", "metrics", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "synchronized", "(", "mWorkerMetrics", ")", "{", "mWorker...
Put the metrics from a worker with a hostname. If all the old metrics associated with this instance will be removed and then replaced by the latest. @param hostname the hostname of the instance @param metrics the new worker metrics
[ "Put", "the", "metrics", "from", "a", "worker", "with", "a", "hostname", ".", "If", "all", "the", "old", "metrics", "associated", "with", "this", "instance", "will", "be", "removed", "and", "then", "replaced", "by", "the", "latest", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/metrics/MetricsStore.java#L91-L104
alkacon/opencms-core
src/org/opencms/main/CmsShellCommands.java
CmsShellCommands.deleteHistoricalVersions
public void deleteHistoricalVersions(int versionsToKeep, int versionsDeleted, long timeDeleted) throws Exception { m_cms.deleteHistoricalVersions( versionsToKeep, versionsDeleted, timeDeleted, new CmsShellReport(m_cms.getRequestContext().getLocale())); }
java
public void deleteHistoricalVersions(int versionsToKeep, int versionsDeleted, long timeDeleted) throws Exception { m_cms.deleteHistoricalVersions( versionsToKeep, versionsDeleted, timeDeleted, new CmsShellReport(m_cms.getRequestContext().getLocale())); }
[ "public", "void", "deleteHistoricalVersions", "(", "int", "versionsToKeep", ",", "int", "versionsDeleted", ",", "long", "timeDeleted", ")", "throws", "Exception", "{", "m_cms", ".", "deleteHistoricalVersions", "(", "versionsToKeep", ",", "versionsDeleted", ",", "timeD...
Deletes the versions from the history tables that are older then the given number of versions.<p> @param versionsToKeep number of versions to keep, is ignored if negative @param versionsDeleted number of versions to keep for deleted resources, is ignored if negative @param timeDeleted deleted resources older than this will also be deleted, is ignored if negative @throws Exception if something goes wrong @see CmsObject#deleteHistoricalVersions( int, int, long, I_CmsReport)
[ "Deletes", "the", "versions", "from", "the", "history", "tables", "that", "are", "older", "then", "the", "given", "number", "of", "versions", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShellCommands.java#L462-L469
google/error-prone-javac
src/jdk.jshell/share/classes/jdk/internal/jshell/tool/Startup.java
Startup.defaultStartup
static Startup defaultStartup(MessageHandler mh) { if (defaultStartup != null) { return defaultStartup; } try { String content = readResource(DEFAULT_STARTUP_NAME); return defaultStartup = new Startup( new StartupEntry(true, DEFAULT_STARTUP_NAME, content)); } catch (AccessDeniedException e) { mh.errormsg("jshell.err.file.not.accessible", "jshell", DEFAULT_STARTUP_NAME, e.getMessage()); } catch (NoSuchFileException e) { mh.errormsg("jshell.err.file.not.found", "jshell", DEFAULT_STARTUP_NAME); } catch (Exception e) { mh.errormsg("jshell.err.file.exception", "jshell", DEFAULT_STARTUP_NAME, e); } return defaultStartup = noStartup(); }
java
static Startup defaultStartup(MessageHandler mh) { if (defaultStartup != null) { return defaultStartup; } try { String content = readResource(DEFAULT_STARTUP_NAME); return defaultStartup = new Startup( new StartupEntry(true, DEFAULT_STARTUP_NAME, content)); } catch (AccessDeniedException e) { mh.errormsg("jshell.err.file.not.accessible", "jshell", DEFAULT_STARTUP_NAME, e.getMessage()); } catch (NoSuchFileException e) { mh.errormsg("jshell.err.file.not.found", "jshell", DEFAULT_STARTUP_NAME); } catch (Exception e) { mh.errormsg("jshell.err.file.exception", "jshell", DEFAULT_STARTUP_NAME, e); } return defaultStartup = noStartup(); }
[ "static", "Startup", "defaultStartup", "(", "MessageHandler", "mh", ")", "{", "if", "(", "defaultStartup", "!=", "null", ")", "{", "return", "defaultStartup", ";", "}", "try", "{", "String", "content", "=", "readResource", "(", "DEFAULT_STARTUP_NAME", ")", ";"...
Factory method: The default Startup ("-default."). @param mh handler for error messages @return The default Startup, or empty startup when error (message has been printed)
[ "Factory", "method", ":", "The", "default", "Startup", "(", "-", "default", ".", ")", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/Startup.java#L334-L350
aalmiray/Json-lib
src/main/java/net/sf/json/JSONArray.java
JSONArray.toList
public static List toList( JSONArray jsonArray, Class objectClass, Map classMap ) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( objectClass ); jsonConfig.setClassMap( classMap ); return toList( jsonArray, jsonConfig ); }
java
public static List toList( JSONArray jsonArray, Class objectClass, Map classMap ) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( objectClass ); jsonConfig.setClassMap( classMap ); return toList( jsonArray, jsonConfig ); }
[ "public", "static", "List", "toList", "(", "JSONArray", "jsonArray", ",", "Class", "objectClass", ",", "Map", "classMap", ")", "{", "JsonConfig", "jsonConfig", "=", "new", "JsonConfig", "(", ")", ";", "jsonConfig", ".", "setRootClass", "(", "objectClass", ")",...
Creates a List from a JSONArray.<br> Any attribute is a JSONObject and matches a key in the classMap, it will be converted to that target class.<br> The classMap has the following conventions: <ul> <li>Every key must be an String.</li> <li>Every value must be a Class.</li> <li>A key may be a regular expression.</li> </ul> @deprecated replaced by toCollection @see #toCollection(JSONArray,Class,Map)
[ "Creates", "a", "List", "from", "a", "JSONArray", ".", "<br", ">", "Any", "attribute", "is", "a", "JSONObject", "and", "matches", "a", "key", "in", "the", "classMap", "it", "will", "be", "converted", "to", "that", "target", "class", ".", "<br", ">", "T...
train
https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/JSONArray.java#L441-L446
Samsung/GearVRf
GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/main/MainScene.java
MainScene.removeChildObjectFromCamera
public void removeChildObjectFromCamera(final Widget child, int camera) { switch (camera) { case LEFT_CAMERA: mLeftCameraRootWidget.removeChild(child); break; case RIGHT_CAMERA: mRightCameraRootWidget.removeChild(child); break; default: mMainCameraRootWidget.removeChild(child); break; } }
java
public void removeChildObjectFromCamera(final Widget child, int camera) { switch (camera) { case LEFT_CAMERA: mLeftCameraRootWidget.removeChild(child); break; case RIGHT_CAMERA: mRightCameraRootWidget.removeChild(child); break; default: mMainCameraRootWidget.removeChild(child); break; } }
[ "public", "void", "removeChildObjectFromCamera", "(", "final", "Widget", "child", ",", "int", "camera", ")", "{", "switch", "(", "camera", ")", "{", "case", "LEFT_CAMERA", ":", "mLeftCameraRootWidget", ".", "removeChild", "(", "child", ")", ";", "break", ";", ...
Removes a scene object from one or both of the left and right cameras. @param child The {@link Widget} to remove. @param camera {@link #LEFT_CAMERA} or {@link #RIGHT_CAMERA}; these can be or'd together to remove {@code child} from both cameras.
[ "Removes", "a", "scene", "object", "from", "one", "or", "both", "of", "the", "left", "and", "right", "cameras", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/main/MainScene.java#L408-L420
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonWriteDriver.java
GeoJsonWriteDriver.write
private void write(MultiPoint points, JsonGenerator gen) throws IOException { gen.writeStringField("type", "MultiPoint"); gen.writeFieldName("coordinates"); writeCoordinates(points.getCoordinates(), gen); }
java
private void write(MultiPoint points, JsonGenerator gen) throws IOException { gen.writeStringField("type", "MultiPoint"); gen.writeFieldName("coordinates"); writeCoordinates(points.getCoordinates(), gen); }
[ "private", "void", "write", "(", "MultiPoint", "points", ",", "JsonGenerator", "gen", ")", "throws", "IOException", "{", "gen", ".", "writeStringField", "(", "\"type\"", ",", "\"MultiPoint\"", ")", ";", "gen", ".", "writeFieldName", "(", "\"coordinates\"", ")", ...
Coordinates of a MultiPoint are an array of positions: { "type": "MultiPoint", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] } @param points @param gen @throws IOException
[ "Coordinates", "of", "a", "MultiPoint", "are", "an", "array", "of", "positions", ":" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonWriteDriver.java#L382-L386
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/reflect/ReflectionUtils.java
ReflectionUtils.getValue
@SuppressWarnings("unchecked") public static <T> T getValue(Class<?> type, String fieldName, Class<T> fieldType) { try { return getValue(null, getField(type, fieldName), fieldType); } catch (FieldNotFoundException e) { throw new IllegalArgumentException(String.format("Field with name (%1$s) does not exist on class type (%2$s)!", fieldName, type.getName()), e); } }
java
@SuppressWarnings("unchecked") public static <T> T getValue(Class<?> type, String fieldName, Class<T> fieldType) { try { return getValue(null, getField(type, fieldName), fieldType); } catch (FieldNotFoundException e) { throw new IllegalArgumentException(String.format("Field with name (%1$s) does not exist on class type (%2$s)!", fieldName, type.getName()), e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "getValue", "(", "Class", "<", "?", ">", "type", ",", "String", "fieldName", ",", "Class", "<", "T", ">", "fieldType", ")", "{", "try", "{", "return", "getValue...
Gets the value of the field with the specified name on the given class type cast to the desired field type. This method assumes the field is a static (class) member field. @param <T> the desired return type in which the field's value will be cast; should be compatible with the field's declared type. @param type the Class type on which the field is declared and defined. @param fieldName a String indicating the name of the field from which to get the value. @param fieldType the declared type of the class field. @return the value of the specified field on the given class type cast to the desired type. @throws IllegalArgumentException if the given class type does not declare a static member field with the specified name. @throws FieldAccessException if the value for the specified field could not be retrieved. @see #getField(Class, String) @see #getValue(Object, java.lang.reflect.Field, Class)
[ "Gets", "the", "value", "of", "the", "field", "with", "the", "specified", "name", "on", "the", "given", "class", "type", "cast", "to", "the", "desired", "field", "type", ".", "This", "method", "assumes", "the", "field", "is", "a", "static", "(", "class",...
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/reflect/ReflectionUtils.java#L100-L109
dlemmermann/CalendarFX
CalendarFXRecurrence/src/main/java/com/google/ical/iter/Generators.java
Generators.byYearGenerator
static Generator byYearGenerator(int[] years, final DateValue dtStart) { final int[] uyears = Util.uniquify(years); // index into years return new Generator() { int i; { while (i < uyears.length && dtStart.year() > uyears[i]) { ++i; } } @Override boolean generate(DTBuilder builder) { if (i >= uyears.length) { return false; } builder.year = uyears[i++]; return true; } @Override public String toString() { return "byYearGenerator"; } }; }
java
static Generator byYearGenerator(int[] years, final DateValue dtStart) { final int[] uyears = Util.uniquify(years); // index into years return new Generator() { int i; { while (i < uyears.length && dtStart.year() > uyears[i]) { ++i; } } @Override boolean generate(DTBuilder builder) { if (i >= uyears.length) { return false; } builder.year = uyears[i++]; return true; } @Override public String toString() { return "byYearGenerator"; } }; }
[ "static", "Generator", "byYearGenerator", "(", "int", "[", "]", "years", ",", "final", "DateValue", "dtStart", ")", "{", "final", "int", "[", "]", "uyears", "=", "Util", ".", "uniquify", "(", "years", ")", ";", "// index into years", "return", "new", "Gene...
constructs a generator that yields the specified years in increasing order.
[ "constructs", "a", "generator", "that", "yields", "the", "specified", "years", "in", "increasing", "order", "." ]
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXRecurrence/src/main/java/com/google/ical/iter/Generators.java#L376-L403
unbescape/unbescape
src/main/java/org/unbescape/properties/PropertiesEscape.java
PropertiesEscape.escapePropertiesValue
public static void escapePropertiesValue(final String text, final Writer writer, final PropertiesValueEscapeLevel level) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } if (level == null) { throw new IllegalArgumentException("The 'level' argument cannot be null"); } PropertiesValueEscapeUtil.escape(new InternalStringReader(text), writer, level); }
java
public static void escapePropertiesValue(final String text, final Writer writer, final PropertiesValueEscapeLevel level) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } if (level == null) { throw new IllegalArgumentException("The 'level' argument cannot be null"); } PropertiesValueEscapeUtil.escape(new InternalStringReader(text), writer, level); }
[ "public", "static", "void", "escapePropertiesValue", "(", "final", "String", "text", ",", "final", "Writer", "writer", ",", "final", "PropertiesValueEscapeLevel", "level", ")", "throws", "IOException", "{", "if", "(", "writer", "==", "null", ")", "{", "throw", ...
<p> Perform a (configurable) Java Properties Value <strong>escape</strong> operation on a <tt>String</tt> input, writing results to a <tt>Writer</tt>. </p> <p> This method will perform an escape operation according to the specified {@link org.unbescape.properties.PropertiesValueEscapeLevel} argument value. </p> <p> All other <tt>String</tt>/<tt>Writer</tt>-based <tt>escapePropertiesValue*(...)</tt> methods call this one with preconfigured <tt>level</tt> values. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>String</tt> to be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @param level the escape level to be applied, see {@link org.unbescape.properties.PropertiesValueEscapeLevel}. @throws IOException if an input/output exception occurs @since 1.1.2
[ "<p", ">", "Perform", "a", "(", "configurable", ")", "Java", "Properties", "Value", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "String<", "/", "tt", ">", "input", "writing", "results", "to", "a", "<tt", ">", "Wri...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/properties/PropertiesEscape.java#L424-L437
jpelzer/pelzer-util
src/main/java/com/pelzer/util/PropertyManager.java
PropertyManager.setOverride
private void setOverride(final String key, final String value) { final boolean doSecurely = key.startsWith("_"); final String fullKey = defaultEnvironment + "." + key; if (value != null) { final String oldValue = _getProperty("", key, null); if (value.equals(oldValue)) { // Same value, not really an override. if (doSecurely) { logger.warning("*** IGNORED *** Ignoring redundant override " + fullKey + "=***PROTECTED***"); } else { logger.warning("*** IGNORED *** Ignoring redundant override " + fullKey + "='" + value + "'"); } } else { logger.warning("*** OVERRIDE *** Setting override " + fullKey); if (doSecurely) { logger.warning(" New value=***PROTECTED***"); logger.warning(" Old value='" + oldValue + "'"); } else { logger.warning(" New value='" + value + "'"); logger.warning(" Old value='" + oldValue + "'"); } allProperties.setProperty(fullKey, value); } } }
java
private void setOverride(final String key, final String value) { final boolean doSecurely = key.startsWith("_"); final String fullKey = defaultEnvironment + "." + key; if (value != null) { final String oldValue = _getProperty("", key, null); if (value.equals(oldValue)) { // Same value, not really an override. if (doSecurely) { logger.warning("*** IGNORED *** Ignoring redundant override " + fullKey + "=***PROTECTED***"); } else { logger.warning("*** IGNORED *** Ignoring redundant override " + fullKey + "='" + value + "'"); } } else { logger.warning("*** OVERRIDE *** Setting override " + fullKey); if (doSecurely) { logger.warning(" New value=***PROTECTED***"); logger.warning(" Old value='" + oldValue + "'"); } else { logger.warning(" New value='" + value + "'"); logger.warning(" Old value='" + oldValue + "'"); } allProperties.setProperty(fullKey, value); } } }
[ "private", "void", "setOverride", "(", "final", "String", "key", ",", "final", "String", "value", ")", "{", "final", "boolean", "doSecurely", "=", "key", ".", "startsWith", "(", "\"_\"", ")", ";", "final", "String", "fullKey", "=", "defaultEnvironment", "+",...
Replaces whatever was in the allProperties object, and clears the cache.
[ "Replaces", "whatever", "was", "in", "the", "allProperties", "object", "and", "clears", "the", "cache", "." ]
train
https://github.com/jpelzer/pelzer-util/blob/ec14f2573fd977d1442dba5d1507a264f5ea9aa6/src/main/java/com/pelzer/util/PropertyManager.java#L576-L600
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbConnection.java
MariaDbConnection.newConnection
public static MariaDbConnection newConnection(UrlParser urlParser, GlobalStateInfo globalInfo) throws SQLException { if (urlParser.getOptions().pool) { return Pools.retrievePool(urlParser).getConnection(); } Protocol protocol = Utils.retrieveProxy(urlParser, globalInfo); return new MariaDbConnection(protocol); }
java
public static MariaDbConnection newConnection(UrlParser urlParser, GlobalStateInfo globalInfo) throws SQLException { if (urlParser.getOptions().pool) { return Pools.retrievePool(urlParser).getConnection(); } Protocol protocol = Utils.retrieveProxy(urlParser, globalInfo); return new MariaDbConnection(protocol); }
[ "public", "static", "MariaDbConnection", "newConnection", "(", "UrlParser", "urlParser", ",", "GlobalStateInfo", "globalInfo", ")", "throws", "SQLException", "{", "if", "(", "urlParser", ".", "getOptions", "(", ")", ".", "pool", ")", "{", "return", "Pools", ".",...
Create new connection Object. @param urlParser parser @param globalInfo global info @return connection object @throws SQLException if any connection error occur
[ "Create", "new", "connection", "Object", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbConnection.java#L168-L176
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/AppEventsLogger.java
AppEventsLogger.newLogger
public static AppEventsLogger newLogger(Context context, String applicationId, Session session) { return new AppEventsLogger(context, applicationId, session); }
java
public static AppEventsLogger newLogger(Context context, String applicationId, Session session) { return new AppEventsLogger(context, applicationId, session); }
[ "public", "static", "AppEventsLogger", "newLogger", "(", "Context", "context", ",", "String", "applicationId", ",", "Session", "session", ")", "{", "return", "new", "AppEventsLogger", "(", "context", ",", "applicationId", ",", "session", ")", ";", "}" ]
Build an AppEventsLogger instance to log events through. @param context Used to access the attributionId for non-authenticated users. @param applicationId Explicitly specified Facebook applicationId to log events against. If null, the default app ID specified in the package metadata will be used. @param session Explicitly specified Session to log events against. If null, the activeSession will be used if it's open, otherwise the logging will happen against the specified app ID. @return AppEventsLogger instance to invoke log* methods on.
[ "Build", "an", "AppEventsLogger", "instance", "to", "log", "events", "through", "." ]
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/AppEventsLogger.java#L371-L373
chocotan/datepicker4j
src/main/java/io/loli/datepicker/DatePanel.java
DatePanel.getDayIndex
private int getDayIndex(int year, int month, int day) { Calendar cal = Calendar.getInstance(); cal.set(year, month, day); return cal.get(Calendar.DAY_OF_WEEK); }
java
private int getDayIndex(int year, int month, int day) { Calendar cal = Calendar.getInstance(); cal.set(year, month, day); return cal.get(Calendar.DAY_OF_WEEK); }
[ "private", "int", "getDayIndex", "(", "int", "year", ",", "int", "month", ",", "int", "day", ")", "{", "Calendar", "cal", "=", "Calendar", ".", "getInstance", "(", ")", ";", "cal", ".", "set", "(", "year", ",", "month", ",", "day", ")", ";", "retur...
Get DAY_OF_WEEK of a day @param year the year @param month the month @param day the day @return DAY_OF_WEEK of this day
[ "Get", "DAY_OF_WEEK", "of", "a", "day" ]
train
https://github.com/chocotan/datepicker4j/blob/d65d7a6b29f9efe77aeec2024dc31a38a7852676/src/main/java/io/loli/datepicker/DatePanel.java#L253-L257
aol/cyclops
cyclops/src/main/java/cyclops/companion/Streams.java
Streams.groupedUntil
public final static <T> Stream<Seq<T>> groupedUntil(final Stream<T> stream, final Predicate<? super T> predicate) { return groupedWhile(stream, predicate.negate()); }
java
public final static <T> Stream<Seq<T>> groupedUntil(final Stream<T> stream, final Predicate<? super T> predicate) { return groupedWhile(stream, predicate.negate()); }
[ "public", "final", "static", "<", "T", ">", "Stream", "<", "Seq", "<", "T", ">", ">", "groupedUntil", "(", "final", "Stream", "<", "T", ">", "stream", ",", "final", "Predicate", "<", "?", "super", "T", ">", "predicate", ")", "{", "return", "groupedWh...
Group a Stream until the supplied predicate holds @see ReactiveSeq#groupedUntil(Predicate) @param stream Stream to group @param predicate Predicate to determine grouping @return Stream grouped into Lists determined by predicate
[ "Group", "a", "Stream", "until", "the", "supplied", "predicate", "holds" ]
train
https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/cyclops/companion/Streams.java#L2651-L2653
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/FieldBuilder.java
FieldBuilder.buildTagInfo
public void buildTagInfo(XMLNode node, Content fieldDocTree) { writer.addTags((FieldDoc) fields.get(currentFieldIndex), fieldDocTree); }
java
public void buildTagInfo(XMLNode node, Content fieldDocTree) { writer.addTags((FieldDoc) fields.get(currentFieldIndex), fieldDocTree); }
[ "public", "void", "buildTagInfo", "(", "XMLNode", "node", ",", "Content", "fieldDocTree", ")", "{", "writer", ".", "addTags", "(", "(", "FieldDoc", ")", "fields", ".", "get", "(", "currentFieldIndex", ")", ",", "fieldDocTree", ")", ";", "}" ]
Build the tag information. @param node the XML element that specifies which components to document @param fieldDocTree the content tree to which the documentation will be added
[ "Build", "the", "tag", "information", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/FieldBuilder.java#L216-L218
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/resources/BaseFileResourceModelSource.java
BaseFileResourceModelSource.writeData
@Override public long writeData(final InputStream data) throws IOException, ResourceModelSourceException { if (!isDataWritable()) { throw new IllegalArgumentException("Cannot write to file, it is not configured to be writeable"); } ResourceFormatParser resourceFormat = getResourceFormatParser(); //validate data File temp = Files.createTempFile("temp", "." + resourceFormat.getPreferredFileExtension()).toFile(); temp.deleteOnExit(); try { try (FileOutputStream fos = new FileOutputStream(temp)) { Streams.copyStream(data, fos); } final ResourceFormatParser parser = getResourceFormatParser(); try { final INodeSet set = parser.parseDocument(temp); } catch (ResourceFormatParserException e) { throw new ResourceModelSourceException(e); } try (FileInputStream tempStream = new FileInputStream(temp)) { return writeFileData(tempStream); } } finally { temp.delete(); } }
java
@Override public long writeData(final InputStream data) throws IOException, ResourceModelSourceException { if (!isDataWritable()) { throw new IllegalArgumentException("Cannot write to file, it is not configured to be writeable"); } ResourceFormatParser resourceFormat = getResourceFormatParser(); //validate data File temp = Files.createTempFile("temp", "." + resourceFormat.getPreferredFileExtension()).toFile(); temp.deleteOnExit(); try { try (FileOutputStream fos = new FileOutputStream(temp)) { Streams.copyStream(data, fos); } final ResourceFormatParser parser = getResourceFormatParser(); try { final INodeSet set = parser.parseDocument(temp); } catch (ResourceFormatParserException e) { throw new ResourceModelSourceException(e); } try (FileInputStream tempStream = new FileInputStream(temp)) { return writeFileData(tempStream); } } finally { temp.delete(); } }
[ "@", "Override", "public", "long", "writeData", "(", "final", "InputStream", "data", ")", "throws", "IOException", ",", "ResourceModelSourceException", "{", "if", "(", "!", "isDataWritable", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\...
Writes the data to a temp file, and attempts to parser it, then if successful it will call {@link #writeFileData(InputStream)} to invoke the sub class @param data data @return number of bytes written @throws IOException if an IO error occurs @throws ResourceModelSourceException if an error occurs parsing the data.
[ "Writes", "the", "data", "to", "a", "temp", "file", "and", "attempts", "to", "parser", "it", "then", "if", "successful", "it", "will", "call", "{", "@link", "#writeFileData", "(", "InputStream", ")", "}", "to", "invoke", "the", "sub", "class" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/resources/BaseFileResourceModelSource.java#L136-L164
alkacon/opencms-core
src/org/opencms/search/solr/CmsSolrIndex.java
CmsSolrIndex.getType
public static final String getType(CmsObject cms, String rootPath) { String type = null; CmsSolrIndex index = CmsSearchManager.getIndexSolr(cms, null); if (index != null) { I_CmsSearchDocument doc = index.getDocument(CmsSearchField.FIELD_PATH, rootPath); if (doc != null) { type = doc.getFieldValueAsString(CmsSearchField.FIELD_TYPE); } } return type; }
java
public static final String getType(CmsObject cms, String rootPath) { String type = null; CmsSolrIndex index = CmsSearchManager.getIndexSolr(cms, null); if (index != null) { I_CmsSearchDocument doc = index.getDocument(CmsSearchField.FIELD_PATH, rootPath); if (doc != null) { type = doc.getFieldValueAsString(CmsSearchField.FIELD_TYPE); } } return type; }
[ "public", "static", "final", "String", "getType", "(", "CmsObject", "cms", ",", "String", "rootPath", ")", "{", "String", "type", "=", "null", ";", "CmsSolrIndex", "index", "=", "CmsSearchManager", ".", "getIndexSolr", "(", "cms", ",", "null", ")", ";", "i...
Returns the resource type for the given root path.<p> @param cms the current CMS context @param rootPath the root path of the resource to get the type for @return the resource type for the given root path
[ "Returns", "the", "resource", "type", "for", "the", "given", "root", "path", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/solr/CmsSolrIndex.java#L278-L289
grpc/grpc-java
api/src/main/java/io/grpc/ClientInterceptors.java
ClientInterceptors.interceptForward
public static Channel interceptForward(Channel channel, ClientInterceptor... interceptors) { return interceptForward(channel, Arrays.asList(interceptors)); }
java
public static Channel interceptForward(Channel channel, ClientInterceptor... interceptors) { return interceptForward(channel, Arrays.asList(interceptors)); }
[ "public", "static", "Channel", "interceptForward", "(", "Channel", "channel", ",", "ClientInterceptor", "...", "interceptors", ")", "{", "return", "interceptForward", "(", "channel", ",", "Arrays", ".", "asList", "(", "interceptors", ")", ")", ";", "}" ]
Create a new {@link Channel} that will call {@code interceptors} before starting a call on the given channel. The first interceptor will have its {@link ClientInterceptor#interceptCall} called first. @param channel the underlying channel to intercept. @param interceptors array of interceptors to bind to {@code channel}. @return a new channel instance with the interceptors applied.
[ "Create", "a", "new", "{", "@link", "Channel", "}", "that", "will", "call", "{", "@code", "interceptors", "}", "before", "starting", "a", "call", "on", "the", "given", "channel", ".", "The", "first", "interceptor", "will", "have", "its", "{", "@link", "C...
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/api/src/main/java/io/grpc/ClientInterceptors.java#L44-L46
microfocus-idol/haven-search-components
hod/src/main/java/com/hp/autonomy/searchcomponents/hod/search/HodDocumentsServiceImpl.java
HodDocumentsServiceImpl.addDomain
private HodSearchResult addDomain(final Iterable<ResourceName> indexIdentifiers, final HodSearchResult document) { // HOD does not return the domain for documents yet, but it does return the index final String index = document.getIndex(); String domain = null; // It's most likely that the returned documents will be in one of the indexes we are querying (hopefully the // names are unique between the domains...) for(final ResourceName indexIdentifier : indexIdentifiers) { if(index.equals(indexIdentifier.getName())) { domain = indexIdentifier.getDomain(); break; } } if(domain == null) { // If not, it might be a public index domain = PUBLIC_INDEX_NAMES.contains(index) ? ResourceName.PUBLIC_INDEXES_DOMAIN : getDomain(); } return document.toBuilder() .domain(domain) .build(); }
java
private HodSearchResult addDomain(final Iterable<ResourceName> indexIdentifiers, final HodSearchResult document) { // HOD does not return the domain for documents yet, but it does return the index final String index = document.getIndex(); String domain = null; // It's most likely that the returned documents will be in one of the indexes we are querying (hopefully the // names are unique between the domains...) for(final ResourceName indexIdentifier : indexIdentifiers) { if(index.equals(indexIdentifier.getName())) { domain = indexIdentifier.getDomain(); break; } } if(domain == null) { // If not, it might be a public index domain = PUBLIC_INDEX_NAMES.contains(index) ? ResourceName.PUBLIC_INDEXES_DOMAIN : getDomain(); } return document.toBuilder() .domain(domain) .build(); }
[ "private", "HodSearchResult", "addDomain", "(", "final", "Iterable", "<", "ResourceName", ">", "indexIdentifiers", ",", "final", "HodSearchResult", "document", ")", "{", "// HOD does not return the domain for documents yet, but it does return the index", "final", "String", "ind...
Add a domain to a FindDocument, given the collection of indexes which were queried against to return it from HOD
[ "Add", "a", "domain", "to", "a", "FindDocument", "given", "the", "collection", "of", "indexes", "which", "were", "queried", "against", "to", "return", "it", "from", "HOD" ]
train
https://github.com/microfocus-idol/haven-search-components/blob/6f5df74ba67ec0d3f86e73bc1dd0d6edd01a8e44/hod/src/main/java/com/hp/autonomy/searchcomponents/hod/search/HodDocumentsServiceImpl.java#L230-L252
mbeiter/util
db/src/main/java/org/beiter/michael/db/propsbuilder/MapBasedConnPropsBuilder.java
MapBasedConnPropsBuilder.logDefault
private static void logDefault(final String key, final String defaultValue) { // Fortify will report a violation here because of disclosure of potentially confidential information. // However, neither the configuration keys nor the default propsbuilder values are confidential, which makes // this a non-issue / false positive. if (LOG.isInfoEnabled()) { final StringBuilder msg = new StringBuilder("Key is not configured ('") .append(key) .append("'), using default value ('"); if (defaultValue == null) { msg.append("null')"); } else { msg.append(defaultValue).append("')"); } LOG.info(msg.toString()); } }
java
private static void logDefault(final String key, final String defaultValue) { // Fortify will report a violation here because of disclosure of potentially confidential information. // However, neither the configuration keys nor the default propsbuilder values are confidential, which makes // this a non-issue / false positive. if (LOG.isInfoEnabled()) { final StringBuilder msg = new StringBuilder("Key is not configured ('") .append(key) .append("'), using default value ('"); if (defaultValue == null) { msg.append("null')"); } else { msg.append(defaultValue).append("')"); } LOG.info(msg.toString()); } }
[ "private", "static", "void", "logDefault", "(", "final", "String", "key", ",", "final", "String", "defaultValue", ")", "{", "// Fortify will report a violation here because of disclosure of potentially confidential information.", "// However, neither the configuration keys nor the defa...
Create a log entry when a default value is being used in case the propsbuilder key has not been provided in the configuration. @param key The configuration key @param defaultValue The default value that is being used
[ "Create", "a", "log", "entry", "when", "a", "default", "value", "is", "being", "used", "in", "case", "the", "propsbuilder", "key", "has", "not", "been", "provided", "in", "the", "configuration", "." ]
train
https://github.com/mbeiter/util/blob/490fcebecb936e00c2f2ce2096b679b2fd10865e/db/src/main/java/org/beiter/michael/db/propsbuilder/MapBasedConnPropsBuilder.java#L663-L679
LearnLib/automatalib
util/src/main/java/net/automatalib/util/minimizer/Block.java
Block.addToSubBlock
void addToSubBlock(State<S, L> state) { if (currSubBlock == null) { throw new IllegalStateException("No current sub block"); } currSubBlock.referencedAdd(state); elementsInSubBlocks++; }
java
void addToSubBlock(State<S, L> state) { if (currSubBlock == null) { throw new IllegalStateException("No current sub block"); } currSubBlock.referencedAdd(state); elementsInSubBlocks++; }
[ "void", "addToSubBlock", "(", "State", "<", "S", ",", "L", ">", "state", ")", "{", "if", "(", "currSubBlock", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"No current sub block\"", ")", ";", "}", "currSubBlock", ".", "referencedAdd...
Adds a state to the current sub block. @param state the state to be added.
[ "Adds", "a", "state", "to", "the", "current", "sub", "block", "." ]
train
https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/util/src/main/java/net/automatalib/util/minimizer/Block.java#L137-L143
apache/incubator-gobblin
gobblin-service/src/main/java/org/apache/gobblin/service/modules/flow/MultiHopsFlowToJobSpecCompiler.java
MultiHopsFlowToJobSpecCompiler.jobSpecURIGenerator
@Override public URI jobSpecURIGenerator(Object... objects) { FlowSpec flowSpec = (FlowSpec) objects[0]; ServiceNode sourceNode = (ServiceNode) objects[1]; ServiceNode targetNode = (ServiceNode) objects[2]; try { return new URI(JobSpec.Builder.DEFAULT_JOB_CATALOG_SCHEME, flowSpec.getUri().getAuthority(), StringUtils.appendIfMissing(StringUtils.prependIfMissing(flowSpec.getUri().getPath(), "/"),"/") + sourceNode.getNodeName() + "-" + targetNode.getNodeName(), null); } catch (URISyntaxException e) { log.error( "URI construction failed when jobSpec from " + sourceNode.getNodeName() + " to " + targetNode.getNodeName()); throw new RuntimeException(); } }
java
@Override public URI jobSpecURIGenerator(Object... objects) { FlowSpec flowSpec = (FlowSpec) objects[0]; ServiceNode sourceNode = (ServiceNode) objects[1]; ServiceNode targetNode = (ServiceNode) objects[2]; try { return new URI(JobSpec.Builder.DEFAULT_JOB_CATALOG_SCHEME, flowSpec.getUri().getAuthority(), StringUtils.appendIfMissing(StringUtils.prependIfMissing(flowSpec.getUri().getPath(), "/"),"/") + sourceNode.getNodeName() + "-" + targetNode.getNodeName(), null); } catch (URISyntaxException e) { log.error( "URI construction failed when jobSpec from " + sourceNode.getNodeName() + " to " + targetNode.getNodeName()); throw new RuntimeException(); } }
[ "@", "Override", "public", "URI", "jobSpecURIGenerator", "(", "Object", "...", "objects", ")", "{", "FlowSpec", "flowSpec", "=", "(", "FlowSpec", ")", "objects", "[", "0", "]", ";", "ServiceNode", "sourceNode", "=", "(", "ServiceNode", ")", "objects", "[", ...
A naive implementation of generating a jobSpec's URI within a multi-hop logical Flow.
[ "A", "naive", "implementation", "of", "generating", "a", "jobSpec", "s", "URI", "within", "a", "multi", "-", "hop", "logical", "Flow", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/flow/MultiHopsFlowToJobSpecCompiler.java#L343-L357
bugsnag/bugsnag-java
bugsnag/src/main/java/com/bugsnag/Bugsnag.java
Bugsnag.clearThreadMetaData
public static void clearThreadMetaData(String tabName, String key) { THREAD_METADATA.get().clearKey(tabName, key); }
java
public static void clearThreadMetaData(String tabName, String key) { THREAD_METADATA.get().clearKey(tabName, key); }
[ "public", "static", "void", "clearThreadMetaData", "(", "String", "tabName", ",", "String", "key", ")", "{", "THREAD_METADATA", ".", "get", "(", ")", ".", "clearKey", "(", "tabName", ",", "key", ")", ";", "}" ]
Clears a metadata key/value pair from a tab on the current thread @param tabName the name of the tab to that the metadata is in @param key the key of the metadata to remove
[ "Clears", "a", "metadata", "key", "/", "value", "pair", "from", "a", "tab", "on", "the", "current", "thread" ]
train
https://github.com/bugsnag/bugsnag-java/blob/11817d63949bcf2b2b6b765a1d37305cdec356f2/bugsnag/src/main/java/com/bugsnag/Bugsnag.java#L642-L644
aboutsip/pkts
pkts-sip/src/main/java/io/pkts/packet/sip/impl/SipMessageBuilder.java
SipMessageBuilder.addTrackedHeader
private short addTrackedHeader(final short index, final SipHeader header) { if (index != -1) { headers.set(index, header.ensure()); return index; } return addHeader(header.ensure()); }
java
private short addTrackedHeader(final short index, final SipHeader header) { if (index != -1) { headers.set(index, header.ensure()); return index; } return addHeader(header.ensure()); }
[ "private", "short", "addTrackedHeader", "(", "final", "short", "index", ",", "final", "SipHeader", "header", ")", "{", "if", "(", "index", "!=", "-", "1", ")", "{", "headers", ".", "set", "(", "index", ",", "header", ".", "ensure", "(", ")", ")", ";"...
There are several headers that we want to know their position and in that case we use this method to add them since we want to either add them to a particular position or we want to remember which index we added them to.
[ "There", "are", "several", "headers", "that", "we", "want", "to", "know", "their", "position", "and", "in", "that", "case", "we", "use", "this", "method", "to", "add", "them", "since", "we", "want", "to", "either", "add", "them", "to", "a", "particular",...
train
https://github.com/aboutsip/pkts/blob/0f06bb0dac76c812187829f580a8d476ca99a1a1/pkts-sip/src/main/java/io/pkts/packet/sip/impl/SipMessageBuilder.java#L167-L173
stratosphere/stratosphere
stratosphere-core/src/main/java/eu/stratosphere/configuration/Configuration.java
Configuration.getFloat
public float getFloat(final String key, final float defaultValue) { String val = getStringInternal(key); if (val == null) { return defaultValue; } else { return Float.parseFloat(val); } }
java
public float getFloat(final String key, final float defaultValue) { String val = getStringInternal(key); if (val == null) { return defaultValue; } else { return Float.parseFloat(val); } }
[ "public", "float", "getFloat", "(", "final", "String", "key", ",", "final", "float", "defaultValue", ")", "{", "String", "val", "=", "getStringInternal", "(", "key", ")", ";", "if", "(", "val", "==", "null", ")", "{", "return", "defaultValue", ";", "}", ...
Returns the value associated with the given key as a float. @param key the key pointing to the associated value @param defaultValue the default value which is returned in case there is no value associated with the given key @return the (default) value associated with the given key
[ "Returns", "the", "value", "associated", "with", "the", "given", "key", "as", "a", "float", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-core/src/main/java/eu/stratosphere/configuration/Configuration.java#L272-L279
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.warnAboutNamespaceAliasing
private void warnAboutNamespaceAliasing(Name nameObj, Ref ref) { compiler.report(JSError.make(ref.getNode(), UNSAFE_NAMESPACE_WARNING, nameObj.getFullName())); }
java
private void warnAboutNamespaceAliasing(Name nameObj, Ref ref) { compiler.report(JSError.make(ref.getNode(), UNSAFE_NAMESPACE_WARNING, nameObj.getFullName())); }
[ "private", "void", "warnAboutNamespaceAliasing", "(", "Name", "nameObj", ",", "Ref", "ref", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "ref", ".", "getNode", "(", ")", ",", "UNSAFE_NAMESPACE_WARNING", ",", "nameObj", ".", "getFull...
Reports a warning because a namespace was aliased. @param nameObj A namespace that is being aliased @param ref The reference that forced the alias
[ "Reports", "a", "warning", "because", "a", "namespace", "was", "aliased", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L224-L226
opendatatrentino/s-match
src/main/java/it/unitn/disi/common/components/Configurable.java
Configurable.makeComponentPrefix
protected static String makeComponentPrefix(String tokenName, String className) { String simpleClassName = className; if (null != className) { int lastDotIdx = className.lastIndexOf("."); if (lastDotIdx > -1) { simpleClassName = className.substring(lastDotIdx + 1, className.length()); } } return tokenName + "." + simpleClassName + "."; }
java
protected static String makeComponentPrefix(String tokenName, String className) { String simpleClassName = className; if (null != className) { int lastDotIdx = className.lastIndexOf("."); if (lastDotIdx > -1) { simpleClassName = className.substring(lastDotIdx + 1, className.length()); } } return tokenName + "." + simpleClassName + "."; }
[ "protected", "static", "String", "makeComponentPrefix", "(", "String", "tokenName", ",", "String", "className", ")", "{", "String", "simpleClassName", "=", "className", ";", "if", "(", "null", "!=", "className", ")", "{", "int", "lastDotIdx", "=", "className", ...
Creates a prefix for component to search for its properties in properties. @param tokenName a component configuration key @param className a component class name @return prefix
[ "Creates", "a", "prefix", "for", "component", "to", "search", "for", "its", "properties", "in", "properties", "." ]
train
https://github.com/opendatatrentino/s-match/blob/ba5982ef406b7010c2f92592e43887a485935aa1/src/main/java/it/unitn/disi/common/components/Configurable.java#L81-L90
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/util/TimeoutHelper.java
TimeoutHelper.callWithTimeout
public void callWithTimeout(String description, int timeout, Runnable task) { Future<?> callFuture = threadPool.submit(task); getWithTimeout(callFuture, timeout, description); }
java
public void callWithTimeout(String description, int timeout, Runnable task) { Future<?> callFuture = threadPool.submit(task); getWithTimeout(callFuture, timeout, description); }
[ "public", "void", "callWithTimeout", "(", "String", "description", ",", "int", "timeout", ",", "Runnable", "task", ")", "{", "Future", "<", "?", ">", "callFuture", "=", "threadPool", ".", "submit", "(", "task", ")", ";", "getWithTimeout", "(", "callFuture", ...
Calls task but ensures it ends. @param description description of task. @param timeout timeout in milliseconds. @param task task to execute.
[ "Calls", "task", "but", "ensures", "it", "ends", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/TimeoutHelper.java#L36-L39
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/util/rawQuerying/RawQueryExecutor.java
RawQueryExecutor.n1qlToRawCustom
public <T> T n1qlToRawCustom(final N1qlQuery query, final Func1<TranscoderUtils.ByteBufToArray, T> deserializer) { return Blocking.blockForSingle(async.n1qlToRawCustom(query, deserializer), env.queryTimeout(), TimeUnit.MILLISECONDS); }
java
public <T> T n1qlToRawCustom(final N1qlQuery query, final Func1<TranscoderUtils.ByteBufToArray, T> deserializer) { return Blocking.blockForSingle(async.n1qlToRawCustom(query, deserializer), env.queryTimeout(), TimeUnit.MILLISECONDS); }
[ "public", "<", "T", ">", "T", "n1qlToRawCustom", "(", "final", "N1qlQuery", "query", ",", "final", "Func1", "<", "TranscoderUtils", ".", "ByteBufToArray", ",", "T", ">", "deserializer", ")", "{", "return", "Blocking", ".", "blockForSingle", "(", "async", "."...
Synchronously perform a {@link N1qlQuery} and apply a user function to deserialize the raw N1QL response, which is represented as a "TranscoderUtils.ByteBufToArray". The array is derived from a {@link ByteBuf} that will be released, so it shouldn't be used to back the returned instance. Its scope should be considered the scope of the call method. Note that the query is executed "as is", without any processing comparable to what is done in {@link Bucket#query(N1qlQuery)} (like enforcing a server side timeout or managing prepared statements). @param query the query to execute. @param deserializer a deserializer function that transforms the byte representation of the response into a custom type T. @param <T> the type of the response, once deserialized by the user-provided function. @return the N1QL response as a T.
[ "Synchronously", "perform", "a", "{", "@link", "N1qlQuery", "}", "and", "apply", "a", "user", "function", "to", "deserialize", "the", "raw", "N1QL", "response", "which", "is", "represented", "as", "a", "TranscoderUtils", ".", "ByteBufToArray", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/util/rawQuerying/RawQueryExecutor.java#L110-L112
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/shape/Line.java
Line.drawDashedLine
protected void drawDashedLine(final Context2D context, double x, double y, final double x2, final double y2, final double[] da, final double plus) { final int dashCount = da.length; final double dx = (x2 - x); final double dy = (y2 - y); final boolean xbig = (Math.abs(dx) > Math.abs(dy)); final double slope = (xbig) ? dy / dx : dx / dy; context.moveTo(x, y); double distRemaining = Math.sqrt((dx * dx) + (dy * dy)) + plus; int dashIndex = 0; while (distRemaining >= 0.1) { final double dashLength = Math.min(distRemaining, da[dashIndex % dashCount]); double step = Math.sqrt((dashLength * dashLength) / (1 + (slope * slope))); if (xbig) { if (dx < 0) { step = -step; } x += step; y += slope * step; } else { if (dy < 0) { step = -step; } x += slope * step; y += step; } if ((dashIndex % 2) == 0) { context.lineTo(x, y); } else { context.moveTo(x, y); } distRemaining -= dashLength; dashIndex++; } }
java
protected void drawDashedLine(final Context2D context, double x, double y, final double x2, final double y2, final double[] da, final double plus) { final int dashCount = da.length; final double dx = (x2 - x); final double dy = (y2 - y); final boolean xbig = (Math.abs(dx) > Math.abs(dy)); final double slope = (xbig) ? dy / dx : dx / dy; context.moveTo(x, y); double distRemaining = Math.sqrt((dx * dx) + (dy * dy)) + plus; int dashIndex = 0; while (distRemaining >= 0.1) { final double dashLength = Math.min(distRemaining, da[dashIndex % dashCount]); double step = Math.sqrt((dashLength * dashLength) / (1 + (slope * slope))); if (xbig) { if (dx < 0) { step = -step; } x += step; y += slope * step; } else { if (dy < 0) { step = -step; } x += slope * step; y += step; } if ((dashIndex % 2) == 0) { context.lineTo(x, y); } else { context.moveTo(x, y); } distRemaining -= dashLength; dashIndex++; } }
[ "protected", "void", "drawDashedLine", "(", "final", "Context2D", "context", ",", "double", "x", ",", "double", "y", ",", "final", "double", "x2", ",", "final", "double", "y2", ",", "final", "double", "[", "]", "da", ",", "final", "double", "plus", ")", ...
Draws a dashed line instead of a solid one for the shape. @param context @param x @param y @param x2 @param y2 @param da @param state @param plus
[ "Draws", "a", "dashed", "line", "instead", "of", "a", "solid", "one", "for", "the", "shape", "." ]
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/shape/Line.java#L231-L287
r0adkll/PostOffice
library/src/main/java/com/r0adkll/postoffice/widgets/MaterialButtonLayout.java
MaterialButtonLayout.onLayout
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if(getOrientation() == HORIZONTAL) { int N = getChildCount(); for (int i = 0; i < N; i++) { View child = getChildAt(i); int width = child.getWidth(); if (width > MAX_BUTTON_WIDTH || (N>=3 && width > MIN_BUTTON_WIDTH)) { // Clear out the children list in preparation for new manipulation children.clear(); // Update the children's params for (int j = 0; j < N; j++) { RippleView chd = (RippleView) getChildAt(j); Button btn = (Button) chd.getChildAt(0); btn.setGravity(Gravity.END|Gravity.CENTER_VERTICAL); children.add(chd); } // Clear out the chitlens removeAllViews(); // Sort buttons properly Collections.sort(children, mButtonComparator); // Re-Add all the views for(int j=0; j<children.size(); j++){ View chd = children.get(j); addView(chd); } // Switch orientation setOrientation(VERTICAL); requestLayout(); return; } } } }
java
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if(getOrientation() == HORIZONTAL) { int N = getChildCount(); for (int i = 0; i < N; i++) { View child = getChildAt(i); int width = child.getWidth(); if (width > MAX_BUTTON_WIDTH || (N>=3 && width > MIN_BUTTON_WIDTH)) { // Clear out the children list in preparation for new manipulation children.clear(); // Update the children's params for (int j = 0; j < N; j++) { RippleView chd = (RippleView) getChildAt(j); Button btn = (Button) chd.getChildAt(0); btn.setGravity(Gravity.END|Gravity.CENTER_VERTICAL); children.add(chd); } // Clear out the chitlens removeAllViews(); // Sort buttons properly Collections.sort(children, mButtonComparator); // Re-Add all the views for(int j=0; j<children.size(); j++){ View chd = children.get(j); addView(chd); } // Switch orientation setOrientation(VERTICAL); requestLayout(); return; } } } }
[ "@", "Override", "protected", "void", "onLayout", "(", "boolean", "changed", ",", "int", "l", ",", "int", "t", ",", "int", "r", ",", "int", "b", ")", "{", "super", ".", "onLayout", "(", "changed", ",", "l", ",", "t", ",", "r", ",", "b", ")", ";...
if we detect that one of the dialog buttons are greater than the max horizontal layout width of 124dp then to switch the orientation to {@link #VERTICAL}
[ "if", "we", "detect", "that", "one", "of", "the", "dialog", "buttons", "are", "greater", "than", "the", "max", "horizontal", "layout", "width", "of", "124dp", "then", "to", "switch", "the", "orientation", "to", "{", "@link", "#VERTICAL", "}" ]
train
https://github.com/r0adkll/PostOffice/blob/f98e365fd66c004ccce64ee87d9f471b97e4e3c2/library/src/main/java/com/r0adkll/postoffice/widgets/MaterialButtonLayout.java#L85-L131
googleads/googleads-java-lib
examples/admanager_axis/src/main/java/admanager/axis/v201808/customfieldservice/GetAllCustomFields.java
GetAllCustomFields.runExample
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the CustomFieldService. CustomFieldServiceInterface customFieldService = adManagerServices.get(session, CustomFieldServiceInterface.class); // Create a statement to get all custom fields. StatementBuilder statementBuilder = new StatementBuilder() .orderBy("id ASC") .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); // Default for total result set size. int totalResultSetSize = 0; do { // Get custom fields by statement. CustomFieldPage page = customFieldService.getCustomFieldsByStatement(statementBuilder.toStatement()); if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); int i = page.getStartIndex(); for (CustomField customField : page.getResults()) { System.out.printf( "%d) Custom field with ID %d and name '%s' was found.%n", i++, customField.getId(), customField.getName()); } } statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.getOffset() < totalResultSetSize); System.out.printf("Number of results found: %d%n", totalResultSetSize); }
java
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the CustomFieldService. CustomFieldServiceInterface customFieldService = adManagerServices.get(session, CustomFieldServiceInterface.class); // Create a statement to get all custom fields. StatementBuilder statementBuilder = new StatementBuilder() .orderBy("id ASC") .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); // Default for total result set size. int totalResultSetSize = 0; do { // Get custom fields by statement. CustomFieldPage page = customFieldService.getCustomFieldsByStatement(statementBuilder.toStatement()); if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); int i = page.getStartIndex(); for (CustomField customField : page.getResults()) { System.out.printf( "%d) Custom field with ID %d and name '%s' was found.%n", i++, customField.getId(), customField.getName()); } } statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.getOffset() < totalResultSetSize); System.out.printf("Number of results found: %d%n", totalResultSetSize); }
[ "public", "static", "void", "runExample", "(", "AdManagerServices", "adManagerServices", ",", "AdManagerSession", "session", ")", "throws", "RemoteException", "{", "// Get the CustomFieldService.", "CustomFieldServiceInterface", "customFieldService", "=", "adManagerServices", "...
Runs the example. @param adManagerServices the services factory. @param session the session. @throws ApiException if the API request failed with one or more service errors. @throws RemoteException if the API request failed due to other errors.
[ "Runs", "the", "example", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201808/customfieldservice/GetAllCustomFields.java#L52-L85
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/scheduler/SchedulerTask.java
SchedulerTask.checkRunnable
private void checkRunnable(Class<?> type) { if(Runnable.class.isAssignableFrom(type)) { try{ this.method = type.getMethod("run"); } catch(Exception e) { throw new RuntimeException("Cannot get run method of runnable class.", e); } } }
java
private void checkRunnable(Class<?> type) { if(Runnable.class.isAssignableFrom(type)) { try{ this.method = type.getMethod("run"); } catch(Exception e) { throw new RuntimeException("Cannot get run method of runnable class.", e); } } }
[ "private", "void", "checkRunnable", "(", "Class", "<", "?", ">", "type", ")", "{", "if", "(", "Runnable", ".", "class", ".", "isAssignableFrom", "(", "type", ")", ")", "{", "try", "{", "this", ".", "method", "=", "type", ".", "getMethod", "(", "\"run...
Checks if the type is a Runnable and gets the run method. @param type
[ "Checks", "if", "the", "type", "is", "a", "Runnable", "and", "gets", "the", "run", "method", "." ]
train
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/scheduler/SchedulerTask.java#L117-L125
dropwizard/dropwizard
dropwizard-core/src/main/java/io/dropwizard/cli/CheckCommand.java
CheckCommand.onError
@Override public void onError(Cli cli, Namespace namespace, Throwable e) { cli.getStdErr().println(e.getMessage()); }
java
@Override public void onError(Cli cli, Namespace namespace, Throwable e) { cli.getStdErr().println(e.getMessage()); }
[ "@", "Override", "public", "void", "onError", "(", "Cli", "cli", ",", "Namespace", "namespace", ",", "Throwable", "e", ")", "{", "cli", ".", "getStdErr", "(", ")", ".", "println", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}" ]
/* The stacktrace is redundant as the message contains the yaml error location
[ "/", "*", "The", "stacktrace", "is", "redundant", "as", "the", "message", "contains", "the", "yaml", "error", "location" ]
train
https://github.com/dropwizard/dropwizard/blob/7ee09a410476b9681e8072ab684788bb440877bd/dropwizard-core/src/main/java/io/dropwizard/cli/CheckCommand.java#L42-L45
FINRAOS/JTAF-ExtWebDriver
src/main/java/org/finra/jtaf/ewd/properties/GUIHierarchyConcatenationProperties.java
GUIHierarchyConcatenationProperties.getPropertyValueAsList
public List<String> getPropertyValueAsList(String key, String... parameters) { return getPropertyValueAsList(new String[] { key }, parameters); }
java
public List<String> getPropertyValueAsList(String key, String... parameters) { return getPropertyValueAsList(new String[] { key }, parameters); }
[ "public", "List", "<", "String", ">", "getPropertyValueAsList", "(", "String", "key", ",", "String", "...", "parameters", ")", "{", "return", "getPropertyValueAsList", "(", "new", "String", "[", "]", "{", "key", "}", ",", "parameters", ")", ";", "}" ]
Searches over the group of {@code GUIProperties} for a property list corresponding to the given key. @param key key to be found @param parameters instances of the {@code String} literal <code>"{n}"</code> in the retrieved value will be replaced by {@code params[n]} @return the first property list found associated with a concatenation of the given names @throws MissingGUIPropertyException
[ "Searches", "over", "the", "group", "of", "{", "@code", "GUIProperties", "}", "for", "a", "property", "list", "corresponding", "to", "the", "given", "key", "." ]
train
https://github.com/FINRAOS/JTAF-ExtWebDriver/blob/78d646def1bf0904f79b19a81df0241e07f2c73a/src/main/java/org/finra/jtaf/ewd/properties/GUIHierarchyConcatenationProperties.java#L254-L256
Ordinastie/MalisisCore
src/main/java/net/malisis/core/util/chunkcollision/ChunkCollision.java
ChunkCollision.updateBlocks
public void updateBlocks(World world, MBlockState state) { AxisAlignedBB[] aabbs = AABBUtils.getCollisionBoundingBoxes(world, state, true); for (AxisAlignedBB aabb : aabbs) { if (aabb == null) continue; for (BlockPos pos : BlockPosUtils.getAllInBox(aabb)) world.neighborChanged(pos, state.getBlock(), state.getPos()); } }
java
public void updateBlocks(World world, MBlockState state) { AxisAlignedBB[] aabbs = AABBUtils.getCollisionBoundingBoxes(world, state, true); for (AxisAlignedBB aabb : aabbs) { if (aabb == null) continue; for (BlockPos pos : BlockPosUtils.getAllInBox(aabb)) world.neighborChanged(pos, state.getBlock(), state.getPos()); } }
[ "public", "void", "updateBlocks", "(", "World", "world", ",", "MBlockState", "state", ")", "{", "AxisAlignedBB", "[", "]", "aabbs", "=", "AABBUtils", ".", "getCollisionBoundingBoxes", "(", "world", ",", "state", ",", "true", ")", ";", "for", "(", "AxisAligne...
Notifies all the blocks colliding with the {@link AxisAlignedBB} of the {@link MBlockState}. @param world the world @param state the state
[ "Notifies", "all", "the", "blocks", "colliding", "with", "the", "{", "@link", "AxisAlignedBB", "}", "of", "the", "{", "@link", "MBlockState", "}", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/chunkcollision/ChunkCollision.java#L288-L299