repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
jeremylong/DependencyCheck
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
BaseDependencyCheckMojo.scanArtifacts
protected ExceptionCollection scanArtifacts(MavenProject project, Engine engine) { """ Scans the project's artifacts and adds them to the engine's dependency list. @param project the project to scan the dependencies of @param engine the engine to use to scan the dependencies @return a collection of exceptions that may have occurred while resolving and scanning the dependencies """ return scanArtifacts(project, engine, false); }
java
protected ExceptionCollection scanArtifacts(MavenProject project, Engine engine) { return scanArtifacts(project, engine, false); }
[ "protected", "ExceptionCollection", "scanArtifacts", "(", "MavenProject", "project", ",", "Engine", "engine", ")", "{", "return", "scanArtifacts", "(", "project", ",", "engine", ",", "false", ")", ";", "}" ]
Scans the project's artifacts and adds them to the engine's dependency list. @param project the project to scan the dependencies of @param engine the engine to use to scan the dependencies @return a collection of exceptions that may have occurred while resolving and scanning the dependencies
[ "Scans", "the", "project", "s", "artifacts", "and", "adds", "them", "to", "the", "engine", "s", "dependency", "list", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L829-L831
taskadapter/redmine-java-api
src/main/java/com/taskadapter/redmineapi/TimeEntryManager.java
TimeEntryManager.getTimeEntries
public ResultsWrapper<TimeEntry> getTimeEntries(Map<String, String> parameters) throws RedmineException { """ Direct method to search for objects using any Redmine REST API parameters you want. <p>Unlike other getXXXObjects() methods in this library, this one does NOT handle paging for you so you have to provide "offset" and "limit" parameters if you want to control paging. <p>Sample usage: <pre> final Map<String, String> params = new HashMap<String, String>(); params.put("project_id", projectId); params.put("activity_id", activityId); final List<TimeEntry> elements = issueManager.getTimeEntries(params); </pre> see other possible parameters on Redmine REST doc page: http://www.redmine.org/projects/redmine/wiki/Rest_TimeEntries#Listing-time-entries @param parameters the http parameters key/value pairs to append to the rest api request @return resultsWrapper with raw response from Redmine REST API @throws RedmineAuthenticationException invalid or no API access key is used with the server, which requires authorization. Check the constructor arguments. @throws RedmineException """ return DirectObjectsSearcher.getObjectsListNoPaging(transport, parameters, TimeEntry.class); }
java
public ResultsWrapper<TimeEntry> getTimeEntries(Map<String, String> parameters) throws RedmineException { return DirectObjectsSearcher.getObjectsListNoPaging(transport, parameters, TimeEntry.class); }
[ "public", "ResultsWrapper", "<", "TimeEntry", ">", "getTimeEntries", "(", "Map", "<", "String", ",", "String", ">", "parameters", ")", "throws", "RedmineException", "{", "return", "DirectObjectsSearcher", ".", "getObjectsListNoPaging", "(", "transport", ",", "parameters", ",", "TimeEntry", ".", "class", ")", ";", "}" ]
Direct method to search for objects using any Redmine REST API parameters you want. <p>Unlike other getXXXObjects() methods in this library, this one does NOT handle paging for you so you have to provide "offset" and "limit" parameters if you want to control paging. <p>Sample usage: <pre> final Map<String, String> params = new HashMap<String, String>(); params.put("project_id", projectId); params.put("activity_id", activityId); final List<TimeEntry> elements = issueManager.getTimeEntries(params); </pre> see other possible parameters on Redmine REST doc page: http://www.redmine.org/projects/redmine/wiki/Rest_TimeEntries#Listing-time-entries @param parameters the http parameters key/value pairs to append to the rest api request @return resultsWrapper with raw response from Redmine REST API @throws RedmineAuthenticationException invalid or no API access key is used with the server, which requires authorization. Check the constructor arguments. @throws RedmineException
[ "Direct", "method", "to", "search", "for", "objects", "using", "any", "Redmine", "REST", "API", "parameters", "you", "want", ".", "<p", ">", "Unlike", "other", "getXXXObjects", "()", "methods", "in", "this", "library", "this", "one", "does", "NOT", "handle", "paging", "for", "you", "so", "you", "have", "to", "provide", "offset", "and", "limit", "parameters", "if", "you", "want", "to", "control", "paging", "." ]
train
https://github.com/taskadapter/redmine-java-api/blob/0bb65f27ee806ec3bd4007e1641f3e996261a04e/src/main/java/com/taskadapter/redmineapi/TimeEntryManager.java#L68-L70
zk1931/jzab
src/main/java/com/github/zk1931/jzab/MessageBuilder.java
MessageBuilder.buildAckEpoch
public static Message buildAckEpoch(long epoch, Zxid lastZxid) { """ Creates a ACK_EPOCH message. @param epoch the last leader proposal the follower has acknowledged. @param lastZxid the last zxid of the follower. @return the protobuf message. """ ZabMessage.Zxid zxid = toProtoZxid(lastZxid); AckEpoch ackEpoch = AckEpoch.newBuilder() .setAcknowledgedEpoch(epoch) .setLastZxid(zxid) .build(); return Message.newBuilder().setType(MessageType.ACK_EPOCH) .setAckEpoch(ackEpoch) .build(); }
java
public static Message buildAckEpoch(long epoch, Zxid lastZxid) { ZabMessage.Zxid zxid = toProtoZxid(lastZxid); AckEpoch ackEpoch = AckEpoch.newBuilder() .setAcknowledgedEpoch(epoch) .setLastZxid(zxid) .build(); return Message.newBuilder().setType(MessageType.ACK_EPOCH) .setAckEpoch(ackEpoch) .build(); }
[ "public", "static", "Message", "buildAckEpoch", "(", "long", "epoch", ",", "Zxid", "lastZxid", ")", "{", "ZabMessage", ".", "Zxid", "zxid", "=", "toProtoZxid", "(", "lastZxid", ")", ";", "AckEpoch", "ackEpoch", "=", "AckEpoch", ".", "newBuilder", "(", ")", ".", "setAcknowledgedEpoch", "(", "epoch", ")", ".", "setLastZxid", "(", "zxid", ")", ".", "build", "(", ")", ";", "return", "Message", ".", "newBuilder", "(", ")", ".", "setType", "(", "MessageType", ".", "ACK_EPOCH", ")", ".", "setAckEpoch", "(", "ackEpoch", ")", ".", "build", "(", ")", ";", "}" ]
Creates a ACK_EPOCH message. @param epoch the last leader proposal the follower has acknowledged. @param lastZxid the last zxid of the follower. @return the protobuf message.
[ "Creates", "a", "ACK_EPOCH", "message", "." ]
train
https://github.com/zk1931/jzab/blob/2a8893bcc1a125f3aebdaddee80ad49c9761bba1/src/main/java/com/github/zk1931/jzab/MessageBuilder.java#L155-L166
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/config/Config.java
Config.setCacheConfigs
public Config setCacheConfigs(Map<String, CacheSimpleConfig> cacheConfigs) { """ Sets the map of cache configurations, mapped by config name. The config name may be a pattern with which the configuration was initially obtained. @param cacheConfigs the cacheConfigs to set @return this config instance """ this.cacheConfigs.clear(); this.cacheConfigs.putAll(cacheConfigs); for (final Entry<String, CacheSimpleConfig> entry : this.cacheConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
java
public Config setCacheConfigs(Map<String, CacheSimpleConfig> cacheConfigs) { this.cacheConfigs.clear(); this.cacheConfigs.putAll(cacheConfigs); for (final Entry<String, CacheSimpleConfig> entry : this.cacheConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
[ "public", "Config", "setCacheConfigs", "(", "Map", "<", "String", ",", "CacheSimpleConfig", ">", "cacheConfigs", ")", "{", "this", ".", "cacheConfigs", ".", "clear", "(", ")", ";", "this", ".", "cacheConfigs", ".", "putAll", "(", "cacheConfigs", ")", ";", "for", "(", "final", "Entry", "<", "String", ",", "CacheSimpleConfig", ">", "entry", ":", "this", ".", "cacheConfigs", ".", "entrySet", "(", ")", ")", "{", "entry", ".", "getValue", "(", ")", ".", "setName", "(", "entry", ".", "getKey", "(", ")", ")", ";", "}", "return", "this", ";", "}" ]
Sets the map of cache configurations, mapped by config name. The config name may be a pattern with which the configuration was initially obtained. @param cacheConfigs the cacheConfigs to set @return this config instance
[ "Sets", "the", "map", "of", "cache", "configurations", "mapped", "by", "config", "name", ".", "The", "config", "name", "may", "be", "a", "pattern", "with", "which", "the", "configuration", "was", "initially", "obtained", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/Config.java#L608-L615
pravega/pravega
common/src/main/java/io/pravega/common/util/BitConverter.java
BitConverter.readShort
public static short readShort(ArrayView source, int position) { """ Reads a 16-bit Short from the given ArrayView starting at the given position. @param source The ArrayView to read from. @param position The position in the ArrayView to start reading at. @return The read number. """ return (short) ((source.get(position) & 0xFF) << 8 | (source.get(position + 1) & 0xFF)); }
java
public static short readShort(ArrayView source, int position) { return (short) ((source.get(position) & 0xFF) << 8 | (source.get(position + 1) & 0xFF)); }
[ "public", "static", "short", "readShort", "(", "ArrayView", "source", ",", "int", "position", ")", "{", "return", "(", "short", ")", "(", "(", "source", ".", "get", "(", "position", ")", "&", "0xFF", ")", "<<", "8", "|", "(", "source", ".", "get", "(", "position", "+", "1", ")", "&", "0xFF", ")", ")", ";", "}" ]
Reads a 16-bit Short from the given ArrayView starting at the given position. @param source The ArrayView to read from. @param position The position in the ArrayView to start reading at. @return The read number.
[ "Reads", "a", "16", "-", "bit", "Short", "from", "the", "given", "ArrayView", "starting", "at", "the", "given", "position", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/util/BitConverter.java#L111-L114
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/TimeSeriesUtils.java
TimeSeriesUtils.reshapeCnnMaskToTimeSeriesMask
public static INDArray reshapeCnnMaskToTimeSeriesMask(INDArray timeSeriesMaskAsCnnMask, int minibatchSize) { """ Reshape CNN-style 4d mask array of shape [seqLength*minibatch,1,1,1] to time series mask [mb,seqLength] This should match the assumptions (f order, etc) in RnnOutputLayer @param timeSeriesMaskAsCnnMask Mask array to reshape @return Sequence mask array - [minibatch, sequenceLength] """ Preconditions.checkArgument(timeSeriesMaskAsCnnMask.rank() == 4 || timeSeriesMaskAsCnnMask.size(1) != 1 || timeSeriesMaskAsCnnMask.size(2) != 1 || timeSeriesMaskAsCnnMask.size(3) != 1, "Expected rank 4 mask with shape [mb*seqLength, 1, 1, 1]. Got rank %s mask array with shape %s", timeSeriesMaskAsCnnMask.rank(), timeSeriesMaskAsCnnMask.shape()); val timeSeriesLength = timeSeriesMaskAsCnnMask.length() / minibatchSize; return timeSeriesMaskAsCnnMask.reshape('f', minibatchSize, timeSeriesLength); }
java
public static INDArray reshapeCnnMaskToTimeSeriesMask(INDArray timeSeriesMaskAsCnnMask, int minibatchSize) { Preconditions.checkArgument(timeSeriesMaskAsCnnMask.rank() == 4 || timeSeriesMaskAsCnnMask.size(1) != 1 || timeSeriesMaskAsCnnMask.size(2) != 1 || timeSeriesMaskAsCnnMask.size(3) != 1, "Expected rank 4 mask with shape [mb*seqLength, 1, 1, 1]. Got rank %s mask array with shape %s", timeSeriesMaskAsCnnMask.rank(), timeSeriesMaskAsCnnMask.shape()); val timeSeriesLength = timeSeriesMaskAsCnnMask.length() / minibatchSize; return timeSeriesMaskAsCnnMask.reshape('f', minibatchSize, timeSeriesLength); }
[ "public", "static", "INDArray", "reshapeCnnMaskToTimeSeriesMask", "(", "INDArray", "timeSeriesMaskAsCnnMask", ",", "int", "minibatchSize", ")", "{", "Preconditions", ".", "checkArgument", "(", "timeSeriesMaskAsCnnMask", ".", "rank", "(", ")", "==", "4", "||", "timeSeriesMaskAsCnnMask", ".", "size", "(", "1", ")", "!=", "1", "||", "timeSeriesMaskAsCnnMask", ".", "size", "(", "2", ")", "!=", "1", "||", "timeSeriesMaskAsCnnMask", ".", "size", "(", "3", ")", "!=", "1", ",", "\"Expected rank 4 mask with shape [mb*seqLength, 1, 1, 1]. Got rank %s mask array with shape %s\"", ",", "timeSeriesMaskAsCnnMask", ".", "rank", "(", ")", ",", "timeSeriesMaskAsCnnMask", ".", "shape", "(", ")", ")", ";", "val", "timeSeriesLength", "=", "timeSeriesMaskAsCnnMask", ".", "length", "(", ")", "/", "minibatchSize", ";", "return", "timeSeriesMaskAsCnnMask", ".", "reshape", "(", "'", "'", ",", "minibatchSize", ",", "timeSeriesLength", ")", ";", "}" ]
Reshape CNN-style 4d mask array of shape [seqLength*minibatch,1,1,1] to time series mask [mb,seqLength] This should match the assumptions (f order, etc) in RnnOutputLayer @param timeSeriesMaskAsCnnMask Mask array to reshape @return Sequence mask array - [minibatch, sequenceLength]
[ "Reshape", "CNN", "-", "style", "4d", "mask", "array", "of", "shape", "[", "seqLength", "*", "minibatch", "1", "1", "1", "]", "to", "time", "series", "mask", "[", "mb", "seqLength", "]", "This", "should", "match", "the", "assumptions", "(", "f", "order", "etc", ")", "in", "RnnOutputLayer" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/TimeSeriesUtils.java#L125-L134
phax/ph-oton
ph-oton-security/src/main/java/com/helger/photon/security/usergroup/UserGroupManager.java
UserGroupManager.createPredefinedUserGroup
@Nonnull public IUserGroup createPredefinedUserGroup (@Nonnull @Nonempty final String sID, @Nonnull @Nonempty final String sName, @Nullable final String sDescription, @Nullable final Map <String, String> aCustomAttrs) { """ Create a predefined user group. @param sID The ID to use @param sName The name of the user group to create. May neither be <code>null</code> nor empty. @param sDescription The optional description of the user group. May be <code>null</code> . @param aCustomAttrs A set of custom attributes. May be <code>null</code>. @return The created user group. """ // Create user group final UserGroup aUserGroup = new UserGroup (StubObject.createForCurrentUserAndID (sID, aCustomAttrs), sName, sDescription); m_aRWLock.writeLocked ( () -> { // Store internalCreateItem (aUserGroup); }); AuditHelper.onAuditCreateSuccess (UserGroup.OT, aUserGroup.getID (), "predefined-usergroup", sName, sDescription, aCustomAttrs); // Execute callback as the very last action m_aCallbacks.forEach (aCB -> aCB.onUserGroupCreated (aUserGroup, true)); return aUserGroup; }
java
@Nonnull public IUserGroup createPredefinedUserGroup (@Nonnull @Nonempty final String sID, @Nonnull @Nonempty final String sName, @Nullable final String sDescription, @Nullable final Map <String, String> aCustomAttrs) { // Create user group final UserGroup aUserGroup = new UserGroup (StubObject.createForCurrentUserAndID (sID, aCustomAttrs), sName, sDescription); m_aRWLock.writeLocked ( () -> { // Store internalCreateItem (aUserGroup); }); AuditHelper.onAuditCreateSuccess (UserGroup.OT, aUserGroup.getID (), "predefined-usergroup", sName, sDescription, aCustomAttrs); // Execute callback as the very last action m_aCallbacks.forEach (aCB -> aCB.onUserGroupCreated (aUserGroup, true)); return aUserGroup; }
[ "@", "Nonnull", "public", "IUserGroup", "createPredefinedUserGroup", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sID", ",", "@", "Nonnull", "@", "Nonempty", "final", "String", "sName", ",", "@", "Nullable", "final", "String", "sDescription", ",", "@", "Nullable", "final", "Map", "<", "String", ",", "String", ">", "aCustomAttrs", ")", "{", "// Create user group", "final", "UserGroup", "aUserGroup", "=", "new", "UserGroup", "(", "StubObject", ".", "createForCurrentUserAndID", "(", "sID", ",", "aCustomAttrs", ")", ",", "sName", ",", "sDescription", ")", ";", "m_aRWLock", ".", "writeLocked", "(", "(", ")", "->", "{", "// Store", "internalCreateItem", "(", "aUserGroup", ")", ";", "}", ")", ";", "AuditHelper", ".", "onAuditCreateSuccess", "(", "UserGroup", ".", "OT", ",", "aUserGroup", ".", "getID", "(", ")", ",", "\"predefined-usergroup\"", ",", "sName", ",", "sDescription", ",", "aCustomAttrs", ")", ";", "// Execute callback as the very last action", "m_aCallbacks", ".", "forEach", "(", "aCB", "->", "aCB", ".", "onUserGroupCreated", "(", "aUserGroup", ",", "true", ")", ")", ";", "return", "aUserGroup", ";", "}" ]
Create a predefined user group. @param sID The ID to use @param sName The name of the user group to create. May neither be <code>null</code> nor empty. @param sDescription The optional description of the user group. May be <code>null</code> . @param aCustomAttrs A set of custom attributes. May be <code>null</code>. @return The created user group.
[ "Create", "a", "predefined", "user", "group", "." ]
train
https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-security/src/main/java/com/helger/photon/security/usergroup/UserGroupManager.java#L171-L197
kiegroup/jbpm
jbpm-query-jpa/src/main/java/org/jbpm/query/jpa/impl/QueryCriteriaUtil.java
QueryCriteriaUtil.getRoot
public static <T> Root getRoot(AbstractQuery<T> query, Class queryType) { """ This is a helper method to retrieve a particular {@link Root} from a {@link CriteriaQuery} instance @param query The {@link CriteriaQuery} instance that we're building @param queryType The {@link Class} matching the {@link Root} we want @return The {@link Root} matching the given {@link Class} or null if it's not in the query """ Root<?> table = null; for( Root<?> root : query.getRoots() ) { if( root.getJavaType().equals(queryType) ) { table = root; break; } } return table; }
java
public static <T> Root getRoot(AbstractQuery<T> query, Class queryType) { Root<?> table = null; for( Root<?> root : query.getRoots() ) { if( root.getJavaType().equals(queryType) ) { table = root; break; } } return table; }
[ "public", "static", "<", "T", ">", "Root", "getRoot", "(", "AbstractQuery", "<", "T", ">", "query", ",", "Class", "queryType", ")", "{", "Root", "<", "?", ">", "table", "=", "null", ";", "for", "(", "Root", "<", "?", ">", "root", ":", "query", ".", "getRoots", "(", ")", ")", "{", "if", "(", "root", ".", "getJavaType", "(", ")", ".", "equals", "(", "queryType", ")", ")", "{", "table", "=", "root", ";", "break", ";", "}", "}", "return", "table", ";", "}" ]
This is a helper method to retrieve a particular {@link Root} from a {@link CriteriaQuery} instance @param query The {@link CriteriaQuery} instance that we're building @param queryType The {@link Class} matching the {@link Root} we want @return The {@link Root} matching the given {@link Class} or null if it's not in the query
[ "This", "is", "a", "helper", "method", "to", "retrieve", "a", "particular", "{", "@link", "Root", "}", "from", "a", "{", "@link", "CriteriaQuery", "}", "instance" ]
train
https://github.com/kiegroup/jbpm/blob/c3473c728aa382ebbea01e380c5e754a96647b82/jbpm-query-jpa/src/main/java/org/jbpm/query/jpa/impl/QueryCriteriaUtil.java#L423-L432
VoltDB/voltdb
examples/geospatial/client/geospatial/AdBrokerBenchmark.java
AdBrokerBenchmark.getRandomPoint
private GeographyPointValue getRandomPoint() { """ Produce a random longitude/latitude point within the bounding box where advertisers are placing bids. @return a random point """ double lngRange = Regions.MAX_LNG - Regions.MIN_LNG; double lng = Regions.MIN_LNG + lngRange * m_rand.nextDouble(); double latRange = Regions.MAX_LAT - Regions.MIN_LAT; double lat = Regions.MIN_LAT + latRange * m_rand.nextDouble(); return new GeographyPointValue(lng, lat); }
java
private GeographyPointValue getRandomPoint() { double lngRange = Regions.MAX_LNG - Regions.MIN_LNG; double lng = Regions.MIN_LNG + lngRange * m_rand.nextDouble(); double latRange = Regions.MAX_LAT - Regions.MIN_LAT; double lat = Regions.MIN_LAT + latRange * m_rand.nextDouble(); return new GeographyPointValue(lng, lat); }
[ "private", "GeographyPointValue", "getRandomPoint", "(", ")", "{", "double", "lngRange", "=", "Regions", ".", "MAX_LNG", "-", "Regions", ".", "MIN_LNG", ";", "double", "lng", "=", "Regions", ".", "MIN_LNG", "+", "lngRange", "*", "m_rand", ".", "nextDouble", "(", ")", ";", "double", "latRange", "=", "Regions", ".", "MAX_LAT", "-", "Regions", ".", "MIN_LAT", ";", "double", "lat", "=", "Regions", ".", "MIN_LAT", "+", "latRange", "*", "m_rand", ".", "nextDouble", "(", ")", ";", "return", "new", "GeographyPointValue", "(", "lng", ",", "lat", ")", ";", "}" ]
Produce a random longitude/latitude point within the bounding box where advertisers are placing bids. @return a random point
[ "Produce", "a", "random", "longitude", "/", "latitude", "point", "within", "the", "bounding", "box", "where", "advertisers", "are", "placing", "bids", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/examples/geospatial/client/geospatial/AdBrokerBenchmark.java#L381-L389
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java
Resolve.resolveMethod
Symbol resolveMethod(DiagnosticPosition pos, Env<AttrContext> env, Name name, List<Type> argtypes, List<Type> typeargtypes) { """ Resolve an unqualified method identifier. @param pos The position to use for error reporting. @param env The environment current at the method invocation. @param name The identifier's name. @param argtypes The types of the invocation's value arguments. @param typeargtypes The types of the invocation's type arguments. """ return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck, new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) { @Override Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) { return findFun(env, name, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()); }}); }
java
Symbol resolveMethod(DiagnosticPosition pos, Env<AttrContext> env, Name name, List<Type> argtypes, List<Type> typeargtypes) { return lookupMethod(env, pos, env.enclClass.sym, resolveMethodCheck, new BasicLookupHelper(name, env.enclClass.sym.type, argtypes, typeargtypes) { @Override Symbol doLookup(Env<AttrContext> env, MethodResolutionPhase phase) { return findFun(env, name, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()); }}); }
[ "Symbol", "resolveMethod", "(", "DiagnosticPosition", "pos", ",", "Env", "<", "AttrContext", ">", "env", ",", "Name", "name", ",", "List", "<", "Type", ">", "argtypes", ",", "List", "<", "Type", ">", "typeargtypes", ")", "{", "return", "lookupMethod", "(", "env", ",", "pos", ",", "env", ".", "enclClass", ".", "sym", ",", "resolveMethodCheck", ",", "new", "BasicLookupHelper", "(", "name", ",", "env", ".", "enclClass", ".", "sym", ".", "type", ",", "argtypes", ",", "typeargtypes", ")", "{", "@", "Override", "Symbol", "doLookup", "(", "Env", "<", "AttrContext", ">", "env", ",", "MethodResolutionPhase", "phase", ")", "{", "return", "findFun", "(", "env", ",", "name", ",", "argtypes", ",", "typeargtypes", ",", "phase", ".", "isBoxingRequired", "(", ")", ",", "phase", ".", "isVarargsRequired", "(", ")", ")", ";", "}", "}", ")", ";", "}" ]
Resolve an unqualified method identifier. @param pos The position to use for error reporting. @param env The environment current at the method invocation. @param name The identifier's name. @param argtypes The types of the invocation's value arguments. @param typeargtypes The types of the invocation's type arguments.
[ "Resolve", "an", "unqualified", "method", "identifier", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java#L2586-L2599
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/bcp/OneVariableInstruction.java
OneVariableInstruction.addOrCheckDefinition
protected MatchResult addOrCheckDefinition(Variable variable, BindingSet bindingSet) { """ Add a variable definition to the given BindingSet, or if there is an existing definition, make sure it is consistent with the new definition. @param variable the Variable which should be added or checked for consistency @param bindingSet the existing set of bindings @return a MatchResult containing the updated BindingSet (if the variable is consistent with the previous bindings), or null if the new variable is inconsistent with the previous bindings """ bindingSet = addOrCheckDefinition(varName, variable, bindingSet); return bindingSet != null ? new MatchResult(this, bindingSet) : null; }
java
protected MatchResult addOrCheckDefinition(Variable variable, BindingSet bindingSet) { bindingSet = addOrCheckDefinition(varName, variable, bindingSet); return bindingSet != null ? new MatchResult(this, bindingSet) : null; }
[ "protected", "MatchResult", "addOrCheckDefinition", "(", "Variable", "variable", ",", "BindingSet", "bindingSet", ")", "{", "bindingSet", "=", "addOrCheckDefinition", "(", "varName", ",", "variable", ",", "bindingSet", ")", ";", "return", "bindingSet", "!=", "null", "?", "new", "MatchResult", "(", "this", ",", "bindingSet", ")", ":", "null", ";", "}" ]
Add a variable definition to the given BindingSet, or if there is an existing definition, make sure it is consistent with the new definition. @param variable the Variable which should be added or checked for consistency @param bindingSet the existing set of bindings @return a MatchResult containing the updated BindingSet (if the variable is consistent with the previous bindings), or null if the new variable is inconsistent with the previous bindings
[ "Add", "a", "variable", "definition", "to", "the", "given", "BindingSet", "or", "if", "there", "is", "an", "existing", "definition", "make", "sure", "it", "is", "consistent", "with", "the", "new", "definition", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/bcp/OneVariableInstruction.java#L53-L56
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/event/FieldDataScratchHandler.java
FieldDataScratchHandler.init
public void init(BaseField field, boolean bChangeDataOnRefresh) { """ Constructor. @param field The basefield owner of this listener (usually null and set on setOwner()). """ super.init(field); m_objOriginalData = null; m_bAlwaysEnabled = false; m_bChangeDataOnRefresh = bChangeDataOnRefresh; this.setRespondsToMode(DBConstants.SCREEN_MOVE, false); }
java
public void init(BaseField field, boolean bChangeDataOnRefresh) { super.init(field); m_objOriginalData = null; m_bAlwaysEnabled = false; m_bChangeDataOnRefresh = bChangeDataOnRefresh; this.setRespondsToMode(DBConstants.SCREEN_MOVE, false); }
[ "public", "void", "init", "(", "BaseField", "field", ",", "boolean", "bChangeDataOnRefresh", ")", "{", "super", ".", "init", "(", "field", ")", ";", "m_objOriginalData", "=", "null", ";", "m_bAlwaysEnabled", "=", "false", ";", "m_bChangeDataOnRefresh", "=", "bChangeDataOnRefresh", ";", "this", ".", "setRespondsToMode", "(", "DBConstants", ".", "SCREEN_MOVE", ",", "false", ")", ";", "}" ]
Constructor. @param field The basefield owner of this listener (usually null and set on setOwner()).
[ "Constructor", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/FieldDataScratchHandler.java#L68-L75
burberius/eve-esi
src/main/java/net/troja/eve/esi/api/FleetsApi.java
FleetsApi.deleteFleetsFleetIdSquadsSquadId
public void deleteFleetsFleetIdSquadsSquadId(Long fleetId, Long squadId, String datasource, String token) throws ApiException { """ Delete fleet squad Delete a fleet squad, only empty squads can be deleted --- SSO Scope: esi-fleets.write_fleet.v1 @param fleetId ID for a fleet (required) @param squadId The squad to delete (required) @param datasource The server name you would like data from (optional, default to tranquility) @param token Access token to use if unable to set a header (optional) @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ deleteFleetsFleetIdSquadsSquadIdWithHttpInfo(fleetId, squadId, datasource, token); }
java
public void deleteFleetsFleetIdSquadsSquadId(Long fleetId, Long squadId, String datasource, String token) throws ApiException { deleteFleetsFleetIdSquadsSquadIdWithHttpInfo(fleetId, squadId, datasource, token); }
[ "public", "void", "deleteFleetsFleetIdSquadsSquadId", "(", "Long", "fleetId", ",", "Long", "squadId", ",", "String", "datasource", ",", "String", "token", ")", "throws", "ApiException", "{", "deleteFleetsFleetIdSquadsSquadIdWithHttpInfo", "(", "fleetId", ",", "squadId", ",", "datasource", ",", "token", ")", ";", "}" ]
Delete fleet squad Delete a fleet squad, only empty squads can be deleted --- SSO Scope: esi-fleets.write_fleet.v1 @param fleetId ID for a fleet (required) @param squadId The squad to delete (required) @param datasource The server name you would like data from (optional, default to tranquility) @param token Access token to use if unable to set a header (optional) @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Delete", "fleet", "squad", "Delete", "a", "fleet", "squad", "only", "empty", "squads", "can", "be", "deleted", "---", "SSO", "Scope", ":", "esi", "-", "fleets", ".", "write_fleet", ".", "v1" ]
train
https://github.com/burberius/eve-esi/blob/24a941c592cfc15f23471ef849b282fbc582ca13/src/main/java/net/troja/eve/esi/api/FleetsApi.java#L317-L320
sualeh/credit_card_number
src/main/java/us/fatehi/creditcardnumber/DisposableStringData.java
DisposableStringData.disposeData
public void disposeData(final int fromIndex, final int toIndex) { """ Wipes the data from memory, starting from the provided index, inclusive, and until the second index. Following recommendations from the <a href= "http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#PBEEx">Java Cryptography Architecture (JCA) Reference Guide</a> Also wipes raw data. """ Arrays.fill(data, max(0, fromIndex), min(data.length, toIndex), (char) 0); }
java
public void disposeData(final int fromIndex, final int toIndex) { Arrays.fill(data, max(0, fromIndex), min(data.length, toIndex), (char) 0); }
[ "public", "void", "disposeData", "(", "final", "int", "fromIndex", ",", "final", "int", "toIndex", ")", "{", "Arrays", ".", "fill", "(", "data", ",", "max", "(", "0", ",", "fromIndex", ")", ",", "min", "(", "data", ".", "length", ",", "toIndex", ")", ",", "(", "char", ")", "0", ")", ";", "}" ]
Wipes the data from memory, starting from the provided index, inclusive, and until the second index. Following recommendations from the <a href= "http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#PBEEx">Java Cryptography Architecture (JCA) Reference Guide</a> Also wipes raw data.
[ "Wipes", "the", "data", "from", "memory", "starting", "from", "the", "provided", "index", "inclusive", "and", "until", "the", "second", "index", ".", "Following", "recommendations", "from", "the", "<a", "href", "=", "http", ":", "//", "docs", ".", "oracle", ".", "com", "/", "javase", "/", "6", "/", "docs", "/", "technotes", "/", "guides", "/", "security", "/", "crypto", "/", "CryptoSpec", ".", "html#PBEEx", ">", "Java", "Cryptography", "Architecture", "(", "JCA", ")", "Reference", "Guide<", "/", "a", ">", "Also", "wipes", "raw", "data", "." ]
train
https://github.com/sualeh/credit_card_number/blob/75238a84bbfdfe9163a70fd5673cba627e8972b6/src/main/java/us/fatehi/creditcardnumber/DisposableStringData.java#L87-L90
seancfoley/IPAddress
IPAddress/src/inet.ipaddr/inet/ipaddr/ipv6/IPv6AddressSection.java
IPv6AddressSection.spanWithSequentialBlocks
public IPv6AddressSection[] spanWithSequentialBlocks(IPv6AddressSection other) throws AddressPositionException { """ Produces a list of range subnets that span from this series to the given series. @param other @return """ if(other.addressSegmentIndex != addressSegmentIndex) { throw new AddressPositionException(other, other.addressSegmentIndex, addressSegmentIndex); } return getSpanningSequentialBlocks( this, other, IPv6AddressSection::getLower, IPv6AddressSection::getUpper, Address.ADDRESS_LOW_VALUE_COMPARATOR::compare, IPv6AddressSection::withoutPrefixLength, getAddressCreator()); }
java
public IPv6AddressSection[] spanWithSequentialBlocks(IPv6AddressSection other) throws AddressPositionException { if(other.addressSegmentIndex != addressSegmentIndex) { throw new AddressPositionException(other, other.addressSegmentIndex, addressSegmentIndex); } return getSpanningSequentialBlocks( this, other, IPv6AddressSection::getLower, IPv6AddressSection::getUpper, Address.ADDRESS_LOW_VALUE_COMPARATOR::compare, IPv6AddressSection::withoutPrefixLength, getAddressCreator()); }
[ "public", "IPv6AddressSection", "[", "]", "spanWithSequentialBlocks", "(", "IPv6AddressSection", "other", ")", "throws", "AddressPositionException", "{", "if", "(", "other", ".", "addressSegmentIndex", "!=", "addressSegmentIndex", ")", "{", "throw", "new", "AddressPositionException", "(", "other", ",", "other", ".", "addressSegmentIndex", ",", "addressSegmentIndex", ")", ";", "}", "return", "getSpanningSequentialBlocks", "(", "this", ",", "other", ",", "IPv6AddressSection", "::", "getLower", ",", "IPv6AddressSection", "::", "getUpper", ",", "Address", ".", "ADDRESS_LOW_VALUE_COMPARATOR", "::", "compare", ",", "IPv6AddressSection", "::", "withoutPrefixLength", ",", "getAddressCreator", "(", ")", ")", ";", "}" ]
Produces a list of range subnets that span from this series to the given series. @param other @return
[ "Produces", "a", "list", "of", "range", "subnets", "that", "span", "from", "this", "series", "to", "the", "given", "series", "." ]
train
https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/ipv6/IPv6AddressSection.java#L2018-L2030
jayantk/jklol
src/com/jayantkrish/jklol/lisp/LispUtil.java
LispUtil.readProgram
public static SExpression readProgram(List<String> filenames, IndexedList<String> symbolTable) { """ Reads a program from a list of files. Lines starting with any amount of whitespace followed by ; are ignored as comments. @param filenames @param symbolTable @return """ StringBuilder programBuilder = new StringBuilder(); programBuilder.append("(begin "); for (String filename : filenames) { for (String line : IoUtils.readLines(filename)) { line = line.replaceAll("^[ \t]*;.*", ""); programBuilder.append(line); programBuilder.append(" "); } } programBuilder.append(" )"); String program = programBuilder.toString(); ExpressionParser<SExpression> parser = ExpressionParser.sExpression(symbolTable); SExpression programExpression = parser.parse(program); return programExpression; }
java
public static SExpression readProgram(List<String> filenames, IndexedList<String> symbolTable) { StringBuilder programBuilder = new StringBuilder(); programBuilder.append("(begin "); for (String filename : filenames) { for (String line : IoUtils.readLines(filename)) { line = line.replaceAll("^[ \t]*;.*", ""); programBuilder.append(line); programBuilder.append(" "); } } programBuilder.append(" )"); String program = programBuilder.toString(); ExpressionParser<SExpression> parser = ExpressionParser.sExpression(symbolTable); SExpression programExpression = parser.parse(program); return programExpression; }
[ "public", "static", "SExpression", "readProgram", "(", "List", "<", "String", ">", "filenames", ",", "IndexedList", "<", "String", ">", "symbolTable", ")", "{", "StringBuilder", "programBuilder", "=", "new", "StringBuilder", "(", ")", ";", "programBuilder", ".", "append", "(", "\"(begin \"", ")", ";", "for", "(", "String", "filename", ":", "filenames", ")", "{", "for", "(", "String", "line", ":", "IoUtils", ".", "readLines", "(", "filename", ")", ")", "{", "line", "=", "line", ".", "replaceAll", "(", "\"^[ \\t]*;.*\"", ",", "\"\"", ")", ";", "programBuilder", ".", "append", "(", "line", ")", ";", "programBuilder", ".", "append", "(", "\" \"", ")", ";", "}", "}", "programBuilder", ".", "append", "(", "\" )\"", ")", ";", "String", "program", "=", "programBuilder", ".", "toString", "(", ")", ";", "ExpressionParser", "<", "SExpression", ">", "parser", "=", "ExpressionParser", ".", "sExpression", "(", "symbolTable", ")", ";", "SExpression", "programExpression", "=", "parser", ".", "parse", "(", "program", ")", ";", "return", "programExpression", ";", "}" ]
Reads a program from a list of files. Lines starting with any amount of whitespace followed by ; are ignored as comments. @param filenames @param symbolTable @return
[ "Reads", "a", "program", "from", "a", "list", "of", "files", ".", "Lines", "starting", "with", "any", "amount", "of", "whitespace", "followed", "by", ";", "are", "ignored", "as", "comments", "." ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/lisp/LispUtil.java#L26-L43
elki-project/elki
elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/utilities/scaling/outlier/MixtureModelOutlierScaling.java
MixtureModelOutlierScaling.calcPosterior
protected static double calcPosterior(double f, double alpha, double mu, double sigma, double lambda) { """ Compute the a posterior probability for the given parameters. @param f value @param alpha Alpha (mixing) parameter @param mu Mu (for gaussian) @param sigma Sigma (for gaussian) @param lambda Lambda (for exponential) @return Probability """ final double pi = calcP_i(f, mu, sigma); final double qi = calcQ_i(f, lambda); return (alpha * pi) / (alpha * pi + (1.0 - alpha) * qi); }
java
protected static double calcPosterior(double f, double alpha, double mu, double sigma, double lambda) { final double pi = calcP_i(f, mu, sigma); final double qi = calcQ_i(f, lambda); return (alpha * pi) / (alpha * pi + (1.0 - alpha) * qi); }
[ "protected", "static", "double", "calcPosterior", "(", "double", "f", ",", "double", "alpha", ",", "double", "mu", ",", "double", "sigma", ",", "double", "lambda", ")", "{", "final", "double", "pi", "=", "calcP_i", "(", "f", ",", "mu", ",", "sigma", ")", ";", "final", "double", "qi", "=", "calcQ_i", "(", "f", ",", "lambda", ")", ";", "return", "(", "alpha", "*", "pi", ")", "/", "(", "alpha", "*", "pi", "+", "(", "1.0", "-", "alpha", ")", "*", "qi", ")", ";", "}" ]
Compute the a posterior probability for the given parameters. @param f value @param alpha Alpha (mixing) parameter @param mu Mu (for gaussian) @param sigma Sigma (for gaussian) @param lambda Lambda (for exponential) @return Probability
[ "Compute", "the", "a", "posterior", "probability", "for", "the", "given", "parameters", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/utilities/scaling/outlier/MixtureModelOutlierScaling.java#L129-L133
jferard/fastods
fastods/src/main/java/com/github/jferard/fastods/odselement/OdsElements.java
OdsElements.setViewSetting
public void setViewSetting(final String viewId, final String item, final String value) { """ Set a view setting @param viewId the id of the view @param item the item name @param value the item value """ this.settingsElement.setViewSetting(viewId, item, value); }
java
public void setViewSetting(final String viewId, final String item, final String value) { this.settingsElement.setViewSetting(viewId, item, value); }
[ "public", "void", "setViewSetting", "(", "final", "String", "viewId", ",", "final", "String", "item", ",", "final", "String", "value", ")", "{", "this", ".", "settingsElement", ".", "setViewSetting", "(", "viewId", ",", "item", ",", "value", ")", ";", "}" ]
Set a view setting @param viewId the id of the view @param item the item name @param value the item value
[ "Set", "a", "view", "setting" ]
train
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/odselement/OdsElements.java#L362-L364
mebigfatguy/fb-contrib
src/main/java/com/mebigfatguy/fbcontrib/detect/ConfusingAutoboxedOverloading.java
ConfusingAutoboxedOverloading.populateMethodInfo
private void populateMethodInfo(JavaClass cls, Map<String, Set<String>> methodInfo) { """ fills out a set of method details for possibly confusing method signatures @param cls the current class being parsed @param methodInfo a collection to hold possibly confusing methods """ try { if (Values.DOTTED_JAVA_LANG_OBJECT.equals(cls.getClassName())) { return; } Method[] methods = cls.getMethods(); for (Method m : methods) { String sig = m.getSignature(); if (isPossiblyConfusingSignature(sig)) { String name = m.getName(); Set<String> sigs = methodInfo.get(name); if (sigs == null) { sigs = new HashSet<>(3); methodInfo.put(name, sigs); } sigs.add(m.getSignature()); } } populateMethodInfo(cls.getSuperClass(), methodInfo); } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } }
java
private void populateMethodInfo(JavaClass cls, Map<String, Set<String>> methodInfo) { try { if (Values.DOTTED_JAVA_LANG_OBJECT.equals(cls.getClassName())) { return; } Method[] methods = cls.getMethods(); for (Method m : methods) { String sig = m.getSignature(); if (isPossiblyConfusingSignature(sig)) { String name = m.getName(); Set<String> sigs = methodInfo.get(name); if (sigs == null) { sigs = new HashSet<>(3); methodInfo.put(name, sigs); } sigs.add(m.getSignature()); } } populateMethodInfo(cls.getSuperClass(), methodInfo); } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } }
[ "private", "void", "populateMethodInfo", "(", "JavaClass", "cls", ",", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "methodInfo", ")", "{", "try", "{", "if", "(", "Values", ".", "DOTTED_JAVA_LANG_OBJECT", ".", "equals", "(", "cls", ".", "getClassName", "(", ")", ")", ")", "{", "return", ";", "}", "Method", "[", "]", "methods", "=", "cls", ".", "getMethods", "(", ")", ";", "for", "(", "Method", "m", ":", "methods", ")", "{", "String", "sig", "=", "m", ".", "getSignature", "(", ")", ";", "if", "(", "isPossiblyConfusingSignature", "(", "sig", ")", ")", "{", "String", "name", "=", "m", ".", "getName", "(", ")", ";", "Set", "<", "String", ">", "sigs", "=", "methodInfo", ".", "get", "(", "name", ")", ";", "if", "(", "sigs", "==", "null", ")", "{", "sigs", "=", "new", "HashSet", "<>", "(", "3", ")", ";", "methodInfo", ".", "put", "(", "name", ",", "sigs", ")", ";", "}", "sigs", ".", "add", "(", "m", ".", "getSignature", "(", ")", ")", ";", "}", "}", "populateMethodInfo", "(", "cls", ".", "getSuperClass", "(", ")", ",", "methodInfo", ")", ";", "}", "catch", "(", "ClassNotFoundException", "cnfe", ")", "{", "bugReporter", ".", "reportMissingClass", "(", "cnfe", ")", ";", "}", "}" ]
fills out a set of method details for possibly confusing method signatures @param cls the current class being parsed @param methodInfo a collection to hold possibly confusing methods
[ "fills", "out", "a", "set", "of", "method", "details", "for", "possibly", "confusing", "method", "signatures" ]
train
https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/ConfusingAutoboxedOverloading.java#L162-L187
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java
AsynchronousRequest.getGuildRankInfo
public void getGuildRankInfo(String id, String api, Callback<List<GuildRank>> callback) throws GuildWars2Exception, NullPointerException { """ For more info on guild rank API go <a href="https://wiki.guildwars2.com/wiki/API:2/guild/:id/ranks">here</a><br/> Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions<br/> @param id guild id @param api Guild leader's Guild Wars 2 API key @param callback callback that is going to be used for {@link Call#enqueue(Callback)} @throws NullPointerException if given {@link Callback} is empty @see GuildRank guild rank info """ isParamValid(new ParamChecker(ParamType.GUILD, id), new ParamChecker(ParamType.API, api)); gw2API.getGuildRankInfo(id, api).enqueue(callback); }
java
public void getGuildRankInfo(String id, String api, Callback<List<GuildRank>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ParamType.GUILD, id), new ParamChecker(ParamType.API, api)); gw2API.getGuildRankInfo(id, api).enqueue(callback); }
[ "public", "void", "getGuildRankInfo", "(", "String", "id", ",", "String", "api", ",", "Callback", "<", "List", "<", "GuildRank", ">", ">", "callback", ")", "throws", "GuildWars2Exception", ",", "NullPointerException", "{", "isParamValid", "(", "new", "ParamChecker", "(", "ParamType", ".", "GUILD", ",", "id", ")", ",", "new", "ParamChecker", "(", "ParamType", ".", "API", ",", "api", ")", ")", ";", "gw2API", ".", "getGuildRankInfo", "(", "id", ",", "api", ")", ".", "enqueue", "(", "callback", ")", ";", "}" ]
For more info on guild rank API go <a href="https://wiki.guildwars2.com/wiki/API:2/guild/:id/ranks">here</a><br/> Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions<br/> @param id guild id @param api Guild leader's Guild Wars 2 API key @param callback callback that is going to be used for {@link Call#enqueue(Callback)} @throws NullPointerException if given {@link Callback} is empty @see GuildRank guild rank info
[ "For", "more", "info", "on", "guild", "rank", "API", "go", "<a", "href", "=", "https", ":", "//", "wiki", ".", "guildwars2", ".", "com", "/", "wiki", "/", "API", ":", "2", "/", "guild", "/", ":", "id", "/", "ranks", ">", "here<", "/", "a", ">", "<br", "/", ">", "Give", "user", "the", "access", "to", "{", "@link", "Callback#onResponse", "(", "Call", "Response", ")", "}", "and", "{", "@link", "Callback#onFailure", "(", "Call", "Throwable", ")", "}", "methods", "for", "custom", "interactions<br", "/", ">" ]
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L1518-L1521
hsiafan/requests
src/main/java/net/dongliu/requests/utils/CookieDateUtil.java
CookieDateUtil.parseDate
@Nullable public static Date parseDate(String dateValue, Collection<String> dateFormats, Date startDate) { """ Parses the date value using the given date formats. @param dateValue the date value to parse @param dateFormats the date formats to use @param startDate During parsing, two digit years will be placed in the range <code>startDate</code> to <code>startDate + 100 years</code>. This value may be <code>null</code>. When <code>null</code> is given as a parameter, year <code>2000</code> will be used. @return the parsed date """ // trim single quotes around date if present // see issue #5279 if (dateValue.length() > 1 && dateValue.startsWith("'") && dateValue.endsWith("'")) { dateValue = dateValue.substring(1, dateValue.length() - 1); } SimpleDateFormat dateParser = null; for (String format : dateFormats) { if (dateParser == null) { dateParser = new SimpleDateFormat(format, Locale.US); dateParser.setTimeZone(TimeZone.getTimeZone("GMT")); dateParser.set2DigitYearStart(startDate); } else { dateParser.applyPattern(format); } try { return dateParser.parse(dateValue); } catch (ParseException pe) { // ignore this exception, we will try the next format } } // we were unable to parse the date return null; }
java
@Nullable public static Date parseDate(String dateValue, Collection<String> dateFormats, Date startDate) { // trim single quotes around date if present // see issue #5279 if (dateValue.length() > 1 && dateValue.startsWith("'") && dateValue.endsWith("'")) { dateValue = dateValue.substring(1, dateValue.length() - 1); } SimpleDateFormat dateParser = null; for (String format : dateFormats) { if (dateParser == null) { dateParser = new SimpleDateFormat(format, Locale.US); dateParser.setTimeZone(TimeZone.getTimeZone("GMT")); dateParser.set2DigitYearStart(startDate); } else { dateParser.applyPattern(format); } try { return dateParser.parse(dateValue); } catch (ParseException pe) { // ignore this exception, we will try the next format } } // we were unable to parse the date return null; }
[ "@", "Nullable", "public", "static", "Date", "parseDate", "(", "String", "dateValue", ",", "Collection", "<", "String", ">", "dateFormats", ",", "Date", "startDate", ")", "{", "// trim single quotes around date if present", "// see issue #5279", "if", "(", "dateValue", ".", "length", "(", ")", ">", "1", "&&", "dateValue", ".", "startsWith", "(", "\"'\"", ")", "&&", "dateValue", ".", "endsWith", "(", "\"'\"", ")", ")", "{", "dateValue", "=", "dateValue", ".", "substring", "(", "1", ",", "dateValue", ".", "length", "(", ")", "-", "1", ")", ";", "}", "SimpleDateFormat", "dateParser", "=", "null", ";", "for", "(", "String", "format", ":", "dateFormats", ")", "{", "if", "(", "dateParser", "==", "null", ")", "{", "dateParser", "=", "new", "SimpleDateFormat", "(", "format", ",", "Locale", ".", "US", ")", ";", "dateParser", ".", "setTimeZone", "(", "TimeZone", ".", "getTimeZone", "(", "\"GMT\"", ")", ")", ";", "dateParser", ".", "set2DigitYearStart", "(", "startDate", ")", ";", "}", "else", "{", "dateParser", ".", "applyPattern", "(", "format", ")", ";", "}", "try", "{", "return", "dateParser", ".", "parse", "(", "dateValue", ")", ";", "}", "catch", "(", "ParseException", "pe", ")", "{", "// ignore this exception, we will try the next format", "}", "}", "// we were unable to parse the date", "return", "null", ";", "}" ]
Parses the date value using the given date formats. @param dateValue the date value to parse @param dateFormats the date formats to use @param startDate During parsing, two digit years will be placed in the range <code>startDate</code> to <code>startDate + 100 years</code>. This value may be <code>null</code>. When <code>null</code> is given as a parameter, year <code>2000</code> will be used. @return the parsed date
[ "Parses", "the", "date", "value", "using", "the", "given", "date", "formats", "." ]
train
https://github.com/hsiafan/requests/blob/a6cc6f8293e808cc937d3789aec2616a8383dee0/src/main/java/net/dongliu/requests/utils/CookieDateUtil.java#L86-L113
UrielCh/ovh-java-sdk
ovh-java-sdk-support/src/main/java/net/minidev/ovh/api/ApiOvhSupport.java
ApiOvhSupport.tickets_ticketId_messages_GET
public ArrayList<OvhMessage> tickets_ticketId_messages_GET(Long ticketId) throws IOException { """ Get ticket messages REST: GET /support/tickets/{ticketId}/messages @param ticketId [required] internal ticket identifier """ String qPath = "/support/tickets/{ticketId}/messages"; StringBuilder sb = path(qPath, ticketId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
java
public ArrayList<OvhMessage> tickets_ticketId_messages_GET(Long ticketId) throws IOException { String qPath = "/support/tickets/{ticketId}/messages"; StringBuilder sb = path(qPath, ticketId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
[ "public", "ArrayList", "<", "OvhMessage", ">", "tickets_ticketId_messages_GET", "(", "Long", "ticketId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/support/tickets/{ticketId}/messages\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "ticketId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t1", ")", ";", "}" ]
Get ticket messages REST: GET /support/tickets/{ticketId}/messages @param ticketId [required] internal ticket identifier
[ "Get", "ticket", "messages" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-support/src/main/java/net/minidev/ovh/api/ApiOvhSupport.java#L78-L83
realtime-framework/RealtimeStorage-Android
library/src/main/java/co/realtime/storage/TableRef.java
TableRef.beginsWith
public TableRef beginsWith(String attributeName, ItemAttribute value) { """ Applies a filter to the table. When fetched, it will return the items that begins with the filter property value. <pre> StorageRef storage = new StorageRef("your_app_key", "your_token"); TableRef tableRef = storage.table("your_table"); // Retrieve all items with property "itemProperty" value starting with "xpto" tableRef.beginsWith("itemProperty",new ItemAttribute("xpto")).getItems(new OnItemSnapshot() { &#064;Override public void run(ItemSnapshot itemSnapshot) { if (itemSnapshot != null) { Log.d("TableRef", "Item retrieved: " + itemSnapshot.val()); } } }, new OnError() { &#064;Override public void run(Integer code, String errorMessage) { Log.e("TableRef", "Error retrieving items: " + errorMessage); } }); </pre> @param attributeName The name of the property to filter. @param value The value of the property to filter. @return Current table reference """ filters.add(new Filter(StorageFilter.BEGINSWITH, attributeName, value, null)); return this; }
java
public TableRef beginsWith(String attributeName, ItemAttribute value){ filters.add(new Filter(StorageFilter.BEGINSWITH, attributeName, value, null)); return this; }
[ "public", "TableRef", "beginsWith", "(", "String", "attributeName", ",", "ItemAttribute", "value", ")", "{", "filters", ".", "add", "(", "new", "Filter", "(", "StorageFilter", ".", "BEGINSWITH", ",", "attributeName", ",", "value", ",", "null", ")", ")", ";", "return", "this", ";", "}" ]
Applies a filter to the table. When fetched, it will return the items that begins with the filter property value. <pre> StorageRef storage = new StorageRef("your_app_key", "your_token"); TableRef tableRef = storage.table("your_table"); // Retrieve all items with property "itemProperty" value starting with "xpto" tableRef.beginsWith("itemProperty",new ItemAttribute("xpto")).getItems(new OnItemSnapshot() { &#064;Override public void run(ItemSnapshot itemSnapshot) { if (itemSnapshot != null) { Log.d("TableRef", "Item retrieved: " + itemSnapshot.val()); } } }, new OnError() { &#064;Override public void run(Integer code, String errorMessage) { Log.e("TableRef", "Error retrieving items: " + errorMessage); } }); </pre> @param attributeName The name of the property to filter. @param value The value of the property to filter. @return Current table reference
[ "Applies", "a", "filter", "to", "the", "table", ".", "When", "fetched", "it", "will", "return", "the", "items", "that", "begins", "with", "the", "filter", "property", "value", "." ]
train
https://github.com/realtime-framework/RealtimeStorage-Android/blob/05816a6b7a6dcc83f9e7400ac3048494dadca302/library/src/main/java/co/realtime/storage/TableRef.java#L931-L934
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.scaleAroundLocal
public Matrix4f scaleAroundLocal(float factor, float ox, float oy, float oz, Matrix4f dest) { """ /* (non-Javadoc) @see org.joml.Matrix4fc#scaleAroundLocal(float, float, float, float, org.joml.Matrix4f) """ return scaleAroundLocal(factor, factor, factor, ox, oy, oz, dest); }
java
public Matrix4f scaleAroundLocal(float factor, float ox, float oy, float oz, Matrix4f dest) { return scaleAroundLocal(factor, factor, factor, ox, oy, oz, dest); }
[ "public", "Matrix4f", "scaleAroundLocal", "(", "float", "factor", ",", "float", "ox", ",", "float", "oy", ",", "float", "oz", ",", "Matrix4f", "dest", ")", "{", "return", "scaleAroundLocal", "(", "factor", ",", "factor", ",", "factor", ",", "ox", ",", "oy", ",", "oz", ",", "dest", ")", ";", "}" ]
/* (non-Javadoc) @see org.joml.Matrix4fc#scaleAroundLocal(float, float, float, float, org.joml.Matrix4f)
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L5051-L5053
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/utilities/ImageIOGreyScale.java
ImageIOGreyScale.getImageTranscoders
public static Iterator<ImageTranscoder> getImageTranscoders(ImageReader reader, ImageWriter writer) { """ Returns an <code>Iterator</code> containing all currently registered <code>ImageTranscoder</code>s that claim to be able to transcode between the metadata of the given <code>ImageReader</code> and <code>ImageWriter</code>. @param reader an <code>ImageReader</code>. @param writer an <code>ImageWriter</code>. @return an <code>Iterator</code> containing <code>ImageTranscoder</code>s. @exception IllegalArgumentException if <code>reader</code> or <code>writer</code> is <code>null</code>. """ if (reader == null) { throw new IllegalArgumentException("reader == null!"); } if (writer == null) { throw new IllegalArgumentException("writer == null!"); } ImageReaderSpi readerSpi = reader.getOriginatingProvider(); ImageWriterSpi writerSpi = writer.getOriginatingProvider(); ServiceRegistry.Filter filter = new TranscoderFilter(readerSpi, writerSpi); Iterator iter; // Ensure category is present try { iter = theRegistry.getServiceProviders(ImageTranscoderSpi.class, filter, true); } catch (IllegalArgumentException e) { return new HashSet().iterator(); } return new ImageTranscoderIterator(iter); }
java
public static Iterator<ImageTranscoder> getImageTranscoders(ImageReader reader, ImageWriter writer) { if (reader == null) { throw new IllegalArgumentException("reader == null!"); } if (writer == null) { throw new IllegalArgumentException("writer == null!"); } ImageReaderSpi readerSpi = reader.getOriginatingProvider(); ImageWriterSpi writerSpi = writer.getOriginatingProvider(); ServiceRegistry.Filter filter = new TranscoderFilter(readerSpi, writerSpi); Iterator iter; // Ensure category is present try { iter = theRegistry.getServiceProviders(ImageTranscoderSpi.class, filter, true); } catch (IllegalArgumentException e) { return new HashSet().iterator(); } return new ImageTranscoderIterator(iter); }
[ "public", "static", "Iterator", "<", "ImageTranscoder", ">", "getImageTranscoders", "(", "ImageReader", "reader", ",", "ImageWriter", "writer", ")", "{", "if", "(", "reader", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"reader == null!\"", ")", ";", "}", "if", "(", "writer", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"writer == null!\"", ")", ";", "}", "ImageReaderSpi", "readerSpi", "=", "reader", ".", "getOriginatingProvider", "(", ")", ";", "ImageWriterSpi", "writerSpi", "=", "writer", ".", "getOriginatingProvider", "(", ")", ";", "ServiceRegistry", ".", "Filter", "filter", "=", "new", "TranscoderFilter", "(", "readerSpi", ",", "writerSpi", ")", ";", "Iterator", "iter", ";", "// Ensure category is present\r", "try", "{", "iter", "=", "theRegistry", ".", "getServiceProviders", "(", "ImageTranscoderSpi", ".", "class", ",", "filter", ",", "true", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "return", "new", "HashSet", "(", ")", ".", "iterator", "(", ")", ";", "}", "return", "new", "ImageTranscoderIterator", "(", "iter", ")", ";", "}" ]
Returns an <code>Iterator</code> containing all currently registered <code>ImageTranscoder</code>s that claim to be able to transcode between the metadata of the given <code>ImageReader</code> and <code>ImageWriter</code>. @param reader an <code>ImageReader</code>. @param writer an <code>ImageWriter</code>. @return an <code>Iterator</code> containing <code>ImageTranscoder</code>s. @exception IllegalArgumentException if <code>reader</code> or <code>writer</code> is <code>null</code>.
[ "Returns", "an", "<code", ">", "Iterator<", "/", "code", ">", "containing", "all", "currently", "registered", "<code", ">", "ImageTranscoder<", "/", "code", ">", "s", "that", "claim", "to", "be", "able", "to", "transcode", "between", "the", "metadata", "of", "the", "given", "<code", ">", "ImageReader<", "/", "code", ">", "and", "<code", ">", "ImageWriter<", "/", "code", ">", "." ]
train
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/ImageIOGreyScale.java#L1092-L1111
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/workspace/VoiceApi.java
VoiceApi.deleteFromConference
public void deleteFromConference(String connId, String dnToDrop) throws WorkspaceApiException { """ Delete the specified DN from the conference call. This operation can only be performed by the owner of the conference call. @param connId The connection ID of the conference. @param dnToDrop The DN of the party to drop from the conference. """ this.deleteFromConference(connId, dnToDrop, null, null); }
java
public void deleteFromConference(String connId, String dnToDrop) throws WorkspaceApiException { this.deleteFromConference(connId, dnToDrop, null, null); }
[ "public", "void", "deleteFromConference", "(", "String", "connId", ",", "String", "dnToDrop", ")", "throws", "WorkspaceApiException", "{", "this", ".", "deleteFromConference", "(", "connId", ",", "dnToDrop", ",", "null", ",", "null", ")", ";", "}" ]
Delete the specified DN from the conference call. This operation can only be performed by the owner of the conference call. @param connId The connection ID of the conference. @param dnToDrop The DN of the party to drop from the conference.
[ "Delete", "the", "specified", "DN", "from", "the", "conference", "call", ".", "This", "operation", "can", "only", "be", "performed", "by", "the", "owner", "of", "the", "conference", "call", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/workspace/VoiceApi.java#L906-L908
EdwardRaff/JSAT
JSAT/src/jsat/classifiers/linear/BBR.java
BBR.setTolerance
public void setTolerance(double tolerance) { """ Sets the convergence tolerance target. Relative changes that are smaller than the given tolerance will determine convergence. <br><br> The default value used is that suggested in the original paper of 0.0005 @param tolerance the positive convergence tolerance goal """ if (Double.isNaN(tolerance) || Double.isInfinite(tolerance) || tolerance <= 0) throw new IllegalArgumentException("Tolerance must be positive, not " + tolerance); this.tolerance = tolerance; }
java
public void setTolerance(double tolerance) { if (Double.isNaN(tolerance) || Double.isInfinite(tolerance) || tolerance <= 0) throw new IllegalArgumentException("Tolerance must be positive, not " + tolerance); this.tolerance = tolerance; }
[ "public", "void", "setTolerance", "(", "double", "tolerance", ")", "{", "if", "(", "Double", ".", "isNaN", "(", "tolerance", ")", "||", "Double", ".", "isInfinite", "(", "tolerance", ")", "||", "tolerance", "<=", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Tolerance must be positive, not \"", "+", "tolerance", ")", ";", "this", ".", "tolerance", "=", "tolerance", ";", "}" ]
Sets the convergence tolerance target. Relative changes that are smaller than the given tolerance will determine convergence. <br><br> The default value used is that suggested in the original paper of 0.0005 @param tolerance the positive convergence tolerance goal
[ "Sets", "the", "convergence", "tolerance", "target", ".", "Relative", "changes", "that", "are", "smaller", "than", "the", "given", "tolerance", "will", "determine", "convergence", ".", "<br", ">", "<br", ">", "The", "default", "value", "used", "is", "that", "suggested", "in", "the", "original", "paper", "of", "0", ".", "0005" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/BBR.java#L217-L222
jeffreyning/nh-micro
nh-micro-template/src/main/java/com/nh/micro/template/MicroServiceTemplateSupport.java
MicroServiceTemplateSupport.updateInfoByBizIdServiceInner
public Integer updateInfoByBizIdServiceInner(String bizId,String tableName,String bizCol,Map requestParamMap,String cusCondition,String cusSetStr,String modelName) throws Exception { """ ���ҵ��id������ݼ�¼ @param bizid ҵ������ @param tableName ����� @param bizCol ҵ������� @param requestParamMap �ύ���� @param cusCondition ���������ַ� @param cusSetStr ����set�ַ� @param modelName ģ����� @return @throws Exception """ //add 20170829 ninghao Integer filterViewRet=filterView(tableName,requestParamMap,bizId,bizCol,TYPE_UPDATE_BIZID); if(filterViewRet!=null && filterViewRet>0){ return filterViewRet; } //add 20170627 ninghao filterParam(tableName,requestParamMap); String tempDbType=calcuDbType(); String condition=Cutil.rep(bizCol+"=?",bizId); if(modelName==null || "".equals(modelName)){ modelName=tableName; } //add 201807 ning //Map requestParamMap=changeCase4Param(requestParamMap0); Map modelEntryMap=getModelEntryMap(requestParamMap,tableName,modelName,dbName); List placeList=new ArrayList(); String setStr=createUpdateInStr(requestParamMap,modelEntryMap,placeList); String nCondition=Cutil.jn(" and ", cusCondition,condition); String nSetStr=Cutil.jn(",", setStr,cusSetStr); placeList.add(bizId); Integer retStatus=getInnerDao().updateObjByCondition(tableName, nCondition, nSetStr,placeList.toArray()); return retStatus; }
java
public Integer updateInfoByBizIdServiceInner(String bizId,String tableName,String bizCol,Map requestParamMap,String cusCondition,String cusSetStr,String modelName) throws Exception{ //add 20170829 ninghao Integer filterViewRet=filterView(tableName,requestParamMap,bizId,bizCol,TYPE_UPDATE_BIZID); if(filterViewRet!=null && filterViewRet>0){ return filterViewRet; } //add 20170627 ninghao filterParam(tableName,requestParamMap); String tempDbType=calcuDbType(); String condition=Cutil.rep(bizCol+"=?",bizId); if(modelName==null || "".equals(modelName)){ modelName=tableName; } //add 201807 ning //Map requestParamMap=changeCase4Param(requestParamMap0); Map modelEntryMap=getModelEntryMap(requestParamMap,tableName,modelName,dbName); List placeList=new ArrayList(); String setStr=createUpdateInStr(requestParamMap,modelEntryMap,placeList); String nCondition=Cutil.jn(" and ", cusCondition,condition); String nSetStr=Cutil.jn(",", setStr,cusSetStr); placeList.add(bizId); Integer retStatus=getInnerDao().updateObjByCondition(tableName, nCondition, nSetStr,placeList.toArray()); return retStatus; }
[ "public", "Integer", "updateInfoByBizIdServiceInner", "(", "String", "bizId", ",", "String", "tableName", ",", "String", "bizCol", ",", "Map", "requestParamMap", ",", "String", "cusCondition", ",", "String", "cusSetStr", ",", "String", "modelName", ")", "throws", "Exception", "{", "//add 20170829 ninghao\r", "Integer", "filterViewRet", "=", "filterView", "(", "tableName", ",", "requestParamMap", ",", "bizId", ",", "bizCol", ",", "TYPE_UPDATE_BIZID", ")", ";", "if", "(", "filterViewRet", "!=", "null", "&&", "filterViewRet", ">", "0", ")", "{", "return", "filterViewRet", ";", "}", "//add 20170627 ninghao\r", "filterParam", "(", "tableName", ",", "requestParamMap", ")", ";", "String", "tempDbType", "=", "calcuDbType", "(", ")", ";", "String", "condition", "=", "Cutil", ".", "rep", "(", "bizCol", "+", "\"=?\"", ",", "bizId", ")", ";", "if", "(", "modelName", "==", "null", "||", "\"\"", ".", "equals", "(", "modelName", ")", ")", "{", "modelName", "=", "tableName", ";", "}", "//add 201807 ning\r", "//Map requestParamMap=changeCase4Param(requestParamMap0);\r", "Map", "modelEntryMap", "=", "getModelEntryMap", "(", "requestParamMap", ",", "tableName", ",", "modelName", ",", "dbName", ")", ";", "List", "placeList", "=", "new", "ArrayList", "(", ")", ";", "String", "setStr", "=", "createUpdateInStr", "(", "requestParamMap", ",", "modelEntryMap", ",", "placeList", ")", ";", "String", "nCondition", "=", "Cutil", ".", "jn", "(", "\" and \"", ",", "cusCondition", ",", "condition", ")", ";", "String", "nSetStr", "=", "Cutil", ".", "jn", "(", "\",\"", ",", "setStr", ",", "cusSetStr", ")", ";", "placeList", ".", "add", "(", "bizId", ")", ";", "Integer", "retStatus", "=", "getInnerDao", "(", ")", ".", "updateObjByCondition", "(", "tableName", ",", "nCondition", ",", "nSetStr", ",", "placeList", ".", "toArray", "(", ")", ")", ";", "return", "retStatus", ";", "}" ]
���ҵ��id������ݼ�¼ @param bizid ҵ������ @param tableName ����� @param bizCol ҵ������� @param requestParamMap �ύ���� @param cusCondition ���������ַ� @param cusSetStr ����set�ַ� @param modelName ģ����� @return @throws Exception
[ "���ҵ��id������ݼ�¼" ]
train
https://github.com/jeffreyning/nh-micro/blob/f1cb420a092f8ba94317519ede739974decb5617/nh-micro-template/src/main/java/com/nh/micro/template/MicroServiceTemplateSupport.java#L1723-L1751
uwolfer/gerrit-rest-java-client
src/main/java/com/urswolfer/gerrit/client/rest/http/GerritRestClient.java
GerritRestClient.tryGerritHttpFormAuth
private Optional<String> tryGerritHttpFormAuth(HttpClientBuilder client, HttpContext httpContext) throws IOException, HttpStatusException { """ Handles LDAP auth (but not LDAP_HTTP) which uses a HTML form. """ if (!authData.isLoginAndPasswordAvailable()) { return Optional.absent(); } String loginUrl = authData.getHost() + "/login/"; HttpPost method = new HttpPost(loginUrl); List<BasicNameValuePair> parameters = Lists.newArrayList( new BasicNameValuePair("username", authData.getLogin()), new BasicNameValuePair("password", authData.getPassword()) ); method.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8)); HttpResponse loginResponse = httpRequestExecutor.execute(client, method, httpContext); return extractGerritAuth(loginResponse); }
java
private Optional<String> tryGerritHttpFormAuth(HttpClientBuilder client, HttpContext httpContext) throws IOException, HttpStatusException { if (!authData.isLoginAndPasswordAvailable()) { return Optional.absent(); } String loginUrl = authData.getHost() + "/login/"; HttpPost method = new HttpPost(loginUrl); List<BasicNameValuePair> parameters = Lists.newArrayList( new BasicNameValuePair("username", authData.getLogin()), new BasicNameValuePair("password", authData.getPassword()) ); method.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8)); HttpResponse loginResponse = httpRequestExecutor.execute(client, method, httpContext); return extractGerritAuth(loginResponse); }
[ "private", "Optional", "<", "String", ">", "tryGerritHttpFormAuth", "(", "HttpClientBuilder", "client", ",", "HttpContext", "httpContext", ")", "throws", "IOException", ",", "HttpStatusException", "{", "if", "(", "!", "authData", ".", "isLoginAndPasswordAvailable", "(", ")", ")", "{", "return", "Optional", ".", "absent", "(", ")", ";", "}", "String", "loginUrl", "=", "authData", ".", "getHost", "(", ")", "+", "\"/login/\"", ";", "HttpPost", "method", "=", "new", "HttpPost", "(", "loginUrl", ")", ";", "List", "<", "BasicNameValuePair", ">", "parameters", "=", "Lists", ".", "newArrayList", "(", "new", "BasicNameValuePair", "(", "\"username\"", ",", "authData", ".", "getLogin", "(", ")", ")", ",", "new", "BasicNameValuePair", "(", "\"password\"", ",", "authData", ".", "getPassword", "(", ")", ")", ")", ";", "method", ".", "setEntity", "(", "new", "UrlEncodedFormEntity", "(", "parameters", ",", "Consts", ".", "UTF_8", ")", ")", ";", "HttpResponse", "loginResponse", "=", "httpRequestExecutor", ".", "execute", "(", "client", ",", "method", ",", "httpContext", ")", ";", "return", "extractGerritAuth", "(", "loginResponse", ")", ";", "}" ]
Handles LDAP auth (but not LDAP_HTTP) which uses a HTML form.
[ "Handles", "LDAP", "auth", "(", "but", "not", "LDAP_HTTP", ")", "which", "uses", "a", "HTML", "form", "." ]
train
https://github.com/uwolfer/gerrit-rest-java-client/blob/fa66cd76270cd12cff9e30e0d96826fe0253d209/src/main/java/com/urswolfer/gerrit/client/rest/http/GerritRestClient.java#L290-L303
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/apple/XcodeProjectWriter.java
XcodeProjectWriter.addProduct
private PBXObjectRef addProduct(final Map objects, final TargetInfo linkTarget) { """ Add file reference of product to map of objects. @param objects object map. @param linkTarget build description for executable or shared library. @return file reference to generated executable or shared library. """ // // create file reference for executable file // forget Ant's location, just place in XCode's default location final PBXObjectRef executable = createPBXFileReference("BUILD_PRODUCTS_DIR", linkTarget.getOutput().getParent(), linkTarget.getOutput()); final Map executableProperties = executable.getProperties(); final String fileType = getFileType(linkTarget); executableProperties.put("explicitFileType", fileType); executableProperties.put("includeInIndex", "0"); objects.put(executable.getID(), executableProperties); return executable; }
java
private PBXObjectRef addProduct(final Map objects, final TargetInfo linkTarget) { // // create file reference for executable file // forget Ant's location, just place in XCode's default location final PBXObjectRef executable = createPBXFileReference("BUILD_PRODUCTS_DIR", linkTarget.getOutput().getParent(), linkTarget.getOutput()); final Map executableProperties = executable.getProperties(); final String fileType = getFileType(linkTarget); executableProperties.put("explicitFileType", fileType); executableProperties.put("includeInIndex", "0"); objects.put(executable.getID(), executableProperties); return executable; }
[ "private", "PBXObjectRef", "addProduct", "(", "final", "Map", "objects", ",", "final", "TargetInfo", "linkTarget", ")", "{", "//", "// create file reference for executable file", "// forget Ant's location, just place in XCode's default location", "final", "PBXObjectRef", "executable", "=", "createPBXFileReference", "(", "\"BUILD_PRODUCTS_DIR\"", ",", "linkTarget", ".", "getOutput", "(", ")", ".", "getParent", "(", ")", ",", "linkTarget", ".", "getOutput", "(", ")", ")", ";", "final", "Map", "executableProperties", "=", "executable", ".", "getProperties", "(", ")", ";", "final", "String", "fileType", "=", "getFileType", "(", "linkTarget", ")", ";", "executableProperties", ".", "put", "(", "\"explicitFileType\"", ",", "fileType", ")", ";", "executableProperties", ".", "put", "(", "\"includeInIndex\"", ",", "\"0\"", ")", ";", "objects", ".", "put", "(", "executable", ".", "getID", "(", ")", ",", "executableProperties", ")", ";", "return", "executable", ";", "}" ]
Add file reference of product to map of objects. @param objects object map. @param linkTarget build description for executable or shared library. @return file reference to generated executable or shared library.
[ "Add", "file", "reference", "of", "product", "to", "map", "of", "objects", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/apple/XcodeProjectWriter.java#L599-L614
google/closure-templates
java/src/com/google/template/soy/pysrc/restricted/PyExprUtils.java
PyExprUtils.wrapAsSanitizedContent
@Deprecated public static PyExpr wrapAsSanitizedContent(ContentKind contentKind, PyExpr pyExpr) { """ Wraps an expression with the proper SanitizedContent constructor. <p>NOTE: The pyExpr provided must be properly escaped for the given ContentKind. Please talk to ISE (ise@) for any questions or concerns. @param contentKind The kind of sanitized content. @param pyExpr The expression to wrap. @deprecated this method is not safe to use without a security review. Do not use it. """ String sanitizer = NodeContentKinds.toPySanitizedContentOrdainer( SanitizedContentKind.valueOf(contentKind.name())); String approval = "sanitize.IActuallyUnderstandSoyTypeSafetyAndHaveSecurityApproval(" + "'Internally created Sanitization.')"; return new PyExpr( sanitizer + "(" + pyExpr.getText() + ", approval=" + approval + ")", Integer.MAX_VALUE); }
java
@Deprecated public static PyExpr wrapAsSanitizedContent(ContentKind contentKind, PyExpr pyExpr) { String sanitizer = NodeContentKinds.toPySanitizedContentOrdainer( SanitizedContentKind.valueOf(contentKind.name())); String approval = "sanitize.IActuallyUnderstandSoyTypeSafetyAndHaveSecurityApproval(" + "'Internally created Sanitization.')"; return new PyExpr( sanitizer + "(" + pyExpr.getText() + ", approval=" + approval + ")", Integer.MAX_VALUE); }
[ "@", "Deprecated", "public", "static", "PyExpr", "wrapAsSanitizedContent", "(", "ContentKind", "contentKind", ",", "PyExpr", "pyExpr", ")", "{", "String", "sanitizer", "=", "NodeContentKinds", ".", "toPySanitizedContentOrdainer", "(", "SanitizedContentKind", ".", "valueOf", "(", "contentKind", ".", "name", "(", ")", ")", ")", ";", "String", "approval", "=", "\"sanitize.IActuallyUnderstandSoyTypeSafetyAndHaveSecurityApproval(\"", "+", "\"'Internally created Sanitization.')\"", ";", "return", "new", "PyExpr", "(", "sanitizer", "+", "\"(\"", "+", "pyExpr", ".", "getText", "(", ")", "+", "\", approval=\"", "+", "approval", "+", "\")\"", ",", "Integer", ".", "MAX_VALUE", ")", ";", "}" ]
Wraps an expression with the proper SanitizedContent constructor. <p>NOTE: The pyExpr provided must be properly escaped for the given ContentKind. Please talk to ISE (ise@) for any questions or concerns. @param contentKind The kind of sanitized content. @param pyExpr The expression to wrap. @deprecated this method is not safe to use without a security review. Do not use it.
[ "Wraps", "an", "expression", "with", "the", "proper", "SanitizedContent", "constructor", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/restricted/PyExprUtils.java#L174-L184
mnlipp/jgrapes
org.jgrapes.http/src/org/jgrapes/http/HttpServer.java
HttpServer.onClosed
@Handler(channels = NetworkChannel.class) public void onClosed(Closed event, IOSubchannel netChannel) { """ Forwards a {@link Closed} event to the application channel. @param event the event @param netChannel the net channel """ LinkedIOSubchannel.downstreamChannel(this, netChannel, WebAppMsgChannel.class).ifPresent(appChannel -> { appChannel.handleClosed(event); }); }
java
@Handler(channels = NetworkChannel.class) public void onClosed(Closed event, IOSubchannel netChannel) { LinkedIOSubchannel.downstreamChannel(this, netChannel, WebAppMsgChannel.class).ifPresent(appChannel -> { appChannel.handleClosed(event); }); }
[ "@", "Handler", "(", "channels", "=", "NetworkChannel", ".", "class", ")", "public", "void", "onClosed", "(", "Closed", "event", ",", "IOSubchannel", "netChannel", ")", "{", "LinkedIOSubchannel", ".", "downstreamChannel", "(", "this", ",", "netChannel", ",", "WebAppMsgChannel", ".", "class", ")", ".", "ifPresent", "(", "appChannel", "->", "{", "appChannel", ".", "handleClosed", "(", "event", ")", ";", "}", ")", ";", "}" ]
Forwards a {@link Closed} event to the application channel. @param event the event @param netChannel the net channel
[ "Forwards", "a", "{", "@link", "Closed", "}", "event", "to", "the", "application", "channel", "." ]
train
https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/HttpServer.java#L270-L276
hankcs/HanLP
src/main/java/com/hankcs/hanlp/dependency/perceptron/parser/KBeamArcEagerDependencyParser.java
KBeamArcEagerDependencyParser.parse
public CoNLLSentence parse(List<Term> termList, int beamWidth, int numOfThreads) { """ 执行句法分析 @param termList 分词结果 @param beamWidth 柱搜索宽度 @param numOfThreads 多线程数 @return 句法树 """ String[] words = new String[termList.size()]; String[] tags = new String[termList.size()]; int k = 0; for (Term term : termList) { words[k] = term.word; tags[k] = term.nature.toString(); ++k; } Configuration bestParse; try { bestParse = parser.parse(words, tags, false, beamWidth, numOfThreads); } catch (Exception e) { throw new RuntimeException(e); } CoNLLWord[] wordArray = new CoNLLWord[termList.size()]; for (int i = 0; i < words.length; i++) { wordArray[i] = new CoNLLWord(i + 1, words[i], tags[i]); } for (int i = 0; i < words.length; i++) { wordArray[i].DEPREL = parser.idWord(bestParse.state.getDependent(i + 1)); int index = bestParse.state.getHead(i + 1) - 1; if (index < 0 || index >= wordArray.length) { wordArray[i].HEAD = CoNLLWord.ROOT; } else { wordArray[i].HEAD = wordArray[index]; } } return new CoNLLSentence(wordArray); }
java
public CoNLLSentence parse(List<Term> termList, int beamWidth, int numOfThreads) { String[] words = new String[termList.size()]; String[] tags = new String[termList.size()]; int k = 0; for (Term term : termList) { words[k] = term.word; tags[k] = term.nature.toString(); ++k; } Configuration bestParse; try { bestParse = parser.parse(words, tags, false, beamWidth, numOfThreads); } catch (Exception e) { throw new RuntimeException(e); } CoNLLWord[] wordArray = new CoNLLWord[termList.size()]; for (int i = 0; i < words.length; i++) { wordArray[i] = new CoNLLWord(i + 1, words[i], tags[i]); } for (int i = 0; i < words.length; i++) { wordArray[i].DEPREL = parser.idWord(bestParse.state.getDependent(i + 1)); int index = bestParse.state.getHead(i + 1) - 1; if (index < 0 || index >= wordArray.length) { wordArray[i].HEAD = CoNLLWord.ROOT; } else { wordArray[i].HEAD = wordArray[index]; } } return new CoNLLSentence(wordArray); }
[ "public", "CoNLLSentence", "parse", "(", "List", "<", "Term", ">", "termList", ",", "int", "beamWidth", ",", "int", "numOfThreads", ")", "{", "String", "[", "]", "words", "=", "new", "String", "[", "termList", ".", "size", "(", ")", "]", ";", "String", "[", "]", "tags", "=", "new", "String", "[", "termList", ".", "size", "(", ")", "]", ";", "int", "k", "=", "0", ";", "for", "(", "Term", "term", ":", "termList", ")", "{", "words", "[", "k", "]", "=", "term", ".", "word", ";", "tags", "[", "k", "]", "=", "term", ".", "nature", ".", "toString", "(", ")", ";", "++", "k", ";", "}", "Configuration", "bestParse", ";", "try", "{", "bestParse", "=", "parser", ".", "parse", "(", "words", ",", "tags", ",", "false", ",", "beamWidth", ",", "numOfThreads", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "CoNLLWord", "[", "]", "wordArray", "=", "new", "CoNLLWord", "[", "termList", ".", "size", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "words", ".", "length", ";", "i", "++", ")", "{", "wordArray", "[", "i", "]", "=", "new", "CoNLLWord", "(", "i", "+", "1", ",", "words", "[", "i", "]", ",", "tags", "[", "i", "]", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "words", ".", "length", ";", "i", "++", ")", "{", "wordArray", "[", "i", "]", ".", "DEPREL", "=", "parser", ".", "idWord", "(", "bestParse", ".", "state", ".", "getDependent", "(", "i", "+", "1", ")", ")", ";", "int", "index", "=", "bestParse", ".", "state", ".", "getHead", "(", "i", "+", "1", ")", "-", "1", ";", "if", "(", "index", "<", "0", "||", "index", ">=", "wordArray", ".", "length", ")", "{", "wordArray", "[", "i", "]", ".", "HEAD", "=", "CoNLLWord", ".", "ROOT", ";", "}", "else", "{", "wordArray", "[", "i", "]", ".", "HEAD", "=", "wordArray", "[", "index", "]", ";", "}", "}", "return", "new", "CoNLLSentence", "(", "wordArray", ")", ";", "}" ]
执行句法分析 @param termList 分词结果 @param beamWidth 柱搜索宽度 @param numOfThreads 多线程数 @return 句法树
[ "执行句法分析" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/dependency/perceptron/parser/KBeamArcEagerDependencyParser.java#L125-L165
groupon/monsoon
intf/src/main/java/com/groupon/lex/metrics/resolver/NamedResolverMap.java
NamedResolverMap.getIntegerOrDefault
public int getIntegerOrDefault(int key, int dfl) { """ Return the integer value indicated by the given numeric key. @param key The key of the value to return. @param dfl The default value to return, if the key is absent. @return The integer value stored under the given key, or dfl. @throws IllegalArgumentException if the value is present, but not an integer. """ Any3<Boolean, Integer, String> value = data.getOrDefault(Any2.<Integer, String>left(key), Any3.<Boolean, Integer, String>create2(dfl)); return value.get2().orElseThrow(() -> new IllegalArgumentException("expected integer argument for param " + key)); }
java
public int getIntegerOrDefault(int key, int dfl) { Any3<Boolean, Integer, String> value = data.getOrDefault(Any2.<Integer, String>left(key), Any3.<Boolean, Integer, String>create2(dfl)); return value.get2().orElseThrow(() -> new IllegalArgumentException("expected integer argument for param " + key)); }
[ "public", "int", "getIntegerOrDefault", "(", "int", "key", ",", "int", "dfl", ")", "{", "Any3", "<", "Boolean", ",", "Integer", ",", "String", ">", "value", "=", "data", ".", "getOrDefault", "(", "Any2", ".", "<", "Integer", ",", "String", ">", "left", "(", "key", ")", ",", "Any3", ".", "<", "Boolean", ",", "Integer", ",", "String", ">", "create2", "(", "dfl", ")", ")", ";", "return", "value", ".", "get2", "(", ")", ".", "orElseThrow", "(", "(", ")", "->", "new", "IllegalArgumentException", "(", "\"expected integer argument for param \"", "+", "key", ")", ")", ";", "}" ]
Return the integer value indicated by the given numeric key. @param key The key of the value to return. @param dfl The default value to return, if the key is absent. @return The integer value stored under the given key, or dfl. @throws IllegalArgumentException if the value is present, but not an integer.
[ "Return", "the", "integer", "value", "indicated", "by", "the", "given", "numeric", "key", "." ]
train
https://github.com/groupon/monsoon/blob/eb68d72ba4c01fe018dc981097dbee033908f5c7/intf/src/main/java/com/groupon/lex/metrics/resolver/NamedResolverMap.java#L73-L76
GCRC/nunaliit
nunaliit2-dbWeb/src/main/java/ca/carleton/gcrc/dbWeb/DbWebServlet.java
DbWebServlet.performMultiQuery
private void performMultiQuery(HttpServletRequest request, HttpServletResponse response) throws Exception { """ Perform multiple SQL queries via dbSec. queries = { key1: { table: <table name> ,select: [ <selectExpression> ,... ] ,where: [ '<columnName>,<comparator>' ,'<columnName>,<comparator>' ,... ] ,groupBy: [ <columnName> ,... ] } ,key2: { ... } , ... } <selectExpression> : <columnName> sum(<columnName>) min(<columnName>) max(<columnName>) <comparator> : eq(<value>) where value is a valid comparison value for the column's data type. ne(<value>) where value is a valid comparison value for the column's data type. ge(<value>) where value is a valid comparison value for the column's data type. le(<value>) where value is a valid comparison value for the column's data type. gt(<value>) where value is a valid comparison value for the column's data type. lt(<value>) where value is a valid comparison value for the column's data type. isNull. isNotNull. response = { key1: [ { c1: 1, c2: 2 } ,{ c1: 4, c2: 5 } ,... ] ,key2: { error: 'Error message' } ,... } @param request http request containing the query parameters. @param response http response to be sent. @throws Exception (for a variety of reasons detected while parsing and validating the http parms). """ User user = AuthenticationUtils.getUserFromRequest(request); String[] queriesStrings = request.getParameterValues("queries"); if( 1 != queriesStrings.length ) { throw new Exception("Parameter 'queries' must be specified exactly oncce"); } // Create list of Query instances List<Query> queries = parseQueriesJson(queriesStrings[0]); // Perform queries JSONObject result = new JSONObject(); { Map<String, DbTableAccess> tableAccessCache = new HashMap<String, DbTableAccess>(); for(Query query : queries) { String tableName = query.getTableName(); List<RecordSelector> whereMap = query.getWhereExpressions(); List<FieldSelector> fieldSelectors = query.getFieldSelectors(); List<FieldSelector> groupByColumnNames = query.getGroupByColumnNames(); List<OrderSpecifier> orderSpecifiers = query.getOrderBySpecifiers(); Integer limit = query.getLimit(); Integer offset = query.getOffset(); DbTableAccess tableAccess = tableAccessCache.get(tableName); if( null == tableAccess ) { tableAccess = DbTableAccess.getAccess(dbSecurity, tableName, new DbUserAdaptor(user)); tableAccessCache.put(tableName, tableAccess); } try { JSONArray queriedObjects = tableAccess.query( whereMap ,fieldSelectors ,groupByColumnNames ,orderSpecifiers ,limit ,offset ); result.put(query.getQueryKey(), queriedObjects); } catch(Exception e) { result.put(query.getQueryKey(), errorToJson(e)); } } } sendJsonResponse(response, result); }
java
private void performMultiQuery(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = AuthenticationUtils.getUserFromRequest(request); String[] queriesStrings = request.getParameterValues("queries"); if( 1 != queriesStrings.length ) { throw new Exception("Parameter 'queries' must be specified exactly oncce"); } // Create list of Query instances List<Query> queries = parseQueriesJson(queriesStrings[0]); // Perform queries JSONObject result = new JSONObject(); { Map<String, DbTableAccess> tableAccessCache = new HashMap<String, DbTableAccess>(); for(Query query : queries) { String tableName = query.getTableName(); List<RecordSelector> whereMap = query.getWhereExpressions(); List<FieldSelector> fieldSelectors = query.getFieldSelectors(); List<FieldSelector> groupByColumnNames = query.getGroupByColumnNames(); List<OrderSpecifier> orderSpecifiers = query.getOrderBySpecifiers(); Integer limit = query.getLimit(); Integer offset = query.getOffset(); DbTableAccess tableAccess = tableAccessCache.get(tableName); if( null == tableAccess ) { tableAccess = DbTableAccess.getAccess(dbSecurity, tableName, new DbUserAdaptor(user)); tableAccessCache.put(tableName, tableAccess); } try { JSONArray queriedObjects = tableAccess.query( whereMap ,fieldSelectors ,groupByColumnNames ,orderSpecifiers ,limit ,offset ); result.put(query.getQueryKey(), queriedObjects); } catch(Exception e) { result.put(query.getQueryKey(), errorToJson(e)); } } } sendJsonResponse(response, result); }
[ "private", "void", "performMultiQuery", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "Exception", "{", "User", "user", "=", "AuthenticationUtils", ".", "getUserFromRequest", "(", "request", ")", ";", "String", "[", "]", "queriesStrings", "=", "request", ".", "getParameterValues", "(", "\"queries\"", ")", ";", "if", "(", "1", "!=", "queriesStrings", ".", "length", ")", "{", "throw", "new", "Exception", "(", "\"Parameter 'queries' must be specified exactly oncce\"", ")", ";", "}", "// Create list of Query instances", "List", "<", "Query", ">", "queries", "=", "parseQueriesJson", "(", "queriesStrings", "[", "0", "]", ")", ";", "// Perform queries", "JSONObject", "result", "=", "new", "JSONObject", "(", ")", ";", "{", "Map", "<", "String", ",", "DbTableAccess", ">", "tableAccessCache", "=", "new", "HashMap", "<", "String", ",", "DbTableAccess", ">", "(", ")", ";", "for", "(", "Query", "query", ":", "queries", ")", "{", "String", "tableName", "=", "query", ".", "getTableName", "(", ")", ";", "List", "<", "RecordSelector", ">", "whereMap", "=", "query", ".", "getWhereExpressions", "(", ")", ";", "List", "<", "FieldSelector", ">", "fieldSelectors", "=", "query", ".", "getFieldSelectors", "(", ")", ";", "List", "<", "FieldSelector", ">", "groupByColumnNames", "=", "query", ".", "getGroupByColumnNames", "(", ")", ";", "List", "<", "OrderSpecifier", ">", "orderSpecifiers", "=", "query", ".", "getOrderBySpecifiers", "(", ")", ";", "Integer", "limit", "=", "query", ".", "getLimit", "(", ")", ";", "Integer", "offset", "=", "query", ".", "getOffset", "(", ")", ";", "DbTableAccess", "tableAccess", "=", "tableAccessCache", ".", "get", "(", "tableName", ")", ";", "if", "(", "null", "==", "tableAccess", ")", "{", "tableAccess", "=", "DbTableAccess", ".", "getAccess", "(", "dbSecurity", ",", "tableName", ",", "new", "DbUserAdaptor", "(", "user", ")", ")", ";", "tableAccessCache", ".", "put", "(", "tableName", ",", "tableAccess", ")", ";", "}", "try", "{", "JSONArray", "queriedObjects", "=", "tableAccess", ".", "query", "(", "whereMap", ",", "fieldSelectors", ",", "groupByColumnNames", ",", "orderSpecifiers", ",", "limit", ",", "offset", ")", ";", "result", ".", "put", "(", "query", ".", "getQueryKey", "(", ")", ",", "queriedObjects", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "result", ".", "put", "(", "query", ".", "getQueryKey", "(", ")", ",", "errorToJson", "(", "e", ")", ")", ";", "}", "}", "}", "sendJsonResponse", "(", "response", ",", "result", ")", ";", "}" ]
Perform multiple SQL queries via dbSec. queries = { key1: { table: <table name> ,select: [ <selectExpression> ,... ] ,where: [ '<columnName>,<comparator>' ,'<columnName>,<comparator>' ,... ] ,groupBy: [ <columnName> ,... ] } ,key2: { ... } , ... } <selectExpression> : <columnName> sum(<columnName>) min(<columnName>) max(<columnName>) <comparator> : eq(<value>) where value is a valid comparison value for the column's data type. ne(<value>) where value is a valid comparison value for the column's data type. ge(<value>) where value is a valid comparison value for the column's data type. le(<value>) where value is a valid comparison value for the column's data type. gt(<value>) where value is a valid comparison value for the column's data type. lt(<value>) where value is a valid comparison value for the column's data type. isNull. isNotNull. response = { key1: [ { c1: 1, c2: 2 } ,{ c1: 4, c2: 5 } ,... ] ,key2: { error: 'Error message' } ,... } @param request http request containing the query parameters. @param response http response to be sent. @throws Exception (for a variety of reasons detected while parsing and validating the http parms).
[ "Perform", "multiple", "SQL", "queries", "via", "dbSec", "." ]
train
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-dbWeb/src/main/java/ca/carleton/gcrc/dbWeb/DbWebServlet.java#L316-L363
knowm/XChange
xchange-bitcoinde/src/main/java/org/knowm/xchange/bitcoinde/BitcoindeAdapters.java
BitcoindeAdapters.adaptAccountInfo
public static AccountInfo adaptAccountInfo(BitcoindeAccountWrapper bitcoindeAccount) { """ Adapt a org.knowm.xchange.bitcoinde.dto.marketdata.BitcoindeAccount object to an AccountInfo object. @param bitcoindeAccount @return """ // This adapter is not complete yet BitcoindeBalance btc = bitcoindeAccount.getData().getBalances().getBtc(); BitcoindeBalance eth = bitcoindeAccount.getData().getBalances().getEth(); BigDecimal eur = bitcoindeAccount.getData().getFidorReservation().getAvailableAmount(); Balance btcBalance = new Balance(Currency.BTC, btc.getAvailableAmount()); Balance ethBalance = new Balance(Currency.ETH, eth.getAvailableAmount()); Balance eurBalance = new Balance(Currency.EUR, eur); Wallet wallet = new Wallet(btcBalance, ethBalance, eurBalance); return new AccountInfo(wallet); }
java
public static AccountInfo adaptAccountInfo(BitcoindeAccountWrapper bitcoindeAccount) { // This adapter is not complete yet BitcoindeBalance btc = bitcoindeAccount.getData().getBalances().getBtc(); BitcoindeBalance eth = bitcoindeAccount.getData().getBalances().getEth(); BigDecimal eur = bitcoindeAccount.getData().getFidorReservation().getAvailableAmount(); Balance btcBalance = new Balance(Currency.BTC, btc.getAvailableAmount()); Balance ethBalance = new Balance(Currency.ETH, eth.getAvailableAmount()); Balance eurBalance = new Balance(Currency.EUR, eur); Wallet wallet = new Wallet(btcBalance, ethBalance, eurBalance); return new AccountInfo(wallet); }
[ "public", "static", "AccountInfo", "adaptAccountInfo", "(", "BitcoindeAccountWrapper", "bitcoindeAccount", ")", "{", "// This adapter is not complete yet", "BitcoindeBalance", "btc", "=", "bitcoindeAccount", ".", "getData", "(", ")", ".", "getBalances", "(", ")", ".", "getBtc", "(", ")", ";", "BitcoindeBalance", "eth", "=", "bitcoindeAccount", ".", "getData", "(", ")", ".", "getBalances", "(", ")", ".", "getEth", "(", ")", ";", "BigDecimal", "eur", "=", "bitcoindeAccount", ".", "getData", "(", ")", ".", "getFidorReservation", "(", ")", ".", "getAvailableAmount", "(", ")", ";", "Balance", "btcBalance", "=", "new", "Balance", "(", "Currency", ".", "BTC", ",", "btc", ".", "getAvailableAmount", "(", ")", ")", ";", "Balance", "ethBalance", "=", "new", "Balance", "(", "Currency", ".", "ETH", ",", "eth", ".", "getAvailableAmount", "(", ")", ")", ";", "Balance", "eurBalance", "=", "new", "Balance", "(", "Currency", ".", "EUR", ",", "eur", ")", ";", "Wallet", "wallet", "=", "new", "Wallet", "(", "btcBalance", ",", "ethBalance", ",", "eurBalance", ")", ";", "return", "new", "AccountInfo", "(", "wallet", ")", ";", "}" ]
Adapt a org.knowm.xchange.bitcoinde.dto.marketdata.BitcoindeAccount object to an AccountInfo object. @param bitcoindeAccount @return
[ "Adapt", "a", "org", ".", "knowm", ".", "xchange", ".", "bitcoinde", ".", "dto", ".", "marketdata", ".", "BitcoindeAccount", "object", "to", "an", "AccountInfo", "object", "." ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-bitcoinde/src/main/java/org/knowm/xchange/bitcoinde/BitcoindeAdapters.java#L94-L108
Azure/azure-sdk-for-java
sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/DatabasesInner.java
DatabasesInner.beginUpgradeDataWarehouse
public void beginUpgradeDataWarehouse(String resourceGroupName, String serverName, String databaseName) { """ Upgrades a data warehouse. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database to be upgraded. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ beginUpgradeDataWarehouseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).toBlocking().single().body(); }
java
public void beginUpgradeDataWarehouse(String resourceGroupName, String serverName, String databaseName) { beginUpgradeDataWarehouseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).toBlocking().single().body(); }
[ "public", "void", "beginUpgradeDataWarehouse", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "databaseName", ")", "{", "beginUpgradeDataWarehouseWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "databaseName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Upgrades a data warehouse. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database to be upgraded. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Upgrades", "a", "data", "warehouse", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/DatabasesInner.java#L227-L229
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/ByteArrayUtil.java
ByteArrayUtil.putDoubleBE
public static void putDoubleBE(final byte[] array, final int offset, final double value) { """ Put the source <i>double</i> into the destination byte array starting at the given offset in big endian order. There is no bounds checking. @param array destination byte array @param offset destination offset @param value source <i>double</i> """ putLongBE(array, offset, Double.doubleToRawLongBits(value)); }
java
public static void putDoubleBE(final byte[] array, final int offset, final double value) { putLongBE(array, offset, Double.doubleToRawLongBits(value)); }
[ "public", "static", "void", "putDoubleBE", "(", "final", "byte", "[", "]", "array", ",", "final", "int", "offset", ",", "final", "double", "value", ")", "{", "putLongBE", "(", "array", ",", "offset", ",", "Double", ".", "doubleToRawLongBits", "(", "value", ")", ")", ";", "}" ]
Put the source <i>double</i> into the destination byte array starting at the given offset in big endian order. There is no bounds checking. @param array destination byte array @param offset destination offset @param value source <i>double</i>
[ "Put", "the", "source", "<i", ">", "double<", "/", "i", ">", "into", "the", "destination", "byte", "array", "starting", "at", "the", "given", "offset", "in", "big", "endian", "order", ".", "There", "is", "no", "bounds", "checking", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/ByteArrayUtil.java#L285-L287
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/util/Interval.java
Interval.compareIntervalOrder
public int compareIntervalOrder(Interval<E> other) { """ Returns order of another interval compared to this one @param other Interval to compare with @return -1 if this interval is before the other interval, 1 if this interval is after 0 otherwise (may indicate the two intervals are same or not comparable) """ int flags = getRelationFlags(other); if (checkFlagExclusiveSet(flags, REL_FLAGS_INTERVAL_BEFORE, REL_FLAGS_INTERVAL_UNKNOWN)) { return -1; } else if (checkFlagExclusiveSet(flags, REL_FLAGS_INTERVAL_AFTER, REL_FLAGS_INTERVAL_UNKNOWN)) { return 1; } else { return 0; } }
java
public int compareIntervalOrder(Interval<E> other) { int flags = getRelationFlags(other); if (checkFlagExclusiveSet(flags, REL_FLAGS_INTERVAL_BEFORE, REL_FLAGS_INTERVAL_UNKNOWN)) { return -1; } else if (checkFlagExclusiveSet(flags, REL_FLAGS_INTERVAL_AFTER, REL_FLAGS_INTERVAL_UNKNOWN)) { return 1; } else { return 0; } }
[ "public", "int", "compareIntervalOrder", "(", "Interval", "<", "E", ">", "other", ")", "{", "int", "flags", "=", "getRelationFlags", "(", "other", ")", ";", "if", "(", "checkFlagExclusiveSet", "(", "flags", ",", "REL_FLAGS_INTERVAL_BEFORE", ",", "REL_FLAGS_INTERVAL_UNKNOWN", ")", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "checkFlagExclusiveSet", "(", "flags", ",", "REL_FLAGS_INTERVAL_AFTER", ",", "REL_FLAGS_INTERVAL_UNKNOWN", ")", ")", "{", "return", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}" ]
Returns order of another interval compared to this one @param other Interval to compare with @return -1 if this interval is before the other interval, 1 if this interval is after 0 otherwise (may indicate the two intervals are same or not comparable)
[ "Returns", "order", "of", "another", "interval", "compared", "to", "this", "one" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/Interval.java#L605-L615
Harium/keel
src/main/java/com/harium/keel/catalano/math/Tools.java
Tools.Clamp
public static double Clamp(double x, DoubleRange range) { """ Clamp values. @param x Value. @param range Range. @return Value. """ return Clamp(x, range.getMin(), range.getMax()); }
java
public static double Clamp(double x, DoubleRange range) { return Clamp(x, range.getMin(), range.getMax()); }
[ "public", "static", "double", "Clamp", "(", "double", "x", ",", "DoubleRange", "range", ")", "{", "return", "Clamp", "(", "x", ",", "range", ".", "getMin", "(", ")", ",", "range", ".", "getMax", "(", ")", ")", ";", "}" ]
Clamp values. @param x Value. @param range Range. @return Value.
[ "Clamp", "values", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/Tools.java#L123-L125
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/doc/DocClient.java
DocClient.createDocumentFromBos
public CreateDocumentFromBosResponse createDocumentFromBos(CreateDocumentFromBosRequest request) { """ Create a Document. @param request The request object containing all the parameters to upload a new doc. @return A CreateDocumentResponse object containing the information returned by Document. """ checkNotNull(request, "request should not be null."); checkNotNull(request.getBucket(), "bucket should not be null."); checkNotNull(request.getObject(), "object should not be null."); checkNotNull(request.getTitle(), "title should not be null."); checkNotNull(request.getFormat(), "format should not be null."); InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, DOC); internalRequest.addParameter("source", "bos"); String strJson = JsonUtils.toJsonString(request); byte[] requestJson = null; try { requestJson = strJson.getBytes(DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new BceClientException("Unsupported encode.", e); } internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(requestJson.length)); internalRequest.addHeader(Headers.CONTENT_TYPE, DEFAULT_CONTENT_TYPE); internalRequest.setContent(RestartableInputStream.wrap(requestJson)); return invokeHttpClient(internalRequest, CreateDocumentFromBosResponse.class); }
java
public CreateDocumentFromBosResponse createDocumentFromBos(CreateDocumentFromBosRequest request) { checkNotNull(request, "request should not be null."); checkNotNull(request.getBucket(), "bucket should not be null."); checkNotNull(request.getObject(), "object should not be null."); checkNotNull(request.getTitle(), "title should not be null."); checkNotNull(request.getFormat(), "format should not be null."); InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, DOC); internalRequest.addParameter("source", "bos"); String strJson = JsonUtils.toJsonString(request); byte[] requestJson = null; try { requestJson = strJson.getBytes(DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new BceClientException("Unsupported encode.", e); } internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(requestJson.length)); internalRequest.addHeader(Headers.CONTENT_TYPE, DEFAULT_CONTENT_TYPE); internalRequest.setContent(RestartableInputStream.wrap(requestJson)); return invokeHttpClient(internalRequest, CreateDocumentFromBosResponse.class); }
[ "public", "CreateDocumentFromBosResponse", "createDocumentFromBos", "(", "CreateDocumentFromBosRequest", "request", ")", "{", "checkNotNull", "(", "request", ",", "\"request should not be null.\"", ")", ";", "checkNotNull", "(", "request", ".", "getBucket", "(", ")", ",", "\"bucket should not be null.\"", ")", ";", "checkNotNull", "(", "request", ".", "getObject", "(", ")", ",", "\"object should not be null.\"", ")", ";", "checkNotNull", "(", "request", ".", "getTitle", "(", ")", ",", "\"title should not be null.\"", ")", ";", "checkNotNull", "(", "request", ".", "getFormat", "(", ")", ",", "\"format should not be null.\"", ")", ";", "InternalRequest", "internalRequest", "=", "createRequest", "(", "HttpMethodName", ".", "POST", ",", "request", ",", "DOC", ")", ";", "internalRequest", ".", "addParameter", "(", "\"source\"", ",", "\"bos\"", ")", ";", "String", "strJson", "=", "JsonUtils", ".", "toJsonString", "(", "request", ")", ";", "byte", "[", "]", "requestJson", "=", "null", ";", "try", "{", "requestJson", "=", "strJson", ".", "getBytes", "(", "DEFAULT_ENCODING", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "BceClientException", "(", "\"Unsupported encode.\"", ",", "e", ")", ";", "}", "internalRequest", ".", "addHeader", "(", "Headers", ".", "CONTENT_LENGTH", ",", "String", ".", "valueOf", "(", "requestJson", ".", "length", ")", ")", ";", "internalRequest", ".", "addHeader", "(", "Headers", ".", "CONTENT_TYPE", ",", "DEFAULT_CONTENT_TYPE", ")", ";", "internalRequest", ".", "setContent", "(", "RestartableInputStream", ".", "wrap", "(", "requestJson", ")", ")", ";", "return", "invokeHttpClient", "(", "internalRequest", ",", "CreateDocumentFromBosResponse", ".", "class", ")", ";", "}" ]
Create a Document. @param request The request object containing all the parameters to upload a new doc. @return A CreateDocumentResponse object containing the information returned by Document.
[ "Create", "a", "Document", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/doc/DocClient.java#L376-L396
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/WebAppSecurityCollaboratorImpl.java
WebAppSecurityCollaboratorImpl.preInvoke
@Override public Object preInvoke(HttpServletRequest req, HttpServletResponse resp, String servletName, boolean enforceSecurity) throws SecurityViolationException, IOException { """ This preInvoke is called for every request and when processing AsyncErrorHandling. It is also called (passing in false for <code>enforceSecurity</code>) for static files to check whether the user has access to the file on the zOS file system. <p> preInvoke also handles runAs delegation. <p> {@inheritDoc} """ Subject invokedSubject = subjectManager.getInvocationSubject(); Subject receivedSubject = subjectManager.getCallerSubject(); WebSecurityContext webSecurityContext = new WebSecurityContext(invokedSubject, receivedSubject); setUnauthenticatedSubjectIfNeeded(invokedSubject, receivedSubject); if (req != null) { SRTServletRequestUtils.setPrivateAttribute(req, SECURITY_CONTEXT, webSecurityContext); } if (enforceSecurity) { // Authentication and authorization are not required // for servlet init or destroy and, per spec, should // not be done for forward or include paths. if (req != null) { performSecurityChecks(req, resp, receivedSubject, webSecurityContext); } if (req != null) { extraAuditData.put("HTTP_SERVLET_REQUEST", req); } //auditManager.setHttpServletRequest(req); performDelegation(servletName); syncToOSThread(webSecurityContext); } return webSecurityContext; }
java
@Override public Object preInvoke(HttpServletRequest req, HttpServletResponse resp, String servletName, boolean enforceSecurity) throws SecurityViolationException, IOException { Subject invokedSubject = subjectManager.getInvocationSubject(); Subject receivedSubject = subjectManager.getCallerSubject(); WebSecurityContext webSecurityContext = new WebSecurityContext(invokedSubject, receivedSubject); setUnauthenticatedSubjectIfNeeded(invokedSubject, receivedSubject); if (req != null) { SRTServletRequestUtils.setPrivateAttribute(req, SECURITY_CONTEXT, webSecurityContext); } if (enforceSecurity) { // Authentication and authorization are not required // for servlet init or destroy and, per spec, should // not be done for forward or include paths. if (req != null) { performSecurityChecks(req, resp, receivedSubject, webSecurityContext); } if (req != null) { extraAuditData.put("HTTP_SERVLET_REQUEST", req); } //auditManager.setHttpServletRequest(req); performDelegation(servletName); syncToOSThread(webSecurityContext); } return webSecurityContext; }
[ "@", "Override", "public", "Object", "preInvoke", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "resp", ",", "String", "servletName", ",", "boolean", "enforceSecurity", ")", "throws", "SecurityViolationException", ",", "IOException", "{", "Subject", "invokedSubject", "=", "subjectManager", ".", "getInvocationSubject", "(", ")", ";", "Subject", "receivedSubject", "=", "subjectManager", ".", "getCallerSubject", "(", ")", ";", "WebSecurityContext", "webSecurityContext", "=", "new", "WebSecurityContext", "(", "invokedSubject", ",", "receivedSubject", ")", ";", "setUnauthenticatedSubjectIfNeeded", "(", "invokedSubject", ",", "receivedSubject", ")", ";", "if", "(", "req", "!=", "null", ")", "{", "SRTServletRequestUtils", ".", "setPrivateAttribute", "(", "req", ",", "SECURITY_CONTEXT", ",", "webSecurityContext", ")", ";", "}", "if", "(", "enforceSecurity", ")", "{", "// Authentication and authorization are not required", "// for servlet init or destroy and, per spec, should", "// not be done for forward or include paths.", "if", "(", "req", "!=", "null", ")", "{", "performSecurityChecks", "(", "req", ",", "resp", ",", "receivedSubject", ",", "webSecurityContext", ")", ";", "}", "if", "(", "req", "!=", "null", ")", "{", "extraAuditData", ".", "put", "(", "\"HTTP_SERVLET_REQUEST\"", ",", "req", ")", ";", "}", "//auditManager.setHttpServletRequest(req);", "performDelegation", "(", "servletName", ")", ";", "syncToOSThread", "(", "webSecurityContext", ")", ";", "}", "return", "webSecurityContext", ";", "}" ]
This preInvoke is called for every request and when processing AsyncErrorHandling. It is also called (passing in false for <code>enforceSecurity</code>) for static files to check whether the user has access to the file on the zOS file system. <p> preInvoke also handles runAs delegation. <p> {@inheritDoc}
[ "This", "preInvoke", "is", "called", "for", "every", "request", "and", "when", "processing", "AsyncErrorHandling", ".", "It", "is", "also", "called", "(", "passing", "in", "false", "for", "<code", ">", "enforceSecurity<", "/", "code", ">", ")", "for", "static", "files", "to", "check", "whether", "the", "user", "has", "access", "to", "the", "file", "on", "the", "zOS", "file", "system", ".", "<p", ">", "preInvoke", "also", "handles", "runAs", "delegation", ".", "<p", ">", "{" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/WebAppSecurityCollaboratorImpl.java#L554-L586
OpenLiberty/open-liberty
dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/twitter/TwitterEndpointServices.java
TwitterEndpointServices.executeRequest
@FFDCIgnore(SocialLoginException.class) @Sensitive public Map<String, Object> executeRequest(SocialLoginConfig config, String requestMethod, String authzHeaderString, String url, String endpointType, String verifierValue) { """ Sends a request to the specified Twitter endpoint and returns a Map object containing the evaluated response. @param config @param requestMethod @param authzHeaderString @param url @param endpointType @param verifierValue Only used for {@value TwitterConstants#TWITTER_ENDPOINT_ACCESS_TOKEN} requests @return """ if (endpointType == null) { endpointType = TwitterConstants.TWITTER_ENDPOINT_REQUEST_TOKEN; if (tc.isDebugEnabled()) { Tr.debug(tc, "A Twitter endpoint path was not found; defaulting to using " + endpointType + " as the Twitter endpoint path."); } } try { SocialUtil.validateEndpointWithQuery(url); } catch (SocialLoginException e) { return createErrorResponse(e); } StringBuilder uri = new StringBuilder(url); if (endpointType.equals(TwitterConstants.TWITTER_ENDPOINT_VERIFY_CREDENTIALS)) { // Include the include_email and skip_status parameters for these endpoint requests uri.append("?").append(TwitterConstants.PARAM_INCLUDE_EMAIL).append("=").append(TwitterConstants.INCLUDE_EMAIL).append("&").append(TwitterConstants.PARAM_SKIP_STATUS).append("=").append(TwitterConstants.SKIP_STATUS); } try { Map<String, Object> result = getEndpointResponse(config, uri.toString(), requestMethod, authzHeaderString, endpointType, verifierValue); String responseContent = httpUtil.extractTokensFromResponse(result); return evaluateRequestResponse(responseContent, endpointType); } catch (SocialLoginException e) { return createErrorResponse("TWITTER_EXCEPTION_EXECUTING_REQUEST", new Object[] { url, e.getLocalizedMessage() }); } }
java
@FFDCIgnore(SocialLoginException.class) @Sensitive public Map<String, Object> executeRequest(SocialLoginConfig config, String requestMethod, String authzHeaderString, String url, String endpointType, String verifierValue) { if (endpointType == null) { endpointType = TwitterConstants.TWITTER_ENDPOINT_REQUEST_TOKEN; if (tc.isDebugEnabled()) { Tr.debug(tc, "A Twitter endpoint path was not found; defaulting to using " + endpointType + " as the Twitter endpoint path."); } } try { SocialUtil.validateEndpointWithQuery(url); } catch (SocialLoginException e) { return createErrorResponse(e); } StringBuilder uri = new StringBuilder(url); if (endpointType.equals(TwitterConstants.TWITTER_ENDPOINT_VERIFY_CREDENTIALS)) { // Include the include_email and skip_status parameters for these endpoint requests uri.append("?").append(TwitterConstants.PARAM_INCLUDE_EMAIL).append("=").append(TwitterConstants.INCLUDE_EMAIL).append("&").append(TwitterConstants.PARAM_SKIP_STATUS).append("=").append(TwitterConstants.SKIP_STATUS); } try { Map<String, Object> result = getEndpointResponse(config, uri.toString(), requestMethod, authzHeaderString, endpointType, verifierValue); String responseContent = httpUtil.extractTokensFromResponse(result); return evaluateRequestResponse(responseContent, endpointType); } catch (SocialLoginException e) { return createErrorResponse("TWITTER_EXCEPTION_EXECUTING_REQUEST", new Object[] { url, e.getLocalizedMessage() }); } }
[ "@", "FFDCIgnore", "(", "SocialLoginException", ".", "class", ")", "@", "Sensitive", "public", "Map", "<", "String", ",", "Object", ">", "executeRequest", "(", "SocialLoginConfig", "config", ",", "String", "requestMethod", ",", "String", "authzHeaderString", ",", "String", "url", ",", "String", "endpointType", ",", "String", "verifierValue", ")", "{", "if", "(", "endpointType", "==", "null", ")", "{", "endpointType", "=", "TwitterConstants", ".", "TWITTER_ENDPOINT_REQUEST_TOKEN", ";", "if", "(", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "\"A Twitter endpoint path was not found; defaulting to using \"", "+", "endpointType", "+", "\" as the Twitter endpoint path.\"", ")", ";", "}", "}", "try", "{", "SocialUtil", ".", "validateEndpointWithQuery", "(", "url", ")", ";", "}", "catch", "(", "SocialLoginException", "e", ")", "{", "return", "createErrorResponse", "(", "e", ")", ";", "}", "StringBuilder", "uri", "=", "new", "StringBuilder", "(", "url", ")", ";", "if", "(", "endpointType", ".", "equals", "(", "TwitterConstants", ".", "TWITTER_ENDPOINT_VERIFY_CREDENTIALS", ")", ")", "{", "// Include the include_email and skip_status parameters for these endpoint requests", "uri", ".", "append", "(", "\"?\"", ")", ".", "append", "(", "TwitterConstants", ".", "PARAM_INCLUDE_EMAIL", ")", ".", "append", "(", "\"=\"", ")", ".", "append", "(", "TwitterConstants", ".", "INCLUDE_EMAIL", ")", ".", "append", "(", "\"&\"", ")", ".", "append", "(", "TwitterConstants", ".", "PARAM_SKIP_STATUS", ")", ".", "append", "(", "\"=\"", ")", ".", "append", "(", "TwitterConstants", ".", "SKIP_STATUS", ")", ";", "}", "try", "{", "Map", "<", "String", ",", "Object", ">", "result", "=", "getEndpointResponse", "(", "config", ",", "uri", ".", "toString", "(", ")", ",", "requestMethod", ",", "authzHeaderString", ",", "endpointType", ",", "verifierValue", ")", ";", "String", "responseContent", "=", "httpUtil", ".", "extractTokensFromResponse", "(", "result", ")", ";", "return", "evaluateRequestResponse", "(", "responseContent", ",", "endpointType", ")", ";", "}", "catch", "(", "SocialLoginException", "e", ")", "{", "return", "createErrorResponse", "(", "\"TWITTER_EXCEPTION_EXECUTING_REQUEST\"", ",", "new", "Object", "[", "]", "{", "url", ",", "e", ".", "getLocalizedMessage", "(", ")", "}", ")", ";", "}", "}" ]
Sends a request to the specified Twitter endpoint and returns a Map object containing the evaluated response. @param config @param requestMethod @param authzHeaderString @param url @param endpointType @param verifierValue Only used for {@value TwitterConstants#TWITTER_ENDPOINT_ACCESS_TOKEN} requests @return
[ "Sends", "a", "request", "to", "the", "specified", "Twitter", "endpoint", "and", "returns", "a", "Map", "object", "containing", "the", "evaluated", "response", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/twitter/TwitterEndpointServices.java#L832-L865
mozilla/rhino
src/org/mozilla/javascript/ScriptRuntime.java
ScriptRuntime.getElemFunctionAndThis
public static Callable getElemFunctionAndThis(Object obj, Object elem, Context cx, Scriptable scope) { """ Prepare for calling obj[id](...): return function corresponding to obj[id] and make obj properly converted to Scriptable available as ScriptRuntime.lastStoredScriptable() for consumption as thisObj. The caller must call ScriptRuntime.lastStoredScriptable() immediately after calling this method. """ Scriptable thisObj; Object value; if (isSymbol(elem)) { thisObj = toObjectOrNull(cx, obj, scope); if (thisObj == null) { throw undefCallError(obj, String.valueOf(elem)); } value = ScriptableObject.getProperty(thisObj, (Symbol)elem); } else { String str = toStringIdOrIndex(cx, elem); if (str != null) { return getPropFunctionAndThis(obj, str, cx, scope); } int index = lastIndexResult(cx); thisObj = toObjectOrNull(cx, obj, scope); if (thisObj == null) { throw undefCallError(obj, String.valueOf(elem)); } value = ScriptableObject.getProperty(thisObj, index); } if (!(value instanceof Callable)) { throw notFunctionError(value, elem); } storeScriptable(cx, thisObj); return (Callable)value; }
java
public static Callable getElemFunctionAndThis(Object obj, Object elem, Context cx, Scriptable scope) { Scriptable thisObj; Object value; if (isSymbol(elem)) { thisObj = toObjectOrNull(cx, obj, scope); if (thisObj == null) { throw undefCallError(obj, String.valueOf(elem)); } value = ScriptableObject.getProperty(thisObj, (Symbol)elem); } else { String str = toStringIdOrIndex(cx, elem); if (str != null) { return getPropFunctionAndThis(obj, str, cx, scope); } int index = lastIndexResult(cx); thisObj = toObjectOrNull(cx, obj, scope); if (thisObj == null) { throw undefCallError(obj, String.valueOf(elem)); } value = ScriptableObject.getProperty(thisObj, index); } if (!(value instanceof Callable)) { throw notFunctionError(value, elem); } storeScriptable(cx, thisObj); return (Callable)value; }
[ "public", "static", "Callable", "getElemFunctionAndThis", "(", "Object", "obj", ",", "Object", "elem", ",", "Context", "cx", ",", "Scriptable", "scope", ")", "{", "Scriptable", "thisObj", ";", "Object", "value", ";", "if", "(", "isSymbol", "(", "elem", ")", ")", "{", "thisObj", "=", "toObjectOrNull", "(", "cx", ",", "obj", ",", "scope", ")", ";", "if", "(", "thisObj", "==", "null", ")", "{", "throw", "undefCallError", "(", "obj", ",", "String", ".", "valueOf", "(", "elem", ")", ")", ";", "}", "value", "=", "ScriptableObject", ".", "getProperty", "(", "thisObj", ",", "(", "Symbol", ")", "elem", ")", ";", "}", "else", "{", "String", "str", "=", "toStringIdOrIndex", "(", "cx", ",", "elem", ")", ";", "if", "(", "str", "!=", "null", ")", "{", "return", "getPropFunctionAndThis", "(", "obj", ",", "str", ",", "cx", ",", "scope", ")", ";", "}", "int", "index", "=", "lastIndexResult", "(", "cx", ")", ";", "thisObj", "=", "toObjectOrNull", "(", "cx", ",", "obj", ",", "scope", ")", ";", "if", "(", "thisObj", "==", "null", ")", "{", "throw", "undefCallError", "(", "obj", ",", "String", ".", "valueOf", "(", "elem", ")", ")", ";", "}", "value", "=", "ScriptableObject", ".", "getProperty", "(", "thisObj", ",", "index", ")", ";", "}", "if", "(", "!", "(", "value", "instanceof", "Callable", ")", ")", "{", "throw", "notFunctionError", "(", "value", ",", "elem", ")", ";", "}", "storeScriptable", "(", "cx", ",", "thisObj", ")", ";", "return", "(", "Callable", ")", "value", ";", "}" ]
Prepare for calling obj[id](...): return function corresponding to obj[id] and make obj properly converted to Scriptable available as ScriptRuntime.lastStoredScriptable() for consumption as thisObj. The caller must call ScriptRuntime.lastStoredScriptable() immediately after calling this method.
[ "Prepare", "for", "calling", "obj", "[", "id", "]", "(", "...", ")", ":", "return", "function", "corresponding", "to", "obj", "[", "id", "]", "and", "make", "obj", "properly", "converted", "to", "Scriptable", "available", "as", "ScriptRuntime", ".", "lastStoredScriptable", "()", "for", "consumption", "as", "thisObj", ".", "The", "caller", "must", "call", "ScriptRuntime", ".", "lastStoredScriptable", "()", "immediately", "after", "calling", "this", "method", "." ]
train
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/ScriptRuntime.java#L2495-L2529
OpenLiberty/open-liberty
dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/DCacheBase.java
DCacheBase.getEntry
public com.ibm.websphere.cache.CacheEntry getEntry(com.ibm.websphere.cache.EntryInfo ei) { """ This returns the cache entry identified by the specified entryInfo. It returns null if not in the cache. @param ei The entryInfo for the entry. @return The entry identified by the entryInfo. """ return getEntry(ei, true); }
java
public com.ibm.websphere.cache.CacheEntry getEntry(com.ibm.websphere.cache.EntryInfo ei) { return getEntry(ei, true); }
[ "public", "com", ".", "ibm", ".", "websphere", ".", "cache", ".", "CacheEntry", "getEntry", "(", "com", ".", "ibm", ".", "websphere", ".", "cache", ".", "EntryInfo", "ei", ")", "{", "return", "getEntry", "(", "ei", ",", "true", ")", ";", "}" ]
This returns the cache entry identified by the specified entryInfo. It returns null if not in the cache. @param ei The entryInfo for the entry. @return The entry identified by the entryInfo.
[ "This", "returns", "the", "cache", "entry", "identified", "by", "the", "specified", "entryInfo", ".", "It", "returns", "null", "if", "not", "in", "the", "cache", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/DCacheBase.java#L336-L338
percolate/caffeine
caffeine/src/main/java/com/percolate/caffeine/ToastUtils.java
ToastUtils.quickToast
public static Toast quickToast(Context context, String message) { """ Display a toast with the given message (Length will be Toast.LENGTH_SHORT -- approx 2 sec). @param context The current Context or Activity that this method is called from @param message Message to display @return Toast object that is being displayed. Note,show() has already been called on this object. """ return quickToast(context, message, false); }
java
public static Toast quickToast(Context context, String message) { return quickToast(context, message, false); }
[ "public", "static", "Toast", "quickToast", "(", "Context", "context", ",", "String", "message", ")", "{", "return", "quickToast", "(", "context", ",", "message", ",", "false", ")", ";", "}" ]
Display a toast with the given message (Length will be Toast.LENGTH_SHORT -- approx 2 sec). @param context The current Context or Activity that this method is called from @param message Message to display @return Toast object that is being displayed. Note,show() has already been called on this object.
[ "Display", "a", "toast", "with", "the", "given", "message", "(", "Length", "will", "be", "Toast", ".", "LENGTH_SHORT", "--", "approx", "2", "sec", ")", "." ]
train
https://github.com/percolate/caffeine/blob/e2265cab474a6397f4d75b1ed928c356a7b9672e/caffeine/src/main/java/com/percolate/caffeine/ToastUtils.java#L21-L23
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/tools/BigramExtractor.java
BigramExtractor.processBigram
private void processBigram(String left, String right) { """ Updates the statistics for the bigram formed from the provided left and right token. @param left the left token in the bigram @param right the right token in the bigram """ TokenStats leftStats = getStatsFor(left); TokenStats rightStats = getStatsFor(right); // mark that both appeared leftStats.count++; rightStats.count++; // Mark the respective positions of each leftStats.leftCount++; rightStats.rightCount++; // Increase the number of bigrams seen numBigramsInCorpus++; // Update the bigram statistics // Map the two token's indices into a single long long bigram = (((long)leftStats.index) << 32) | rightStats.index; Number curBigramCount = bigramCounts.get(bigram); int i = (curBigramCount == null) ? 1 : 1 + curBigramCount.intValue(); // Compact the count into the smallest numeric type that can represent // it. This hopefully results in some space savings. Number val = null; if (i < Byte.MAX_VALUE) val = Byte.valueOf((byte)i); else if (i < Short.MAX_VALUE) val = Short.valueOf((short)i); else val = Integer.valueOf(i); bigramCounts.put(bigram, val); }
java
private void processBigram(String left, String right) { TokenStats leftStats = getStatsFor(left); TokenStats rightStats = getStatsFor(right); // mark that both appeared leftStats.count++; rightStats.count++; // Mark the respective positions of each leftStats.leftCount++; rightStats.rightCount++; // Increase the number of bigrams seen numBigramsInCorpus++; // Update the bigram statistics // Map the two token's indices into a single long long bigram = (((long)leftStats.index) << 32) | rightStats.index; Number curBigramCount = bigramCounts.get(bigram); int i = (curBigramCount == null) ? 1 : 1 + curBigramCount.intValue(); // Compact the count into the smallest numeric type that can represent // it. This hopefully results in some space savings. Number val = null; if (i < Byte.MAX_VALUE) val = Byte.valueOf((byte)i); else if (i < Short.MAX_VALUE) val = Short.valueOf((short)i); else val = Integer.valueOf(i); bigramCounts.put(bigram, val); }
[ "private", "void", "processBigram", "(", "String", "left", ",", "String", "right", ")", "{", "TokenStats", "leftStats", "=", "getStatsFor", "(", "left", ")", ";", "TokenStats", "rightStats", "=", "getStatsFor", "(", "right", ")", ";", "// mark that both appeared", "leftStats", ".", "count", "++", ";", "rightStats", ".", "count", "++", ";", "// Mark the respective positions of each", "leftStats", ".", "leftCount", "++", ";", "rightStats", ".", "rightCount", "++", ";", "// Increase the number of bigrams seen", "numBigramsInCorpus", "++", ";", "// Update the bigram statistics", "// Map the two token's indices into a single long", "long", "bigram", "=", "(", "(", "(", "long", ")", "leftStats", ".", "index", ")", "<<", "32", ")", "|", "rightStats", ".", "index", ";", "Number", "curBigramCount", "=", "bigramCounts", ".", "get", "(", "bigram", ")", ";", "int", "i", "=", "(", "curBigramCount", "==", "null", ")", "?", "1", ":", "1", "+", "curBigramCount", ".", "intValue", "(", ")", ";", "// Compact the count into the smallest numeric type that can represent", "// it. This hopefully results in some space savings.", "Number", "val", "=", "null", ";", "if", "(", "i", "<", "Byte", ".", "MAX_VALUE", ")", "val", "=", "Byte", ".", "valueOf", "(", "(", "byte", ")", "i", ")", ";", "else", "if", "(", "i", "<", "Short", ".", "MAX_VALUE", ")", "val", "=", "Short", ".", "valueOf", "(", "(", "short", ")", "i", ")", ";", "else", "val", "=", "Integer", ".", "valueOf", "(", "i", ")", ";", "bigramCounts", ".", "put", "(", "bigram", ",", "val", ")", ";", "}" ]
Updates the statistics for the bigram formed from the provided left and right token. @param left the left token in the bigram @param right the right token in the bigram
[ "Updates", "the", "statistics", "for", "the", "bigram", "formed", "from", "the", "provided", "left", "and", "right", "token", "." ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/tools/BigramExtractor.java#L177-L210
OpenLiberty/open-liberty
dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/VariableEvaluator.java
VariableEvaluator.getProperty
private String getProperty(String variable, EvaluationContext context, boolean ignoreWarnings, boolean useEnvironment) throws ConfigEvaluatorException { """ Returns the value of the variable as a string, or null if the property does not exist. @param variable the variable name """ return stringUtils.convertToString(getPropertyObject(variable, context, ignoreWarnings, useEnvironment)); }
java
private String getProperty(String variable, EvaluationContext context, boolean ignoreWarnings, boolean useEnvironment) throws ConfigEvaluatorException { return stringUtils.convertToString(getPropertyObject(variable, context, ignoreWarnings, useEnvironment)); }
[ "private", "String", "getProperty", "(", "String", "variable", ",", "EvaluationContext", "context", ",", "boolean", "ignoreWarnings", ",", "boolean", "useEnvironment", ")", "throws", "ConfigEvaluatorException", "{", "return", "stringUtils", ".", "convertToString", "(", "getPropertyObject", "(", "variable", ",", "context", ",", "ignoreWarnings", ",", "useEnvironment", ")", ")", ";", "}" ]
Returns the value of the variable as a string, or null if the property does not exist. @param variable the variable name
[ "Returns", "the", "value", "of", "the", "variable", "as", "a", "string", "or", "null", "if", "the", "property", "does", "not", "exist", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/VariableEvaluator.java#L81-L83
lucee/Lucee
core/src/main/java/lucee/runtime/type/util/ListUtil.java
ListUtil.arrayToListTrim
public static String arrayToListTrim(String[] array, String delimiter) { """ convert a string array to string list, removes empty values at begin and end of the list @param array array to convert @param delimiter delimiter for the new list @return list generated from string array """ return trim(arrayToList(array, delimiter), delimiter, false); }
java
public static String arrayToListTrim(String[] array, String delimiter) { return trim(arrayToList(array, delimiter), delimiter, false); }
[ "public", "static", "String", "arrayToListTrim", "(", "String", "[", "]", "array", ",", "String", "delimiter", ")", "{", "return", "trim", "(", "arrayToList", "(", "array", ",", "delimiter", ")", ",", "delimiter", ",", "false", ")", ";", "}" ]
convert a string array to string list, removes empty values at begin and end of the list @param array array to convert @param delimiter delimiter for the new list @return list generated from string array
[ "convert", "a", "string", "array", "to", "string", "list", "removes", "empty", "values", "at", "begin", "and", "end", "of", "the", "list" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/type/util/ListUtil.java#L890-L892
gresrun/jesque
src/main/java/net/greghaines/jesque/worker/WorkerImpl.java
WorkerImpl.statusMsg
protected String statusMsg(final String queue, final Job job) throws IOException { """ Create and serialize a WorkerStatus. @param queue the queue the Job came from @param job the Job currently being processed @return the JSON representation of a new WorkerStatus @throws IOException if there was an error serializing the WorkerStatus """ final WorkerStatus status = new WorkerStatus(); status.setRunAt(new Date()); status.setQueue(queue); status.setPayload(job); return ObjectMapperFactory.get().writeValueAsString(status); }
java
protected String statusMsg(final String queue, final Job job) throws IOException { final WorkerStatus status = new WorkerStatus(); status.setRunAt(new Date()); status.setQueue(queue); status.setPayload(job); return ObjectMapperFactory.get().writeValueAsString(status); }
[ "protected", "String", "statusMsg", "(", "final", "String", "queue", ",", "final", "Job", "job", ")", "throws", "IOException", "{", "final", "WorkerStatus", "status", "=", "new", "WorkerStatus", "(", ")", ";", "status", ".", "setRunAt", "(", "new", "Date", "(", ")", ")", ";", "status", ".", "setQueue", "(", "queue", ")", ";", "status", ".", "setPayload", "(", "job", ")", ";", "return", "ObjectMapperFactory", ".", "get", "(", ")", ".", "writeValueAsString", "(", "status", ")", ";", "}" ]
Create and serialize a WorkerStatus. @param queue the queue the Job came from @param job the Job currently being processed @return the JSON representation of a new WorkerStatus @throws IOException if there was an error serializing the WorkerStatus
[ "Create", "and", "serialize", "a", "WorkerStatus", "." ]
train
https://github.com/gresrun/jesque/blob/44749183dccc40962a94c2af547ea7d0d880b5d1/src/main/java/net/greghaines/jesque/worker/WorkerImpl.java#L740-L746
thymeleaf/thymeleaf
src/main/java/org/thymeleaf/util/TextUtils.java
TextUtils.compareTo
public static int compareTo(final boolean caseSensitive, final CharSequence text1, final CharSequence text2) { """ <p> Compares two texts lexicographically. </p> <p> The comparison is based on the Unicode value of each character in the CharSequences. The character sequence represented by the first text object is compared lexicographically to the character sequence represented by the second text. </p> <p> The result is a negative integer if the first text lexicographically precedes the second text. The result is a positive integer if the first text lexicographically follows the second text. The result is zero if the texts are equal. </p> <p> This method works in a way equivalent to that of the {@link java.lang.String#compareTo(String)} and {@link java.lang.String#compareToIgnoreCase(String)} methods. </p> @param caseSensitive whether the comparison must be done in a case-sensitive or case-insensitive way. @param text1 the first text to be compared. @param text2 the second text to be compared. @return the value {@code 0} if both texts are equal; a value less than {@code 0} if the first text is lexicographically less than the second text; and a value greater than {@code 0} if the first text is lexicographically greater than the second text. """ if (text1 == null) { throw new IllegalArgumentException("First text being compared cannot be null"); } if (text2 == null) { throw new IllegalArgumentException("Second text being compared cannot be null"); } if (text1 instanceof String && text2 instanceof String) { return (caseSensitive ? ((String)text1).compareTo((String)text2) : ((String)text1).compareToIgnoreCase((String)text2)); } return compareTo(caseSensitive, text1, 0, text1.length(), text2, 0, text2.length()); }
java
public static int compareTo(final boolean caseSensitive, final CharSequence text1, final CharSequence text2) { if (text1 == null) { throw new IllegalArgumentException("First text being compared cannot be null"); } if (text2 == null) { throw new IllegalArgumentException("Second text being compared cannot be null"); } if (text1 instanceof String && text2 instanceof String) { return (caseSensitive ? ((String)text1).compareTo((String)text2) : ((String)text1).compareToIgnoreCase((String)text2)); } return compareTo(caseSensitive, text1, 0, text1.length(), text2, 0, text2.length()); }
[ "public", "static", "int", "compareTo", "(", "final", "boolean", "caseSensitive", ",", "final", "CharSequence", "text1", ",", "final", "CharSequence", "text2", ")", "{", "if", "(", "text1", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"First text being compared cannot be null\"", ")", ";", "}", "if", "(", "text2", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Second text being compared cannot be null\"", ")", ";", "}", "if", "(", "text1", "instanceof", "String", "&&", "text2", "instanceof", "String", ")", "{", "return", "(", "caseSensitive", "?", "(", "(", "String", ")", "text1", ")", ".", "compareTo", "(", "(", "String", ")", "text2", ")", ":", "(", "(", "String", ")", "text1", ")", ".", "compareToIgnoreCase", "(", "(", "String", ")", "text2", ")", ")", ";", "}", "return", "compareTo", "(", "caseSensitive", ",", "text1", ",", "0", ",", "text1", ".", "length", "(", ")", ",", "text2", ",", "0", ",", "text2", ".", "length", "(", ")", ")", ";", "}" ]
<p> Compares two texts lexicographically. </p> <p> The comparison is based on the Unicode value of each character in the CharSequences. The character sequence represented by the first text object is compared lexicographically to the character sequence represented by the second text. </p> <p> The result is a negative integer if the first text lexicographically precedes the second text. The result is a positive integer if the first text lexicographically follows the second text. The result is zero if the texts are equal. </p> <p> This method works in a way equivalent to that of the {@link java.lang.String#compareTo(String)} and {@link java.lang.String#compareToIgnoreCase(String)} methods. </p> @param caseSensitive whether the comparison must be done in a case-sensitive or case-insensitive way. @param text1 the first text to be compared. @param text2 the second text to be compared. @return the value {@code 0} if both texts are equal; a value less than {@code 0} if the first text is lexicographically less than the second text; and a value greater than {@code 0} if the first text is lexicographically greater than the second text.
[ "<p", ">", "Compares", "two", "texts", "lexicographically", ".", "<", "/", "p", ">", "<p", ">", "The", "comparison", "is", "based", "on", "the", "Unicode", "value", "of", "each", "character", "in", "the", "CharSequences", ".", "The", "character", "sequence", "represented", "by", "the", "first", "text", "object", "is", "compared", "lexicographically", "to", "the", "character", "sequence", "represented", "by", "the", "second", "text", ".", "<", "/", "p", ">", "<p", ">", "The", "result", "is", "a", "negative", "integer", "if", "the", "first", "text", "lexicographically", "precedes", "the", "second", "text", ".", "The", "result", "is", "a", "positive", "integer", "if", "the", "first", "text", "lexicographically", "follows", "the", "second", "text", ".", "The", "result", "is", "zero", "if", "the", "texts", "are", "equal", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "works", "in", "a", "way", "equivalent", "to", "that", "of", "the", "{", "@link", "java", ".", "lang", ".", "String#compareTo", "(", "String", ")", "}", "and", "{", "@link", "java", ".", "lang", ".", "String#compareToIgnoreCase", "(", "String", ")", "}", "methods", ".", "<", "/", "p", ">" ]
train
https://github.com/thymeleaf/thymeleaf/blob/2b0e6d6d7571fbe638904b5fd222fc9e77188879/src/main/java/org/thymeleaf/util/TextUtils.java#L1455-L1470
line/armeria
core/src/main/java/com/linecorp/armeria/common/util/TextFormatter.java
TextFormatter.appendEpoch
@Deprecated public static void appendEpoch(StringBuilder buf, long timeMillis) { """ Formats the given epoch time in milliseconds to typical human-readable format "yyyy-MM-dd'T'HH_mm:ss.SSSX" and appends it to the specified {@link StringBuilder}. @deprecated Use {@link #appendEpochMillis(StringBuilder, long)}. """ buf.append(dateTimeFormatter.format(Instant.ofEpochMilli(timeMillis))) .append('(').append(timeMillis).append(')'); }
java
@Deprecated public static void appendEpoch(StringBuilder buf, long timeMillis) { buf.append(dateTimeFormatter.format(Instant.ofEpochMilli(timeMillis))) .append('(').append(timeMillis).append(')'); }
[ "@", "Deprecated", "public", "static", "void", "appendEpoch", "(", "StringBuilder", "buf", ",", "long", "timeMillis", ")", "{", "buf", ".", "append", "(", "dateTimeFormatter", ".", "format", "(", "Instant", ".", "ofEpochMilli", "(", "timeMillis", ")", ")", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "timeMillis", ")", ".", "append", "(", "'", "'", ")", ";", "}" ]
Formats the given epoch time in milliseconds to typical human-readable format "yyyy-MM-dd'T'HH_mm:ss.SSSX" and appends it to the specified {@link StringBuilder}. @deprecated Use {@link #appendEpochMillis(StringBuilder, long)}.
[ "Formats", "the", "given", "epoch", "time", "in", "milliseconds", "to", "typical", "human", "-", "readable", "format", "yyyy", "-", "MM", "-", "dd", "T", "HH_mm", ":", "ss", ".", "SSSX", "and", "appends", "it", "to", "the", "specified", "{", "@link", "StringBuilder", "}", "." ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/common/util/TextFormatter.java#L148-L152
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/collidable/CollisionConfig.java
CollisionConfig.createCollision
public static Collision createCollision(XmlReader node) { """ Create an collision from its node. @param node The collision node (must not be <code>null</code>). @return The collision instance. @throws LionEngineException If error when reading collision data. """ Check.notNull(node); final String name = node.readString(ATT_NAME); final int offsetX = node.readInteger(ATT_OFFSETX); final int offsetY = node.readInteger(ATT_OFFSETY); final int width = node.readInteger(ATT_WIDTH); final int height = node.readInteger(ATT_HEIGHT); final boolean mirror = node.readBoolean(ATT_MIRROR); return new Collision(name, offsetX, offsetY, width, height, mirror); }
java
public static Collision createCollision(XmlReader node) { Check.notNull(node); final String name = node.readString(ATT_NAME); final int offsetX = node.readInteger(ATT_OFFSETX); final int offsetY = node.readInteger(ATT_OFFSETY); final int width = node.readInteger(ATT_WIDTH); final int height = node.readInteger(ATT_HEIGHT); final boolean mirror = node.readBoolean(ATT_MIRROR); return new Collision(name, offsetX, offsetY, width, height, mirror); }
[ "public", "static", "Collision", "createCollision", "(", "XmlReader", "node", ")", "{", "Check", ".", "notNull", "(", "node", ")", ";", "final", "String", "name", "=", "node", ".", "readString", "(", "ATT_NAME", ")", ";", "final", "int", "offsetX", "=", "node", ".", "readInteger", "(", "ATT_OFFSETX", ")", ";", "final", "int", "offsetY", "=", "node", ".", "readInteger", "(", "ATT_OFFSETY", ")", ";", "final", "int", "width", "=", "node", ".", "readInteger", "(", "ATT_WIDTH", ")", ";", "final", "int", "height", "=", "node", ".", "readInteger", "(", "ATT_HEIGHT", ")", ";", "final", "boolean", "mirror", "=", "node", ".", "readBoolean", "(", "ATT_MIRROR", ")", ";", "return", "new", "Collision", "(", "name", ",", "offsetX", ",", "offsetY", ",", "width", ",", "height", ",", "mirror", ")", ";", "}" ]
Create an collision from its node. @param node The collision node (must not be <code>null</code>). @return The collision instance. @throws LionEngineException If error when reading collision data.
[ "Create", "an", "collision", "from", "its", "node", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/collidable/CollisionConfig.java#L89-L101
huahang/crypto-utils
crypto-utils/src/main/java/im/chic/utils/crypto/Rc4Utils.java
Rc4Utils.createRC4DropCipher
public static StreamCipher createRC4DropCipher(byte[] key, int drop) { """ Creates an RC4-drop cipher @param key rc4 key (40..2048 bits) @param drop number of bytes to drop @return decrypted input stream """ checkArgument(key.length >= 5 && key.length <= 256); checkArgument(drop > 0); RC4Engine rc4Engine = new RC4Engine(); rc4Engine.init(true, new KeyParameter(key)); byte[] dropBytes = new byte[drop]; Arrays.fill(dropBytes, (byte) 0); rc4Engine.processBytes(dropBytes, 0, dropBytes.length, dropBytes, 0); return rc4Engine; }
java
public static StreamCipher createRC4DropCipher(byte[] key, int drop) { checkArgument(key.length >= 5 && key.length <= 256); checkArgument(drop > 0); RC4Engine rc4Engine = new RC4Engine(); rc4Engine.init(true, new KeyParameter(key)); byte[] dropBytes = new byte[drop]; Arrays.fill(dropBytes, (byte) 0); rc4Engine.processBytes(dropBytes, 0, dropBytes.length, dropBytes, 0); return rc4Engine; }
[ "public", "static", "StreamCipher", "createRC4DropCipher", "(", "byte", "[", "]", "key", ",", "int", "drop", ")", "{", "checkArgument", "(", "key", ".", "length", ">=", "5", "&&", "key", ".", "length", "<=", "256", ")", ";", "checkArgument", "(", "drop", ">", "0", ")", ";", "RC4Engine", "rc4Engine", "=", "new", "RC4Engine", "(", ")", ";", "rc4Engine", ".", "init", "(", "true", ",", "new", "KeyParameter", "(", "key", ")", ")", ";", "byte", "[", "]", "dropBytes", "=", "new", "byte", "[", "drop", "]", ";", "Arrays", ".", "fill", "(", "dropBytes", ",", "(", "byte", ")", "0", ")", ";", "rc4Engine", ".", "processBytes", "(", "dropBytes", ",", "0", ",", "dropBytes", ".", "length", ",", "dropBytes", ",", "0", ")", ";", "return", "rc4Engine", ";", "}" ]
Creates an RC4-drop cipher @param key rc4 key (40..2048 bits) @param drop number of bytes to drop @return decrypted input stream
[ "Creates", "an", "RC4", "-", "drop", "cipher" ]
train
https://github.com/huahang/crypto-utils/blob/5f158478612698ecfd65fb0a0f9862a54ca17a8d/crypto-utils/src/main/java/im/chic/utils/crypto/Rc4Utils.java#L116-L125
spring-projects/spring-retry
src/main/java/org/springframework/retry/backoff/UniformRandomBackOffPolicy.java
UniformRandomBackOffPolicy.doBackOff
protected void doBackOff() throws BackOffInterruptedException { """ Pause for the {@link #setMinBackOffPeriod(long)}. @throws BackOffInterruptedException if interrupted during sleep. """ try { long delta = maxBackOffPeriod == minBackOffPeriod ? 0 : random.nextInt((int) (maxBackOffPeriod - minBackOffPeriod)); sleeper.sleep(minBackOffPeriod + delta); } catch (InterruptedException e) { throw new BackOffInterruptedException("Thread interrupted while sleeping", e); } }
java
protected void doBackOff() throws BackOffInterruptedException { try { long delta = maxBackOffPeriod == minBackOffPeriod ? 0 : random.nextInt((int) (maxBackOffPeriod - minBackOffPeriod)); sleeper.sleep(minBackOffPeriod + delta); } catch (InterruptedException e) { throw new BackOffInterruptedException("Thread interrupted while sleeping", e); } }
[ "protected", "void", "doBackOff", "(", ")", "throws", "BackOffInterruptedException", "{", "try", "{", "long", "delta", "=", "maxBackOffPeriod", "==", "minBackOffPeriod", "?", "0", ":", "random", ".", "nextInt", "(", "(", "int", ")", "(", "maxBackOffPeriod", "-", "minBackOffPeriod", ")", ")", ";", "sleeper", ".", "sleep", "(", "minBackOffPeriod", "+", "delta", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "throw", "new", "BackOffInterruptedException", "(", "\"Thread interrupted while sleeping\"", ",", "e", ")", ";", "}", "}" ]
Pause for the {@link #setMinBackOffPeriod(long)}. @throws BackOffInterruptedException if interrupted during sleep.
[ "Pause", "for", "the", "{" ]
train
https://github.com/spring-projects/spring-retry/blob/e2b0555f96594c2321990d0deeac45fc44d4f123/src/main/java/org/springframework/retry/backoff/UniformRandomBackOffPolicy.java#L106-L115
aerogear/aerogear-android-push
library/src/main/java/org/jboss/aerogear/android/unifiedpush/fcm/AeroGearFCMPushRegistrar.java
AeroGearFCMPushRegistrar.presistPostInformation
private void presistPostInformation(Context appContext, JsonObject postData) { """ Save the post sent to UPS. This will be used by {@link AeroGearUPSMessageService} to refresh the registration token if the registration token changes. @param appContext the application Context """ preferenceProvider.get(appContext).edit() .putString(String.format(REGISTRAR_PREFERENCE_TEMPLATE, senderId), postData.toString()) .commit(); }
java
private void presistPostInformation(Context appContext, JsonObject postData) { preferenceProvider.get(appContext).edit() .putString(String.format(REGISTRAR_PREFERENCE_TEMPLATE, senderId), postData.toString()) .commit(); }
[ "private", "void", "presistPostInformation", "(", "Context", "appContext", ",", "JsonObject", "postData", ")", "{", "preferenceProvider", ".", "get", "(", "appContext", ")", ".", "edit", "(", ")", ".", "putString", "(", "String", ".", "format", "(", "REGISTRAR_PREFERENCE_TEMPLATE", ",", "senderId", ")", ",", "postData", ".", "toString", "(", ")", ")", ".", "commit", "(", ")", ";", "}" ]
Save the post sent to UPS. This will be used by {@link AeroGearUPSMessageService} to refresh the registration token if the registration token changes. @param appContext the application Context
[ "Save", "the", "post", "sent", "to", "UPS", ".", "This", "will", "be", "used", "by", "{", "@link", "AeroGearUPSMessageService", "}", "to", "refresh", "the", "registration", "token", "if", "the", "registration", "token", "changes", "." ]
train
https://github.com/aerogear/aerogear-android-push/blob/f21f93393a9f4590e9a8d6d045ab9aabca3d211f/library/src/main/java/org/jboss/aerogear/android/unifiedpush/fcm/AeroGearFCMPushRegistrar.java#L371-L375
radkovo/jStyleParser
src/main/java/cz/vutbr/web/css/CSSFactory.java
CSSFactory.parseString
public static final StyleSheet parseString(String css, URL base, NetworkProcessor network) throws IOException, CSSException { """ Parses text into a StyleSheet @param css Text with CSS declarations @param base The URL to be used as a base for loading external resources. Base URL may be {@code null} if there are no external resources in the CSS string referenced by relative URLs. @param network Network processor for retrieving the URL resources @return Parsed StyleSheet @throws IOException When exception during read occurs @throws CSSException When exception during parse occurs """ URL baseurl = base; if (baseurl == null) baseurl = new URL("file:///base/url/is/not/specified"); //prevent errors if there are still some relative URLs used return getCSSParserFactory().parse(css, network, null, SourceType.EMBEDDED, baseurl); }
java
public static final StyleSheet parseString(String css, URL base, NetworkProcessor network) throws IOException, CSSException { URL baseurl = base; if (baseurl == null) baseurl = new URL("file:///base/url/is/not/specified"); //prevent errors if there are still some relative URLs used return getCSSParserFactory().parse(css, network, null, SourceType.EMBEDDED, baseurl); }
[ "public", "static", "final", "StyleSheet", "parseString", "(", "String", "css", ",", "URL", "base", ",", "NetworkProcessor", "network", ")", "throws", "IOException", ",", "CSSException", "{", "URL", "baseurl", "=", "base", ";", "if", "(", "baseurl", "==", "null", ")", "baseurl", "=", "new", "URL", "(", "\"file:///base/url/is/not/specified\"", ")", ";", "//prevent errors if there are still some relative URLs used", "return", "getCSSParserFactory", "(", ")", ".", "parse", "(", "css", ",", "network", ",", "null", ",", "SourceType", ".", "EMBEDDED", ",", "baseurl", ")", ";", "}" ]
Parses text into a StyleSheet @param css Text with CSS declarations @param base The URL to be used as a base for loading external resources. Base URL may be {@code null} if there are no external resources in the CSS string referenced by relative URLs. @param network Network processor for retrieving the URL resources @return Parsed StyleSheet @throws IOException When exception during read occurs @throws CSSException When exception during parse occurs
[ "Parses", "text", "into", "a", "StyleSheet" ]
train
https://github.com/radkovo/jStyleParser/blob/8ab049ac6866aa52c4d7deee25c9e294e7191957/src/main/java/cz/vutbr/web/css/CSSFactory.java#L541-L547
kejunxia/AndroidMvc
library/poke/src/main/java/com/shipdream/lib/poke/Graph.java
Graph.isFieldVisited
private boolean isFieldVisited(Object object, Field objectField, Field field) { """ Indicates whether the field of a target object is visited @param object The field holder @param objectField The field which holds the object in its parent @param field The field of the holder """ Map<String, Set<String>> bag = visitedFields.get(object); if (bag == null) { return false; } String objectFiledKey = objectField == null ? "" : objectField.toGenericString(); Set<String> fields = bag.get(objectFiledKey); return fields != null && fields.contains(field); }
java
private boolean isFieldVisited(Object object, Field objectField, Field field) { Map<String, Set<String>> bag = visitedFields.get(object); if (bag == null) { return false; } String objectFiledKey = objectField == null ? "" : objectField.toGenericString(); Set<String> fields = bag.get(objectFiledKey); return fields != null && fields.contains(field); }
[ "private", "boolean", "isFieldVisited", "(", "Object", "object", ",", "Field", "objectField", ",", "Field", "field", ")", "{", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "bag", "=", "visitedFields", ".", "get", "(", "object", ")", ";", "if", "(", "bag", "==", "null", ")", "{", "return", "false", ";", "}", "String", "objectFiledKey", "=", "objectField", "==", "null", "?", "\"\"", ":", "objectField", ".", "toGenericString", "(", ")", ";", "Set", "<", "String", ">", "fields", "=", "bag", ".", "get", "(", "objectFiledKey", ")", ";", "return", "fields", "!=", "null", "&&", "fields", ".", "contains", "(", "field", ")", ";", "}" ]
Indicates whether the field of a target object is visited @param object The field holder @param objectField The field which holds the object in its parent @param field The field of the holder
[ "Indicates", "whether", "the", "field", "of", "a", "target", "object", "is", "visited" ]
train
https://github.com/kejunxia/AndroidMvc/blob/c7893f0a13119d64297b9eb2988f7323b7da5bbc/library/poke/src/main/java/com/shipdream/lib/poke/Graph.java#L558-L567
sangupta/jerry-services
src/main/java/com/sangupta/jerry/email/domain/EmailAddress.java
EmailAddress.parseMultiple
public static Set<EmailAddress> parseMultiple(String email) { """ Parse a string that contains multiple email addresses and return a {@link Set} of {@link EmailAddress} objects that can then be set to various properties of {@link Email} object. @param email the email string @return a {@link Set} of {@link EmailAddress} objects """ if(AssertUtils.isEmpty(email)) { throw new IllegalArgumentException("Email cannot be empty/null"); } Set<EmailAddress> emails = new HashSet<EmailAddress>(); String[] tokens = email.split("[;,]"); for(String token : tokens) { token = token.trim(); // check for angular brackets if(token.contains("<") || token.contains(">")) { int start = token.indexOf('<'); int end = token.indexOf('>'); if(start >= 0 && end > start) { String name = token.substring(start + 1, end).trim(); String em = token.substring(end + 1).trim(); emails.add(new EmailAddress(name, em)); } else { emails.add(new EmailAddress(token)); } } else { emails.add(new EmailAddress(token)); } } return emails; }
java
public static Set<EmailAddress> parseMultiple(String email) { if(AssertUtils.isEmpty(email)) { throw new IllegalArgumentException("Email cannot be empty/null"); } Set<EmailAddress> emails = new HashSet<EmailAddress>(); String[] tokens = email.split("[;,]"); for(String token : tokens) { token = token.trim(); // check for angular brackets if(token.contains("<") || token.contains(">")) { int start = token.indexOf('<'); int end = token.indexOf('>'); if(start >= 0 && end > start) { String name = token.substring(start + 1, end).trim(); String em = token.substring(end + 1).trim(); emails.add(new EmailAddress(name, em)); } else { emails.add(new EmailAddress(token)); } } else { emails.add(new EmailAddress(token)); } } return emails; }
[ "public", "static", "Set", "<", "EmailAddress", ">", "parseMultiple", "(", "String", "email", ")", "{", "if", "(", "AssertUtils", ".", "isEmpty", "(", "email", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Email cannot be empty/null\"", ")", ";", "}", "Set", "<", "EmailAddress", ">", "emails", "=", "new", "HashSet", "<", "EmailAddress", ">", "(", ")", ";", "String", "[", "]", "tokens", "=", "email", ".", "split", "(", "\"[;,]\"", ")", ";", "for", "(", "String", "token", ":", "tokens", ")", "{", "token", "=", "token", ".", "trim", "(", ")", ";", "// check for angular brackets", "if", "(", "token", ".", "contains", "(", "\"<\"", ")", "||", "token", ".", "contains", "(", "\">\"", ")", ")", "{", "int", "start", "=", "token", ".", "indexOf", "(", "'", "'", ")", ";", "int", "end", "=", "token", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "start", ">=", "0", "&&", "end", ">", "start", ")", "{", "String", "name", "=", "token", ".", "substring", "(", "start", "+", "1", ",", "end", ")", ".", "trim", "(", ")", ";", "String", "em", "=", "token", ".", "substring", "(", "end", "+", "1", ")", ".", "trim", "(", ")", ";", "emails", ".", "add", "(", "new", "EmailAddress", "(", "name", ",", "em", ")", ")", ";", "}", "else", "{", "emails", ".", "add", "(", "new", "EmailAddress", "(", "token", ")", ")", ";", "}", "}", "else", "{", "emails", ".", "add", "(", "new", "EmailAddress", "(", "token", ")", ")", ";", "}", "}", "return", "emails", ";", "}" ]
Parse a string that contains multiple email addresses and return a {@link Set} of {@link EmailAddress} objects that can then be set to various properties of {@link Email} object. @param email the email string @return a {@link Set} of {@link EmailAddress} objects
[ "Parse", "a", "string", "that", "contains", "multiple", "email", "addresses", "and", "return", "a", "{", "@link", "Set", "}", "of", "{", "@link", "EmailAddress", "}", "objects", "that", "can", "then", "be", "set", "to", "various", "properties", "of", "{", "@link", "Email", "}", "object", "." ]
train
https://github.com/sangupta/jerry-services/blob/25ff6577445850916425c72068d654c08eba9bcc/src/main/java/com/sangupta/jerry/email/domain/EmailAddress.java#L153-L180
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/RTFEmbeddedObject.java
RTFEmbeddedObject.getBlockLength
private static int getBlockLength(String text, int offset) { """ Calculates the length of the next block of RTF data. @param text RTF data @param offset current offset into this data @return block length """ int startIndex = offset; boolean finished = false; char c; while (finished == false) { c = text.charAt(offset); switch (c) { case '\r': case '\n': case '}': { finished = true; break; } default: { ++offset; break; } } } int length = offset - startIndex; return (length); }
java
private static int getBlockLength(String text, int offset) { int startIndex = offset; boolean finished = false; char c; while (finished == false) { c = text.charAt(offset); switch (c) { case '\r': case '\n': case '}': { finished = true; break; } default: { ++offset; break; } } } int length = offset - startIndex; return (length); }
[ "private", "static", "int", "getBlockLength", "(", "String", "text", ",", "int", "offset", ")", "{", "int", "startIndex", "=", "offset", ";", "boolean", "finished", "=", "false", ";", "char", "c", ";", "while", "(", "finished", "==", "false", ")", "{", "c", "=", "text", ".", "charAt", "(", "offset", ")", ";", "switch", "(", "c", ")", "{", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "{", "finished", "=", "true", ";", "break", ";", "}", "default", ":", "{", "++", "offset", ";", "break", ";", "}", "}", "}", "int", "length", "=", "offset", "-", "startIndex", ";", "return", "(", "length", ")", ";", "}" ]
Calculates the length of the next block of RTF data. @param text RTF data @param offset current offset into this data @return block length
[ "Calculates", "the", "length", "of", "the", "next", "block", "of", "RTF", "data", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/RTFEmbeddedObject.java#L328-L358
tvesalainen/util
util/src/main/java/org/vesalainen/ui/AbstractView.java
AbstractView.setMargin
public void setMargin(Rectangle2D bounds, Direction... dirs) { """ Enlarges margin in screen coordinates to given directions @param bounds @param dirs """ for (Direction dir : dirs) { switch (dir) { case BOTTOM: combinedTransform.transform(userBounds.getCenterX(), userBounds.getMinY(), (x,y)-> { inverse.transform(x, y+bounds.getHeight(), this::updatePoint); }); break; case LEFT: combinedTransform.transform(userBounds.getMinX(), userBounds.getCenterY(), (x,y)-> { inverse.transform(x-bounds.getWidth(), y, this::updatePoint); }); break; case RIGHT: combinedTransform.transform(userBounds.getMaxX(), userBounds.getCenterY(), (x,y)-> { inverse.transform(x+bounds.getWidth(), y, this::updatePoint); }); break; case TOP: combinedTransform.transform(userBounds.getCenterX(), userBounds.getMaxY(), (x,y)-> { inverse.transform(x, y-bounds.getHeight(), this::updatePoint); }); break; } } }
java
public void setMargin(Rectangle2D bounds, Direction... dirs) { for (Direction dir : dirs) { switch (dir) { case BOTTOM: combinedTransform.transform(userBounds.getCenterX(), userBounds.getMinY(), (x,y)-> { inverse.transform(x, y+bounds.getHeight(), this::updatePoint); }); break; case LEFT: combinedTransform.transform(userBounds.getMinX(), userBounds.getCenterY(), (x,y)-> { inverse.transform(x-bounds.getWidth(), y, this::updatePoint); }); break; case RIGHT: combinedTransform.transform(userBounds.getMaxX(), userBounds.getCenterY(), (x,y)-> { inverse.transform(x+bounds.getWidth(), y, this::updatePoint); }); break; case TOP: combinedTransform.transform(userBounds.getCenterX(), userBounds.getMaxY(), (x,y)-> { inverse.transform(x, y-bounds.getHeight(), this::updatePoint); }); break; } } }
[ "public", "void", "setMargin", "(", "Rectangle2D", "bounds", ",", "Direction", "...", "dirs", ")", "{", "for", "(", "Direction", "dir", ":", "dirs", ")", "{", "switch", "(", "dir", ")", "{", "case", "BOTTOM", ":", "combinedTransform", ".", "transform", "(", "userBounds", ".", "getCenterX", "(", ")", ",", "userBounds", ".", "getMinY", "(", ")", ",", "(", "x", ",", "y", ")", "->", "{", "inverse", ".", "transform", "(", "x", ",", "y", "+", "bounds", ".", "getHeight", "(", ")", ",", "this", "::", "updatePoint", ")", ";", "}", ")", ";", "break", ";", "case", "LEFT", ":", "combinedTransform", ".", "transform", "(", "userBounds", ".", "getMinX", "(", ")", ",", "userBounds", ".", "getCenterY", "(", ")", ",", "(", "x", ",", "y", ")", "->", "{", "inverse", ".", "transform", "(", "x", "-", "bounds", ".", "getWidth", "(", ")", ",", "y", ",", "this", "::", "updatePoint", ")", ";", "}", ")", ";", "break", ";", "case", "RIGHT", ":", "combinedTransform", ".", "transform", "(", "userBounds", ".", "getMaxX", "(", ")", ",", "userBounds", ".", "getCenterY", "(", ")", ",", "(", "x", ",", "y", ")", "->", "{", "inverse", ".", "transform", "(", "x", "+", "bounds", ".", "getWidth", "(", ")", ",", "y", ",", "this", "::", "updatePoint", ")", ";", "}", ")", ";", "break", ";", "case", "TOP", ":", "combinedTransform", ".", "transform", "(", "userBounds", ".", "getCenterX", "(", ")", ",", "userBounds", ".", "getMaxY", "(", ")", ",", "(", "x", ",", "y", ")", "->", "{", "inverse", ".", "transform", "(", "x", ",", "y", "-", "bounds", ".", "getHeight", "(", ")", ",", "this", "::", "updatePoint", ")", ";", "}", ")", ";", "break", ";", "}", "}", "}" ]
Enlarges margin in screen coordinates to given directions @param bounds @param dirs
[ "Enlarges", "margin", "in", "screen", "coordinates", "to", "given", "directions" ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/ui/AbstractView.java#L109-L141
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/StylesheetHandler.java
StylesheetHandler.ignorableWhitespace
public void ignorableWhitespace(char ch[], int start, int length) throws org.xml.sax.SAXException { """ Receive notification of ignorable whitespace in element content. @param ch The whitespace characters. @param start The start position in the character array. @param length The number of characters to use from the character array. @see org.xml.sax.ContentHandler#ignorableWhitespace @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception. """ if (!m_shouldProcess) return; getCurrentProcessor().ignorableWhitespace(this, ch, start, length); }
java
public void ignorableWhitespace(char ch[], int start, int length) throws org.xml.sax.SAXException { if (!m_shouldProcess) return; getCurrentProcessor().ignorableWhitespace(this, ch, start, length); }
[ "public", "void", "ignorableWhitespace", "(", "char", "ch", "[", "]", ",", "int", "start", ",", "int", "length", ")", "throws", "org", ".", "xml", ".", "sax", ".", "SAXException", "{", "if", "(", "!", "m_shouldProcess", ")", "return", ";", "getCurrentProcessor", "(", ")", ".", "ignorableWhitespace", "(", "this", ",", "ch", ",", "start", ",", "length", ")", ";", "}" ]
Receive notification of ignorable whitespace in element content. @param ch The whitespace characters. @param start The start position in the character array. @param length The number of characters to use from the character array. @see org.xml.sax.ContentHandler#ignorableWhitespace @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception.
[ "Receive", "notification", "of", "ignorable", "whitespace", "in", "element", "content", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/StylesheetHandler.java#L720-L728
groves/yarrgs
src/main/java/com/bungleton/yarrgs/Yarrgs.java
Yarrgs.parseInMain
public static <T> T parseInMain (Class<T> argsType, String[] args, FieldParserFactory parsers) { """ Parses <code>args</code> into an instance of <code>argsType</code> using <code>parsers</code>. Calls <code>System.exit(1)</code> if the user supplied bad arguments after printing a reason to <code>System.err</code>. Thus, this is suitable to be called from a <code>main</code> method that's parsing arguments. """ try { return parse(argsType, args, parsers); } catch (YarrgParseException e) { System.err.println(e.getExitMessage()); System.exit(1); throw new IllegalStateException("Java continued past a System.exit call"); } }
java
public static <T> T parseInMain (Class<T> argsType, String[] args, FieldParserFactory parsers) { try { return parse(argsType, args, parsers); } catch (YarrgParseException e) { System.err.println(e.getExitMessage()); System.exit(1); throw new IllegalStateException("Java continued past a System.exit call"); } }
[ "public", "static", "<", "T", ">", "T", "parseInMain", "(", "Class", "<", "T", ">", "argsType", ",", "String", "[", "]", "args", ",", "FieldParserFactory", "parsers", ")", "{", "try", "{", "return", "parse", "(", "argsType", ",", "args", ",", "parsers", ")", ";", "}", "catch", "(", "YarrgParseException", "e", ")", "{", "System", ".", "err", ".", "println", "(", "e", ".", "getExitMessage", "(", ")", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "throw", "new", "IllegalStateException", "(", "\"Java continued past a System.exit call\"", ")", ";", "}", "}" ]
Parses <code>args</code> into an instance of <code>argsType</code> using <code>parsers</code>. Calls <code>System.exit(1)</code> if the user supplied bad arguments after printing a reason to <code>System.err</code>. Thus, this is suitable to be called from a <code>main</code> method that's parsing arguments.
[ "Parses", "<code", ">", "args<", "/", "code", ">", "into", "an", "instance", "of", "<code", ">", "argsType<", "/", "code", ">", "using", "<code", ">", "parsers<", "/", "code", ">", ".", "Calls", "<code", ">", "System", ".", "exit", "(", "1", ")", "<", "/", "code", ">", "if", "the", "user", "supplied", "bad", "arguments", "after", "printing", "a", "reason", "to", "<code", ">", "System", ".", "err<", "/", "code", ">", ".", "Thus", "this", "is", "suitable", "to", "be", "called", "from", "a", "<code", ">", "main<", "/", "code", ">", "method", "that", "s", "parsing", "arguments", "." ]
train
https://github.com/groves/yarrgs/blob/5599e82b63db56db3b0c2f7668d9a535cde456e1/src/main/java/com/bungleton/yarrgs/Yarrgs.java#L36-L45
alkacon/opencms-core
src/org/opencms/jsp/CmsJspTagProperty.java
CmsJspTagProperty.propertiesTagAction
public static Map<String, String> propertiesTagAction(String action, ServletRequest req) throws CmsException { """ Internal action method.<p> @param action the search action @param req the current request @return String the value of the property or <code>null</code> if not found (and no defaultValue provided) @throws CmsException if something goes wrong """ CmsFlexController controller = CmsFlexController.getController(req); // now read the property from the VFS Map<String, String> value = new HashMap<String, String>(); CmsPropertyAction propertyAction = new CmsPropertyAction(req, action); if (null != propertyAction.getVfsUri()) { value = CmsProperty.toMap( controller.getCmsObject().readPropertyObjects(propertyAction.getVfsUri(), propertyAction.isSearch())); } return value; }
java
public static Map<String, String> propertiesTagAction(String action, ServletRequest req) throws CmsException { CmsFlexController controller = CmsFlexController.getController(req); // now read the property from the VFS Map<String, String> value = new HashMap<String, String>(); CmsPropertyAction propertyAction = new CmsPropertyAction(req, action); if (null != propertyAction.getVfsUri()) { value = CmsProperty.toMap( controller.getCmsObject().readPropertyObjects(propertyAction.getVfsUri(), propertyAction.isSearch())); } return value; }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "propertiesTagAction", "(", "String", "action", ",", "ServletRequest", "req", ")", "throws", "CmsException", "{", "CmsFlexController", "controller", "=", "CmsFlexController", ".", "getController", "(", "req", ")", ";", "// now read the property from the VFS", "Map", "<", "String", ",", "String", ">", "value", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "CmsPropertyAction", "propertyAction", "=", "new", "CmsPropertyAction", "(", "req", ",", "action", ")", ";", "if", "(", "null", "!=", "propertyAction", ".", "getVfsUri", "(", ")", ")", "{", "value", "=", "CmsProperty", ".", "toMap", "(", "controller", ".", "getCmsObject", "(", ")", ".", "readPropertyObjects", "(", "propertyAction", ".", "getVfsUri", "(", ")", ",", "propertyAction", ".", "isSearch", "(", ")", ")", ")", ";", "}", "return", "value", ";", "}" ]
Internal action method.<p> @param action the search action @param req the current request @return String the value of the property or <code>null</code> if not found (and no defaultValue provided) @throws CmsException if something goes wrong
[ "Internal", "action", "method", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagProperty.java#L276-L288
adyliu/jafka
src/main/java/io/jafka/admin/AdminOperation.java
AdminOperation.deleteTopic
public int deleteTopic(String topic, String password) throws IOException { """ delete topic never used @param topic topic name @param password password @return number of partitions deleted @throws IOException if an I/O error """ KV<Receive, ErrorMapping> response = send(new DeleterRequest(topic, password)); return Utils.deserializeIntArray(response.k.buffer())[0]; }
java
public int deleteTopic(String topic, String password) throws IOException { KV<Receive, ErrorMapping> response = send(new DeleterRequest(topic, password)); return Utils.deserializeIntArray(response.k.buffer())[0]; }
[ "public", "int", "deleteTopic", "(", "String", "topic", ",", "String", "password", ")", "throws", "IOException", "{", "KV", "<", "Receive", ",", "ErrorMapping", ">", "response", "=", "send", "(", "new", "DeleterRequest", "(", "topic", ",", "password", ")", ")", ";", "return", "Utils", ".", "deserializeIntArray", "(", "response", ".", "k", ".", "buffer", "(", ")", ")", "[", "0", "]", ";", "}" ]
delete topic never used @param topic topic name @param password password @return number of partitions deleted @throws IOException if an I/O error
[ "delete", "topic", "never", "used" ]
train
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/admin/AdminOperation.java#L64-L67
rhuss/jolokia
agent/core/src/main/java/org/jolokia/util/EscapeUtil.java
EscapeUtil.parsePath
public static List<String> parsePath(String pPath) { """ Parse a string path and return a list of split up parts. @param pPath the path to parse. Can be null @return list of path elements or null if the initial path is null. """ // Special cases which simply implies 'no path' if (pPath == null || pPath.equals("") || pPath.equals("/")) { return null; } return replaceWildcardsWithNull(split(pPath, PATH_ESCAPE, "/")); }
java
public static List<String> parsePath(String pPath) { // Special cases which simply implies 'no path' if (pPath == null || pPath.equals("") || pPath.equals("/")) { return null; } return replaceWildcardsWithNull(split(pPath, PATH_ESCAPE, "/")); }
[ "public", "static", "List", "<", "String", ">", "parsePath", "(", "String", "pPath", ")", "{", "// Special cases which simply implies 'no path'", "if", "(", "pPath", "==", "null", "||", "pPath", ".", "equals", "(", "\"\"", ")", "||", "pPath", ".", "equals", "(", "\"/\"", ")", ")", "{", "return", "null", ";", "}", "return", "replaceWildcardsWithNull", "(", "split", "(", "pPath", ",", "PATH_ESCAPE", ",", "\"/\"", ")", ")", ";", "}" ]
Parse a string path and return a list of split up parts. @param pPath the path to parse. Can be null @return list of path elements or null if the initial path is null.
[ "Parse", "a", "string", "path", "and", "return", "a", "list", "of", "split", "up", "parts", "." ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/util/EscapeUtil.java#L88-L94
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/ringbuffer/impl/operations/ReplicationOperation.java
ReplicationOperation.getRingbufferConfig
private RingbufferConfig getRingbufferConfig(RingbufferService service, ObjectNamespace ns) { """ Returns the ringbuffer config for the provided namespace. The namespace provides information whether the requested ringbuffer is a ringbuffer that the user is directly interacting with through a ringbuffer proxy or if this is a backing ringbuffer for an event journal. If a ringbuffer configuration for an event journal is requested, this method will expect the configuration for the relevant map or cache to be available. @param service the ringbuffer service @param ns the object namespace for which we are creating a ringbuffer @return the ringbuffer configuration @throws CacheNotExistsException if a config for a cache event journal was requested and the cache configuration was not found """ final String serviceName = ns.getServiceName(); if (RingbufferService.SERVICE_NAME.equals(serviceName)) { return service.getRingbufferConfig(ns.getObjectName()); } else if (MapService.SERVICE_NAME.equals(serviceName)) { final MapService mapService = getNodeEngine().getService(MapService.SERVICE_NAME); final MapEventJournal journal = mapService.getMapServiceContext().getEventJournal(); final EventJournalConfig journalConfig = journal.getEventJournalConfig(ns); return journal.toRingbufferConfig(journalConfig, ns); } else if (CacheService.SERVICE_NAME.equals(serviceName)) { final CacheService cacheService = getNodeEngine().getService(CacheService.SERVICE_NAME); final CacheEventJournal journal = cacheService.getEventJournal(); final EventJournalConfig journalConfig = journal.getEventJournalConfig(ns); return journal.toRingbufferConfig(journalConfig, ns); } else { throw new IllegalArgumentException("Unsupported ringbuffer service name " + serviceName); } }
java
private RingbufferConfig getRingbufferConfig(RingbufferService service, ObjectNamespace ns) { final String serviceName = ns.getServiceName(); if (RingbufferService.SERVICE_NAME.equals(serviceName)) { return service.getRingbufferConfig(ns.getObjectName()); } else if (MapService.SERVICE_NAME.equals(serviceName)) { final MapService mapService = getNodeEngine().getService(MapService.SERVICE_NAME); final MapEventJournal journal = mapService.getMapServiceContext().getEventJournal(); final EventJournalConfig journalConfig = journal.getEventJournalConfig(ns); return journal.toRingbufferConfig(journalConfig, ns); } else if (CacheService.SERVICE_NAME.equals(serviceName)) { final CacheService cacheService = getNodeEngine().getService(CacheService.SERVICE_NAME); final CacheEventJournal journal = cacheService.getEventJournal(); final EventJournalConfig journalConfig = journal.getEventJournalConfig(ns); return journal.toRingbufferConfig(journalConfig, ns); } else { throw new IllegalArgumentException("Unsupported ringbuffer service name " + serviceName); } }
[ "private", "RingbufferConfig", "getRingbufferConfig", "(", "RingbufferService", "service", ",", "ObjectNamespace", "ns", ")", "{", "final", "String", "serviceName", "=", "ns", ".", "getServiceName", "(", ")", ";", "if", "(", "RingbufferService", ".", "SERVICE_NAME", ".", "equals", "(", "serviceName", ")", ")", "{", "return", "service", ".", "getRingbufferConfig", "(", "ns", ".", "getObjectName", "(", ")", ")", ";", "}", "else", "if", "(", "MapService", ".", "SERVICE_NAME", ".", "equals", "(", "serviceName", ")", ")", "{", "final", "MapService", "mapService", "=", "getNodeEngine", "(", ")", ".", "getService", "(", "MapService", ".", "SERVICE_NAME", ")", ";", "final", "MapEventJournal", "journal", "=", "mapService", ".", "getMapServiceContext", "(", ")", ".", "getEventJournal", "(", ")", ";", "final", "EventJournalConfig", "journalConfig", "=", "journal", ".", "getEventJournalConfig", "(", "ns", ")", ";", "return", "journal", ".", "toRingbufferConfig", "(", "journalConfig", ",", "ns", ")", ";", "}", "else", "if", "(", "CacheService", ".", "SERVICE_NAME", ".", "equals", "(", "serviceName", ")", ")", "{", "final", "CacheService", "cacheService", "=", "getNodeEngine", "(", ")", ".", "getService", "(", "CacheService", ".", "SERVICE_NAME", ")", ";", "final", "CacheEventJournal", "journal", "=", "cacheService", ".", "getEventJournal", "(", ")", ";", "final", "EventJournalConfig", "journalConfig", "=", "journal", ".", "getEventJournalConfig", "(", "ns", ")", ";", "return", "journal", ".", "toRingbufferConfig", "(", "journalConfig", ",", "ns", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Unsupported ringbuffer service name \"", "+", "serviceName", ")", ";", "}", "}" ]
Returns the ringbuffer config for the provided namespace. The namespace provides information whether the requested ringbuffer is a ringbuffer that the user is directly interacting with through a ringbuffer proxy or if this is a backing ringbuffer for an event journal. If a ringbuffer configuration for an event journal is requested, this method will expect the configuration for the relevant map or cache to be available. @param service the ringbuffer service @param ns the object namespace for which we are creating a ringbuffer @return the ringbuffer configuration @throws CacheNotExistsException if a config for a cache event journal was requested and the cache configuration was not found
[ "Returns", "the", "ringbuffer", "config", "for", "the", "provided", "namespace", ".", "The", "namespace", "provides", "information", "whether", "the", "requested", "ringbuffer", "is", "a", "ringbuffer", "that", "the", "user", "is", "directly", "interacting", "with", "through", "a", "ringbuffer", "proxy", "or", "if", "this", "is", "a", "backing", "ringbuffer", "for", "an", "event", "journal", ".", "If", "a", "ringbuffer", "configuration", "for", "an", "event", "journal", "is", "requested", "this", "method", "will", "expect", "the", "configuration", "for", "the", "relevant", "map", "or", "cache", "to", "be", "available", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/ringbuffer/impl/operations/ReplicationOperation.java#L82-L99
icode/ameba
src/main/java/ameba/core/Application.java
Application.readModeConfig
@SuppressWarnings("unchecked") public static void readModeConfig(Properties properties, Mode mode) { """ <p>readModeConfig.</p> @param properties a {@link java.util.Properties} object. @param mode a {@link ameba.core.Application.Mode} object. """ //读取相应模式的配置文件 Enumeration<java.net.URL> confs = IOUtils.getResources("conf/" + mode.name().toLowerCase() + ".conf"); while (confs.hasMoreElements()) { InputStream in = null; try { URLConnection connection = confs.nextElement().openConnection(); if (mode.isDev()) { connection.setUseCaches(false); } in = connection.getInputStream(); properties.load(in); } catch (IOException e) { logger.warn(Messages.get("info.module.conf.error", "conf/" + mode.name().toLowerCase() + ".conf"), e); } finally { closeQuietly(in); } } }
java
@SuppressWarnings("unchecked") public static void readModeConfig(Properties properties, Mode mode) { //读取相应模式的配置文件 Enumeration<java.net.URL> confs = IOUtils.getResources("conf/" + mode.name().toLowerCase() + ".conf"); while (confs.hasMoreElements()) { InputStream in = null; try { URLConnection connection = confs.nextElement().openConnection(); if (mode.isDev()) { connection.setUseCaches(false); } in = connection.getInputStream(); properties.load(in); } catch (IOException e) { logger.warn(Messages.get("info.module.conf.error", "conf/" + mode.name().toLowerCase() + ".conf"), e); } finally { closeQuietly(in); } } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "void", "readModeConfig", "(", "Properties", "properties", ",", "Mode", "mode", ")", "{", "//读取相应模式的配置文件", "Enumeration", "<", "java", ".", "net", ".", "URL", ">", "confs", "=", "IOUtils", ".", "getResources", "(", "\"conf/\"", "+", "mode", ".", "name", "(", ")", ".", "toLowerCase", "(", ")", "+", "\".conf\"", ")", ";", "while", "(", "confs", ".", "hasMoreElements", "(", ")", ")", "{", "InputStream", "in", "=", "null", ";", "try", "{", "URLConnection", "connection", "=", "confs", ".", "nextElement", "(", ")", ".", "openConnection", "(", ")", ";", "if", "(", "mode", ".", "isDev", "(", ")", ")", "{", "connection", ".", "setUseCaches", "(", "false", ")", ";", "}", "in", "=", "connection", ".", "getInputStream", "(", ")", ";", "properties", ".", "load", "(", "in", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "warn", "(", "Messages", ".", "get", "(", "\"info.module.conf.error\"", ",", "\"conf/\"", "+", "mode", ".", "name", "(", ")", ".", "toLowerCase", "(", ")", "+", "\".conf\"", ")", ",", "e", ")", ";", "}", "finally", "{", "closeQuietly", "(", "in", ")", ";", "}", "}", "}" ]
<p>readModeConfig.</p> @param properties a {@link java.util.Properties} object. @param mode a {@link ameba.core.Application.Mode} object.
[ "<p", ">", "readModeConfig", ".", "<", "/", "p", ">" ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/core/Application.java#L266-L286
jboss/jboss-common-beans
src/main/java/org/jboss/common/beans/property/BeanUtils.java
BeanUtils.convertValue
public static Object convertValue(String text, String typeName) throws ClassNotFoundException, IntrospectionException { """ Convert a string value into the true value for typeName using the PropertyEditor associated with typeName. @param text the string represention of the value. This is passed to the PropertyEditor.setAsText method. @param typeName the fully qualified class name of the true value type @return the PropertyEditor.getValue() result @exception ClassNotFoundException thrown if the typeName class cannot be found @exception IntrospectionException thrown if a PropertyEditor for typeName cannot be found """ // see if it is a primitive type first Class<?> typeClass = getPrimitiveTypeForName(typeName); if (typeClass == null) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); typeClass = loader.loadClass(typeName); } PropertyEditor editor = PropertyEditorFinder.getInstance().find(typeClass); if (editor == null) { throw new IntrospectionException("No property editor for type=" + typeClass); } editor.setAsText(text); return editor.getValue(); }
java
public static Object convertValue(String text, String typeName) throws ClassNotFoundException, IntrospectionException { // see if it is a primitive type first Class<?> typeClass = getPrimitiveTypeForName(typeName); if (typeClass == null) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); typeClass = loader.loadClass(typeName); } PropertyEditor editor = PropertyEditorFinder.getInstance().find(typeClass); if (editor == null) { throw new IntrospectionException("No property editor for type=" + typeClass); } editor.setAsText(text); return editor.getValue(); }
[ "public", "static", "Object", "convertValue", "(", "String", "text", ",", "String", "typeName", ")", "throws", "ClassNotFoundException", ",", "IntrospectionException", "{", "// see if it is a primitive type first", "Class", "<", "?", ">", "typeClass", "=", "getPrimitiveTypeForName", "(", "typeName", ")", ";", "if", "(", "typeClass", "==", "null", ")", "{", "ClassLoader", "loader", "=", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "typeClass", "=", "loader", ".", "loadClass", "(", "typeName", ")", ";", "}", "PropertyEditor", "editor", "=", "PropertyEditorFinder", ".", "getInstance", "(", ")", ".", "find", "(", "typeClass", ")", ";", "if", "(", "editor", "==", "null", ")", "{", "throw", "new", "IntrospectionException", "(", "\"No property editor for type=\"", "+", "typeClass", ")", ";", "}", "editor", ".", "setAsText", "(", "text", ")", ";", "return", "editor", ".", "getValue", "(", ")", ";", "}" ]
Convert a string value into the true value for typeName using the PropertyEditor associated with typeName. @param text the string represention of the value. This is passed to the PropertyEditor.setAsText method. @param typeName the fully qualified class name of the true value type @return the PropertyEditor.getValue() result @exception ClassNotFoundException thrown if the typeName class cannot be found @exception IntrospectionException thrown if a PropertyEditor for typeName cannot be found
[ "Convert", "a", "string", "value", "into", "the", "true", "value", "for", "typeName", "using", "the", "PropertyEditor", "associated", "with", "typeName", "." ]
train
https://github.com/jboss/jboss-common-beans/blob/ffb48b1719762534bf92d762eadf91d1815f6748/src/main/java/org/jboss/common/beans/property/BeanUtils.java#L213-L227
SvenEwald/xmlbeam
src/main/java/org/xmlbeam/util/intern/DOMHelper.java
DOMHelper.setDocumentElement
public static void setDocumentElement(final Document document, final Element element) { """ Replace the current root element. If element is null, the current root element will be removed. @param document @param element """ Element documentElement = document.getDocumentElement(); if (documentElement != null) { document.removeChild(documentElement); } if (element != null) { if (element.getOwnerDocument().equals(document)) { document.appendChild(element); return; } Node node = document.adoptNode(element); document.appendChild(node); } }
java
public static void setDocumentElement(final Document document, final Element element) { Element documentElement = document.getDocumentElement(); if (documentElement != null) { document.removeChild(documentElement); } if (element != null) { if (element.getOwnerDocument().equals(document)) { document.appendChild(element); return; } Node node = document.adoptNode(element); document.appendChild(node); } }
[ "public", "static", "void", "setDocumentElement", "(", "final", "Document", "document", ",", "final", "Element", "element", ")", "{", "Element", "documentElement", "=", "document", ".", "getDocumentElement", "(", ")", ";", "if", "(", "documentElement", "!=", "null", ")", "{", "document", ".", "removeChild", "(", "documentElement", ")", ";", "}", "if", "(", "element", "!=", "null", ")", "{", "if", "(", "element", ".", "getOwnerDocument", "(", ")", ".", "equals", "(", "document", ")", ")", "{", "document", ".", "appendChild", "(", "element", ")", ";", "return", ";", "}", "Node", "node", "=", "document", ".", "adoptNode", "(", "element", ")", ";", "document", ".", "appendChild", "(", "node", ")", ";", "}", "}" ]
Replace the current root element. If element is null, the current root element will be removed. @param document @param element
[ "Replace", "the", "current", "root", "element", ".", "If", "element", "is", "null", "the", "current", "root", "element", "will", "be", "removed", "." ]
train
https://github.com/SvenEwald/xmlbeam/blob/acaac1b8fa28d246f17187f5e3c6696458a0b447/src/main/java/org/xmlbeam/util/intern/DOMHelper.java#L154-L167
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java
BoxApiFile.getPromoteVersionRequest
public BoxRequestsFile.PromoteFileVersion getPromoteVersionRequest(String id, String versionId) { """ Gets a request that promotes a version to the top of the version stack for a file. This will create a copy of the old version to put on top of the version stack. The file will have the exact same contents, the same SHA1/etag, and the same name as the original. Other properties such as comments do not get updated to their former values. @param id id of the file to promote the version of @param versionId id of the file version to promote to the top @return request to promote a version of a file """ BoxRequestsFile.PromoteFileVersion request = new BoxRequestsFile.PromoteFileVersion(id, versionId, getPromoteFileVersionUrl(id), mSession); return request; }
java
public BoxRequestsFile.PromoteFileVersion getPromoteVersionRequest(String id, String versionId) { BoxRequestsFile.PromoteFileVersion request = new BoxRequestsFile.PromoteFileVersion(id, versionId, getPromoteFileVersionUrl(id), mSession); return request; }
[ "public", "BoxRequestsFile", ".", "PromoteFileVersion", "getPromoteVersionRequest", "(", "String", "id", ",", "String", "versionId", ")", "{", "BoxRequestsFile", ".", "PromoteFileVersion", "request", "=", "new", "BoxRequestsFile", ".", "PromoteFileVersion", "(", "id", ",", "versionId", ",", "getPromoteFileVersionUrl", "(", "id", ")", ",", "mSession", ")", ";", "return", "request", ";", "}" ]
Gets a request that promotes a version to the top of the version stack for a file. This will create a copy of the old version to put on top of the version stack. The file will have the exact same contents, the same SHA1/etag, and the same name as the original. Other properties such as comments do not get updated to their former values. @param id id of the file to promote the version of @param versionId id of the file version to promote to the top @return request to promote a version of a file
[ "Gets", "a", "request", "that", "promotes", "a", "version", "to", "the", "top", "of", "the", "version", "stack", "for", "a", "file", ".", "This", "will", "create", "a", "copy", "of", "the", "old", "version", "to", "put", "on", "top", "of", "the", "version", "stack", ".", "The", "file", "will", "have", "the", "exact", "same", "contents", "the", "same", "SHA1", "/", "etag", "and", "the", "same", "name", "as", "the", "original", ".", "Other", "properties", "such", "as", "comments", "do", "not", "get", "updated", "to", "their", "former", "values", "." ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java#L521-L524
dwdyer/watchmaker
examples/src/java/main/org/uncommons/watchmaker/examples/geneticprogramming/TreeEvaluator.java
TreeEvaluator.getFitness
public double getFitness(Node candidate, List<? extends Node> population) { """ If the evolved program correctly calculates the right answer for all sets of inputs then it has a fitness of zero. Otherwise, its fitness is an error value that indicates how accurate it was (the larger the combined error value, the less accurate the function is). The combined error value is calculated by summing the squares of each individual error (the difference between the expected output and the actual output). @param candidate The program tree to evaluate. @param population Ignored by this implementation. @return The fitness score for the specified candidate. """ double error = 0; for (Map.Entry<double[], Double> entry : data.entrySet()) { double actualValue = candidate.evaluate(entry.getKey()); double diff = actualValue - entry.getValue(); error += (diff * diff); } return error; }
java
public double getFitness(Node candidate, List<? extends Node> population) { double error = 0; for (Map.Entry<double[], Double> entry : data.entrySet()) { double actualValue = candidate.evaluate(entry.getKey()); double diff = actualValue - entry.getValue(); error += (diff * diff); } return error; }
[ "public", "double", "getFitness", "(", "Node", "candidate", ",", "List", "<", "?", "extends", "Node", ">", "population", ")", "{", "double", "error", "=", "0", ";", "for", "(", "Map", ".", "Entry", "<", "double", "[", "]", ",", "Double", ">", "entry", ":", "data", ".", "entrySet", "(", ")", ")", "{", "double", "actualValue", "=", "candidate", ".", "evaluate", "(", "entry", ".", "getKey", "(", ")", ")", ";", "double", "diff", "=", "actualValue", "-", "entry", ".", "getValue", "(", ")", ";", "error", "+=", "(", "diff", "*", "diff", ")", ";", "}", "return", "error", ";", "}" ]
If the evolved program correctly calculates the right answer for all sets of inputs then it has a fitness of zero. Otherwise, its fitness is an error value that indicates how accurate it was (the larger the combined error value, the less accurate the function is). The combined error value is calculated by summing the squares of each individual error (the difference between the expected output and the actual output). @param candidate The program tree to evaluate. @param population Ignored by this implementation. @return The fitness score for the specified candidate.
[ "If", "the", "evolved", "program", "correctly", "calculates", "the", "right", "answer", "for", "all", "sets", "of", "inputs", "then", "it", "has", "a", "fitness", "of", "zero", ".", "Otherwise", "its", "fitness", "is", "an", "error", "value", "that", "indicates", "how", "accurate", "it", "was", "(", "the", "larger", "the", "combined", "error", "value", "the", "less", "accurate", "the", "function", "is", ")", ".", "The", "combined", "error", "value", "is", "calculated", "by", "summing", "the", "squares", "of", "each", "individual", "error", "(", "the", "difference", "between", "the", "expected", "output", "and", "the", "actual", "output", ")", "." ]
train
https://github.com/dwdyer/watchmaker/blob/33d942350e6bf7d9a17b9262a4f898158530247e/examples/src/java/main/org/uncommons/watchmaker/examples/geneticprogramming/TreeEvaluator.java#L57-L67
Codearte/catch-exception
catch-throwable/src/main/java/com/googlecode/catchexception/throwable/CatchThrowable.java
CatchThrowable.verifyThrowable
public static void verifyThrowable(ThrowingCallable actor, Class<? extends Throwable> clazz) { """ Use it to verify that an throwable of specific type is thrown and to get access to the thrown throwable (for further verifications). The following example verifies that obj.doX() throws a MyThrowable: <code>verifyThrowable(obj, MyThrowable.class).doX(); // catch and verify assert "foobar".equals(caughtThrowable().getMessage()); // further analysis </code> If <code>doX()</code> does not throw a <code>MyThrowable</code>, then a {@link ThrowableNotThrownAssertionError} is thrown. Otherwise the thrown throwable can be retrieved via {@link #caughtThrowable()}. @param actor The instance that shall be proxied. Must not be <code>null</code>. @param clazz The type of the throwable that shall be thrown by the underlying object. Must not be <code>null</code> """ validateArguments(actor, clazz); catchThrowable(actor, clazz, true); }
java
public static void verifyThrowable(ThrowingCallable actor, Class<? extends Throwable> clazz) { validateArguments(actor, clazz); catchThrowable(actor, clazz, true); }
[ "public", "static", "void", "verifyThrowable", "(", "ThrowingCallable", "actor", ",", "Class", "<", "?", "extends", "Throwable", ">", "clazz", ")", "{", "validateArguments", "(", "actor", ",", "clazz", ")", ";", "catchThrowable", "(", "actor", ",", "clazz", ",", "true", ")", ";", "}" ]
Use it to verify that an throwable of specific type is thrown and to get access to the thrown throwable (for further verifications). The following example verifies that obj.doX() throws a MyThrowable: <code>verifyThrowable(obj, MyThrowable.class).doX(); // catch and verify assert "foobar".equals(caughtThrowable().getMessage()); // further analysis </code> If <code>doX()</code> does not throw a <code>MyThrowable</code>, then a {@link ThrowableNotThrownAssertionError} is thrown. Otherwise the thrown throwable can be retrieved via {@link #caughtThrowable()}. @param actor The instance that shall be proxied. Must not be <code>null</code>. @param clazz The type of the throwable that shall be thrown by the underlying object. Must not be <code>null</code>
[ "Use", "it", "to", "verify", "that", "an", "throwable", "of", "specific", "type", "is", "thrown", "and", "to", "get", "access", "to", "the", "thrown", "throwable", "(", "for", "further", "verifications", ")", "." ]
train
https://github.com/Codearte/catch-exception/blob/8cfb1c0a68661ef622011484ff0061b41796b165/catch-throwable/src/main/java/com/googlecode/catchexception/throwable/CatchThrowable.java#L79-L82
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric_ca/sdk/HFCAClient.java
HFCAClient.getHFCAIdentities
public Collection<HFCAIdentity> getHFCAIdentities(User registrar) throws IdentityException, InvalidArgumentException { """ gets all identities that the registrar is allowed to see @param registrar The identity of the registrar (i.e. who is performing the registration). @return the identity that was requested @throws IdentityException if adding an identity fails. @throws InvalidArgumentException Invalid (null) argument specified """ if (registrar == null) { throw new InvalidArgumentException("Registrar should be a valid member"); } logger.debug(format("identity url: %s, registrar: %s", url, registrar.getName())); try { JsonObject result = httpGet(HFCAIdentity.HFCA_IDENTITY, registrar); Collection<HFCAIdentity> allIdentities = new ArrayList<>(); JsonArray identities = result.getJsonArray("identities"); if (identities != null && !identities.isEmpty()) { for (int i = 0; i < identities.size(); i++) { JsonObject identity = identities.getJsonObject(i); HFCAIdentity idObj = new HFCAIdentity(identity); allIdentities.add(idObj); } } logger.debug(format("identity url: %s, registrar: %s done.", url, registrar)); return allIdentities; } catch (HTTPException e) { String msg = format("[HTTP Status Code: %d] - Error while getting all users from url '%s': %s", e.getStatusCode(), url, e.getMessage()); IdentityException identityException = new IdentityException(msg, e); logger.error(msg); throw identityException; } catch (Exception e) { String msg = format("Error while getting all users from url '%s': %s", url, e.getMessage()); IdentityException identityException = new IdentityException(msg, e); logger.error(msg); throw identityException; } }
java
public Collection<HFCAIdentity> getHFCAIdentities(User registrar) throws IdentityException, InvalidArgumentException { if (registrar == null) { throw new InvalidArgumentException("Registrar should be a valid member"); } logger.debug(format("identity url: %s, registrar: %s", url, registrar.getName())); try { JsonObject result = httpGet(HFCAIdentity.HFCA_IDENTITY, registrar); Collection<HFCAIdentity> allIdentities = new ArrayList<>(); JsonArray identities = result.getJsonArray("identities"); if (identities != null && !identities.isEmpty()) { for (int i = 0; i < identities.size(); i++) { JsonObject identity = identities.getJsonObject(i); HFCAIdentity idObj = new HFCAIdentity(identity); allIdentities.add(idObj); } } logger.debug(format("identity url: %s, registrar: %s done.", url, registrar)); return allIdentities; } catch (HTTPException e) { String msg = format("[HTTP Status Code: %d] - Error while getting all users from url '%s': %s", e.getStatusCode(), url, e.getMessage()); IdentityException identityException = new IdentityException(msg, e); logger.error(msg); throw identityException; } catch (Exception e) { String msg = format("Error while getting all users from url '%s': %s", url, e.getMessage()); IdentityException identityException = new IdentityException(msg, e); logger.error(msg); throw identityException; } }
[ "public", "Collection", "<", "HFCAIdentity", ">", "getHFCAIdentities", "(", "User", "registrar", ")", "throws", "IdentityException", ",", "InvalidArgumentException", "{", "if", "(", "registrar", "==", "null", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Registrar should be a valid member\"", ")", ";", "}", "logger", ".", "debug", "(", "format", "(", "\"identity url: %s, registrar: %s\"", ",", "url", ",", "registrar", ".", "getName", "(", ")", ")", ")", ";", "try", "{", "JsonObject", "result", "=", "httpGet", "(", "HFCAIdentity", ".", "HFCA_IDENTITY", ",", "registrar", ")", ";", "Collection", "<", "HFCAIdentity", ">", "allIdentities", "=", "new", "ArrayList", "<>", "(", ")", ";", "JsonArray", "identities", "=", "result", ".", "getJsonArray", "(", "\"identities\"", ")", ";", "if", "(", "identities", "!=", "null", "&&", "!", "identities", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "identities", ".", "size", "(", ")", ";", "i", "++", ")", "{", "JsonObject", "identity", "=", "identities", ".", "getJsonObject", "(", "i", ")", ";", "HFCAIdentity", "idObj", "=", "new", "HFCAIdentity", "(", "identity", ")", ";", "allIdentities", ".", "add", "(", "idObj", ")", ";", "}", "}", "logger", ".", "debug", "(", "format", "(", "\"identity url: %s, registrar: %s done.\"", ",", "url", ",", "registrar", ")", ")", ";", "return", "allIdentities", ";", "}", "catch", "(", "HTTPException", "e", ")", "{", "String", "msg", "=", "format", "(", "\"[HTTP Status Code: %d] - Error while getting all users from url '%s': %s\"", ",", "e", ".", "getStatusCode", "(", ")", ",", "url", ",", "e", ".", "getMessage", "(", ")", ")", ";", "IdentityException", "identityException", "=", "new", "IdentityException", "(", "msg", ",", "e", ")", ";", "logger", ".", "error", "(", "msg", ")", ";", "throw", "identityException", ";", "}", "catch", "(", "Exception", "e", ")", "{", "String", "msg", "=", "format", "(", "\"Error while getting all users from url '%s': %s\"", ",", "url", ",", "e", ".", "getMessage", "(", ")", ")", ";", "IdentityException", "identityException", "=", "new", "IdentityException", "(", "msg", ",", "e", ")", ";", "logger", ".", "error", "(", "msg", ")", ";", "throw", "identityException", ";", "}", "}" ]
gets all identities that the registrar is allowed to see @param registrar The identity of the registrar (i.e. who is performing the registration). @return the identity that was requested @throws IdentityException if adding an identity fails. @throws InvalidArgumentException Invalid (null) argument specified
[ "gets", "all", "identities", "that", "the", "registrar", "is", "allowed", "to", "see" ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric_ca/sdk/HFCAClient.java#L1000-L1035
overturetool/overture
ide/debug/src/main/java/org/overture/ide/debug/ui/propertypages/VdmBreakpointPropertyPage.java
VdmBreakpointPropertyPage.storeHitCount
private void storeHitCount(IVdmBreakpoint breakpoint) throws CoreException { """ Stores the value of the hit count in the breakpoint. @param breakpoint the breakpoint to update @throws CoreException if an exception occurs while setting the hit count """ int hitCount = -1; // if (fHitCountButton.getSelection()) // { try { hitCount = Integer.parseInt(fHitValueText.getText()); } catch (NumberFormatException e) { // JDIDebugUIPlugin.log(new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, MessageFormat.format("JavaBreakpointPage allowed input of invalid string for hit count value: {0}.", new String[] { fHitCountText.getText() }), e)); //$NON-NLS-1$ } // } breakpoint.setHitValue(hitCount); breakpoint.setHitCondition(fHitValueButton.getSelection() ? IVdmBreakpoint.HIT_CONDITION_GREATER_OR_EQUAL : -1); }
java
private void storeHitCount(IVdmBreakpoint breakpoint) throws CoreException { int hitCount = -1; // if (fHitCountButton.getSelection()) // { try { hitCount = Integer.parseInt(fHitValueText.getText()); } catch (NumberFormatException e) { // JDIDebugUIPlugin.log(new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, MessageFormat.format("JavaBreakpointPage allowed input of invalid string for hit count value: {0}.", new String[] { fHitCountText.getText() }), e)); //$NON-NLS-1$ } // } breakpoint.setHitValue(hitCount); breakpoint.setHitCondition(fHitValueButton.getSelection() ? IVdmBreakpoint.HIT_CONDITION_GREATER_OR_EQUAL : -1); }
[ "private", "void", "storeHitCount", "(", "IVdmBreakpoint", "breakpoint", ")", "throws", "CoreException", "{", "int", "hitCount", "=", "-", "1", ";", "// if (fHitCountButton.getSelection())", "// {", "try", "{", "hitCount", "=", "Integer", ".", "parseInt", "(", "fHitValueText", ".", "getText", "(", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "//\t\t\t\tJDIDebugUIPlugin.log(new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, MessageFormat.format(\"JavaBreakpointPage allowed input of invalid string for hit count value: {0}.\", new String[] { fHitCountText.getText() }), e)); //$NON-NLS-1$", "}", "// }", "breakpoint", ".", "setHitValue", "(", "hitCount", ")", ";", "breakpoint", ".", "setHitCondition", "(", "fHitValueButton", ".", "getSelection", "(", ")", "?", "IVdmBreakpoint", ".", "HIT_CONDITION_GREATER_OR_EQUAL", ":", "-", "1", ")", ";", "}" ]
Stores the value of the hit count in the breakpoint. @param breakpoint the breakpoint to update @throws CoreException if an exception occurs while setting the hit count
[ "Stores", "the", "value", "of", "the", "hit", "count", "in", "the", "breakpoint", "." ]
train
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/debug/src/main/java/org/overture/ide/debug/ui/propertypages/VdmBreakpointPropertyPage.java#L183-L199
mockito/mockito
src/main/java/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java
EqualsBuilder.reflectionEquals
public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients) { """ <p>This method uses reflection to determine if the two <code>Object</code>s are equal.</p> <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly.</p> <p>If the TestTransients parameter is set to <code>true</code>, transient members will be tested, otherwise they are ignored, as they are likely derived fields, and not part of the value of the <code>Object</code>.</p> <p>Static fields will not be tested. Superclass fields will be included.</p> @param lhs <code>this</code> object @param rhs the other object @param testTransients whether to include transient fields @return <code>true</code> if the two Objects have tested equals. """ return reflectionEquals(lhs, rhs, testTransients, null, null); }
java
public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients) { return reflectionEquals(lhs, rhs, testTransients, null, null); }
[ "public", "static", "boolean", "reflectionEquals", "(", "Object", "lhs", ",", "Object", "rhs", ",", "boolean", "testTransients", ")", "{", "return", "reflectionEquals", "(", "lhs", ",", "rhs", ",", "testTransients", ",", "null", ",", "null", ")", ";", "}" ]
<p>This method uses reflection to determine if the two <code>Object</code>s are equal.</p> <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly.</p> <p>If the TestTransients parameter is set to <code>true</code>, transient members will be tested, otherwise they are ignored, as they are likely derived fields, and not part of the value of the <code>Object</code>.</p> <p>Static fields will not be tested. Superclass fields will be included.</p> @param lhs <code>this</code> object @param rhs the other object @param testTransients whether to include transient fields @return <code>true</code> if the two Objects have tested equals.
[ "<p", ">", "This", "method", "uses", "reflection", "to", "determine", "if", "the", "two", "<code", ">", "Object<", "/", "code", ">", "s", "are", "equal", ".", "<", "/", "p", ">" ]
train
https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java#L162-L164
Azure/azure-sdk-for-java
labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/LabAccountsInner.java
LabAccountsInner.listByResourceGroupAsync
public Observable<Page<LabAccountInner>> listByResourceGroupAsync(final String resourceGroupName, final String expand, final String filter, final Integer top, final String orderby) { """ List lab accounts in a resource group. @param resourceGroupName The name of the resource group. @param expand Specify the $expand query. Example: 'properties($expand=sizeConfiguration)' @param filter The filter to apply to the operation. @param top The maximum number of resources to return from the operation. @param orderby The ordering expression for the results, using OData notation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;LabAccountInner&gt; object """ return listByResourceGroupWithServiceResponseAsync(resourceGroupName, expand, filter, top, orderby) .map(new Func1<ServiceResponse<Page<LabAccountInner>>, Page<LabAccountInner>>() { @Override public Page<LabAccountInner> call(ServiceResponse<Page<LabAccountInner>> response) { return response.body(); } }); }
java
public Observable<Page<LabAccountInner>> listByResourceGroupAsync(final String resourceGroupName, final String expand, final String filter, final Integer top, final String orderby) { return listByResourceGroupWithServiceResponseAsync(resourceGroupName, expand, filter, top, orderby) .map(new Func1<ServiceResponse<Page<LabAccountInner>>, Page<LabAccountInner>>() { @Override public Page<LabAccountInner> call(ServiceResponse<Page<LabAccountInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "LabAccountInner", ">", ">", "listByResourceGroupAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "expand", ",", "final", "String", "filter", ",", "final", "Integer", "top", ",", "final", "String", "orderby", ")", "{", "return", "listByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "expand", ",", "filter", ",", "top", ",", "orderby", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "LabAccountInner", ">", ">", ",", "Page", "<", "LabAccountInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "LabAccountInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "LabAccountInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
List lab accounts in a resource group. @param resourceGroupName The name of the resource group. @param expand Specify the $expand query. Example: 'properties($expand=sizeConfiguration)' @param filter The filter to apply to the operation. @param top The maximum number of resources to return from the operation. @param orderby The ordering expression for the results, using OData notation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;LabAccountInner&gt; object
[ "List", "lab", "accounts", "in", "a", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/LabAccountsInner.java#L518-L526
dlemmermann/CalendarFX
CalendarFXView/src/main/java/com/calendarfx/view/MonthSheetView.java
MonthSheetView.setHeaderCellFactory
public final void setHeaderCellFactory(Callback<HeaderParameter, Node> factory) { """ Sets the value of {@link #headerCellFactoryProperty()}. @param factory the "header" cell factory """ requireNonNull(factory); headerCellFactoryProperty().set(factory); }
java
public final void setHeaderCellFactory(Callback<HeaderParameter, Node> factory) { requireNonNull(factory); headerCellFactoryProperty().set(factory); }
[ "public", "final", "void", "setHeaderCellFactory", "(", "Callback", "<", "HeaderParameter", ",", "Node", ">", "factory", ")", "{", "requireNonNull", "(", "factory", ")", ";", "headerCellFactoryProperty", "(", ")", ".", "set", "(", "factory", ")", ";", "}" ]
Sets the value of {@link #headerCellFactoryProperty()}. @param factory the "header" cell factory
[ "Sets", "the", "value", "of", "{", "@link", "#headerCellFactoryProperty", "()", "}", "." ]
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXView/src/main/java/com/calendarfx/view/MonthSheetView.java#L235-L238
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPPrefixesInner.java
PublicIPPrefixesInner.createOrUpdate
public PublicIPPrefixInner createOrUpdate(String resourceGroupName, String publicIpPrefixName, PublicIPPrefixInner parameters) { """ Creates or updates a static or dynamic public IP prefix. @param resourceGroupName The name of the resource group. @param publicIpPrefixName The name of the public IP prefix. @param parameters Parameters supplied to the create or update public IP prefix operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PublicIPPrefixInner object if successful. """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, publicIpPrefixName, parameters).toBlocking().last().body(); }
java
public PublicIPPrefixInner createOrUpdate(String resourceGroupName, String publicIpPrefixName, PublicIPPrefixInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, publicIpPrefixName, parameters).toBlocking().last().body(); }
[ "public", "PublicIPPrefixInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "publicIpPrefixName", ",", "PublicIPPrefixInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "publicIpPrefixName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates a static or dynamic public IP prefix. @param resourceGroupName The name of the resource group. @param publicIpPrefixName The name of the public IP prefix. @param parameters Parameters supplied to the create or update public IP prefix operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PublicIPPrefixInner object if successful.
[ "Creates", "or", "updates", "a", "static", "or", "dynamic", "public", "IP", "prefix", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPPrefixesInner.java#L444-L446
netty/netty
common/src/main/java/io/netty/util/internal/ThreadLocalRandom.java
ThreadLocalRandom.nextDouble
public double nextDouble(double least, double bound) { """ Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive). @param least the least value returned @param bound the upper bound (exclusive) @return the next value @throws IllegalArgumentException if least greater than or equal to bound """ if (least >= bound) { throw new IllegalArgumentException(); } return nextDouble() * (bound - least) + least; }
java
public double nextDouble(double least, double bound) { if (least >= bound) { throw new IllegalArgumentException(); } return nextDouble() * (bound - least) + least; }
[ "public", "double", "nextDouble", "(", "double", "least", ",", "double", "bound", ")", "{", "if", "(", "least", ">=", "bound", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "return", "nextDouble", "(", ")", "*", "(", "bound", "-", "least", ")", "+", "least", ";", "}" ]
Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive). @param least the least value returned @param bound the upper bound (exclusive) @return the next value @throws IllegalArgumentException if least greater than or equal to bound
[ "Returns", "a", "pseudorandom", "uniformly", "distributed", "value", "between", "the", "given", "least", "value", "(", "inclusive", ")", "and", "bound", "(", "exclusive", ")", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/internal/ThreadLocalRandom.java#L378-L383
hsiafan/requests
src/main/java/net/dongliu/requests/RequestBuilder.java
RequestBuilder.forms
@Deprecated @SafeVarargs public final RequestBuilder forms(Map.Entry<String, ?>... formBody) { """ Set www-form-encoded body. Only for Post @deprecated use {@link #body(Map.Entry[])} instead """ return forms(Lists.of(formBody)); }
java
@Deprecated @SafeVarargs public final RequestBuilder forms(Map.Entry<String, ?>... formBody) { return forms(Lists.of(formBody)); }
[ "@", "Deprecated", "@", "SafeVarargs", "public", "final", "RequestBuilder", "forms", "(", "Map", ".", "Entry", "<", "String", ",", "?", ">", "...", "formBody", ")", "{", "return", "forms", "(", "Lists", ".", "of", "(", "formBody", ")", ")", ";", "}" ]
Set www-form-encoded body. Only for Post @deprecated use {@link #body(Map.Entry[])} instead
[ "Set", "www", "-", "form", "-", "encoded", "body", ".", "Only", "for", "Post" ]
train
https://github.com/hsiafan/requests/blob/a6cc6f8293e808cc937d3789aec2616a8383dee0/src/main/java/net/dongliu/requests/RequestBuilder.java#L218-L222
actorapp/actor-platform
actor-server/actor-frontend/src/main/java/im/actor/crypto/primitives/kuznechik/KuznechikCipher.java
KuznechikCipher.decryptBlock
@Override public void decryptBlock(byte[] data, int offset, byte[] dest, int destOffset) { """ Decrypting block with Kuznechik encryption @param data source data for decryption @param offset offset in data @param dest destination array @param destOffset destination offset """ // w128_t x; // x.q[0] = ((uint64_t *) blk)[0] ^ key->k[9].q[0]; // x.q[1] = ((uint64_t *) blk)[1] ^ key->k[9].q[1]; Kuz128 x = new Kuz128(); x.setQ(0, ByteStrings.bytesToLong(data, offset) ^ key.getK()[9].getQ(0)); x.setQ(1, ByteStrings.bytesToLong(data, offset + 8) ^ key.getK()[9].getQ(1)); for (int i = 8; i >= 0; i--) { // kuz_l_inv(&x); KuznechikMath.kuz_l_inv(x); for (int j = 0; j < 16; j++) { // x.b[j] = kuz_pi_inv[x.b[j]]; x.getB()[j] = KuznechikTables.kuz_pi_inv[x.getB()[j] & 0xFF]; } // x.q[0] ^= key->k[i].q[0]; x.setQ(0, x.getQ(0) ^ key.getK()[i].getQ(0)); // x.q[1] ^= key->k[i].q[1]; x.setQ(1, x.getQ(1) ^ key.getK()[i].getQ(1)); } // ((uint64_t *) blk)[0] = x.q[0]; // ((uint64_t *) blk)[1] = x.q[1]; ByteStrings.write(dest, destOffset, ByteStrings.longToBytes(x.getQ(0)), 0, 8); ByteStrings.write(dest, destOffset + 8, ByteStrings.longToBytes(x.getQ(1)), 0, 8); }
java
@Override public void decryptBlock(byte[] data, int offset, byte[] dest, int destOffset) { // w128_t x; // x.q[0] = ((uint64_t *) blk)[0] ^ key->k[9].q[0]; // x.q[1] = ((uint64_t *) blk)[1] ^ key->k[9].q[1]; Kuz128 x = new Kuz128(); x.setQ(0, ByteStrings.bytesToLong(data, offset) ^ key.getK()[9].getQ(0)); x.setQ(1, ByteStrings.bytesToLong(data, offset + 8) ^ key.getK()[9].getQ(1)); for (int i = 8; i >= 0; i--) { // kuz_l_inv(&x); KuznechikMath.kuz_l_inv(x); for (int j = 0; j < 16; j++) { // x.b[j] = kuz_pi_inv[x.b[j]]; x.getB()[j] = KuznechikTables.kuz_pi_inv[x.getB()[j] & 0xFF]; } // x.q[0] ^= key->k[i].q[0]; x.setQ(0, x.getQ(0) ^ key.getK()[i].getQ(0)); // x.q[1] ^= key->k[i].q[1]; x.setQ(1, x.getQ(1) ^ key.getK()[i].getQ(1)); } // ((uint64_t *) blk)[0] = x.q[0]; // ((uint64_t *) blk)[1] = x.q[1]; ByteStrings.write(dest, destOffset, ByteStrings.longToBytes(x.getQ(0)), 0, 8); ByteStrings.write(dest, destOffset + 8, ByteStrings.longToBytes(x.getQ(1)), 0, 8); }
[ "@", "Override", "public", "void", "decryptBlock", "(", "byte", "[", "]", "data", ",", "int", "offset", ",", "byte", "[", "]", "dest", ",", "int", "destOffset", ")", "{", "// w128_t x;", "// x.q[0] = ((uint64_t *) blk)[0] ^ key->k[9].q[0];", "// x.q[1] = ((uint64_t *) blk)[1] ^ key->k[9].q[1];", "Kuz128", "x", "=", "new", "Kuz128", "(", ")", ";", "x", ".", "setQ", "(", "0", ",", "ByteStrings", ".", "bytesToLong", "(", "data", ",", "offset", ")", "^", "key", ".", "getK", "(", ")", "[", "9", "]", ".", "getQ", "(", "0", ")", ")", ";", "x", ".", "setQ", "(", "1", ",", "ByteStrings", ".", "bytesToLong", "(", "data", ",", "offset", "+", "8", ")", "^", "key", ".", "getK", "(", ")", "[", "9", "]", ".", "getQ", "(", "1", ")", ")", ";", "for", "(", "int", "i", "=", "8", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "// kuz_l_inv(&x);", "KuznechikMath", ".", "kuz_l_inv", "(", "x", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "16", ";", "j", "++", ")", "{", "// x.b[j] = kuz_pi_inv[x.b[j]];", "x", ".", "getB", "(", ")", "[", "j", "]", "=", "KuznechikTables", ".", "kuz_pi_inv", "[", "x", ".", "getB", "(", ")", "[", "j", "]", "&", "0xFF", "]", ";", "}", "// x.q[0] ^= key->k[i].q[0];", "x", ".", "setQ", "(", "0", ",", "x", ".", "getQ", "(", "0", ")", "^", "key", ".", "getK", "(", ")", "[", "i", "]", ".", "getQ", "(", "0", ")", ")", ";", "// x.q[1] ^= key->k[i].q[1];", "x", ".", "setQ", "(", "1", ",", "x", ".", "getQ", "(", "1", ")", "^", "key", ".", "getK", "(", ")", "[", "i", "]", ".", "getQ", "(", "1", ")", ")", ";", "}", "// ((uint64_t *) blk)[0] = x.q[0];", "// ((uint64_t *) blk)[1] = x.q[1];", "ByteStrings", ".", "write", "(", "dest", ",", "destOffset", ",", "ByteStrings", ".", "longToBytes", "(", "x", ".", "getQ", "(", "0", ")", ")", ",", "0", ",", "8", ")", ";", "ByteStrings", ".", "write", "(", "dest", ",", "destOffset", "+", "8", ",", "ByteStrings", ".", "longToBytes", "(", "x", ".", "getQ", "(", "1", ")", ")", ",", "0", ",", "8", ")", ";", "}" ]
Decrypting block with Kuznechik encryption @param data source data for decryption @param offset offset in data @param dest destination array @param destOffset destination offset
[ "Decrypting", "block", "with", "Kuznechik", "encryption" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-server/actor-frontend/src/main/java/im/actor/crypto/primitives/kuznechik/KuznechikCipher.java#L67-L95
sebastiangraf/jSCSI
bundles/initiator/src/main/java/org/jscsi/initiator/Configuration.java
Configuration.getSessionSetting
public final String getSessionSetting (final String targetName, final OperationalTextKey textKey) throws OperationalTextKeyException { """ Returns the value of a single parameter. It can only return session and global parameters. @param targetName Name of the iSCSI Target to connect. @param textKey The name of the parameter. @return The value of the given parameter. @throws OperationalTextKeyException If the given parameter cannot be found. """ return getSetting(targetName, -1, textKey); }
java
public final String getSessionSetting (final String targetName, final OperationalTextKey textKey) throws OperationalTextKeyException { return getSetting(targetName, -1, textKey); }
[ "public", "final", "String", "getSessionSetting", "(", "final", "String", "targetName", ",", "final", "OperationalTextKey", "textKey", ")", "throws", "OperationalTextKeyException", "{", "return", "getSetting", "(", "targetName", ",", "-", "1", ",", "textKey", ")", ";", "}" ]
Returns the value of a single parameter. It can only return session and global parameters. @param targetName Name of the iSCSI Target to connect. @param textKey The name of the parameter. @return The value of the given parameter. @throws OperationalTextKeyException If the given parameter cannot be found.
[ "Returns", "the", "value", "of", "a", "single", "parameter", ".", "It", "can", "only", "return", "session", "and", "global", "parameters", "." ]
train
https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/initiator/src/main/java/org/jscsi/initiator/Configuration.java#L283-L286
EdwardRaff/JSAT
JSAT/src/jsat/distributions/LogUniform.java
LogUniform.setMinMax
public void setMinMax(double min, double max) { """ Sets the minimum and maximum values for this distribution @param min the minimum value, must be positive @param max the maximum value, must be larger than {@code min} """ if(min <= 0 || Double.isNaN(min) || Double.isInfinite(min)) throw new IllegalArgumentException("min value must be positive, not " + min); else if(min >= max || Double.isNaN(max) || Double.isInfinite(max)) throw new IllegalArgumentException("max (" + max + ") must be larger than min (" + min+")" ); this.max = max; this.min = min; this.logMax = Math.log(max); this.logMin = Math.log(min); this.logDiff = logMax-logMin; this.diff = max-min; }
java
public void setMinMax(double min, double max) { if(min <= 0 || Double.isNaN(min) || Double.isInfinite(min)) throw new IllegalArgumentException("min value must be positive, not " + min); else if(min >= max || Double.isNaN(max) || Double.isInfinite(max)) throw new IllegalArgumentException("max (" + max + ") must be larger than min (" + min+")" ); this.max = max; this.min = min; this.logMax = Math.log(max); this.logMin = Math.log(min); this.logDiff = logMax-logMin; this.diff = max-min; }
[ "public", "void", "setMinMax", "(", "double", "min", ",", "double", "max", ")", "{", "if", "(", "min", "<=", "0", "||", "Double", ".", "isNaN", "(", "min", ")", "||", "Double", ".", "isInfinite", "(", "min", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"min value must be positive, not \"", "+", "min", ")", ";", "else", "if", "(", "min", ">=", "max", "||", "Double", ".", "isNaN", "(", "max", ")", "||", "Double", ".", "isInfinite", "(", "max", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"max (\"", "+", "max", "+", "\") must be larger than min (\"", "+", "min", "+", "\")\"", ")", ";", "this", ".", "max", "=", "max", ";", "this", ".", "min", "=", "min", ";", "this", ".", "logMax", "=", "Math", ".", "log", "(", "max", ")", ";", "this", ".", "logMin", "=", "Math", ".", "log", "(", "min", ")", ";", "this", ".", "logDiff", "=", "logMax", "-", "logMin", ";", "this", ".", "diff", "=", "max", "-", "min", ";", "}" ]
Sets the minimum and maximum values for this distribution @param min the minimum value, must be positive @param max the maximum value, must be larger than {@code min}
[ "Sets", "the", "minimum", "and", "maximum", "values", "for", "this", "distribution" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/distributions/LogUniform.java#L59-L71
Azure/azure-sdk-for-java
redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java
RedisInner.listKeys
public RedisAccessKeysInner listKeys(String resourceGroupName, String name) { """ Retrieve a Redis cache's access keys. This operation requires write permission to the cache resource. @param resourceGroupName The name of the resource group. @param name The name of the Redis cache. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the RedisAccessKeysInner object if successful. """ return listKeysWithServiceResponseAsync(resourceGroupName, name).toBlocking().single().body(); }
java
public RedisAccessKeysInner listKeys(String resourceGroupName, String name) { return listKeysWithServiceResponseAsync(resourceGroupName, name).toBlocking().single().body(); }
[ "public", "RedisAccessKeysInner", "listKeys", "(", "String", "resourceGroupName", ",", "String", "name", ")", "{", "return", "listKeysWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Retrieve a Redis cache's access keys. This operation requires write permission to the cache resource. @param resourceGroupName The name of the resource group. @param name The name of the Redis cache. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the RedisAccessKeysInner object if successful.
[ "Retrieve", "a", "Redis", "cache", "s", "access", "keys", ".", "This", "operation", "requires", "write", "permission", "to", "the", "cache", "resource", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java#L1062-L1064
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/util/DirectedGraph.java
DirectedGraph.addEdge
public void addEdge(VertexT from, VertexT to) { """ this assumes that {@code from} and {@code to} were part of the vertices passed to the constructor """ Preconditions.checkArgument(vertices.containsKey(from) && vertices.containsKey(to)); adjacencyList.put(from, to); vertices.put(to, vertices.get(to) + 1); }
java
public void addEdge(VertexT from, VertexT to) { Preconditions.checkArgument(vertices.containsKey(from) && vertices.containsKey(to)); adjacencyList.put(from, to); vertices.put(to, vertices.get(to) + 1); }
[ "public", "void", "addEdge", "(", "VertexT", "from", ",", "VertexT", "to", ")", "{", "Preconditions", ".", "checkArgument", "(", "vertices", ".", "containsKey", "(", "from", ")", "&&", "vertices", ".", "containsKey", "(", "to", ")", ")", ";", "adjacencyList", ".", "put", "(", "from", ",", "to", ")", ";", "vertices", ".", "put", "(", "to", ",", "vertices", ".", "get", "(", "to", ")", "+", "1", ")", ";", "}" ]
this assumes that {@code from} and {@code to} were part of the vertices passed to the constructor
[ "this", "assumes", "that", "{" ]
train
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/DirectedGraph.java#L61-L65
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java
ThreadSafety.checkInvocation
public Violation checkInvocation(Type methodType, Symbol symbol) { """ Checks the instantiation of any thread-safe type parameters in the current invocation. """ if (methodType == null) { return Violation.absent(); } List<TypeVariableSymbol> typeParameters = symbol.getTypeParameters(); if (typeParameters.stream().noneMatch(this::hasThreadSafeTypeParameterAnnotation)) { // fast path return Violation.absent(); } ImmutableMap<TypeVariableSymbol, Type> instantiation = getInstantiation(state.getTypes(), methodType); // javac does not instantiate all types, so filter out ones that were not instantiated. Ideally // we wouldn't have to do this. typeParameters = typeParameters.stream().filter(instantiation::containsKey).collect(toImmutableList()); return checkInstantiation( typeParameters, typeParameters.stream().map(instantiation::get).collect(toImmutableList())); }
java
public Violation checkInvocation(Type methodType, Symbol symbol) { if (methodType == null) { return Violation.absent(); } List<TypeVariableSymbol> typeParameters = symbol.getTypeParameters(); if (typeParameters.stream().noneMatch(this::hasThreadSafeTypeParameterAnnotation)) { // fast path return Violation.absent(); } ImmutableMap<TypeVariableSymbol, Type> instantiation = getInstantiation(state.getTypes(), methodType); // javac does not instantiate all types, so filter out ones that were not instantiated. Ideally // we wouldn't have to do this. typeParameters = typeParameters.stream().filter(instantiation::containsKey).collect(toImmutableList()); return checkInstantiation( typeParameters, typeParameters.stream().map(instantiation::get).collect(toImmutableList())); }
[ "public", "Violation", "checkInvocation", "(", "Type", "methodType", ",", "Symbol", "symbol", ")", "{", "if", "(", "methodType", "==", "null", ")", "{", "return", "Violation", ".", "absent", "(", ")", ";", "}", "List", "<", "TypeVariableSymbol", ">", "typeParameters", "=", "symbol", ".", "getTypeParameters", "(", ")", ";", "if", "(", "typeParameters", ".", "stream", "(", ")", ".", "noneMatch", "(", "this", "::", "hasThreadSafeTypeParameterAnnotation", ")", ")", "{", "// fast path", "return", "Violation", ".", "absent", "(", ")", ";", "}", "ImmutableMap", "<", "TypeVariableSymbol", ",", "Type", ">", "instantiation", "=", "getInstantiation", "(", "state", ".", "getTypes", "(", ")", ",", "methodType", ")", ";", "// javac does not instantiate all types, so filter out ones that were not instantiated. Ideally", "// we wouldn't have to do this.", "typeParameters", "=", "typeParameters", ".", "stream", "(", ")", ".", "filter", "(", "instantiation", "::", "containsKey", ")", ".", "collect", "(", "toImmutableList", "(", ")", ")", ";", "return", "checkInstantiation", "(", "typeParameters", ",", "typeParameters", ".", "stream", "(", ")", ".", "map", "(", "instantiation", "::", "get", ")", ".", "collect", "(", "toImmutableList", "(", ")", ")", ")", ";", "}" ]
Checks the instantiation of any thread-safe type parameters in the current invocation.
[ "Checks", "the", "instantiation", "of", "any", "thread", "-", "safe", "type", "parameters", "in", "the", "current", "invocation", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java#L873-L892
tango-controls/JTango
server/src/main/java/org/tango/server/ServerManager.java
ServerManager.addClass
public void addClass(final String tangoClass, final Class<?> deviceClass) { """ Add a class to the server. @param tangoClass The class name as defined in the tango database @param deviceClass The class that define a device with {@link Device} """ lastClass = tangoClass; tangoClasses.put(tangoClass, deviceClass); }
java
public void addClass(final String tangoClass, final Class<?> deviceClass) { lastClass = tangoClass; tangoClasses.put(tangoClass, deviceClass); }
[ "public", "void", "addClass", "(", "final", "String", "tangoClass", ",", "final", "Class", "<", "?", ">", "deviceClass", ")", "{", "lastClass", "=", "tangoClass", ";", "tangoClasses", ".", "put", "(", "tangoClass", ",", "deviceClass", ")", ";", "}" ]
Add a class to the server. @param tangoClass The class name as defined in the tango database @param deviceClass The class that define a device with {@link Device}
[ "Add", "a", "class", "to", "the", "server", "." ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/ServerManager.java#L135-L138
jmxtrans/jmxtrans
jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/support/opentsdb/OpenTSDBMessageFormatter.java
OpenTSDBMessageFormatter.formatResultString
private void formatResultString(StringBuilder resultString, String metricName, long epoch, Object value) { """ Format the result string given the class name and attribute name of the source value, the timestamp, and the value. @param epoch - the timestamp of the metric. @param value - value of the attribute to use as the metric value. @return String - the formatted result string. """ resultString.append(sanitizeString(metricName)); resultString.append(" "); resultString.append(Long.toString(epoch)); resultString.append(" "); resultString.append(sanitizeString(value.toString())); }
java
private void formatResultString(StringBuilder resultString, String metricName, long epoch, Object value) { resultString.append(sanitizeString(metricName)); resultString.append(" "); resultString.append(Long.toString(epoch)); resultString.append(" "); resultString.append(sanitizeString(value.toString())); }
[ "private", "void", "formatResultString", "(", "StringBuilder", "resultString", ",", "String", "metricName", ",", "long", "epoch", ",", "Object", "value", ")", "{", "resultString", ".", "append", "(", "sanitizeString", "(", "metricName", ")", ")", ";", "resultString", ".", "append", "(", "\" \"", ")", ";", "resultString", ".", "append", "(", "Long", ".", "toString", "(", "epoch", ")", ")", ";", "resultString", ".", "append", "(", "\" \"", ")", ";", "resultString", ".", "append", "(", "sanitizeString", "(", "value", ".", "toString", "(", ")", ")", ")", ";", "}" ]
Format the result string given the class name and attribute name of the source value, the timestamp, and the value. @param epoch - the timestamp of the metric. @param value - value of the attribute to use as the metric value. @return String - the formatted result string.
[ "Format", "the", "result", "string", "given", "the", "class", "name", "and", "attribute", "name", "of", "the", "source", "value", "the", "timestamp", "and", "the", "value", "." ]
train
https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/support/opentsdb/OpenTSDBMessageFormatter.java#L134-L140
Wolfgang-Schuetzelhofer/jcypher
src/main/java/iot/jcypher/domainquery/api/TraversalStep.java
TraversalStep.DISTANCE
public TraversalStep DISTANCE(int minDistance, int maxDistance) { """ Define the distance in terms of how many hops to take when navigating the domain graph along a given attribute. The default is one hop (minDistance = maxDistance = 1), maxDistance -1 means hop as far as you will get (either to a leaf in the graph or to a detected loop). @param minDistance the minimum number of hops to navigate @param maxDistance the maximum number of hops to navigate @return """ TraversalExpression te = (TraversalExpression)this.astObject; Step step = te.getSteps().get(te.getSteps().size() - 1); step.setMinDistance(minDistance); step.setMaxDistance(maxDistance); QueryRecorder.recordInvocation(this, "DISTANCE", this, QueryRecorder.literal(minDistance), QueryRecorder.literal(maxDistance)); return this; }
java
public TraversalStep DISTANCE(int minDistance, int maxDistance) { TraversalExpression te = (TraversalExpression)this.astObject; Step step = te.getSteps().get(te.getSteps().size() - 1); step.setMinDistance(minDistance); step.setMaxDistance(maxDistance); QueryRecorder.recordInvocation(this, "DISTANCE", this, QueryRecorder.literal(minDistance), QueryRecorder.literal(maxDistance)); return this; }
[ "public", "TraversalStep", "DISTANCE", "(", "int", "minDistance", ",", "int", "maxDistance", ")", "{", "TraversalExpression", "te", "=", "(", "TraversalExpression", ")", "this", ".", "astObject", ";", "Step", "step", "=", "te", ".", "getSteps", "(", ")", ".", "get", "(", "te", ".", "getSteps", "(", ")", ".", "size", "(", ")", "-", "1", ")", ";", "step", ".", "setMinDistance", "(", "minDistance", ")", ";", "step", ".", "setMaxDistance", "(", "maxDistance", ")", ";", "QueryRecorder", ".", "recordInvocation", "(", "this", ",", "\"DISTANCE\"", ",", "this", ",", "QueryRecorder", ".", "literal", "(", "minDistance", ")", ",", "QueryRecorder", ".", "literal", "(", "maxDistance", ")", ")", ";", "return", "this", ";", "}" ]
Define the distance in terms of how many hops to take when navigating the domain graph along a given attribute. The default is one hop (minDistance = maxDistance = 1), maxDistance -1 means hop as far as you will get (either to a leaf in the graph or to a detected loop). @param minDistance the minimum number of hops to navigate @param maxDistance the maximum number of hops to navigate @return
[ "Define", "the", "distance", "in", "terms", "of", "how", "many", "hops", "to", "take", "when", "navigating", "the", "domain", "graph", "along", "a", "given", "attribute", ".", "The", "default", "is", "one", "hop", "(", "minDistance", "=", "maxDistance", "=", "1", ")", "maxDistance", "-", "1", "means", "hop", "as", "far", "as", "you", "will", "get", "(", "either", "to", "a", "leaf", "in", "the", "graph", "or", "to", "a", "detected", "loop", ")", "." ]
train
https://github.com/Wolfgang-Schuetzelhofer/jcypher/blob/0f36914b4d6993a004cc235bb18dd3e02a59d253/src/main/java/iot/jcypher/domainquery/api/TraversalStep.java#L65-L73
Azure/azure-sdk-for-java
labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/EnvironmentsInner.java
EnvironmentsInner.claimAsync
public Observable<Void> claimAsync(String resourceGroupName, String labAccountName, String labName, String environmentSettingName, String environmentName) { """ Claims the environment and assigns it to the user. @param resourceGroupName The name of the resource group. @param labAccountName The name of the lab Account. @param labName The name of the lab. @param environmentSettingName The name of the environment Setting. @param environmentName The name of the environment. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful. """ return claimWithServiceResponseAsync(resourceGroupName, labAccountName, labName, environmentSettingName, environmentName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> claimAsync(String resourceGroupName, String labAccountName, String labName, String environmentSettingName, String environmentName) { return claimWithServiceResponseAsync(resourceGroupName, labAccountName, labName, environmentSettingName, environmentName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "claimAsync", "(", "String", "resourceGroupName", ",", "String", "labAccountName", ",", "String", "labName", ",", "String", "environmentSettingName", ",", "String", "environmentName", ")", "{", "return", "claimWithServiceResponseAsync", "(", "resourceGroupName", ",", "labAccountName", ",", "labName", ",", "environmentSettingName", ",", "environmentName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Claims the environment and assigns it to the user. @param resourceGroupName The name of the resource group. @param labAccountName The name of the lab Account. @param labName The name of the lab. @param environmentSettingName The name of the environment Setting. @param environmentName The name of the environment. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Claims", "the", "environment", "and", "assigns", "it", "to", "the", "user", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/EnvironmentsInner.java#L1103-L1110
BotMill/fb-botmill
src/main/java/co/aurasphere/botmill/fb/model/outcoming/factory/AirlineCheckinTemplateBuilder.java
AirlineCheckinTemplateBuilder.addQuickReply
public AirlineCheckinTemplateBuilder addQuickReply(String title, String payload) { """ Adds a {@link QuickReply} to the current object. @param title the quick reply button label. It can't be empty. @param payload the payload sent back when the button is pressed. It can't be empty. @return this builder. @see <a href= "https://developers.facebook.com/docs/messenger-platform/send-api-reference/quick-replies" > Facebook's Messenger Platform Quick Replies Documentation</a> """ this.messageBuilder.addQuickReply(title, payload); return this; }
java
public AirlineCheckinTemplateBuilder addQuickReply(String title, String payload) { this.messageBuilder.addQuickReply(title, payload); return this; }
[ "public", "AirlineCheckinTemplateBuilder", "addQuickReply", "(", "String", "title", ",", "String", "payload", ")", "{", "this", ".", "messageBuilder", ".", "addQuickReply", "(", "title", ",", "payload", ")", ";", "return", "this", ";", "}" ]
Adds a {@link QuickReply} to the current object. @param title the quick reply button label. It can't be empty. @param payload the payload sent back when the button is pressed. It can't be empty. @return this builder. @see <a href= "https://developers.facebook.com/docs/messenger-platform/send-api-reference/quick-replies" > Facebook's Messenger Platform Quick Replies Documentation</a>
[ "Adds", "a", "{", "@link", "QuickReply", "}", "to", "the", "current", "object", "." ]
train
https://github.com/BotMill/fb-botmill/blob/d94da3615a7339822c137ef75c92a03d791ee969/src/main/java/co/aurasphere/botmill/fb/model/outcoming/factory/AirlineCheckinTemplateBuilder.java#L139-L143
j256/simplejmx
src/main/java/com/j256/simplejmx/client/JmxClient.java
JmxClient.getAttributesInfo
public MBeanAttributeInfo[] getAttributesInfo(String domainName, String beanName) throws JMException { """ Return an array of the attributes associated with the bean name. """ return getAttributesInfo(ObjectNameUtil.makeObjectName(domainName, beanName)); }
java
public MBeanAttributeInfo[] getAttributesInfo(String domainName, String beanName) throws JMException { return getAttributesInfo(ObjectNameUtil.makeObjectName(domainName, beanName)); }
[ "public", "MBeanAttributeInfo", "[", "]", "getAttributesInfo", "(", "String", "domainName", ",", "String", "beanName", ")", "throws", "JMException", "{", "return", "getAttributesInfo", "(", "ObjectNameUtil", ".", "makeObjectName", "(", "domainName", ",", "beanName", ")", ")", ";", "}" ]
Return an array of the attributes associated with the bean name.
[ "Return", "an", "array", "of", "the", "attributes", "associated", "with", "the", "bean", "name", "." ]
train
https://github.com/j256/simplejmx/blob/1a04f52512dfa0a711ba0cc7023c604dbc82a352/src/main/java/com/j256/simplejmx/client/JmxClient.java#L240-L242
classgraph/classgraph
src/main/java/io/github/classgraph/ClassInfo.java
ClassInfo.getAllAnnotationClasses
static ClassInfoList getAllAnnotationClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) { """ Get all annotation classes found during the scan. See also {@link #getAllInterfacesOrAnnotationClasses(Collection, ScanSpec, ScanResult)} ()}. @param classes the classes @param scanSpec the scan spec @return A list of all annotation classes found during the scan, or the empty list if none. """ return new ClassInfoList( ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.ANNOTATION), /* sortByName = */ true); }
java
static ClassInfoList getAllAnnotationClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) { return new ClassInfoList( ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.ANNOTATION), /* sortByName = */ true); }
[ "static", "ClassInfoList", "getAllAnnotationClasses", "(", "final", "Collection", "<", "ClassInfo", ">", "classes", ",", "final", "ScanSpec", "scanSpec", ")", "{", "return", "new", "ClassInfoList", "(", "ClassInfo", ".", "filterClassInfo", "(", "classes", ",", "scanSpec", ",", "/* strictWhitelist = */", "true", ",", "ClassType", ".", "ANNOTATION", ")", ",", "/* sortByName = */", "true", ")", ";", "}" ]
Get all annotation classes found during the scan. See also {@link #getAllInterfacesOrAnnotationClasses(Collection, ScanSpec, ScanResult)} ()}. @param classes the classes @param scanSpec the scan spec @return A list of all annotation classes found during the scan, or the empty list if none.
[ "Get", "all", "annotation", "classes", "found", "during", "the", "scan", ".", "See", "also", "{", "@link", "#getAllInterfacesOrAnnotationClasses", "(", "Collection", "ScanSpec", "ScanResult", ")", "}", "()", "}", "." ]
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/io/github/classgraph/ClassInfo.java#L870-L874
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/component/carouselControl/CarouselControlRenderer.java
CarouselControlRenderer.decode
@Override public void decode(FacesContext context, UIComponent component) { """ This methods receives and processes input made by the user. More specifically, it checks whether the user has interacted with the current b:carouselControl. The default implementation simply stores the input value in the list of submitted values. If the validation checks are passed, the values in the <code>submittedValues</code> list are store in the backend bean. @param context the FacesContext. @param component the current b:carouselControl. """ CarouselControl carouselControl = (CarouselControl) component; if (carouselControl.isDisabled()) { return; } new AJAXRenderer().decode(context, component); }
java
@Override public void decode(FacesContext context, UIComponent component) { CarouselControl carouselControl = (CarouselControl) component; if (carouselControl.isDisabled()) { return; } new AJAXRenderer().decode(context, component); }
[ "@", "Override", "public", "void", "decode", "(", "FacesContext", "context", ",", "UIComponent", "component", ")", "{", "CarouselControl", "carouselControl", "=", "(", "CarouselControl", ")", "component", ";", "if", "(", "carouselControl", ".", "isDisabled", "(", ")", ")", "{", "return", ";", "}", "new", "AJAXRenderer", "(", ")", ".", "decode", "(", "context", ",", "component", ")", ";", "}" ]
This methods receives and processes input made by the user. More specifically, it checks whether the user has interacted with the current b:carouselControl. The default implementation simply stores the input value in the list of submitted values. If the validation checks are passed, the values in the <code>submittedValues</code> list are store in the backend bean. @param context the FacesContext. @param component the current b:carouselControl.
[ "This", "methods", "receives", "and", "processes", "input", "made", "by", "the", "user", ".", "More", "specifically", "it", "checks", "whether", "the", "user", "has", "interacted", "with", "the", "current", "b", ":", "carouselControl", ".", "The", "default", "implementation", "simply", "stores", "the", "input", "value", "in", "the", "list", "of", "submitted", "values", ".", "If", "the", "validation", "checks", "are", "passed", "the", "values", "in", "the", "<code", ">", "submittedValues<", "/", "code", ">", "list", "are", "store", "in", "the", "backend", "bean", "." ]
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/carouselControl/CarouselControlRenderer.java#L48-L57
lunarray-org/common-event
src/main/java/org/lunarray/common/event/Bus.java
Bus.removeListener
public <T> void removeListener(final Listener<T> listener, final Object instance) { """ Remove a listener. @param listener The listener to remove. @param instance The associated marker. @param <T> The listener event type. """ final ListenerInstancePair<T> pair = new ListenerInstancePair<T>(listener, instance); this.listeners.remove(pair); for (final List<ListenerInstancePair<?>> entry : this.cachedListeners.values()) { entry.remove(pair); } }
java
public <T> void removeListener(final Listener<T> listener, final Object instance) { final ListenerInstancePair<T> pair = new ListenerInstancePair<T>(listener, instance); this.listeners.remove(pair); for (final List<ListenerInstancePair<?>> entry : this.cachedListeners.values()) { entry.remove(pair); } }
[ "public", "<", "T", ">", "void", "removeListener", "(", "final", "Listener", "<", "T", ">", "listener", ",", "final", "Object", "instance", ")", "{", "final", "ListenerInstancePair", "<", "T", ">", "pair", "=", "new", "ListenerInstancePair", "<", "T", ">", "(", "listener", ",", "instance", ")", ";", "this", ".", "listeners", ".", "remove", "(", "pair", ")", ";", "for", "(", "final", "List", "<", "ListenerInstancePair", "<", "?", ">", ">", "entry", ":", "this", ".", "cachedListeners", ".", "values", "(", ")", ")", "{", "entry", ".", "remove", "(", "pair", ")", ";", "}", "}" ]
Remove a listener. @param listener The listener to remove. @param instance The associated marker. @param <T> The listener event type.
[ "Remove", "a", "listener", "." ]
train
https://github.com/lunarray-org/common-event/blob/a92102546d136d5f4270cfe8dbd69e4188a46202/src/main/java/org/lunarray/common/event/Bus.java#L206-L212
h2oai/h2o-3
h2o-core/src/main/java/water/rapids/ast/prims/search/AstWhichFunc.java
AstWhichFunc.colwiseWhichVal
private ValFrame colwiseWhichVal(Frame fr, final boolean na_rm) { """ Compute column-wise (i.e.value index of each column), and return a frame having a single row. """ Frame res = new Frame(); Vec vec1 = Vec.makeCon(null, 0); assert vec1.length() == 1; for (int i = 0; i < fr.numCols(); i++) { Vec v = fr.vec(i); double searchValue = op(v); boolean valid = (v.isNumeric() || v.isTime() || v.isBinary()) && v.length() > 0 && (na_rm || v.naCnt() == 0); FindIndexCol findIndexCol = new FindIndexCol(searchValue).doAll(new byte[]{Vec.T_NUM}, v); Vec newvec = vec1.makeCon(valid ? findIndexCol._valIndex : Double.NaN, v.isTime()? Vec.T_TIME : Vec.T_NUM); res.add(fr.name(i), newvec); } vec1.remove(); return new ValFrame(res); }
java
private ValFrame colwiseWhichVal(Frame fr, final boolean na_rm) { Frame res = new Frame(); Vec vec1 = Vec.makeCon(null, 0); assert vec1.length() == 1; for (int i = 0; i < fr.numCols(); i++) { Vec v = fr.vec(i); double searchValue = op(v); boolean valid = (v.isNumeric() || v.isTime() || v.isBinary()) && v.length() > 0 && (na_rm || v.naCnt() == 0); FindIndexCol findIndexCol = new FindIndexCol(searchValue).doAll(new byte[]{Vec.T_NUM}, v); Vec newvec = vec1.makeCon(valid ? findIndexCol._valIndex : Double.NaN, v.isTime()? Vec.T_TIME : Vec.T_NUM); res.add(fr.name(i), newvec); } vec1.remove(); return new ValFrame(res); }
[ "private", "ValFrame", "colwiseWhichVal", "(", "Frame", "fr", ",", "final", "boolean", "na_rm", ")", "{", "Frame", "res", "=", "new", "Frame", "(", ")", ";", "Vec", "vec1", "=", "Vec", ".", "makeCon", "(", "null", ",", "0", ")", ";", "assert", "vec1", ".", "length", "(", ")", "==", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "fr", ".", "numCols", "(", ")", ";", "i", "++", ")", "{", "Vec", "v", "=", "fr", ".", "vec", "(", "i", ")", ";", "double", "searchValue", "=", "op", "(", "v", ")", ";", "boolean", "valid", "=", "(", "v", ".", "isNumeric", "(", ")", "||", "v", ".", "isTime", "(", ")", "||", "v", ".", "isBinary", "(", ")", ")", "&&", "v", ".", "length", "(", ")", ">", "0", "&&", "(", "na_rm", "||", "v", ".", "naCnt", "(", ")", "==", "0", ")", ";", "FindIndexCol", "findIndexCol", "=", "new", "FindIndexCol", "(", "searchValue", ")", ".", "doAll", "(", "new", "byte", "[", "]", "{", "Vec", ".", "T_NUM", "}", ",", "v", ")", ";", "Vec", "newvec", "=", "vec1", ".", "makeCon", "(", "valid", "?", "findIndexCol", ".", "_valIndex", ":", "Double", ".", "NaN", ",", "v", ".", "isTime", "(", ")", "?", "Vec", ".", "T_TIME", ":", "Vec", ".", "T_NUM", ")", ";", "res", ".", "add", "(", "fr", ".", "name", "(", "i", ")", ",", "newvec", ")", ";", "}", "vec1", ".", "remove", "(", ")", ";", "return", "new", "ValFrame", "(", "res", ")", ";", "}" ]
Compute column-wise (i.e.value index of each column), and return a frame having a single row.
[ "Compute", "column", "-", "wise", "(", "i", ".", "e", ".", "value", "index", "of", "each", "column", ")", "and", "return", "a", "frame", "having", "a", "single", "row", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/rapids/ast/prims/search/AstWhichFunc.java#L180-L197
kaazing/gateway
transport/ws/src/main/java/org/kaazing/gateway/transport/ws/bridge/extensions/pingpong/PingPongFilter.java
PingPongFilter.wsPingReceived
@Override protected void wsPingReceived(NextFilter nextFilter, IoSession session, WsPingMessage wsPing) throws Exception { """ Reply to native ping (from browser's native websocket layer) with native pong """ WsPongMessage reply = new WsPongMessage(wsPing.getBytes()); nextFilter.filterWrite(session, new DefaultWriteRequestEx(reply)); }
java
@Override protected void wsPingReceived(NextFilter nextFilter, IoSession session, WsPingMessage wsPing) throws Exception { WsPongMessage reply = new WsPongMessage(wsPing.getBytes()); nextFilter.filterWrite(session, new DefaultWriteRequestEx(reply)); }
[ "@", "Override", "protected", "void", "wsPingReceived", "(", "NextFilter", "nextFilter", ",", "IoSession", "session", ",", "WsPingMessage", "wsPing", ")", "throws", "Exception", "{", "WsPongMessage", "reply", "=", "new", "WsPongMessage", "(", "wsPing", ".", "getBytes", "(", ")", ")", ";", "nextFilter", ".", "filterWrite", "(", "session", ",", "new", "DefaultWriteRequestEx", "(", "reply", ")", ")", ";", "}" ]
Reply to native ping (from browser's native websocket layer) with native pong
[ "Reply", "to", "native", "ping", "(", "from", "browser", "s", "native", "websocket", "layer", ")", "with", "native", "pong" ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/transport/ws/src/main/java/org/kaazing/gateway/transport/ws/bridge/extensions/pingpong/PingPongFilter.java#L95-L99
apereo/cas
core/cas-server-core-authentication-mfa-api/src/main/java/org/apereo/cas/authentication/bypass/HttpRequestMultifactorAuthenticationProviderBypass.java
HttpRequestMultifactorAuthenticationProviderBypass.locateMatchingHttpRequest
protected boolean locateMatchingHttpRequest(final Authentication authentication, final HttpServletRequest request) { """ Locate matching http request and determine if bypass should be enabled. @param authentication the authentication @param request the request @return true /false """ if (StringUtils.isNotBlank(bypassProperties.getHttpRequestRemoteAddress())) { if (httpRequestRemoteAddressPattern.matcher(request.getRemoteAddr()).find()) { LOGGER.debug("Http request remote address [{}] matches [{}]", bypassProperties.getHttpRequestRemoteAddress(), request.getRemoteAddr()); return true; } if (httpRequestRemoteAddressPattern.matcher(request.getRemoteHost()).find()) { LOGGER.debug("Http request remote host [{}] matches [{}]", bypassProperties.getHttpRequestRemoteAddress(), request.getRemoteHost()); return true; } } if (StringUtils.isNotBlank(bypassProperties.getHttpRequestHeaders())) { val headerNames = Collections.list(request.getHeaderNames()); val matched = this.httpRequestHeaderPatterns.stream() .anyMatch(pattern -> headerNames.stream().anyMatch(name -> pattern.matcher(name).matches())); if (matched) { LOGGER.debug("Http request remote headers [{}] match [{}]", headerNames, bypassProperties.getHttpRequestHeaders()); return true; } } return false; }
java
protected boolean locateMatchingHttpRequest(final Authentication authentication, final HttpServletRequest request) { if (StringUtils.isNotBlank(bypassProperties.getHttpRequestRemoteAddress())) { if (httpRequestRemoteAddressPattern.matcher(request.getRemoteAddr()).find()) { LOGGER.debug("Http request remote address [{}] matches [{}]", bypassProperties.getHttpRequestRemoteAddress(), request.getRemoteAddr()); return true; } if (httpRequestRemoteAddressPattern.matcher(request.getRemoteHost()).find()) { LOGGER.debug("Http request remote host [{}] matches [{}]", bypassProperties.getHttpRequestRemoteAddress(), request.getRemoteHost()); return true; } } if (StringUtils.isNotBlank(bypassProperties.getHttpRequestHeaders())) { val headerNames = Collections.list(request.getHeaderNames()); val matched = this.httpRequestHeaderPatterns.stream() .anyMatch(pattern -> headerNames.stream().anyMatch(name -> pattern.matcher(name).matches())); if (matched) { LOGGER.debug("Http request remote headers [{}] match [{}]", headerNames, bypassProperties.getHttpRequestHeaders()); return true; } } return false; }
[ "protected", "boolean", "locateMatchingHttpRequest", "(", "final", "Authentication", "authentication", ",", "final", "HttpServletRequest", "request", ")", "{", "if", "(", "StringUtils", ".", "isNotBlank", "(", "bypassProperties", ".", "getHttpRequestRemoteAddress", "(", ")", ")", ")", "{", "if", "(", "httpRequestRemoteAddressPattern", ".", "matcher", "(", "request", ".", "getRemoteAddr", "(", ")", ")", ".", "find", "(", ")", ")", "{", "LOGGER", ".", "debug", "(", "\"Http request remote address [{}] matches [{}]\"", ",", "bypassProperties", ".", "getHttpRequestRemoteAddress", "(", ")", ",", "request", ".", "getRemoteAddr", "(", ")", ")", ";", "return", "true", ";", "}", "if", "(", "httpRequestRemoteAddressPattern", ".", "matcher", "(", "request", ".", "getRemoteHost", "(", ")", ")", ".", "find", "(", ")", ")", "{", "LOGGER", ".", "debug", "(", "\"Http request remote host [{}] matches [{}]\"", ",", "bypassProperties", ".", "getHttpRequestRemoteAddress", "(", ")", ",", "request", ".", "getRemoteHost", "(", ")", ")", ";", "return", "true", ";", "}", "}", "if", "(", "StringUtils", ".", "isNotBlank", "(", "bypassProperties", ".", "getHttpRequestHeaders", "(", ")", ")", ")", "{", "val", "headerNames", "=", "Collections", ".", "list", "(", "request", ".", "getHeaderNames", "(", ")", ")", ";", "val", "matched", "=", "this", ".", "httpRequestHeaderPatterns", ".", "stream", "(", ")", ".", "anyMatch", "(", "pattern", "->", "headerNames", ".", "stream", "(", ")", ".", "anyMatch", "(", "name", "->", "pattern", ".", "matcher", "(", "name", ")", ".", "matches", "(", ")", ")", ")", ";", "if", "(", "matched", ")", "{", "LOGGER", ".", "debug", "(", "\"Http request remote headers [{}] match [{}]\"", ",", "headerNames", ",", "bypassProperties", ".", "getHttpRequestHeaders", "(", ")", ")", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Locate matching http request and determine if bypass should be enabled. @param authentication the authentication @param request the request @return true /false
[ "Locate", "matching", "http", "request", "and", "determine", "if", "bypass", "should", "be", "enabled", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-authentication-mfa-api/src/main/java/org/apereo/cas/authentication/bypass/HttpRequestMultifactorAuthenticationProviderBypass.java#L69-L92
Crab2died/Excel4J
src/main/java/com/github/crab2died/utils/Utils.java
Utils.getProperty
public static String getProperty(Object bean, String fieldName, WriteConvertible writeConvertible) throws Excel4JException { """ 根据属性名与属性类型获取字段内容 @param bean 对象 @param fieldName 字段名 @param writeConvertible 写入转换器 @return 对象指定字段内容 @throws Excel4JException 异常 """ if (bean == null || fieldName == null) throw new IllegalArgumentException("Operating bean or filed class must not be null"); Method method; Object object; try { method = getterOrSetter(bean.getClass(), fieldName, FieldAccessType.GETTER); object = method.invoke(bean); } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) { throw new Excel4JException(e); } if (null != writeConvertible && writeConvertible.getClass() != DefaultConvertible.class) { // 写入转换器 object = writeConvertible.execWrite(object); } return object == null ? "" : object.toString(); }
java
public static String getProperty(Object bean, String fieldName, WriteConvertible writeConvertible) throws Excel4JException { if (bean == null || fieldName == null) throw new IllegalArgumentException("Operating bean or filed class must not be null"); Method method; Object object; try { method = getterOrSetter(bean.getClass(), fieldName, FieldAccessType.GETTER); object = method.invoke(bean); } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) { throw new Excel4JException(e); } if (null != writeConvertible && writeConvertible.getClass() != DefaultConvertible.class) { // 写入转换器 object = writeConvertible.execWrite(object); } return object == null ? "" : object.toString(); }
[ "public", "static", "String", "getProperty", "(", "Object", "bean", ",", "String", "fieldName", ",", "WriteConvertible", "writeConvertible", ")", "throws", "Excel4JException", "{", "if", "(", "bean", "==", "null", "||", "fieldName", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"Operating bean or filed class must not be null\"", ")", ";", "Method", "method", ";", "Object", "object", ";", "try", "{", "method", "=", "getterOrSetter", "(", "bean", ".", "getClass", "(", ")", ",", "fieldName", ",", "FieldAccessType", ".", "GETTER", ")", ";", "object", "=", "method", ".", "invoke", "(", "bean", ")", ";", "}", "catch", "(", "IntrospectionException", "|", "IllegalAccessException", "|", "InvocationTargetException", "e", ")", "{", "throw", "new", "Excel4JException", "(", "e", ")", ";", "}", "if", "(", "null", "!=", "writeConvertible", "&&", "writeConvertible", ".", "getClass", "(", ")", "!=", "DefaultConvertible", ".", "class", ")", "{", "// 写入转换器", "object", "=", "writeConvertible", ".", "execWrite", "(", "object", ")", ";", "}", "return", "object", "==", "null", "?", "\"\"", ":", "object", ".", "toString", "(", ")", ";", "}" ]
根据属性名与属性类型获取字段内容 @param bean 对象 @param fieldName 字段名 @param writeConvertible 写入转换器 @return 对象指定字段内容 @throws Excel4JException 异常
[ "根据属性名与属性类型获取字段内容" ]
train
https://github.com/Crab2died/Excel4J/blob/2ab0a3b8226a69ff868c3ead6e724f3a774f5f77/src/main/java/com/github/crab2died/utils/Utils.java#L282-L300