repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
wuman/orientdb-android
commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java
OMVRBTree.buildFromSorted
private void buildFromSorted(final int size, final Iterator<?> it, final java.io.ObjectInputStream str, final V defaultVal) throws java.io.IOException, ClassNotFoundException { """ Linear time tree building algorithm from sorted data. Can accept keys and/or values from iterator or stream. This leads to too many parameters, but seems better than alternatives. The four formats that this method accepts are: 1) An iterator of Map.Entries. (it != null, defaultVal == null). 2) An iterator of keys. (it != null, defaultVal != null). 3) A stream of alternating serialized keys and values. (it == null, defaultVal == null). 4) A stream of serialized keys. (it == null, defaultVal != null). It is assumed that the comparator of the OMVRBTree is already set prior to calling this method. @param size the number of keys (or key-value pairs) to be read from the iterator or stream @param it If non-null, new entries are created from entries or keys read from this iterator. @param str If non-null, new entries are created from keys and possibly values read from this stream in serialized form. Exactly one of it and str should be non-null. @param defaultVal if non-null, this default value is used for each value in the map. If null, each value is read from iterator or stream, as described above. @throws IOException propagated from stream reads. This cannot occur if str is null. @throws ClassNotFoundException propagated from readObject. This cannot occur if str is null. """ setSize(size); root = buildFromSorted(0, 0, size - 1, computeRedLevel(size), it, str, defaultVal); }
java
private void buildFromSorted(final int size, final Iterator<?> it, final java.io.ObjectInputStream str, final V defaultVal) throws java.io.IOException, ClassNotFoundException { setSize(size); root = buildFromSorted(0, 0, size - 1, computeRedLevel(size), it, str, defaultVal); }
[ "private", "void", "buildFromSorted", "(", "final", "int", "size", ",", "final", "Iterator", "<", "?", ">", "it", ",", "final", "java", ".", "io", ".", "ObjectInputStream", "str", ",", "final", "V", "defaultVal", ")", "throws", "java", ".", "io", ".", "IOException", ",", "ClassNotFoundException", "{", "setSize", "(", "size", ")", ";", "root", "=", "buildFromSorted", "(", "0", ",", "0", ",", "size", "-", "1", ",", "computeRedLevel", "(", "size", ")", ",", "it", ",", "str", ",", "defaultVal", ")", ";", "}" ]
Linear time tree building algorithm from sorted data. Can accept keys and/or values from iterator or stream. This leads to too many parameters, but seems better than alternatives. The four formats that this method accepts are: 1) An iterator of Map.Entries. (it != null, defaultVal == null). 2) An iterator of keys. (it != null, defaultVal != null). 3) A stream of alternating serialized keys and values. (it == null, defaultVal == null). 4) A stream of serialized keys. (it == null, defaultVal != null). It is assumed that the comparator of the OMVRBTree is already set prior to calling this method. @param size the number of keys (or key-value pairs) to be read from the iterator or stream @param it If non-null, new entries are created from entries or keys read from this iterator. @param str If non-null, new entries are created from keys and possibly values read from this stream in serialized form. Exactly one of it and str should be non-null. @param defaultVal if non-null, this default value is used for each value in the map. If null, each value is read from iterator or stream, as described above. @throws IOException propagated from stream reads. This cannot occur if str is null. @throws ClassNotFoundException propagated from readObject. This cannot occur if str is null.
[ "Linear", "time", "tree", "building", "algorithm", "from", "sorted", "data", ".", "Can", "accept", "keys", "and", "/", "or", "values", "from", "iterator", "or", "stream", ".", "This", "leads", "to", "too", "many", "parameters", "but", "seems", "better", "than", "alternatives", ".", "The", "four", "formats", "that", "this", "method", "accepts", "are", ":" ]
train
https://github.com/wuman/orientdb-android/blob/ff9b17e4349f26168b2d0c4facb1a18cbfbe8cf0/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java#L2667-L2671
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataOneOfImpl_CustomFieldSerializer.java
OWLDataOneOfImpl_CustomFieldSerializer.serializeInstance
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataOneOfImpl instance) throws SerializationException { """ Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful """ serialize(streamWriter, instance); }
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataOneOfImpl instance) throws SerializationException { serialize(streamWriter, instance); }
[ "@", "Override", "public", "void", "serializeInstance", "(", "SerializationStreamWriter", "streamWriter", ",", "OWLDataOneOfImpl", "instance", ")", "throws", "SerializationException", "{", "serialize", "(", "streamWriter", ",", "instance", ")", ";", "}" ]
Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful
[ "Serializes", "the", "content", "of", "the", "object", "into", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamWriter", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataOneOfImpl_CustomFieldSerializer.java#L69-L72
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/NetworkEnvironmentConfiguration.java
NetworkEnvironmentConfiguration.createNettyConfig
@Nullable private static NettyConfig createNettyConfig( Configuration configuration, boolean localTaskManagerCommunication, InetAddress taskManagerAddress, int dataport) { """ Generates {@link NettyConfig} from Flink {@link Configuration}. @param configuration configuration object @param localTaskManagerCommunication true, to skip initializing the network stack @param taskManagerAddress identifying the IP address under which the TaskManager will be accessible @param dataport data port for communication and data exchange @return the netty configuration or {@code null} if communication is in the same task manager """ final NettyConfig nettyConfig; if (!localTaskManagerCommunication) { final InetSocketAddress taskManagerInetSocketAddress = new InetSocketAddress(taskManagerAddress, dataport); nettyConfig = new NettyConfig(taskManagerInetSocketAddress.getAddress(), taskManagerInetSocketAddress.getPort(), getPageSize(configuration), ConfigurationParserUtils.getSlot(configuration), configuration); } else { nettyConfig = null; } return nettyConfig; }
java
@Nullable private static NettyConfig createNettyConfig( Configuration configuration, boolean localTaskManagerCommunication, InetAddress taskManagerAddress, int dataport) { final NettyConfig nettyConfig; if (!localTaskManagerCommunication) { final InetSocketAddress taskManagerInetSocketAddress = new InetSocketAddress(taskManagerAddress, dataport); nettyConfig = new NettyConfig(taskManagerInetSocketAddress.getAddress(), taskManagerInetSocketAddress.getPort(), getPageSize(configuration), ConfigurationParserUtils.getSlot(configuration), configuration); } else { nettyConfig = null; } return nettyConfig; }
[ "@", "Nullable", "private", "static", "NettyConfig", "createNettyConfig", "(", "Configuration", "configuration", ",", "boolean", "localTaskManagerCommunication", ",", "InetAddress", "taskManagerAddress", ",", "int", "dataport", ")", "{", "final", "NettyConfig", "nettyConfig", ";", "if", "(", "!", "localTaskManagerCommunication", ")", "{", "final", "InetSocketAddress", "taskManagerInetSocketAddress", "=", "new", "InetSocketAddress", "(", "taskManagerAddress", ",", "dataport", ")", ";", "nettyConfig", "=", "new", "NettyConfig", "(", "taskManagerInetSocketAddress", ".", "getAddress", "(", ")", ",", "taskManagerInetSocketAddress", ".", "getPort", "(", ")", ",", "getPageSize", "(", "configuration", ")", ",", "ConfigurationParserUtils", ".", "getSlot", "(", "configuration", ")", ",", "configuration", ")", ";", "}", "else", "{", "nettyConfig", "=", "null", ";", "}", "return", "nettyConfig", ";", "}" ]
Generates {@link NettyConfig} from Flink {@link Configuration}. @param configuration configuration object @param localTaskManagerCommunication true, to skip initializing the network stack @param taskManagerAddress identifying the IP address under which the TaskManager will be accessible @param dataport data port for communication and data exchange @return the netty configuration or {@code null} if communication is in the same task manager
[ "Generates", "{", "@link", "NettyConfig", "}", "from", "Flink", "{", "@link", "Configuration", "}", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/NetworkEnvironmentConfiguration.java#L424-L442
alkacon/opencms-core
src/org/opencms/workplace/CmsWorkplace.java
CmsWorkplace.initTimeWarp
protected void initTimeWarp(CmsUserSettings settings, HttpSession session) { """ Sets the users time warp if configured and if the current timewarp setting is different or clears the current time warp setting if the user has no configured timewarp.<p> Timwarping is controlled by the session attribute {@link CmsContextInfo#ATTRIBUTE_REQUEST_TIME} with a value of type <code>Long</code>.<p> @param settings the user settings which are configured via the preferences dialog @param session the session of the user """ long timeWarpConf = settings.getTimeWarp(); Long timeWarpSetLong = (Long)session.getAttribute(CmsContextInfo.ATTRIBUTE_REQUEST_TIME); long timeWarpSet = (timeWarpSetLong != null) ? timeWarpSetLong.longValue() : CmsContextInfo.CURRENT_TIME; if (timeWarpConf == CmsContextInfo.CURRENT_TIME) { // delete: if (timeWarpSetLong != null) { // we may come from direct_edit.jsp: don't remove attribute, this is session.removeAttribute(CmsContextInfo.ATTRIBUTE_REQUEST_TIME); } } else { // this is dominant: if configured we will use it if (timeWarpSet != timeWarpConf) { session.setAttribute(CmsContextInfo.ATTRIBUTE_REQUEST_TIME, new Long(timeWarpConf)); } } }
java
protected void initTimeWarp(CmsUserSettings settings, HttpSession session) { long timeWarpConf = settings.getTimeWarp(); Long timeWarpSetLong = (Long)session.getAttribute(CmsContextInfo.ATTRIBUTE_REQUEST_TIME); long timeWarpSet = (timeWarpSetLong != null) ? timeWarpSetLong.longValue() : CmsContextInfo.CURRENT_TIME; if (timeWarpConf == CmsContextInfo.CURRENT_TIME) { // delete: if (timeWarpSetLong != null) { // we may come from direct_edit.jsp: don't remove attribute, this is session.removeAttribute(CmsContextInfo.ATTRIBUTE_REQUEST_TIME); } } else { // this is dominant: if configured we will use it if (timeWarpSet != timeWarpConf) { session.setAttribute(CmsContextInfo.ATTRIBUTE_REQUEST_TIME, new Long(timeWarpConf)); } } }
[ "protected", "void", "initTimeWarp", "(", "CmsUserSettings", "settings", ",", "HttpSession", "session", ")", "{", "long", "timeWarpConf", "=", "settings", ".", "getTimeWarp", "(", ")", ";", "Long", "timeWarpSetLong", "=", "(", "Long", ")", "session", ".", "getAttribute", "(", "CmsContextInfo", ".", "ATTRIBUTE_REQUEST_TIME", ")", ";", "long", "timeWarpSet", "=", "(", "timeWarpSetLong", "!=", "null", ")", "?", "timeWarpSetLong", ".", "longValue", "(", ")", ":", "CmsContextInfo", ".", "CURRENT_TIME", ";", "if", "(", "timeWarpConf", "==", "CmsContextInfo", ".", "CURRENT_TIME", ")", "{", "// delete:", "if", "(", "timeWarpSetLong", "!=", "null", ")", "{", "// we may come from direct_edit.jsp: don't remove attribute, this is", "session", ".", "removeAttribute", "(", "CmsContextInfo", ".", "ATTRIBUTE_REQUEST_TIME", ")", ";", "}", "}", "else", "{", "// this is dominant: if configured we will use it", "if", "(", "timeWarpSet", "!=", "timeWarpConf", ")", "{", "session", ".", "setAttribute", "(", "CmsContextInfo", ".", "ATTRIBUTE_REQUEST_TIME", ",", "new", "Long", "(", "timeWarpConf", ")", ")", ";", "}", "}", "}" ]
Sets the users time warp if configured and if the current timewarp setting is different or clears the current time warp setting if the user has no configured timewarp.<p> Timwarping is controlled by the session attribute {@link CmsContextInfo#ATTRIBUTE_REQUEST_TIME} with a value of type <code>Long</code>.<p> @param settings the user settings which are configured via the preferences dialog @param session the session of the user
[ "Sets", "the", "users", "time", "warp", "if", "configured", "and", "if", "the", "current", "timewarp", "setting", "is", "different", "or", "clears", "the", "current", "time", "warp", "setting", "if", "the", "user", "has", "no", "configured", "timewarp", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsWorkplace.java#L2298-L2316
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslvserver_binding.java
sslvserver_binding.get
public static sslvserver_binding get(nitro_service service, String vservername) throws Exception { """ Use this API to fetch sslvserver_binding resource of given name . """ sslvserver_binding obj = new sslvserver_binding(); obj.set_vservername(vservername); sslvserver_binding response = (sslvserver_binding) obj.get_resource(service); return response; }
java
public static sslvserver_binding get(nitro_service service, String vservername) throws Exception{ sslvserver_binding obj = new sslvserver_binding(); obj.set_vservername(vservername); sslvserver_binding response = (sslvserver_binding) obj.get_resource(service); return response; }
[ "public", "static", "sslvserver_binding", "get", "(", "nitro_service", "service", ",", "String", "vservername", ")", "throws", "Exception", "{", "sslvserver_binding", "obj", "=", "new", "sslvserver_binding", "(", ")", ";", "obj", ".", "set_vservername", "(", "vservername", ")", ";", "sslvserver_binding", "response", "=", "(", "sslvserver_binding", ")", "obj", ".", "get_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch sslvserver_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "sslvserver_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslvserver_binding.java#L136-L141
cache2k/cache2k
cache2k-api/src/main/java/org/cache2k/Cache2kBuilder.java
Cache2kBuilder.buildForIntKey
@SuppressWarnings("unchecked") public final IntCache<V> buildForIntKey() { """ Builds a cache with the specified configuration parameters. The behavior is identical to {@link #build()} except that it checks that the key type is {@code Integer} and casts the created cache to the specialized interface. @throws IllegalArgumentException if a cache of the same name is already active in the cache manager @throws IllegalArgumentException if key type is unexpected @throws IllegalArgumentException if a configuration entry for the named cache is required but not present """ Cache2kConfiguration<K,V> cfg = config(); if (cfg.getKeyType().getType() != Integer.class) { throw new IllegalArgumentException("Integer key type expected, was: " + cfg.getKeyType()); } return (IntCache<V>) CacheManager.PROVIDER.createCache(manager, config()); }
java
@SuppressWarnings("unchecked") public final IntCache<V> buildForIntKey() { Cache2kConfiguration<K,V> cfg = config(); if (cfg.getKeyType().getType() != Integer.class) { throw new IllegalArgumentException("Integer key type expected, was: " + cfg.getKeyType()); } return (IntCache<V>) CacheManager.PROVIDER.createCache(manager, config()); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "final", "IntCache", "<", "V", ">", "buildForIntKey", "(", ")", "{", "Cache2kConfiguration", "<", "K", ",", "V", ">", "cfg", "=", "config", "(", ")", ";", "if", "(", "cfg", ".", "getKeyType", "(", ")", ".", "getType", "(", ")", "!=", "Integer", ".", "class", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Integer key type expected, was: \"", "+", "cfg", ".", "getKeyType", "(", ")", ")", ";", "}", "return", "(", "IntCache", "<", "V", ">", ")", "CacheManager", ".", "PROVIDER", ".", "createCache", "(", "manager", ",", "config", "(", ")", ")", ";", "}" ]
Builds a cache with the specified configuration parameters. The behavior is identical to {@link #build()} except that it checks that the key type is {@code Integer} and casts the created cache to the specialized interface. @throws IllegalArgumentException if a cache of the same name is already active in the cache manager @throws IllegalArgumentException if key type is unexpected @throws IllegalArgumentException if a configuration entry for the named cache is required but not present
[ "Builds", "a", "cache", "with", "the", "specified", "configuration", "parameters", ".", "The", "behavior", "is", "identical", "to", "{", "@link", "#build", "()", "}", "except", "that", "it", "checks", "that", "the", "key", "type", "is", "{", "@code", "Integer", "}", "and", "casts", "the", "created", "cache", "to", "the", "specialized", "interface", "." ]
train
https://github.com/cache2k/cache2k/blob/3c9ccff12608c598c387ec50957089784cc4b618/cache2k-api/src/main/java/org/cache2k/Cache2kBuilder.java#L887-L894
Azure/azure-sdk-for-java
eventgrid/resource-manager/v2018_05_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_05_01_preview/implementation/EventSubscriptionsInner.java
EventSubscriptionsInner.listRegionalByResourceGroup
public List<EventSubscriptionInner> listRegionalByResourceGroup(String resourceGroupName, String location) { """ List all regional event subscriptions under an Azure subscription and resource group. List all event subscriptions from the given location under a specific Azure subscription and resource group. @param resourceGroupName The name of the resource group within the user's subscription. @param location Name of the location @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 List&lt;EventSubscriptionInner&gt; object if successful. """ return listRegionalByResourceGroupWithServiceResponseAsync(resourceGroupName, location).toBlocking().single().body(); }
java
public List<EventSubscriptionInner> listRegionalByResourceGroup(String resourceGroupName, String location) { return listRegionalByResourceGroupWithServiceResponseAsync(resourceGroupName, location).toBlocking().single().body(); }
[ "public", "List", "<", "EventSubscriptionInner", ">", "listRegionalByResourceGroup", "(", "String", "resourceGroupName", ",", "String", "location", ")", "{", "return", "listRegionalByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "location", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
List all regional event subscriptions under an Azure subscription and resource group. List all event subscriptions from the given location under a specific Azure subscription and resource group. @param resourceGroupName The name of the resource group within the user's subscription. @param location Name of the location @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 List&lt;EventSubscriptionInner&gt; object if successful.
[ "List", "all", "regional", "event", "subscriptions", "under", "an", "Azure", "subscription", "and", "resource", "group", ".", "List", "all", "event", "subscriptions", "from", "the", "given", "location", "under", "a", "specific", "Azure", "subscription", "and", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2018_05_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_05_01_preview/implementation/EventSubscriptionsInner.java#L1272-L1274
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java
ElementsExceptionsFactory.newAuthenticationException
public static AuthenticationException newAuthenticationException(String message, Object... args) { """ Constructs and initializes a new {@link AuthenticationException} with the given {@link String message} formatted with the given {@link Object[] arguments}. @param message {@link String} describing the {@link AuthenticationException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link AuthenticationException} with the given {@link String message}. @see #newAuthenticationException(Throwable, String, Object...) @see org.cp.elements.security.AuthenticationException """ return newAuthenticationException(null, message, args); }
java
public static AuthenticationException newAuthenticationException(String message, Object... args) { return newAuthenticationException(null, message, args); }
[ "public", "static", "AuthenticationException", "newAuthenticationException", "(", "String", "message", ",", "Object", "...", "args", ")", "{", "return", "newAuthenticationException", "(", "null", ",", "message", ",", "args", ")", ";", "}" ]
Constructs and initializes a new {@link AuthenticationException} with the given {@link String message} formatted with the given {@link Object[] arguments}. @param message {@link String} describing the {@link AuthenticationException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link AuthenticationException} with the given {@link String message}. @see #newAuthenticationException(Throwable, String, Object...) @see org.cp.elements.security.AuthenticationException
[ "Constructs", "and", "initializes", "a", "new", "{", "@link", "AuthenticationException", "}", "with", "the", "given", "{", "@link", "String", "message", "}", "formatted", "with", "the", "given", "{", "@link", "Object", "[]", "arguments", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L585-L587
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/PIXAuditor.java
PIXAuditor.auditQueryEvent
protected void auditQueryEvent(boolean systemIsSource, IHETransactionEventTypeCodes transaction, RFC3881EventOutcomeCodes eventOutcome, String sourceFacility, String sourceApp, String sourceAltUserId, String sourceNetworkId, String destinationFacility, String destinationApp, String destinationAltUserId, String destinationNetworkId, String humanRequestor, String hl7MessageId, String hl7QueryParameters, String[] patientIds, List<CodedValueType> purposesOfUse, List<CodedValueType> userRoles) { """ Audit a QUERY event for PIX and PDQ transactions. Useful for PIX Query, PDQ Query, and PDVQ Query in the PIX Manager as well as the PIX and PDQ Consumer @param systemIsSource Whether the system sending the message is the source active participant @param transaction IHE Transaction sending the message @param eventOutcome The event outcome indicator @param sourceFacility Source (sending/receiving) facility, from the MSH segment @param sourceApp Source (sending/receiving) application, from the MSH segment @param sourceAltUserId Source Active Participant Alternate User ID @param sourceNetworkId Source Active Participant Network ID @param destinationFacility Destination (sending/receiving) facility, from the MSH segment @param destinationApp Destination (sending/receiving) application, from the MSH segment @param destinationAltUserId Destination Active Participant Alternate User ID @param destinationNetworkId Destination Active Participant Network ID @param humanRequestor Identity of the human that initiated the transaction (if known) @param hl7MessageId The HL7 Message ID (v2 from the MSH segment field 10, v3 from message.Id) @param hl7QueryParameters The HL7 Query Parameters from the QPD segment @param patientIds List of patient IDs that were seen in this transaction @param purposesOfUse purpose of use codes (may be taken from XUA token) @param userRoles roles of the human user (may be taken from XUA token) """ // Create query event QueryEvent queryEvent = new QueryEvent(systemIsSource, eventOutcome, transaction, purposesOfUse); queryEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId()); // Set the source active participant queryEvent.addSourceActiveParticipant(EventUtils.concatHL7FacilityApplication(sourceFacility,sourceApp), sourceAltUserId, null, sourceNetworkId, true); // Set the human requestor active participant if (!EventUtils.isEmptyOrNull(humanRequestor)) { queryEvent.addHumanRequestorActiveParticipant(humanRequestor, null, null, userRoles); } // Set the destination active participant queryEvent.addDestinationActiveParticipant(EventUtils.concatHL7FacilityApplication(destinationFacility,destinationApp), destinationAltUserId, null, destinationNetworkId, false); // Add a patient participant object for each patient id if (!EventUtils.isEmptyOrNull(patientIds)) { for (int i=0; i<patientIds.length; i++) { queryEvent.addPatientParticipantObject(patientIds[i]); } } byte[] queryParamsBytes = null, msgControlBytes = null; if (hl7QueryParameters != null) { queryParamsBytes = hl7QueryParameters.getBytes(); } if (hl7MessageId != null) { msgControlBytes = hl7MessageId.getBytes(); } // Add the Query participant object queryEvent.addQueryParticipantObject(null, null, queryParamsBytes, msgControlBytes, transaction); audit(queryEvent); }
java
protected void auditQueryEvent(boolean systemIsSource, IHETransactionEventTypeCodes transaction, RFC3881EventOutcomeCodes eventOutcome, String sourceFacility, String sourceApp, String sourceAltUserId, String sourceNetworkId, String destinationFacility, String destinationApp, String destinationAltUserId, String destinationNetworkId, String humanRequestor, String hl7MessageId, String hl7QueryParameters, String[] patientIds, List<CodedValueType> purposesOfUse, List<CodedValueType> userRoles) { // Create query event QueryEvent queryEvent = new QueryEvent(systemIsSource, eventOutcome, transaction, purposesOfUse); queryEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId()); // Set the source active participant queryEvent.addSourceActiveParticipant(EventUtils.concatHL7FacilityApplication(sourceFacility,sourceApp), sourceAltUserId, null, sourceNetworkId, true); // Set the human requestor active participant if (!EventUtils.isEmptyOrNull(humanRequestor)) { queryEvent.addHumanRequestorActiveParticipant(humanRequestor, null, null, userRoles); } // Set the destination active participant queryEvent.addDestinationActiveParticipant(EventUtils.concatHL7FacilityApplication(destinationFacility,destinationApp), destinationAltUserId, null, destinationNetworkId, false); // Add a patient participant object for each patient id if (!EventUtils.isEmptyOrNull(patientIds)) { for (int i=0; i<patientIds.length; i++) { queryEvent.addPatientParticipantObject(patientIds[i]); } } byte[] queryParamsBytes = null, msgControlBytes = null; if (hl7QueryParameters != null) { queryParamsBytes = hl7QueryParameters.getBytes(); } if (hl7MessageId != null) { msgControlBytes = hl7MessageId.getBytes(); } // Add the Query participant object queryEvent.addQueryParticipantObject(null, null, queryParamsBytes, msgControlBytes, transaction); audit(queryEvent); }
[ "protected", "void", "auditQueryEvent", "(", "boolean", "systemIsSource", ",", "IHETransactionEventTypeCodes", "transaction", ",", "RFC3881EventOutcomeCodes", "eventOutcome", ",", "String", "sourceFacility", ",", "String", "sourceApp", ",", "String", "sourceAltUserId", ",", "String", "sourceNetworkId", ",", "String", "destinationFacility", ",", "String", "destinationApp", ",", "String", "destinationAltUserId", ",", "String", "destinationNetworkId", ",", "String", "humanRequestor", ",", "String", "hl7MessageId", ",", "String", "hl7QueryParameters", ",", "String", "[", "]", "patientIds", ",", "List", "<", "CodedValueType", ">", "purposesOfUse", ",", "List", "<", "CodedValueType", ">", "userRoles", ")", "{", "// Create query event", "QueryEvent", "queryEvent", "=", "new", "QueryEvent", "(", "systemIsSource", ",", "eventOutcome", ",", "transaction", ",", "purposesOfUse", ")", ";", "queryEvent", ".", "setAuditSourceId", "(", "getAuditSourceId", "(", ")", ",", "getAuditEnterpriseSiteId", "(", ")", ")", ";", "// Set the source active participant", "queryEvent", ".", "addSourceActiveParticipant", "(", "EventUtils", ".", "concatHL7FacilityApplication", "(", "sourceFacility", ",", "sourceApp", ")", ",", "sourceAltUserId", ",", "null", ",", "sourceNetworkId", ",", "true", ")", ";", "// Set the human requestor active participant", "if", "(", "!", "EventUtils", ".", "isEmptyOrNull", "(", "humanRequestor", ")", ")", "{", "queryEvent", ".", "addHumanRequestorActiveParticipant", "(", "humanRequestor", ",", "null", ",", "null", ",", "userRoles", ")", ";", "}", "// Set the destination active participant", "queryEvent", ".", "addDestinationActiveParticipant", "(", "EventUtils", ".", "concatHL7FacilityApplication", "(", "destinationFacility", ",", "destinationApp", ")", ",", "destinationAltUserId", ",", "null", ",", "destinationNetworkId", ",", "false", ")", ";", "// Add a patient participant object for each patient id", "if", "(", "!", "EventUtils", ".", "isEmptyOrNull", "(", "patientIds", ")", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "patientIds", ".", "length", ";", "i", "++", ")", "{", "queryEvent", ".", "addPatientParticipantObject", "(", "patientIds", "[", "i", "]", ")", ";", "}", "}", "byte", "[", "]", "queryParamsBytes", "=", "null", ",", "msgControlBytes", "=", "null", ";", "if", "(", "hl7QueryParameters", "!=", "null", ")", "{", "queryParamsBytes", "=", "hl7QueryParameters", ".", "getBytes", "(", ")", ";", "}", "if", "(", "hl7MessageId", "!=", "null", ")", "{", "msgControlBytes", "=", "hl7MessageId", ".", "getBytes", "(", ")", ";", "}", "// Add the Query participant object", "queryEvent", ".", "addQueryParticipantObject", "(", "null", ",", "null", ",", "queryParamsBytes", ",", "msgControlBytes", ",", "transaction", ")", ";", "audit", "(", "queryEvent", ")", ";", "}" ]
Audit a QUERY event for PIX and PDQ transactions. Useful for PIX Query, PDQ Query, and PDVQ Query in the PIX Manager as well as the PIX and PDQ Consumer @param systemIsSource Whether the system sending the message is the source active participant @param transaction IHE Transaction sending the message @param eventOutcome The event outcome indicator @param sourceFacility Source (sending/receiving) facility, from the MSH segment @param sourceApp Source (sending/receiving) application, from the MSH segment @param sourceAltUserId Source Active Participant Alternate User ID @param sourceNetworkId Source Active Participant Network ID @param destinationFacility Destination (sending/receiving) facility, from the MSH segment @param destinationApp Destination (sending/receiving) application, from the MSH segment @param destinationAltUserId Destination Active Participant Alternate User ID @param destinationNetworkId Destination Active Participant Network ID @param humanRequestor Identity of the human that initiated the transaction (if known) @param hl7MessageId The HL7 Message ID (v2 from the MSH segment field 10, v3 from message.Id) @param hl7QueryParameters The HL7 Query Parameters from the QPD segment @param patientIds List of patient IDs that were seen in this transaction @param purposesOfUse purpose of use codes (may be taken from XUA token) @param userRoles roles of the human user (may be taken from XUA token)
[ "Audit", "a", "QUERY", "event", "for", "PIX", "and", "PDQ", "transactions", ".", "Useful", "for", "PIX", "Query", "PDQ", "Query", "and", "PDVQ", "Query", "in", "the", "PIX", "Manager", "as", "well", "as", "the", "PIX", "and", "PDQ", "Consumer" ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/PIXAuditor.java#L55-L95
jenkinsci/jenkins
core/src/main/java/hudson/FilePath.java
FilePath.createTextTempFile
public FilePath createTextTempFile(final String prefix, final String suffix, final String contents, final boolean inThisDirectory) throws IOException, InterruptedException { """ Creates a temporary file in this directory (or the system temporary directory) and set the contents to the given text (encoded in the platform default encoding) @param prefix The prefix string to be used in generating the file's name; must be at least three characters long @param suffix The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used @param contents The initial contents of the temporary file. @param inThisDirectory If true, then create this temporary in the directory pointed to by this. If false, then the temporary file is created in the system temporary directory (java.io.tmpdir) @return The new FilePath pointing to the temporary file @see File#createTempFile(String, String) """ try { return new FilePath(channel, act(new CreateTextTempFile(inThisDirectory, prefix, suffix, contents))); } catch (IOException e) { throw new IOException("Failed to create a temp file on "+remote,e); } }
java
public FilePath createTextTempFile(final String prefix, final String suffix, final String contents, final boolean inThisDirectory) throws IOException, InterruptedException { try { return new FilePath(channel, act(new CreateTextTempFile(inThisDirectory, prefix, suffix, contents))); } catch (IOException e) { throw new IOException("Failed to create a temp file on "+remote,e); } }
[ "public", "FilePath", "createTextTempFile", "(", "final", "String", "prefix", ",", "final", "String", "suffix", ",", "final", "String", "contents", ",", "final", "boolean", "inThisDirectory", ")", "throws", "IOException", ",", "InterruptedException", "{", "try", "{", "return", "new", "FilePath", "(", "channel", ",", "act", "(", "new", "CreateTextTempFile", "(", "inThisDirectory", ",", "prefix", ",", "suffix", ",", "contents", ")", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IOException", "(", "\"Failed to create a temp file on \"", "+", "remote", ",", "e", ")", ";", "}", "}" ]
Creates a temporary file in this directory (or the system temporary directory) and set the contents to the given text (encoded in the platform default encoding) @param prefix The prefix string to be used in generating the file's name; must be at least three characters long @param suffix The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used @param contents The initial contents of the temporary file. @param inThisDirectory If true, then create this temporary in the directory pointed to by this. If false, then the temporary file is created in the system temporary directory (java.io.tmpdir) @return The new FilePath pointing to the temporary file @see File#createTempFile(String, String)
[ "Creates", "a", "temporary", "file", "in", "this", "directory", "(", "or", "the", "system", "temporary", "directory", ")", "and", "set", "the", "contents", "to", "the", "given", "text", "(", "encoded", "in", "the", "platform", "default", "encoding", ")" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/FilePath.java#L1438-L1444
osiam/connector4java
src/main/java/org/osiam/client/OsiamConnector.java
OsiamConnector.createUser
public User createUser(User user, AccessToken accessToken) { """ saves the given {@link User} to the OSIAM DB. @param user user to be saved @param accessToken the OSIAM access token from for the current session @return the same user Object like the given but with filled metadata and a new valid id @throws UnauthorizedException if the request could not be authorized. @throws ConflictException if the User could not be created @throws ForbiddenException if the scope doesn't allow this request @throws ConnectionInitializationException if the connection to the given OSIAM service could not be initialized @throws IllegalStateException if OSIAM's endpoint(s) are not properly configured """ return getUserService().createUser(user, accessToken); }
java
public User createUser(User user, AccessToken accessToken) { return getUserService().createUser(user, accessToken); }
[ "public", "User", "createUser", "(", "User", "user", ",", "AccessToken", "accessToken", ")", "{", "return", "getUserService", "(", ")", ".", "createUser", "(", "user", ",", "accessToken", ")", ";", "}" ]
saves the given {@link User} to the OSIAM DB. @param user user to be saved @param accessToken the OSIAM access token from for the current session @return the same user Object like the given but with filled metadata and a new valid id @throws UnauthorizedException if the request could not be authorized. @throws ConflictException if the User could not be created @throws ForbiddenException if the scope doesn't allow this request @throws ConnectionInitializationException if the connection to the given OSIAM service could not be initialized @throws IllegalStateException if OSIAM's endpoint(s) are not properly configured
[ "saves", "the", "given", "{", "@link", "User", "}", "to", "the", "OSIAM", "DB", "." ]
train
https://github.com/osiam/connector4java/blob/a5e6ae1e706f4889d662a069fe2f3bf8e3848d12/src/main/java/org/osiam/client/OsiamConnector.java#L454-L456
leadware/jpersistence-tools
jpersistence-tools-core/src/main/java/net/leadware/persistence/tools/core/dao/utils/DAOValidatorHelper.java
DAOValidatorHelper.checkContainsInvalidCharacter
public static boolean checkContainsInvalidCharacter(String text, String invalidCharacters) { """ Methode qui teste si une chaine donnee contient un des caracteres d'une liste @param text Chaine dans laquelle on rcherche les caracteres @param invalidCharacters Liste ds caracteres recherches @return Etat de contenance """ if(text == null || text.trim().length() == 0 || invalidCharacters == null) return false; for (char c : invalidCharacters.toCharArray()) { if(text.indexOf(new String(new char[]{c})) >= 0) return true; } return false; }
java
public static boolean checkContainsInvalidCharacter(String text, String invalidCharacters){ if(text == null || text.trim().length() == 0 || invalidCharacters == null) return false; for (char c : invalidCharacters.toCharArray()) { if(text.indexOf(new String(new char[]{c})) >= 0) return true; } return false; }
[ "public", "static", "boolean", "checkContainsInvalidCharacter", "(", "String", "text", ",", "String", "invalidCharacters", ")", "{", "if", "(", "text", "==", "null", "||", "text", ".", "trim", "(", ")", ".", "length", "(", ")", "==", "0", "||", "invalidCharacters", "==", "null", ")", "return", "false", ";", "for", "(", "char", "c", ":", "invalidCharacters", ".", "toCharArray", "(", ")", ")", "{", "if", "(", "text", ".", "indexOf", "(", "new", "String", "(", "new", "char", "[", "]", "{", "c", "}", ")", ")", ">=", "0", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Methode qui teste si une chaine donnee contient un des caracteres d'une liste @param text Chaine dans laquelle on rcherche les caracteres @param invalidCharacters Liste ds caracteres recherches @return Etat de contenance
[ "Methode", "qui", "teste", "si", "une", "chaine", "donnee", "contient", "un", "des", "caracteres", "d", "une", "liste" ]
train
https://github.com/leadware/jpersistence-tools/blob/4c15372993584579d7dbb9b23dd4c0c0fdc9e789/jpersistence-tools-core/src/main/java/net/leadware/persistence/tools/core/dao/utils/DAOValidatorHelper.java#L810-L818
grails/grails-core
grails-web-common/src/main/groovy/org/grails/web/pages/GroovyPagesUriSupport.java
GroovyPagesUriSupport.getTemplateURI
@Override public String getTemplateURI(String controllerName, String templateName, boolean includeExtension) { """ Obtains the URI to a template using the controller name and template name @param controllerName The controller name @param templateName The template name @param includeExtension The flag to include the template extension @return The template URI """ if (templateName.startsWith(SLASH_STR)) { return getAbsoluteTemplateURI(templateName, includeExtension); } else if(templateName.startsWith(RELATIVE_STRING)) { return getRelativeTemplateURIInternal(templateName, includeExtension); } FastStringWriter buf = new FastStringWriter(); String pathToTemplate = BLANK; int lastSlash = templateName.lastIndexOf(SLASH); if (lastSlash > -1) { pathToTemplate = templateName.substring(0, lastSlash + 1); templateName = templateName.substring(lastSlash + 1); } if(controllerName != null) { buf.append(SLASH) .append(controllerName); } buf.append(SLASH) .append(pathToTemplate) .append(UNDERSCORE) .append(templateName); if(includeExtension) { return buf.append(EXTENSION).toString(); } else { return buf.toString(); } }
java
@Override public String getTemplateURI(String controllerName, String templateName, boolean includeExtension) { if (templateName.startsWith(SLASH_STR)) { return getAbsoluteTemplateURI(templateName, includeExtension); } else if(templateName.startsWith(RELATIVE_STRING)) { return getRelativeTemplateURIInternal(templateName, includeExtension); } FastStringWriter buf = new FastStringWriter(); String pathToTemplate = BLANK; int lastSlash = templateName.lastIndexOf(SLASH); if (lastSlash > -1) { pathToTemplate = templateName.substring(0, lastSlash + 1); templateName = templateName.substring(lastSlash + 1); } if(controllerName != null) { buf.append(SLASH) .append(controllerName); } buf.append(SLASH) .append(pathToTemplate) .append(UNDERSCORE) .append(templateName); if(includeExtension) { return buf.append(EXTENSION).toString(); } else { return buf.toString(); } }
[ "@", "Override", "public", "String", "getTemplateURI", "(", "String", "controllerName", ",", "String", "templateName", ",", "boolean", "includeExtension", ")", "{", "if", "(", "templateName", ".", "startsWith", "(", "SLASH_STR", ")", ")", "{", "return", "getAbsoluteTemplateURI", "(", "templateName", ",", "includeExtension", ")", ";", "}", "else", "if", "(", "templateName", ".", "startsWith", "(", "RELATIVE_STRING", ")", ")", "{", "return", "getRelativeTemplateURIInternal", "(", "templateName", ",", "includeExtension", ")", ";", "}", "FastStringWriter", "buf", "=", "new", "FastStringWriter", "(", ")", ";", "String", "pathToTemplate", "=", "BLANK", ";", "int", "lastSlash", "=", "templateName", ".", "lastIndexOf", "(", "SLASH", ")", ";", "if", "(", "lastSlash", ">", "-", "1", ")", "{", "pathToTemplate", "=", "templateName", ".", "substring", "(", "0", ",", "lastSlash", "+", "1", ")", ";", "templateName", "=", "templateName", ".", "substring", "(", "lastSlash", "+", "1", ")", ";", "}", "if", "(", "controllerName", "!=", "null", ")", "{", "buf", ".", "append", "(", "SLASH", ")", ".", "append", "(", "controllerName", ")", ";", "}", "buf", ".", "append", "(", "SLASH", ")", ".", "append", "(", "pathToTemplate", ")", ".", "append", "(", "UNDERSCORE", ")", ".", "append", "(", "templateName", ")", ";", "if", "(", "includeExtension", ")", "{", "return", "buf", ".", "append", "(", "EXTENSION", ")", ".", "toString", "(", ")", ";", "}", "else", "{", "return", "buf", ".", "toString", "(", ")", ";", "}", "}" ]
Obtains the URI to a template using the controller name and template name @param controllerName The controller name @param templateName The template name @param includeExtension The flag to include the template extension @return The template URI
[ "Obtains", "the", "URI", "to", "a", "template", "using", "the", "controller", "name", "and", "template", "name" ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-web-common/src/main/groovy/org/grails/web/pages/GroovyPagesUriSupport.java#L116-L148
gallandarakhneorg/afc
advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapPolyline.java
MapPolyline.getDistance
@Override @Pure public final double getDistance(Point2D<?, ?> point) { """ Replies the distance between this MapElement and point. @return the distance. Should be negative depending of the MapElement type. """ if (isWidePolyline()) { return distance(point, getWidth()); } return distance(point, 0); }
java
@Override @Pure public final double getDistance(Point2D<?, ?> point) { if (isWidePolyline()) { return distance(point, getWidth()); } return distance(point, 0); }
[ "@", "Override", "@", "Pure", "public", "final", "double", "getDistance", "(", "Point2D", "<", "?", ",", "?", ">", "point", ")", "{", "if", "(", "isWidePolyline", "(", ")", ")", "{", "return", "distance", "(", "point", ",", "getWidth", "(", ")", ")", ";", "}", "return", "distance", "(", "point", ",", "0", ")", ";", "}" ]
Replies the distance between this MapElement and point. @return the distance. Should be negative depending of the MapElement type.
[ "Replies", "the", "distance", "between", "this", "MapElement", "and", "point", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapPolyline.java#L133-L140
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/AbstractRegionPainter.java
AbstractRegionPainter.createHorizontalGradient
protected Paint createHorizontalGradient(Shape s, TwoColors colors) { """ Creates a simple horizontal gradient using the shape for bounds and the colors for top and bottom colors. @param s the shape to use for bounds. @param colors the colors to use for the gradient. @return the gradient. """ Rectangle2D bounds = s.getBounds2D(); float xMin = (float) bounds.getMinX(); float xMax = (float) bounds.getMaxX(); float yCenter = (float) bounds.getCenterY(); return createGradient(xMin, yCenter, xMax, yCenter, new float[] { 0f, 1f }, new Color[] { colors.top, colors.bottom }); }
java
protected Paint createHorizontalGradient(Shape s, TwoColors colors) { Rectangle2D bounds = s.getBounds2D(); float xMin = (float) bounds.getMinX(); float xMax = (float) bounds.getMaxX(); float yCenter = (float) bounds.getCenterY(); return createGradient(xMin, yCenter, xMax, yCenter, new float[] { 0f, 1f }, new Color[] { colors.top, colors.bottom }); }
[ "protected", "Paint", "createHorizontalGradient", "(", "Shape", "s", ",", "TwoColors", "colors", ")", "{", "Rectangle2D", "bounds", "=", "s", ".", "getBounds2D", "(", ")", ";", "float", "xMin", "=", "(", "float", ")", "bounds", ".", "getMinX", "(", ")", ";", "float", "xMax", "=", "(", "float", ")", "bounds", ".", "getMaxX", "(", ")", ";", "float", "yCenter", "=", "(", "float", ")", "bounds", ".", "getCenterY", "(", ")", ";", "return", "createGradient", "(", "xMin", ",", "yCenter", ",", "xMax", ",", "yCenter", ",", "new", "float", "[", "]", "{", "0f", ",", "1f", "}", ",", "new", "Color", "[", "]", "{", "colors", ".", "top", ",", "colors", ".", "bottom", "}", ")", ";", "}" ]
Creates a simple horizontal gradient using the shape for bounds and the colors for top and bottom colors. @param s the shape to use for bounds. @param colors the colors to use for the gradient. @return the gradient.
[ "Creates", "a", "simple", "horizontal", "gradient", "using", "the", "shape", "for", "bounds", "and", "the", "colors", "for", "top", "and", "bottom", "colors", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/AbstractRegionPainter.java#L413-L420
cloudant/sync-android
cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/AttachmentManager.java
AttachmentManager.prepareAttachment
protected static PreparedAttachment prepareAttachment(String attachmentsDir, AttachmentStreamFactory attachmentStreamFactory, Attachment attachment, long length, long encodedLength) throws AttachmentException { """ prepare an attachment and check validity of length and encodedLength metadata """ PreparedAttachment pa = new PreparedAttachment(attachment, attachmentsDir, length, attachmentStreamFactory); // check the length on disk is correct: // - plain encoding, length on disk is signalled by the "length" metadata property // - all other encodings, length on disk is signalled by the "encoded_length" metadata property if (pa.attachment.encoding == Attachment.Encoding.Plain) { if (pa.length != length) { throw new AttachmentNotSavedException(String.format("Actual length of %d does not equal expected length of %d", pa.length, length)); } } else { if (pa.encodedLength != encodedLength) { throw new AttachmentNotSavedException(String.format("Actual encoded length of %d does not equal expected encoded length of %d", pa.encodedLength, pa.length)); } } return pa; }
java
protected static PreparedAttachment prepareAttachment(String attachmentsDir, AttachmentStreamFactory attachmentStreamFactory, Attachment attachment, long length, long encodedLength) throws AttachmentException { PreparedAttachment pa = new PreparedAttachment(attachment, attachmentsDir, length, attachmentStreamFactory); // check the length on disk is correct: // - plain encoding, length on disk is signalled by the "length" metadata property // - all other encodings, length on disk is signalled by the "encoded_length" metadata property if (pa.attachment.encoding == Attachment.Encoding.Plain) { if (pa.length != length) { throw new AttachmentNotSavedException(String.format("Actual length of %d does not equal expected length of %d", pa.length, length)); } } else { if (pa.encodedLength != encodedLength) { throw new AttachmentNotSavedException(String.format("Actual encoded length of %d does not equal expected encoded length of %d", pa.encodedLength, pa.length)); } } return pa; }
[ "protected", "static", "PreparedAttachment", "prepareAttachment", "(", "String", "attachmentsDir", ",", "AttachmentStreamFactory", "attachmentStreamFactory", ",", "Attachment", "attachment", ",", "long", "length", ",", "long", "encodedLength", ")", "throws", "AttachmentException", "{", "PreparedAttachment", "pa", "=", "new", "PreparedAttachment", "(", "attachment", ",", "attachmentsDir", ",", "length", ",", "attachmentStreamFactory", ")", ";", "// check the length on disk is correct:", "// - plain encoding, length on disk is signalled by the \"length\" metadata property", "// - all other encodings, length on disk is signalled by the \"encoded_length\" metadata property", "if", "(", "pa", ".", "attachment", ".", "encoding", "==", "Attachment", ".", "Encoding", ".", "Plain", ")", "{", "if", "(", "pa", ".", "length", "!=", "length", ")", "{", "throw", "new", "AttachmentNotSavedException", "(", "String", ".", "format", "(", "\"Actual length of %d does not equal expected length of %d\"", ",", "pa", ".", "length", ",", "length", ")", ")", ";", "}", "}", "else", "{", "if", "(", "pa", ".", "encodedLength", "!=", "encodedLength", ")", "{", "throw", "new", "AttachmentNotSavedException", "(", "String", ".", "format", "(", "\"Actual encoded length of %d does not equal expected encoded length of %d\"", ",", "pa", ".", "encodedLength", ",", "pa", ".", "length", ")", ")", ";", "}", "}", "return", "pa", ";", "}" ]
prepare an attachment and check validity of length and encodedLength metadata
[ "prepare", "an", "attachment", "and", "check", "validity", "of", "length", "and", "encodedLength", "metadata" ]
train
https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/AttachmentManager.java#L212-L228
alkacon/opencms-core
src-modules/org/opencms/workplace/commons/CmsPreferences.java
CmsPreferences.buildSelectEditorButtonStyle
public String buildSelectEditorButtonStyle(String htmlAttributes) { """ Builds the html for the editor button style select box.<p> @param htmlAttributes optional html attributes for the &lgt;select&gt; tag @return the html for the editor button style select box """ int selectedIndex = Integer.parseInt(getParamTabEdButtonStyle()); return buildSelectButtonStyle(htmlAttributes, selectedIndex); }
java
public String buildSelectEditorButtonStyle(String htmlAttributes) { int selectedIndex = Integer.parseInt(getParamTabEdButtonStyle()); return buildSelectButtonStyle(htmlAttributes, selectedIndex); }
[ "public", "String", "buildSelectEditorButtonStyle", "(", "String", "htmlAttributes", ")", "{", "int", "selectedIndex", "=", "Integer", ".", "parseInt", "(", "getParamTabEdButtonStyle", "(", ")", ")", ";", "return", "buildSelectButtonStyle", "(", "htmlAttributes", ",", "selectedIndex", ")", ";", "}" ]
Builds the html for the editor button style select box.<p> @param htmlAttributes optional html attributes for the &lgt;select&gt; tag @return the html for the editor button style select box
[ "Builds", "the", "html", "for", "the", "editor", "button", "style", "select", "box", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsPreferences.java#L657-L661
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/EventSerializer.java
EventSerializer.isEvent
public static boolean isEvent(Buffer buffer, Class<?> eventClass) throws IOException { """ Identifies whether the given buffer encodes the given event. Custom events are not supported. @param buffer the buffer to peak into @param eventClass the expected class of the event type @return whether the event class of the <tt>buffer</tt> matches the given <tt>eventClass</tt> """ return !buffer.isBuffer() && isEvent(buffer.getNioBufferReadable(), eventClass); }
java
public static boolean isEvent(Buffer buffer, Class<?> eventClass) throws IOException { return !buffer.isBuffer() && isEvent(buffer.getNioBufferReadable(), eventClass); }
[ "public", "static", "boolean", "isEvent", "(", "Buffer", "buffer", ",", "Class", "<", "?", ">", "eventClass", ")", "throws", "IOException", "{", "return", "!", "buffer", ".", "isBuffer", "(", ")", "&&", "isEvent", "(", "buffer", ".", "getNioBufferReadable", "(", ")", ",", "eventClass", ")", ";", "}" ]
Identifies whether the given buffer encodes the given event. Custom events are not supported. @param buffer the buffer to peak into @param eventClass the expected class of the event type @return whether the event class of the <tt>buffer</tt> matches the given <tt>eventClass</tt>
[ "Identifies", "whether", "the", "given", "buffer", "encodes", "the", "given", "event", ".", "Custom", "events", "are", "not", "supported", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/EventSerializer.java#L306-L308
infinispan/infinispan
extended-statistics/src/main/java/org/infinispan/stats/CacheStatisticManager.java
CacheStatisticManager.terminateTransaction
public final void terminateTransaction(GlobalTransaction globalTransaction, boolean local, boolean remote) { """ Signals the ending of a transaction. After this, no more statistics are updated for this transaction and the values measured are merged with the cache statistics. @param local {@code true} if the transaction is local. @param remote {@code true} if the transaction is remote. """ TransactionStatistics txs = null; if (local) { txs = removeTransactionStatistic(globalTransaction, true); } if (txs != null) { txs.terminateTransaction(); cacheStatisticCollector.merge(txs); txs = null; } if (remote) { txs = removeTransactionStatistic(globalTransaction, false); } if (txs != null) { txs.terminateTransaction(); cacheStatisticCollector.merge(txs); } }
java
public final void terminateTransaction(GlobalTransaction globalTransaction, boolean local, boolean remote) { TransactionStatistics txs = null; if (local) { txs = removeTransactionStatistic(globalTransaction, true); } if (txs != null) { txs.terminateTransaction(); cacheStatisticCollector.merge(txs); txs = null; } if (remote) { txs = removeTransactionStatistic(globalTransaction, false); } if (txs != null) { txs.terminateTransaction(); cacheStatisticCollector.merge(txs); } }
[ "public", "final", "void", "terminateTransaction", "(", "GlobalTransaction", "globalTransaction", ",", "boolean", "local", ",", "boolean", "remote", ")", "{", "TransactionStatistics", "txs", "=", "null", ";", "if", "(", "local", ")", "{", "txs", "=", "removeTransactionStatistic", "(", "globalTransaction", ",", "true", ")", ";", "}", "if", "(", "txs", "!=", "null", ")", "{", "txs", ".", "terminateTransaction", "(", ")", ";", "cacheStatisticCollector", ".", "merge", "(", "txs", ")", ";", "txs", "=", "null", ";", "}", "if", "(", "remote", ")", "{", "txs", "=", "removeTransactionStatistic", "(", "globalTransaction", ",", "false", ")", ";", "}", "if", "(", "txs", "!=", "null", ")", "{", "txs", ".", "terminateTransaction", "(", ")", ";", "cacheStatisticCollector", ".", "merge", "(", "txs", ")", ";", "}", "}" ]
Signals the ending of a transaction. After this, no more statistics are updated for this transaction and the values measured are merged with the cache statistics. @param local {@code true} if the transaction is local. @param remote {@code true} if the transaction is remote.
[ "Signals", "the", "ending", "of", "a", "transaction", ".", "After", "this", "no", "more", "statistics", "are", "updated", "for", "this", "transaction", "and", "the", "values", "measured", "are", "merged", "with", "the", "cache", "statistics", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/extended-statistics/src/main/java/org/infinispan/stats/CacheStatisticManager.java#L192-L210
apache/incubator-druid
core/src/main/java/org/apache/druid/java/util/common/lifecycle/Lifecycle.java
Lifecycle.addHandler
public void addHandler(Handler handler, Stage stage) { """ Adds a handler to the Lifecycle. If the lifecycle has already been started, it throws an {@link ISE} @param handler The hander to add to the lifecycle @param stage The stage to add the lifecycle at @throws ISE indicates that the lifecycle has already been started and thus cannot be added to """ if (!startStopLock.tryLock()) { throw new ISE("Cannot add a handler in the process of Lifecycle starting or stopping"); } try { if (!state.get().equals(State.NOT_STARTED)) { throw new ISE("Cannot add a handler after the Lifecycle has started, it doesn't work that way."); } handlers.get(stage).add(handler); } finally { startStopLock.unlock(); } }
java
public void addHandler(Handler handler, Stage stage) { if (!startStopLock.tryLock()) { throw new ISE("Cannot add a handler in the process of Lifecycle starting or stopping"); } try { if (!state.get().equals(State.NOT_STARTED)) { throw new ISE("Cannot add a handler after the Lifecycle has started, it doesn't work that way."); } handlers.get(stage).add(handler); } finally { startStopLock.unlock(); } }
[ "public", "void", "addHandler", "(", "Handler", "handler", ",", "Stage", "stage", ")", "{", "if", "(", "!", "startStopLock", ".", "tryLock", "(", ")", ")", "{", "throw", "new", "ISE", "(", "\"Cannot add a handler in the process of Lifecycle starting or stopping\"", ")", ";", "}", "try", "{", "if", "(", "!", "state", ".", "get", "(", ")", ".", "equals", "(", "State", ".", "NOT_STARTED", ")", ")", "{", "throw", "new", "ISE", "(", "\"Cannot add a handler after the Lifecycle has started, it doesn't work that way.\"", ")", ";", "}", "handlers", ".", "get", "(", "stage", ")", ".", "add", "(", "handler", ")", ";", "}", "finally", "{", "startStopLock", ".", "unlock", "(", ")", ";", "}", "}" ]
Adds a handler to the Lifecycle. If the lifecycle has already been started, it throws an {@link ISE} @param handler The hander to add to the lifecycle @param stage The stage to add the lifecycle at @throws ISE indicates that the lifecycle has already been started and thus cannot be added to
[ "Adds", "a", "handler", "to", "the", "Lifecycle", ".", "If", "the", "lifecycle", "has", "already", "been", "started", "it", "throws", "an", "{", "@link", "ISE", "}" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/java/util/common/lifecycle/Lifecycle.java#L195-L209
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.deleteLogEntries
public void deleteLogEntries(CmsDbContext dbc, CmsLogFilter filter) throws CmsException { """ Deletes all log entries matching the given filter.<p> @param dbc the current db context @param filter the filter to use for deletion @throws CmsException if something goes wrong @see CmsSecurityManager#deleteLogEntries(CmsRequestContext, CmsLogFilter) """ updateLog(dbc); m_projectDriver.deleteLog(dbc, filter); }
java
public void deleteLogEntries(CmsDbContext dbc, CmsLogFilter filter) throws CmsException { updateLog(dbc); m_projectDriver.deleteLog(dbc, filter); }
[ "public", "void", "deleteLogEntries", "(", "CmsDbContext", "dbc", ",", "CmsLogFilter", "filter", ")", "throws", "CmsException", "{", "updateLog", "(", "dbc", ")", ";", "m_projectDriver", ".", "deleteLog", "(", "dbc", ",", "filter", ")", ";", "}" ]
Deletes all log entries matching the given filter.<p> @param dbc the current db context @param filter the filter to use for deletion @throws CmsException if something goes wrong @see CmsSecurityManager#deleteLogEntries(CmsRequestContext, CmsLogFilter)
[ "Deletes", "all", "log", "entries", "matching", "the", "given", "filter", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L2557-L2561
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CRLImpl.java
X509CRLImpl.getIssuerX500Principal
public static X500Principal getIssuerX500Principal(X509CRL crl) { """ Extract the issuer X500Principal from an X509CRL. Parses the encoded form of the CRL to preserve the principal's ASN.1 encoding. Called by java.security.cert.X509CRL.getIssuerX500Principal(). """ try { byte[] encoded = crl.getEncoded(); DerInputStream derIn = new DerInputStream(encoded); DerValue tbsCert = derIn.getSequence(3)[0]; DerInputStream tbsIn = tbsCert.data; DerValue tmp; // skip version number if present byte nextByte = (byte)tbsIn.peekByte(); if (nextByte == DerValue.tag_Integer) { tmp = tbsIn.getDerValue(); } tmp = tbsIn.getDerValue(); // skip signature tmp = tbsIn.getDerValue(); // issuer byte[] principalBytes = tmp.toByteArray(); return new X500Principal(principalBytes); } catch (Exception e) { throw new RuntimeException("Could not parse issuer", e); } }
java
public static X500Principal getIssuerX500Principal(X509CRL crl) { try { byte[] encoded = crl.getEncoded(); DerInputStream derIn = new DerInputStream(encoded); DerValue tbsCert = derIn.getSequence(3)[0]; DerInputStream tbsIn = tbsCert.data; DerValue tmp; // skip version number if present byte nextByte = (byte)tbsIn.peekByte(); if (nextByte == DerValue.tag_Integer) { tmp = tbsIn.getDerValue(); } tmp = tbsIn.getDerValue(); // skip signature tmp = tbsIn.getDerValue(); // issuer byte[] principalBytes = tmp.toByteArray(); return new X500Principal(principalBytes); } catch (Exception e) { throw new RuntimeException("Could not parse issuer", e); } }
[ "public", "static", "X500Principal", "getIssuerX500Principal", "(", "X509CRL", "crl", ")", "{", "try", "{", "byte", "[", "]", "encoded", "=", "crl", ".", "getEncoded", "(", ")", ";", "DerInputStream", "derIn", "=", "new", "DerInputStream", "(", "encoded", ")", ";", "DerValue", "tbsCert", "=", "derIn", ".", "getSequence", "(", "3", ")", "[", "0", "]", ";", "DerInputStream", "tbsIn", "=", "tbsCert", ".", "data", ";", "DerValue", "tmp", ";", "// skip version number if present", "byte", "nextByte", "=", "(", "byte", ")", "tbsIn", ".", "peekByte", "(", ")", ";", "if", "(", "nextByte", "==", "DerValue", ".", "tag_Integer", ")", "{", "tmp", "=", "tbsIn", ".", "getDerValue", "(", ")", ";", "}", "tmp", "=", "tbsIn", ".", "getDerValue", "(", ")", ";", "// skip signature", "tmp", "=", "tbsIn", ".", "getDerValue", "(", ")", ";", "// issuer", "byte", "[", "]", "principalBytes", "=", "tmp", ".", "toByteArray", "(", ")", ";", "return", "new", "X500Principal", "(", "principalBytes", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Could not parse issuer\"", ",", "e", ")", ";", "}", "}" ]
Extract the issuer X500Principal from an X509CRL. Parses the encoded form of the CRL to preserve the principal's ASN.1 encoding. Called by java.security.cert.X509CRL.getIssuerX500Principal().
[ "Extract", "the", "issuer", "X500Principal", "from", "an", "X509CRL", ".", "Parses", "the", "encoded", "form", "of", "the", "CRL", "to", "preserve", "the", "principal", "s", "ASN", ".", "1", "encoding", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CRLImpl.java#L1131-L1152
ckpoint/CheckPoint
src/main/java/hsim/checkpoint/util/ValidationObjUtil.java
ValidationObjUtil.getSetterMethodNotCheckParamType
public static Method getSetterMethodNotCheckParamType(Class<?> cType, String fieldName) { """ Gets setter method not check param type. @param cType the c type @param fieldName the field name @return the setter method not check param type """ String methodName = getMethodName(fieldName, SET_METHOD_PREFIX); Method[] methods = cType.getMethods(); for (Method m : methods) { if (m.getName().equals(methodName) && m.getParameterCount() == 1) { return m; } } return null; }
java
public static Method getSetterMethodNotCheckParamType(Class<?> cType, String fieldName) { String methodName = getMethodName(fieldName, SET_METHOD_PREFIX); Method[] methods = cType.getMethods(); for (Method m : methods) { if (m.getName().equals(methodName) && m.getParameterCount() == 1) { return m; } } return null; }
[ "public", "static", "Method", "getSetterMethodNotCheckParamType", "(", "Class", "<", "?", ">", "cType", ",", "String", "fieldName", ")", "{", "String", "methodName", "=", "getMethodName", "(", "fieldName", ",", "SET_METHOD_PREFIX", ")", ";", "Method", "[", "]", "methods", "=", "cType", ".", "getMethods", "(", ")", ";", "for", "(", "Method", "m", ":", "methods", ")", "{", "if", "(", "m", ".", "getName", "(", ")", ".", "equals", "(", "methodName", ")", "&&", "m", ".", "getParameterCount", "(", ")", "==", "1", ")", "{", "return", "m", ";", "}", "}", "return", "null", ";", "}" ]
Gets setter method not check param type. @param cType the c type @param fieldName the field name @return the setter method not check param type
[ "Gets", "setter", "method", "not", "check", "param", "type", "." ]
train
https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/util/ValidationObjUtil.java#L141-L150
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBDeleteExpression.java
DynamoDBDeleteExpression.withExpectedEntry
public DynamoDBDeleteExpression withExpectedEntry(String attributeName, ExpectedAttributeValue expected) { """ Adds one entry to the expected conditions and returns a pointer to this object for method-chaining. @param attributeName The name of the attribute. @param expected The expected attribute value. """ if (expectedAttributes == null) { expectedAttributes = new HashMap<String,ExpectedAttributeValue>(); } expectedAttributes.put(attributeName, expected); return this; }
java
public DynamoDBDeleteExpression withExpectedEntry(String attributeName, ExpectedAttributeValue expected) { if (expectedAttributes == null) { expectedAttributes = new HashMap<String,ExpectedAttributeValue>(); } expectedAttributes.put(attributeName, expected); return this; }
[ "public", "DynamoDBDeleteExpression", "withExpectedEntry", "(", "String", "attributeName", ",", "ExpectedAttributeValue", "expected", ")", "{", "if", "(", "expectedAttributes", "==", "null", ")", "{", "expectedAttributes", "=", "new", "HashMap", "<", "String", ",", "ExpectedAttributeValue", ">", "(", ")", ";", "}", "expectedAttributes", ".", "put", "(", "attributeName", ",", "expected", ")", ";", "return", "this", ";", "}" ]
Adds one entry to the expected conditions and returns a pointer to this object for method-chaining. @param attributeName The name of the attribute. @param expected The expected attribute value.
[ "Adds", "one", "entry", "to", "the", "expected", "conditions", "and", "returns", "a", "pointer", "to", "this", "object", "for", "method", "-", "chaining", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBDeleteExpression.java#L98-L104
outbrain/ob1k
ob1k-core/src/main/java/com/outbrain/ob1k/server/netty/HttpStaticFileServerHandler.java
HttpStaticFileServerHandler.setDateHeader
private static void setDateHeader(final FullHttpResponse response) { """ Sets the Date header for the HTTP response @param response HTTP response """ final SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE)); final Calendar time = new GregorianCalendar(); response.headers().set(DATE, dateFormatter.format(time.getTime())); }
java
private static void setDateHeader(final FullHttpResponse response) { final SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE)); final Calendar time = new GregorianCalendar(); response.headers().set(DATE, dateFormatter.format(time.getTime())); }
[ "private", "static", "void", "setDateHeader", "(", "final", "FullHttpResponse", "response", ")", "{", "final", "SimpleDateFormat", "dateFormatter", "=", "new", "SimpleDateFormat", "(", "HTTP_DATE_FORMAT", ",", "Locale", ".", "US", ")", ";", "dateFormatter", ".", "setTimeZone", "(", "TimeZone", ".", "getTimeZone", "(", "HTTP_DATE_GMT_TIMEZONE", ")", ")", ";", "final", "Calendar", "time", "=", "new", "GregorianCalendar", "(", ")", ";", "response", ".", "headers", "(", ")", ".", "set", "(", "DATE", ",", "dateFormatter", ".", "format", "(", "time", ".", "getTime", "(", ")", ")", ")", ";", "}" ]
Sets the Date header for the HTTP response @param response HTTP response
[ "Sets", "the", "Date", "header", "for", "the", "HTTP", "response" ]
train
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-core/src/main/java/com/outbrain/ob1k/server/netty/HttpStaticFileServerHandler.java#L213-L219
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/AbstractColumnFamilyOutputFormat.java
AbstractColumnFamilyOutputFormat.createAuthenticatedClient
public static Cassandra.Client createAuthenticatedClient(String host, int port, Configuration conf) throws Exception { """ Connects to the given server:port and returns a client based on the given socket that points to the configured keyspace, and is logged in with the configured credentials. @param host fully qualified host name to connect to @param port RPC port of the server @param conf a job configuration @return a cassandra client @throws Exception set of thrown exceptions may be implementation defined, depending on the used transport factory """ logger.debug("Creating authenticated client for CF output format"); TTransport transport = ConfigHelper.getClientTransportFactory(conf).openTransport(host, port); TProtocol binaryProtocol = new TBinaryProtocol(transport, true, true); Cassandra.Client client = new Cassandra.Client(binaryProtocol); client.set_keyspace(ConfigHelper.getOutputKeyspace(conf)); String user = ConfigHelper.getOutputKeyspaceUserName(conf); String password = ConfigHelper.getOutputKeyspacePassword(conf); if ((user != null) && (password != null)) login(user, password, client); logger.debug("Authenticated client for CF output format created successfully"); return client; }
java
public static Cassandra.Client createAuthenticatedClient(String host, int port, Configuration conf) throws Exception { logger.debug("Creating authenticated client for CF output format"); TTransport transport = ConfigHelper.getClientTransportFactory(conf).openTransport(host, port); TProtocol binaryProtocol = new TBinaryProtocol(transport, true, true); Cassandra.Client client = new Cassandra.Client(binaryProtocol); client.set_keyspace(ConfigHelper.getOutputKeyspace(conf)); String user = ConfigHelper.getOutputKeyspaceUserName(conf); String password = ConfigHelper.getOutputKeyspacePassword(conf); if ((user != null) && (password != null)) login(user, password, client); logger.debug("Authenticated client for CF output format created successfully"); return client; }
[ "public", "static", "Cassandra", ".", "Client", "createAuthenticatedClient", "(", "String", "host", ",", "int", "port", ",", "Configuration", "conf", ")", "throws", "Exception", "{", "logger", ".", "debug", "(", "\"Creating authenticated client for CF output format\"", ")", ";", "TTransport", "transport", "=", "ConfigHelper", ".", "getClientTransportFactory", "(", "conf", ")", ".", "openTransport", "(", "host", ",", "port", ")", ";", "TProtocol", "binaryProtocol", "=", "new", "TBinaryProtocol", "(", "transport", ",", "true", ",", "true", ")", ";", "Cassandra", ".", "Client", "client", "=", "new", "Cassandra", ".", "Client", "(", "binaryProtocol", ")", ";", "client", ".", "set_keyspace", "(", "ConfigHelper", ".", "getOutputKeyspace", "(", "conf", ")", ")", ";", "String", "user", "=", "ConfigHelper", ".", "getOutputKeyspaceUserName", "(", "conf", ")", ";", "String", "password", "=", "ConfigHelper", ".", "getOutputKeyspacePassword", "(", "conf", ")", ";", "if", "(", "(", "user", "!=", "null", ")", "&&", "(", "password", "!=", "null", ")", ")", "login", "(", "user", ",", "password", ",", "client", ")", ";", "logger", ".", "debug", "(", "\"Authenticated client for CF output format created successfully\"", ")", ";", "return", "client", ";", "}" ]
Connects to the given server:port and returns a client based on the given socket that points to the configured keyspace, and is logged in with the configured credentials. @param host fully qualified host name to connect to @param port RPC port of the server @param conf a job configuration @return a cassandra client @throws Exception set of thrown exceptions may be implementation defined, depending on the used transport factory
[ "Connects", "to", "the", "given", "server", ":", "port", "and", "returns", "a", "client", "based", "on", "the", "given", "socket", "that", "points", "to", "the", "configured", "keyspace", "and", "is", "logged", "in", "with", "the", "configured", "credentials", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/AbstractColumnFamilyOutputFormat.java#L120-L134
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/io/GeoPackageIOUtils.java
GeoPackageIOUtils.copyStream
public static void copyStream(InputStream copyFrom, File copyTo) throws IOException { """ Copy an input stream to a file location @param copyFrom from file @param copyTo to file @throws IOException upon failure """ copyStream(copyFrom, copyTo, null); }
java
public static void copyStream(InputStream copyFrom, File copyTo) throws IOException { copyStream(copyFrom, copyTo, null); }
[ "public", "static", "void", "copyStream", "(", "InputStream", "copyFrom", ",", "File", "copyTo", ")", "throws", "IOException", "{", "copyStream", "(", "copyFrom", ",", "copyTo", ",", "null", ")", ";", "}" ]
Copy an input stream to a file location @param copyFrom from file @param copyTo to file @throws IOException upon failure
[ "Copy", "an", "input", "stream", "to", "a", "file", "location" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/io/GeoPackageIOUtils.java#L121-L124
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UnicodeSetStringSpan.java
UnicodeSetStringSpan.matches16
private static boolean matches16(CharSequence s, int start, final String t, int length) { """ Compare strings without any argument checks. Requires length>0. """ int end = start + length; while (length-- > 0) { if (s.charAt(--end) != t.charAt(length)) { return false; } } return true; }
java
private static boolean matches16(CharSequence s, int start, final String t, int length) { int end = start + length; while (length-- > 0) { if (s.charAt(--end) != t.charAt(length)) { return false; } } return true; }
[ "private", "static", "boolean", "matches16", "(", "CharSequence", "s", ",", "int", "start", ",", "final", "String", "t", ",", "int", "length", ")", "{", "int", "end", "=", "start", "+", "length", ";", "while", "(", "length", "--", ">", "0", ")", "{", "if", "(", "s", ".", "charAt", "(", "--", "end", ")", "!=", "t", ".", "charAt", "(", "length", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Compare strings without any argument checks. Requires length>0.
[ "Compare", "strings", "without", "any", "argument", "checks", ".", "Requires", "length", ">", "0", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UnicodeSetStringSpan.java#L944-L952
google/closure-compiler
src/com/google/javascript/jscomp/TypeValidator.java
TypeValidator.expectAsyncGeneratorSupertype
void expectAsyncGeneratorSupertype(Node n, JSType type, String msg) { """ Expect the type to be a AsyncGenerator or supertype of AsyncGenerator. """ if (!getNativeType(ASYNC_GENERATOR_TYPE).isSubtypeOf(type)) { mismatch(n, msg, type, ASYNC_GENERATOR_TYPE); } }
java
void expectAsyncGeneratorSupertype(Node n, JSType type, String msg) { if (!getNativeType(ASYNC_GENERATOR_TYPE).isSubtypeOf(type)) { mismatch(n, msg, type, ASYNC_GENERATOR_TYPE); } }
[ "void", "expectAsyncGeneratorSupertype", "(", "Node", "n", ",", "JSType", "type", ",", "String", "msg", ")", "{", "if", "(", "!", "getNativeType", "(", "ASYNC_GENERATOR_TYPE", ")", ".", "isSubtypeOf", "(", "type", ")", ")", "{", "mismatch", "(", "n", ",", "msg", ",", "type", ",", "ASYNC_GENERATOR_TYPE", ")", ";", "}", "}" ]
Expect the type to be a AsyncGenerator or supertype of AsyncGenerator.
[ "Expect", "the", "type", "to", "be", "a", "AsyncGenerator", "or", "supertype", "of", "AsyncGenerator", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeValidator.java#L330-L334
pressgang-ccms/PressGangCCMSContentSpecProcessor
src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecValidator.java
ContentSpecValidator.doesPublicanCfgsContainValue
private boolean doesPublicanCfgsContainValue(final ContentSpec contentSpec, final String value) { """ Check if the default or additional publican cfg files have a specified value @param contentSpec The content spec to check from. @param value The value to check for. eg: mainfile @return True if the value exists in any publican.cfg """ final Pattern pattern = Pattern.compile("^(.*\\n)?( |\\t)*" + value + ":.*", java.util.regex.Pattern.DOTALL); if (!isNullOrEmpty(contentSpec.getPublicanCfg()) && pattern.matcher(contentSpec.getPublicanCfg()).matches()) { return true; } else if (!contentSpec.getAllAdditionalPublicanCfgs().isEmpty()) { for (final Entry<String, String> entry : contentSpec.getAllAdditionalPublicanCfgs().entrySet()) { if (!isNullOrEmpty(entry.getValue()) && pattern.matcher(entry.getValue()).matches()) { return true; } } } return false; }
java
private boolean doesPublicanCfgsContainValue(final ContentSpec contentSpec, final String value) { final Pattern pattern = Pattern.compile("^(.*\\n)?( |\\t)*" + value + ":.*", java.util.regex.Pattern.DOTALL); if (!isNullOrEmpty(contentSpec.getPublicanCfg()) && pattern.matcher(contentSpec.getPublicanCfg()).matches()) { return true; } else if (!contentSpec.getAllAdditionalPublicanCfgs().isEmpty()) { for (final Entry<String, String> entry : contentSpec.getAllAdditionalPublicanCfgs().entrySet()) { if (!isNullOrEmpty(entry.getValue()) && pattern.matcher(entry.getValue()).matches()) { return true; } } } return false; }
[ "private", "boolean", "doesPublicanCfgsContainValue", "(", "final", "ContentSpec", "contentSpec", ",", "final", "String", "value", ")", "{", "final", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "\"^(.*\\\\n)?( |\\\\t)*\"", "+", "value", "+", "\":.*\"", ",", "java", ".", "util", ".", "regex", ".", "Pattern", ".", "DOTALL", ")", ";", "if", "(", "!", "isNullOrEmpty", "(", "contentSpec", ".", "getPublicanCfg", "(", ")", ")", "&&", "pattern", ".", "matcher", "(", "contentSpec", ".", "getPublicanCfg", "(", ")", ")", ".", "matches", "(", ")", ")", "{", "return", "true", ";", "}", "else", "if", "(", "!", "contentSpec", ".", "getAllAdditionalPublicanCfgs", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "final", "Entry", "<", "String", ",", "String", ">", "entry", ":", "contentSpec", ".", "getAllAdditionalPublicanCfgs", "(", ")", ".", "entrySet", "(", ")", ")", "{", "if", "(", "!", "isNullOrEmpty", "(", "entry", ".", "getValue", "(", ")", ")", "&&", "pattern", ".", "matcher", "(", "entry", ".", "getValue", "(", ")", ")", ".", "matches", "(", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Check if the default or additional publican cfg files have a specified value @param contentSpec The content spec to check from. @param value The value to check for. eg: mainfile @return True if the value exists in any publican.cfg
[ "Check", "if", "the", "default", "or", "additional", "publican", "cfg", "files", "have", "a", "specified", "value" ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpecProcessor/blob/85ffac047c4ede0f972364ab1f03f7d61a4de5f1/src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecValidator.java#L466-L479
lkwg82/enforcer-rules
src/main/java/org/apache/maven/plugins/enforcer/AbstractVersionEnforcer.java
AbstractVersionEnforcer.containsVersion
public static boolean containsVersion( VersionRange allowedRange, ArtifactVersion theVersion ) { """ Copied from Artifact.VersionRange. This is tweaked to handle singular ranges properly. Currently the default containsVersion method assumes a singular version means allow everything. This method assumes that "2.0.4" == "[2.0.4,)" @param allowedRange range of allowed versions. @param theVersion the version to be checked. @return true if the version is contained by the range. """ boolean matched = false; ArtifactVersion recommendedVersion = allowedRange.getRecommendedVersion(); if ( recommendedVersion == null ) { @SuppressWarnings( "unchecked" ) List<Restriction> restrictions = allowedRange.getRestrictions(); for ( Restriction restriction : restrictions ) { if ( restriction.containsVersion( theVersion ) ) { matched = true; break; } } } else { // only singular versions ever have a recommendedVersion @SuppressWarnings( "unchecked" ) int compareTo = recommendedVersion.compareTo( theVersion ); matched = ( compareTo <= 0 ); } return matched; }
java
public static boolean containsVersion( VersionRange allowedRange, ArtifactVersion theVersion ) { boolean matched = false; ArtifactVersion recommendedVersion = allowedRange.getRecommendedVersion(); if ( recommendedVersion == null ) { @SuppressWarnings( "unchecked" ) List<Restriction> restrictions = allowedRange.getRestrictions(); for ( Restriction restriction : restrictions ) { if ( restriction.containsVersion( theVersion ) ) { matched = true; break; } } } else { // only singular versions ever have a recommendedVersion @SuppressWarnings( "unchecked" ) int compareTo = recommendedVersion.compareTo( theVersion ); matched = ( compareTo <= 0 ); } return matched; }
[ "public", "static", "boolean", "containsVersion", "(", "VersionRange", "allowedRange", ",", "ArtifactVersion", "theVersion", ")", "{", "boolean", "matched", "=", "false", ";", "ArtifactVersion", "recommendedVersion", "=", "allowedRange", ".", "getRecommendedVersion", "(", ")", ";", "if", "(", "recommendedVersion", "==", "null", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "List", "<", "Restriction", ">", "restrictions", "=", "allowedRange", ".", "getRestrictions", "(", ")", ";", "for", "(", "Restriction", "restriction", ":", "restrictions", ")", "{", "if", "(", "restriction", ".", "containsVersion", "(", "theVersion", ")", ")", "{", "matched", "=", "true", ";", "break", ";", "}", "}", "}", "else", "{", "// only singular versions ever have a recommendedVersion", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "int", "compareTo", "=", "recommendedVersion", ".", "compareTo", "(", "theVersion", ")", ";", "matched", "=", "(", "compareTo", "<=", "0", ")", ";", "}", "return", "matched", ";", "}" ]
Copied from Artifact.VersionRange. This is tweaked to handle singular ranges properly. Currently the default containsVersion method assumes a singular version means allow everything. This method assumes that "2.0.4" == "[2.0.4,)" @param allowedRange range of allowed versions. @param theVersion the version to be checked. @return true if the version is contained by the range.
[ "Copied", "from", "Artifact", ".", "VersionRange", ".", "This", "is", "tweaked", "to", "handle", "singular", "ranges", "properly", ".", "Currently", "the", "default", "containsVersion", "method", "assumes", "a", "singular", "version", "means", "allow", "everything", ".", "This", "method", "assumes", "that", "2", ".", "0", ".", "4", "==", "[", "2", ".", "0", ".", "4", ")" ]
train
https://github.com/lkwg82/enforcer-rules/blob/fa2d309af7907b17fc8eaf386f8056d77b654749/src/main/java/org/apache/maven/plugins/enforcer/AbstractVersionEnforcer.java#L127-L152
fcrepo3/fcrepo
fcrepo-security/fcrepo-security-pep/src/main/java/org/fcrepo/server/security/xacml/pep/rest/PEP.java
PEP.denyAccess
private void denyAccess(HttpServletResponse response, String message) throws IOException { """ Outputs an access denied message. @param out the output stream to send the message to @param message the message to send """ StringBuilder sb = new StringBuilder(); sb.append("Fedora: 403 ").append(message.toUpperCase()); response.reset(); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.setContentType("text/plain"); response.setContentLength(sb.length()); ServletOutputStream out = response.getOutputStream(); out.write(sb.toString().getBytes()); out.flush(); out.close(); }
java
private void denyAccess(HttpServletResponse response, String message) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("Fedora: 403 ").append(message.toUpperCase()); response.reset(); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.setContentType("text/plain"); response.setContentLength(sb.length()); ServletOutputStream out = response.getOutputStream(); out.write(sb.toString().getBytes()); out.flush(); out.close(); }
[ "private", "void", "denyAccess", "(", "HttpServletResponse", "response", ",", "String", "message", ")", "throws", "IOException", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"Fedora: 403 \"", ")", ".", "append", "(", "message", ".", "toUpperCase", "(", ")", ")", ";", "response", ".", "reset", "(", ")", ";", "response", ".", "setStatus", "(", "HttpServletResponse", ".", "SC_FORBIDDEN", ")", ";", "response", ".", "setContentType", "(", "\"text/plain\"", ")", ";", "response", ".", "setContentLength", "(", "sb", ".", "length", "(", ")", ")", ";", "ServletOutputStream", "out", "=", "response", ".", "getOutputStream", "(", ")", ";", "out", ".", "write", "(", "sb", ".", "toString", "(", ")", ".", "getBytes", "(", ")", ")", ";", "out", ".", "flush", "(", ")", ";", "out", ".", "close", "(", ")", ";", "}" ]
Outputs an access denied message. @param out the output stream to send the message to @param message the message to send
[ "Outputs", "an", "access", "denied", "message", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-security/fcrepo-security-pep/src/main/java/org/fcrepo/server/security/xacml/pep/rest/PEP.java#L266-L279
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/TableProcessor.java
TableProcessor.onFamilyType
private void onFamilyType(EntityMetadata entityMetadata, final Class clazz, Field f) { """ On family type. @param entityMetadata the entity metadata @param clazz the clazz @param f the f """ if (entityMetadata.getType() == null || !entityMetadata.getType().equals(Type.SUPER_COLUMN_FAMILY)) { if ((f.isAnnotationPresent(Embedded.class) && f.getType().getAnnotation(Embeddable.class) != null)) { entityMetadata.setType(Type.SUPER_COLUMN_FAMILY); } else if (f.isAnnotationPresent(ElementCollection.class) && !MetadataUtils.isBasicElementCollectionField(f)) { entityMetadata.setType(Type.SUPER_COLUMN_FAMILY); } else { entityMetadata.setType(Type.COLUMN_FAMILY); } } }
java
private void onFamilyType(EntityMetadata entityMetadata, final Class clazz, Field f) { if (entityMetadata.getType() == null || !entityMetadata.getType().equals(Type.SUPER_COLUMN_FAMILY)) { if ((f.isAnnotationPresent(Embedded.class) && f.getType().getAnnotation(Embeddable.class) != null)) { entityMetadata.setType(Type.SUPER_COLUMN_FAMILY); } else if (f.isAnnotationPresent(ElementCollection.class) && !MetadataUtils.isBasicElementCollectionField(f)) { entityMetadata.setType(Type.SUPER_COLUMN_FAMILY); } else { entityMetadata.setType(Type.COLUMN_FAMILY); } } }
[ "private", "void", "onFamilyType", "(", "EntityMetadata", "entityMetadata", ",", "final", "Class", "clazz", ",", "Field", "f", ")", "{", "if", "(", "entityMetadata", ".", "getType", "(", ")", "==", "null", "||", "!", "entityMetadata", ".", "getType", "(", ")", ".", "equals", "(", "Type", ".", "SUPER_COLUMN_FAMILY", ")", ")", "{", "if", "(", "(", "f", ".", "isAnnotationPresent", "(", "Embedded", ".", "class", ")", "&&", "f", ".", "getType", "(", ")", ".", "getAnnotation", "(", "Embeddable", ".", "class", ")", "!=", "null", ")", ")", "{", "entityMetadata", ".", "setType", "(", "Type", ".", "SUPER_COLUMN_FAMILY", ")", ";", "}", "else", "if", "(", "f", ".", "isAnnotationPresent", "(", "ElementCollection", ".", "class", ")", "&&", "!", "MetadataUtils", ".", "isBasicElementCollectionField", "(", "f", ")", ")", "{", "entityMetadata", ".", "setType", "(", "Type", ".", "SUPER_COLUMN_FAMILY", ")", ";", "}", "else", "{", "entityMetadata", ".", "setType", "(", "Type", ".", "COLUMN_FAMILY", ")", ";", "}", "}", "}" ]
On family type. @param entityMetadata the entity metadata @param clazz the clazz @param f the f
[ "On", "family", "type", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/TableProcessor.java#L332-L349
OpenLiberty/open-liberty
dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/BNFHeadersImpl.java
BNFHeadersImpl.eraseValue
private void eraseValue(HeaderElement elem) { """ Method to completely erase the input header from the parse buffers. @param elem """ // wipe out the removed value if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Erasing existing header: " + elem.getName()); } int next_index = this.lastCRLFBufferIndex; int next_pos = this.lastCRLFPosition; if (null != elem.nextSequence && !elem.nextSequence.wasAdded()) { next_index = elem.nextSequence.getLastCRLFBufferIndex(); next_pos = elem.nextSequence.getLastCRLFPosition(); } int start = elem.getLastCRLFPosition(); // if it's only in one buffer, this for loop does nothing for (int x = elem.getLastCRLFBufferIndex(); x < next_index; x++) { // wiping out this buffer from start to limit this.parseBuffers[x].position(start); this.parseBuffers[x].limit(start); start = 0; } // last buffer, scribble from start until next_pos scribbleWhiteSpace(this.parseBuffers[next_index], start, next_pos); }
java
private void eraseValue(HeaderElement elem) { // wipe out the removed value if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Erasing existing header: " + elem.getName()); } int next_index = this.lastCRLFBufferIndex; int next_pos = this.lastCRLFPosition; if (null != elem.nextSequence && !elem.nextSequence.wasAdded()) { next_index = elem.nextSequence.getLastCRLFBufferIndex(); next_pos = elem.nextSequence.getLastCRLFPosition(); } int start = elem.getLastCRLFPosition(); // if it's only in one buffer, this for loop does nothing for (int x = elem.getLastCRLFBufferIndex(); x < next_index; x++) { // wiping out this buffer from start to limit this.parseBuffers[x].position(start); this.parseBuffers[x].limit(start); start = 0; } // last buffer, scribble from start until next_pos scribbleWhiteSpace(this.parseBuffers[next_index], start, next_pos); }
[ "private", "void", "eraseValue", "(", "HeaderElement", "elem", ")", "{", "// wipe out the removed value", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "\"Erasing existing header: \"", "+", "elem", ".", "getName", "(", ")", ")", ";", "}", "int", "next_index", "=", "this", ".", "lastCRLFBufferIndex", ";", "int", "next_pos", "=", "this", ".", "lastCRLFPosition", ";", "if", "(", "null", "!=", "elem", ".", "nextSequence", "&&", "!", "elem", ".", "nextSequence", ".", "wasAdded", "(", ")", ")", "{", "next_index", "=", "elem", ".", "nextSequence", ".", "getLastCRLFBufferIndex", "(", ")", ";", "next_pos", "=", "elem", ".", "nextSequence", ".", "getLastCRLFPosition", "(", ")", ";", "}", "int", "start", "=", "elem", ".", "getLastCRLFPosition", "(", ")", ";", "// if it's only in one buffer, this for loop does nothing", "for", "(", "int", "x", "=", "elem", ".", "getLastCRLFBufferIndex", "(", ")", ";", "x", "<", "next_index", ";", "x", "++", ")", "{", "// wiping out this buffer from start to limit", "this", ".", "parseBuffers", "[", "x", "]", ".", "position", "(", "start", ")", ";", "this", ".", "parseBuffers", "[", "x", "]", ".", "limit", "(", "start", ")", ";", "start", "=", "0", ";", "}", "// last buffer, scribble from start until next_pos", "scribbleWhiteSpace", "(", "this", ".", "parseBuffers", "[", "next_index", "]", ",", "start", ",", "next_pos", ")", ";", "}" ]
Method to completely erase the input header from the parse buffers. @param elem
[ "Method", "to", "completely", "erase", "the", "input", "header", "from", "the", "parse", "buffers", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/BNFHeadersImpl.java#L1234-L1255
gallandarakhneorg/afc
core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java
XMLUtil.getAttributeFloatWithDefault
@Pure public static Float getAttributeFloatWithDefault(Node document, boolean caseSensitive, Float defaultValue, String... path) { """ Replies the float value that corresponds to the specified attribute's path. <p>The path is an ordered list of tag's names and ended by the name of the attribute. @param document is the XML document to explore. @param caseSensitive indicates of the {@code path}'s components are case sensitive. @param defaultValue is the default value to reply. @param path is the list of and ended by the attribute's name. @return the float value of the specified attribute or <code>null</code> if it was node found in the document """ assert document != null : AssertMessages.notNullParameter(0); final String v = getAttributeValue(document, caseSensitive, 0, path); if (v != null) { try { return Float.parseFloat(v); } catch (NumberFormatException e) { // } } return defaultValue; }
java
@Pure public static Float getAttributeFloatWithDefault(Node document, boolean caseSensitive, Float defaultValue, String... path) { assert document != null : AssertMessages.notNullParameter(0); final String v = getAttributeValue(document, caseSensitive, 0, path); if (v != null) { try { return Float.parseFloat(v); } catch (NumberFormatException e) { // } } return defaultValue; }
[ "@", "Pure", "public", "static", "Float", "getAttributeFloatWithDefault", "(", "Node", "document", ",", "boolean", "caseSensitive", ",", "Float", "defaultValue", ",", "String", "...", "path", ")", "{", "assert", "document", "!=", "null", ":", "AssertMessages", ".", "notNullParameter", "(", "0", ")", ";", "final", "String", "v", "=", "getAttributeValue", "(", "document", ",", "caseSensitive", ",", "0", ",", "path", ")", ";", "if", "(", "v", "!=", "null", ")", "{", "try", "{", "return", "Float", ".", "parseFloat", "(", "v", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "//", "}", "}", "return", "defaultValue", ";", "}" ]
Replies the float value that corresponds to the specified attribute's path. <p>The path is an ordered list of tag's names and ended by the name of the attribute. @param document is the XML document to explore. @param caseSensitive indicates of the {@code path}'s components are case sensitive. @param defaultValue is the default value to reply. @param path is the list of and ended by the attribute's name. @return the float value of the specified attribute or <code>null</code> if it was node found in the document
[ "Replies", "the", "float", "value", "that", "corresponds", "to", "the", "specified", "attribute", "s", "path", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java#L769-L781
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/FolderResourcesImpl.java
FolderResourcesImpl.copyFolder
public Folder copyFolder(long folderId, ContainerDestination containerDestination, EnumSet<FolderCopyInclusion> includes, EnumSet<FolderRemapExclusion> skipRemap) throws SmartsheetException { """ Creates a copy of the specified Folder. It mirrors to the following Smartsheet REST API method: POST /folders/{folderId}/copy Exceptions: IllegalArgumentException : if folder is null InvalidRequestException : if there is any problem with the REST API request AuthorizationException : if there is any problem with the REST API authorization(access token) ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) SmartsheetRestException : if there is any other REST API related error occurred during the operation SmartsheetException : if there is any other error occurred during the operation @param folderId the folder id @param containerDestination describes the destination container @param includes optional parameters to include @param skipRemap optional parameters to exclude @return the folder @throws SmartsheetException the smartsheet exception """ return copyFolder(folderId, containerDestination, includes, skipRemap, null); }
java
public Folder copyFolder(long folderId, ContainerDestination containerDestination, EnumSet<FolderCopyInclusion> includes, EnumSet<FolderRemapExclusion> skipRemap) throws SmartsheetException { return copyFolder(folderId, containerDestination, includes, skipRemap, null); }
[ "public", "Folder", "copyFolder", "(", "long", "folderId", ",", "ContainerDestination", "containerDestination", ",", "EnumSet", "<", "FolderCopyInclusion", ">", "includes", ",", "EnumSet", "<", "FolderRemapExclusion", ">", "skipRemap", ")", "throws", "SmartsheetException", "{", "return", "copyFolder", "(", "folderId", ",", "containerDestination", ",", "includes", ",", "skipRemap", ",", "null", ")", ";", "}" ]
Creates a copy of the specified Folder. It mirrors to the following Smartsheet REST API method: POST /folders/{folderId}/copy Exceptions: IllegalArgumentException : if folder is null InvalidRequestException : if there is any problem with the REST API request AuthorizationException : if there is any problem with the REST API authorization(access token) ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) SmartsheetRestException : if there is any other REST API related error occurred during the operation SmartsheetException : if there is any other error occurred during the operation @param folderId the folder id @param containerDestination describes the destination container @param includes optional parameters to include @param skipRemap optional parameters to exclude @return the folder @throws SmartsheetException the smartsheet exception
[ "Creates", "a", "copy", "of", "the", "specified", "Folder", "." ]
train
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/FolderResourcesImpl.java#L204-L206
wellner/jcarafe
jcarafe-core/src/main/java/org/mitre/jcarafe/jarafe/JarafeMEDecoder.java
JarafeMEDecoder.classifyValuedInstanceDistribution
public List<StringDoublePair> classifyValuedInstanceDistribution(List<StringDoublePair> features) { """ /* @param features - A list of string-double pairs representing the valued features for a classification instance @return string-double pair list - A list of pairs that include each label and a posterior probability mass """ List<scala.Tuple2<String,Double>> nfs = new ArrayList<scala.Tuple2<String,Double>>(); for (StringDoublePair el : features) { nfs.add(new scala.Tuple2<String,Double>(el.getString(), el.getDouble())); } List<scala.Tuple2<String,Double>> r = maxEnt.decodeValuedInstanceAsDistribution(nfs); List<StringDoublePair> res = new ArrayList<StringDoublePair>(); for (scala.Tuple2<String,Double> el : r) { res.add(new StringDoublePair(el._1, el._2)); } return res; }
java
public List<StringDoublePair> classifyValuedInstanceDistribution(List<StringDoublePair> features) { List<scala.Tuple2<String,Double>> nfs = new ArrayList<scala.Tuple2<String,Double>>(); for (StringDoublePair el : features) { nfs.add(new scala.Tuple2<String,Double>(el.getString(), el.getDouble())); } List<scala.Tuple2<String,Double>> r = maxEnt.decodeValuedInstanceAsDistribution(nfs); List<StringDoublePair> res = new ArrayList<StringDoublePair>(); for (scala.Tuple2<String,Double> el : r) { res.add(new StringDoublePair(el._1, el._2)); } return res; }
[ "public", "List", "<", "StringDoublePair", ">", "classifyValuedInstanceDistribution", "(", "List", "<", "StringDoublePair", ">", "features", ")", "{", "List", "<", "scala", ".", "Tuple2", "<", "String", ",", "Double", ">", ">", "nfs", "=", "new", "ArrayList", "<", "scala", ".", "Tuple2", "<", "String", ",", "Double", ">", ">", "(", ")", ";", "for", "(", "StringDoublePair", "el", ":", "features", ")", "{", "nfs", ".", "add", "(", "new", "scala", ".", "Tuple2", "<", "String", ",", "Double", ">", "(", "el", ".", "getString", "(", ")", ",", "el", ".", "getDouble", "(", ")", ")", ")", ";", "}", "List", "<", "scala", ".", "Tuple2", "<", "String", ",", "Double", ">", ">", "r", "=", "maxEnt", ".", "decodeValuedInstanceAsDistribution", "(", "nfs", ")", ";", "List", "<", "StringDoublePair", ">", "res", "=", "new", "ArrayList", "<", "StringDoublePair", ">", "(", ")", ";", "for", "(", "scala", ".", "Tuple2", "<", "String", ",", "Double", ">", "el", ":", "r", ")", "{", "res", ".", "add", "(", "new", "StringDoublePair", "(", "el", ".", "_1", ",", "el", ".", "_2", ")", ")", ";", "}", "return", "res", ";", "}" ]
/* @param features - A list of string-double pairs representing the valued features for a classification instance @return string-double pair list - A list of pairs that include each label and a posterior probability mass
[ "/", "*" ]
train
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/org/mitre/jcarafe/jarafe/JarafeMEDecoder.java#L63-L74
VoltDB/voltdb
src/frontend/org/voltdb/compiler/AdHocPlannedStmtBatch.java
AdHocPlannedStmtBatch.explainStatement
public String explainStatement(int i, Database db, boolean getJSONString) { """ Return the "EXPLAIN" string of the batched statement at the index @param i the index @param db the database context (for adding catalog details). """ AdHocPlannedStatement plannedStatement = plannedStatements.get(i); String aggplan = new String(plannedStatement.core.aggregatorFragment, Constants.UTF8ENCODING); PlanNodeTree pnt = new PlanNodeTree(); try { String result = null; JSONObject jobj = new JSONObject(aggplan); if (getJSONString) { result = jobj.toString(4); } pnt.loadFromJSONPlan(jobj, db); if (plannedStatement.core.collectorFragment != null) { // multi-partition query plan String collplan = new String(plannedStatement.core.collectorFragment, Constants.UTF8ENCODING); PlanNodeTree collpnt = new PlanNodeTree(); // reattach plan fragments JSONObject jobMP = new JSONObject(collplan); collpnt.loadFromJSONPlan(jobMP, db); assert(collpnt.getRootPlanNode() instanceof SendPlanNode); pnt.getRootPlanNode().reattachFragment(collpnt.getRootPlanNode()); if (getJSONString) { result += "\n" + jobMP.toString(4); } } if (! getJSONString) { result = pnt.getRootPlanNode().toExplainPlanString(); } return result; } catch (JSONException e) { System.out.println(e); return "Internal Error (JSONException): " + e.getMessage(); } }
java
public String explainStatement(int i, Database db, boolean getJSONString) { AdHocPlannedStatement plannedStatement = plannedStatements.get(i); String aggplan = new String(plannedStatement.core.aggregatorFragment, Constants.UTF8ENCODING); PlanNodeTree pnt = new PlanNodeTree(); try { String result = null; JSONObject jobj = new JSONObject(aggplan); if (getJSONString) { result = jobj.toString(4); } pnt.loadFromJSONPlan(jobj, db); if (plannedStatement.core.collectorFragment != null) { // multi-partition query plan String collplan = new String(plannedStatement.core.collectorFragment, Constants.UTF8ENCODING); PlanNodeTree collpnt = new PlanNodeTree(); // reattach plan fragments JSONObject jobMP = new JSONObject(collplan); collpnt.loadFromJSONPlan(jobMP, db); assert(collpnt.getRootPlanNode() instanceof SendPlanNode); pnt.getRootPlanNode().reattachFragment(collpnt.getRootPlanNode()); if (getJSONString) { result += "\n" + jobMP.toString(4); } } if (! getJSONString) { result = pnt.getRootPlanNode().toExplainPlanString(); } return result; } catch (JSONException e) { System.out.println(e); return "Internal Error (JSONException): " + e.getMessage(); } }
[ "public", "String", "explainStatement", "(", "int", "i", ",", "Database", "db", ",", "boolean", "getJSONString", ")", "{", "AdHocPlannedStatement", "plannedStatement", "=", "plannedStatements", ".", "get", "(", "i", ")", ";", "String", "aggplan", "=", "new", "String", "(", "plannedStatement", ".", "core", ".", "aggregatorFragment", ",", "Constants", ".", "UTF8ENCODING", ")", ";", "PlanNodeTree", "pnt", "=", "new", "PlanNodeTree", "(", ")", ";", "try", "{", "String", "result", "=", "null", ";", "JSONObject", "jobj", "=", "new", "JSONObject", "(", "aggplan", ")", ";", "if", "(", "getJSONString", ")", "{", "result", "=", "jobj", ".", "toString", "(", "4", ")", ";", "}", "pnt", ".", "loadFromJSONPlan", "(", "jobj", ",", "db", ")", ";", "if", "(", "plannedStatement", ".", "core", ".", "collectorFragment", "!=", "null", ")", "{", "// multi-partition query plan", "String", "collplan", "=", "new", "String", "(", "plannedStatement", ".", "core", ".", "collectorFragment", ",", "Constants", ".", "UTF8ENCODING", ")", ";", "PlanNodeTree", "collpnt", "=", "new", "PlanNodeTree", "(", ")", ";", "// reattach plan fragments", "JSONObject", "jobMP", "=", "new", "JSONObject", "(", "collplan", ")", ";", "collpnt", ".", "loadFromJSONPlan", "(", "jobMP", ",", "db", ")", ";", "assert", "(", "collpnt", ".", "getRootPlanNode", "(", ")", "instanceof", "SendPlanNode", ")", ";", "pnt", ".", "getRootPlanNode", "(", ")", ".", "reattachFragment", "(", "collpnt", ".", "getRootPlanNode", "(", ")", ")", ";", "if", "(", "getJSONString", ")", "{", "result", "+=", "\"\\n\"", "+", "jobMP", ".", "toString", "(", "4", ")", ";", "}", "}", "if", "(", "!", "getJSONString", ")", "{", "result", "=", "pnt", ".", "getRootPlanNode", "(", ")", ".", "toExplainPlanString", "(", ")", ";", "}", "return", "result", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "System", ".", "out", ".", "println", "(", "e", ")", ";", "return", "\"Internal Error (JSONException): \"", "+", "e", ".", "getMessage", "(", ")", ";", "}", "}" ]
Return the "EXPLAIN" string of the batched statement at the index @param i the index @param db the database context (for adding catalog details).
[ "Return", "the", "EXPLAIN", "string", "of", "the", "batched", "statement", "at", "the", "index" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/compiler/AdHocPlannedStmtBatch.java#L352-L386
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/reflect/TypeReflector.java
TypeReflector.getType
public static Class<?> getType(String name, String library) { """ Gets object type by its name and library where it is defined. @param name an object type name. @param library a library where the type is defined @return the object type or null is the type wasn't found. """ try { // Load module if (library != null && !library.isEmpty()) { URL moduleUrl = new File(library).toURI().toURL(); URLClassLoader child = new URLClassLoader(new URL[] { moduleUrl }, ClassLoader.getSystemClassLoader()); return Class.forName(name, true, child); } else { return Class.forName(name); } } catch (Exception ex) { return null; } }
java
public static Class<?> getType(String name, String library) { try { // Load module if (library != null && !library.isEmpty()) { URL moduleUrl = new File(library).toURI().toURL(); URLClassLoader child = new URLClassLoader(new URL[] { moduleUrl }, ClassLoader.getSystemClassLoader()); return Class.forName(name, true, child); } else { return Class.forName(name); } } catch (Exception ex) { return null; } }
[ "public", "static", "Class", "<", "?", ">", "getType", "(", "String", "name", ",", "String", "library", ")", "{", "try", "{", "// Load module", "if", "(", "library", "!=", "null", "&&", "!", "library", ".", "isEmpty", "(", ")", ")", "{", "URL", "moduleUrl", "=", "new", "File", "(", "library", ")", ".", "toURI", "(", ")", ".", "toURL", "(", ")", ";", "URLClassLoader", "child", "=", "new", "URLClassLoader", "(", "new", "URL", "[", "]", "{", "moduleUrl", "}", ",", "ClassLoader", ".", "getSystemClassLoader", "(", ")", ")", ";", "return", "Class", ".", "forName", "(", "name", ",", "true", ",", "child", ")", ";", "}", "else", "{", "return", "Class", ".", "forName", "(", "name", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "return", "null", ";", "}", "}" ]
Gets object type by its name and library where it is defined. @param name an object type name. @param library a library where the type is defined @return the object type or null is the type wasn't found.
[ "Gets", "object", "type", "by", "its", "name", "and", "library", "where", "it", "is", "defined", "." ]
train
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/reflect/TypeReflector.java#L42-L55
google/closure-compiler
src/com/google/javascript/jscomp/NodeUtil.java
NodeUtil.addFeatureToScript
static void addFeatureToScript(Node scriptNode, Feature feature) { """ Adds the given features to a SCRIPT node's FeatureSet property. """ checkState(scriptNode.isScript(), scriptNode); FeatureSet currentFeatures = getFeatureSetOfScript(scriptNode); FeatureSet newFeatures = currentFeatures != null ? currentFeatures.with(feature) : FeatureSet.BARE_MINIMUM.with(feature); scriptNode.putProp(Node.FEATURE_SET, newFeatures); }
java
static void addFeatureToScript(Node scriptNode, Feature feature) { checkState(scriptNode.isScript(), scriptNode); FeatureSet currentFeatures = getFeatureSetOfScript(scriptNode); FeatureSet newFeatures = currentFeatures != null ? currentFeatures.with(feature) : FeatureSet.BARE_MINIMUM.with(feature); scriptNode.putProp(Node.FEATURE_SET, newFeatures); }
[ "static", "void", "addFeatureToScript", "(", "Node", "scriptNode", ",", "Feature", "feature", ")", "{", "checkState", "(", "scriptNode", ".", "isScript", "(", ")", ",", "scriptNode", ")", ";", "FeatureSet", "currentFeatures", "=", "getFeatureSetOfScript", "(", "scriptNode", ")", ";", "FeatureSet", "newFeatures", "=", "currentFeatures", "!=", "null", "?", "currentFeatures", ".", "with", "(", "feature", ")", ":", "FeatureSet", ".", "BARE_MINIMUM", ".", "with", "(", "feature", ")", ";", "scriptNode", ".", "putProp", "(", "Node", ".", "FEATURE_SET", ",", "newFeatures", ")", ";", "}" ]
Adds the given features to a SCRIPT node's FeatureSet property.
[ "Adds", "the", "given", "features", "to", "a", "SCRIPT", "node", "s", "FeatureSet", "property", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/NodeUtil.java#L6003-L6011
pravega/pravega
segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/Ledgers.java
Ledgers.openRead
static LedgerHandle openRead(long ledgerId, BookKeeper bookKeeper, BookKeeperConfig config) throws DurableDataLogException { """ Opens a ledger for reading. This operation does not fence out the ledger. @param ledgerId The Id of the Ledger to open. @param bookKeeper A references to the BookKeeper client to use. @param config Configuration to use. @return A LedgerHandle for the newly opened ledger. @throws DurableDataLogException If an exception occurred. The causing exception is wrapped inside it. """ try { return Exceptions.handleInterruptedCall( () -> bookKeeper.openLedgerNoRecovery(ledgerId, LEDGER_DIGEST_TYPE, config.getBKPassword())); } catch (BKException bkEx) { throw new DurableDataLogException(String.format("Unable to open-read ledger %d.", ledgerId), bkEx); } }
java
static LedgerHandle openRead(long ledgerId, BookKeeper bookKeeper, BookKeeperConfig config) throws DurableDataLogException { try { return Exceptions.handleInterruptedCall( () -> bookKeeper.openLedgerNoRecovery(ledgerId, LEDGER_DIGEST_TYPE, config.getBKPassword())); } catch (BKException bkEx) { throw new DurableDataLogException(String.format("Unable to open-read ledger %d.", ledgerId), bkEx); } }
[ "static", "LedgerHandle", "openRead", "(", "long", "ledgerId", ",", "BookKeeper", "bookKeeper", ",", "BookKeeperConfig", "config", ")", "throws", "DurableDataLogException", "{", "try", "{", "return", "Exceptions", ".", "handleInterruptedCall", "(", "(", ")", "->", "bookKeeper", ".", "openLedgerNoRecovery", "(", "ledgerId", ",", "LEDGER_DIGEST_TYPE", ",", "config", ".", "getBKPassword", "(", ")", ")", ")", ";", "}", "catch", "(", "BKException", "bkEx", ")", "{", "throw", "new", "DurableDataLogException", "(", "String", ".", "format", "(", "\"Unable to open-read ledger %d.\"", ",", "ledgerId", ")", ",", "bkEx", ")", ";", "}", "}" ]
Opens a ledger for reading. This operation does not fence out the ledger. @param ledgerId The Id of the Ledger to open. @param bookKeeper A references to the BookKeeper client to use. @param config Configuration to use. @return A LedgerHandle for the newly opened ledger. @throws DurableDataLogException If an exception occurred. The causing exception is wrapped inside it.
[ "Opens", "a", "ledger", "for", "reading", ".", "This", "operation", "does", "not", "fence", "out", "the", "ledger", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/Ledgers.java#L88-L95
VoltDB/voltdb
third_party/java/src/org/apache/commons_voltpatches/cli/HelpFormatter.java
HelpFormatter.printUsage
public void printUsage(PrintWriter pw, int width, String app, Options options) { """ Prints the usage statement for the specified application. @param pw The PrintWriter to print the usage statement @param width The number of characters to display per line @param app The application name @param options The command line Options """ // initialise the string buffer StringBuffer buff = new StringBuffer(getSyntaxPrefix()).append(app).append(" "); // create a list for processed option groups Collection<OptionGroup> processedGroups = new ArrayList<OptionGroup>(); List<Option> optList = new ArrayList<Option>(options.getOptions()); if (getOptionComparator() != null) { Collections.sort(optList, getOptionComparator()); } // iterate over the options for (Iterator<Option> it = optList.iterator(); it.hasNext();) { // get the next Option Option option = it.next(); // check if the option is part of an OptionGroup OptionGroup group = options.getOptionGroup(option); // if the option is part of a group if (group != null) { // and if the group has not already been processed if (!processedGroups.contains(group)) { // add the group to the processed list processedGroups.add(group); // add the usage clause appendOptionGroup(buff, group); } // otherwise the option was displayed in the group // previously so ignore it. } // if the Option is not part of an OptionGroup else { appendOption(buff, option, option.isRequired()); } if (it.hasNext()) { buff.append(" "); } } // call printWrapped printWrapped(pw, width, buff.toString().indexOf(' ') + 1, buff.toString()); }
java
public void printUsage(PrintWriter pw, int width, String app, Options options) { // initialise the string buffer StringBuffer buff = new StringBuffer(getSyntaxPrefix()).append(app).append(" "); // create a list for processed option groups Collection<OptionGroup> processedGroups = new ArrayList<OptionGroup>(); List<Option> optList = new ArrayList<Option>(options.getOptions()); if (getOptionComparator() != null) { Collections.sort(optList, getOptionComparator()); } // iterate over the options for (Iterator<Option> it = optList.iterator(); it.hasNext();) { // get the next Option Option option = it.next(); // check if the option is part of an OptionGroup OptionGroup group = options.getOptionGroup(option); // if the option is part of a group if (group != null) { // and if the group has not already been processed if (!processedGroups.contains(group)) { // add the group to the processed list processedGroups.add(group); // add the usage clause appendOptionGroup(buff, group); } // otherwise the option was displayed in the group // previously so ignore it. } // if the Option is not part of an OptionGroup else { appendOption(buff, option, option.isRequired()); } if (it.hasNext()) { buff.append(" "); } } // call printWrapped printWrapped(pw, width, buff.toString().indexOf(' ') + 1, buff.toString()); }
[ "public", "void", "printUsage", "(", "PrintWriter", "pw", ",", "int", "width", ",", "String", "app", ",", "Options", "options", ")", "{", "// initialise the string buffer", "StringBuffer", "buff", "=", "new", "StringBuffer", "(", "getSyntaxPrefix", "(", ")", ")", ".", "append", "(", "app", ")", ".", "append", "(", "\" \"", ")", ";", "// create a list for processed option groups", "Collection", "<", "OptionGroup", ">", "processedGroups", "=", "new", "ArrayList", "<", "OptionGroup", ">", "(", ")", ";", "List", "<", "Option", ">", "optList", "=", "new", "ArrayList", "<", "Option", ">", "(", "options", ".", "getOptions", "(", ")", ")", ";", "if", "(", "getOptionComparator", "(", ")", "!=", "null", ")", "{", "Collections", ".", "sort", "(", "optList", ",", "getOptionComparator", "(", ")", ")", ";", "}", "// iterate over the options", "for", "(", "Iterator", "<", "Option", ">", "it", "=", "optList", ".", "iterator", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "// get the next Option", "Option", "option", "=", "it", ".", "next", "(", ")", ";", "// check if the option is part of an OptionGroup", "OptionGroup", "group", "=", "options", ".", "getOptionGroup", "(", "option", ")", ";", "// if the option is part of a group ", "if", "(", "group", "!=", "null", ")", "{", "// and if the group has not already been processed", "if", "(", "!", "processedGroups", ".", "contains", "(", "group", ")", ")", "{", "// add the group to the processed list", "processedGroups", ".", "add", "(", "group", ")", ";", "// add the usage clause", "appendOptionGroup", "(", "buff", ",", "group", ")", ";", "}", "// otherwise the option was displayed in the group", "// previously so ignore it.", "}", "// if the Option is not part of an OptionGroup", "else", "{", "appendOption", "(", "buff", ",", "option", ",", "option", ".", "isRequired", "(", ")", ")", ";", "}", "if", "(", "it", ".", "hasNext", "(", ")", ")", "{", "buff", ".", "append", "(", "\" \"", ")", ";", "}", "}", "// call printWrapped", "printWrapped", "(", "pw", ",", "width", ",", "buff", ".", "toString", "(", ")", ".", "indexOf", "(", "'", "'", ")", "+", "1", ",", "buff", ".", "toString", "(", ")", ")", ";", "}" ]
Prints the usage statement for the specified application. @param pw The PrintWriter to print the usage statement @param width The number of characters to display per line @param app The application name @param options The command line Options
[ "Prints", "the", "usage", "statement", "for", "the", "specified", "application", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/commons_voltpatches/cli/HelpFormatter.java#L579-L634
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/event/ChangeFocusOnChangeHandler.java
ChangeFocusOnChangeHandler.fieldChanged
public int fieldChanged(boolean bDisplayOption, int iMoveMode) { """ The Field has Changed. Change to focus to the target field. @param bDisplayOption If true, display the change. @param iMoveMode The type of move being done (init/read/screen). @return The error code (or NORMAL_RETURN if okay). """ if (m_screenField == null) this.lookupSField(); if (m_bChangeIfNull != null) { if ((m_bChangeIfNull.booleanValue()) && (!this.getOwner().isNull())) return DBConstants.NORMAL_RETURN; if ((!m_bChangeIfNull.booleanValue()) && (this.getOwner().isNull())) return DBConstants.NORMAL_RETURN; } if (m_screenField != null) m_screenField.requestFocus(); return DBConstants.NORMAL_RETURN; }
java
public int fieldChanged(boolean bDisplayOption, int iMoveMode) { if (m_screenField == null) this.lookupSField(); if (m_bChangeIfNull != null) { if ((m_bChangeIfNull.booleanValue()) && (!this.getOwner().isNull())) return DBConstants.NORMAL_RETURN; if ((!m_bChangeIfNull.booleanValue()) && (this.getOwner().isNull())) return DBConstants.NORMAL_RETURN; } if (m_screenField != null) m_screenField.requestFocus(); return DBConstants.NORMAL_RETURN; }
[ "public", "int", "fieldChanged", "(", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "if", "(", "m_screenField", "==", "null", ")", "this", ".", "lookupSField", "(", ")", ";", "if", "(", "m_bChangeIfNull", "!=", "null", ")", "{", "if", "(", "(", "m_bChangeIfNull", ".", "booleanValue", "(", ")", ")", "&&", "(", "!", "this", ".", "getOwner", "(", ")", ".", "isNull", "(", ")", ")", ")", "return", "DBConstants", ".", "NORMAL_RETURN", ";", "if", "(", "(", "!", "m_bChangeIfNull", ".", "booleanValue", "(", ")", ")", "&&", "(", "this", ".", "getOwner", "(", ")", ".", "isNull", "(", ")", ")", ")", "return", "DBConstants", ".", "NORMAL_RETURN", ";", "}", "if", "(", "m_screenField", "!=", "null", ")", "m_screenField", ".", "requestFocus", "(", ")", ";", "return", "DBConstants", ".", "NORMAL_RETURN", ";", "}" ]
The Field has Changed. Change to focus to the target field. @param bDisplayOption If true, display the change. @param iMoveMode The type of move being done (init/read/screen). @return The error code (or NORMAL_RETURN if okay).
[ "The", "Field", "has", "Changed", ".", "Change", "to", "focus", "to", "the", "target", "field", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/ChangeFocusOnChangeHandler.java#L102-L116
artikcloud/artikcloud-java
src/main/java/cloud/artik/api/SubscriptionsApi.java
SubscriptionsApi.getMessagesAsync
public com.squareup.okhttp.Call getMessagesAsync(String notifId, Integer offset, Integer count, String order, final ApiCallback<NotifMessagesResponse> callback) throws ApiException { """ Get Messages (asynchronously) Get Messages @param notifId Notification ID. (required) @param offset Offset for pagination. (optional) @param count Desired count of items in the result set. (optional) @param order Sort order of results by ts. Either &#39;asc&#39; or &#39;desc&#39;. (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object """ ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getMessagesValidateBeforeCall(notifId, offset, count, order, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<NotifMessagesResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
java
public com.squareup.okhttp.Call getMessagesAsync(String notifId, Integer offset, Integer count, String order, final ApiCallback<NotifMessagesResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getMessagesValidateBeforeCall(notifId, offset, count, order, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<NotifMessagesResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "getMessagesAsync", "(", "String", "notifId", ",", "Integer", "offset", ",", "Integer", "count", ",", "String", "order", ",", "final", "ApiCallback", "<", "NotifMessagesResponse", ">", "callback", ")", "throws", "ApiException", "{", "ProgressResponseBody", ".", "ProgressListener", "progressListener", "=", "null", ";", "ProgressRequestBody", ".", "ProgressRequestListener", "progressRequestListener", "=", "null", ";", "if", "(", "callback", "!=", "null", ")", "{", "progressListener", "=", "new", "ProgressResponseBody", ".", "ProgressListener", "(", ")", "{", "@", "Override", "public", "void", "update", "(", "long", "bytesRead", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onDownloadProgress", "(", "bytesRead", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "progressRequestListener", "=", "new", "ProgressRequestBody", ".", "ProgressRequestListener", "(", ")", "{", "@", "Override", "public", "void", "onRequestProgress", "(", "long", "bytesWritten", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onUploadProgress", "(", "bytesWritten", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "}", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "getMessagesValidateBeforeCall", "(", "notifId", ",", "offset", ",", "count", ",", "order", ",", "progressListener", ",", "progressRequestListener", ")", ";", "Type", "localVarReturnType", "=", "new", "TypeToken", "<", "NotifMessagesResponse", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "apiClient", ".", "executeAsync", "(", "call", ",", "localVarReturnType", ",", "callback", ")", ";", "return", "call", ";", "}" ]
Get Messages (asynchronously) Get Messages @param notifId Notification ID. (required) @param offset Offset for pagination. (optional) @param count Desired count of items in the result set. (optional) @param order Sort order of results by ts. Either &#39;asc&#39; or &#39;desc&#39;. (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
[ "Get", "Messages", "(", "asynchronously", ")", "Get", "Messages" ]
train
https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/SubscriptionsApi.java#L531-L556
jkyamog/DeDS
sample_clients/java/src/main/java/nz/net/catalyst/mobile/dds/sample/DDSClient.java
DDSClient.getCapabilities
public static Map<String, String> getCapabilities(HttpServletRequest request, String ddsUrl) throws IOException { """ Get the capabilities as a map of capabilities. There are times that a strict data type is not desirable. Getting it as map provides some flexibility. This does not require any knowledge of what capabilities will be returned by the service. @param request @param ddsUrl @return @throws IOException """ URL url; try { url = new URL(ddsUrl + "/get_capabilities?capability=resolution_width&capability=model_name&capability=xhtml_support_level&" + "headers=" + URLEncoder.encode(jsonEncode(getHeadersAsHashMap(request)), "UTF-8")); } catch (MalformedURLException e) { throw new IOException(e); } String httpResponse = fetchHttpResponse(url); return jsonDecode(httpResponse, new TypeReference<Map<String, String>>() { }); }
java
public static Map<String, String> getCapabilities(HttpServletRequest request, String ddsUrl) throws IOException { URL url; try { url = new URL(ddsUrl + "/get_capabilities?capability=resolution_width&capability=model_name&capability=xhtml_support_level&" + "headers=" + URLEncoder.encode(jsonEncode(getHeadersAsHashMap(request)), "UTF-8")); } catch (MalformedURLException e) { throw new IOException(e); } String httpResponse = fetchHttpResponse(url); return jsonDecode(httpResponse, new TypeReference<Map<String, String>>() { }); }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "getCapabilities", "(", "HttpServletRequest", "request", ",", "String", "ddsUrl", ")", "throws", "IOException", "{", "URL", "url", ";", "try", "{", "url", "=", "new", "URL", "(", "ddsUrl", "+", "\"/get_capabilities?capability=resolution_width&capability=model_name&capability=xhtml_support_level&\"", "+", "\"headers=\"", "+", "URLEncoder", ".", "encode", "(", "jsonEncode", "(", "getHeadersAsHashMap", "(", "request", ")", ")", ",", "\"UTF-8\"", ")", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "throw", "new", "IOException", "(", "e", ")", ";", "}", "String", "httpResponse", "=", "fetchHttpResponse", "(", "url", ")", ";", "return", "jsonDecode", "(", "httpResponse", ",", "new", "TypeReference", "<", "Map", "<", "String", ",", "String", ">", ">", "(", ")", "{", "}", ")", ";", "}" ]
Get the capabilities as a map of capabilities. There are times that a strict data type is not desirable. Getting it as map provides some flexibility. This does not require any knowledge of what capabilities will be returned by the service. @param request @param ddsUrl @return @throws IOException
[ "Get", "the", "capabilities", "as", "a", "map", "of", "capabilities", ".", "There", "are", "times", "that", "a", "strict", "data", "type", "is", "not", "desirable", ".", "Getting", "it", "as", "map", "provides", "some", "flexibility", ".", "This", "does", "not", "require", "any", "knowledge", "of", "what", "capabilities", "will", "be", "returned", "by", "the", "service", "." ]
train
https://github.com/jkyamog/DeDS/blob/d8cf6a294a23daa8e8a92073827c73b1befe3fa1/sample_clients/java/src/main/java/nz/net/catalyst/mobile/dds/sample/DDSClient.java#L50-L63
algolia/algoliasearch-client-java
src/main/java/com/algolia/search/saas/Index.java
Index.saveRule
public JSONObject saveRule(String objectID, JSONObject rule) throws AlgoliaException { """ Save a query rule @param objectID the objectId of the query rule to save @param rule the content of this query rule """ return saveRule(objectID, rule, false); }
java
public JSONObject saveRule(String objectID, JSONObject rule) throws AlgoliaException { return saveRule(objectID, rule, false); }
[ "public", "JSONObject", "saveRule", "(", "String", "objectID", ",", "JSONObject", "rule", ")", "throws", "AlgoliaException", "{", "return", "saveRule", "(", "objectID", ",", "rule", ",", "false", ")", ";", "}" ]
Save a query rule @param objectID the objectId of the query rule to save @param rule the content of this query rule
[ "Save", "a", "query", "rule" ]
train
https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Index.java#L1713-L1715
hal/core
processors/src/main/java/org/jboss/hal/processors/AbstractHalProcessor.java
AbstractHalProcessor.writeResource
protected void writeResource(final String packageName, final String resourceName, final StringBuffer content) { """ Writes the specified resource and wraps any {@code IOException} as {@link GenerationException}. @param packageName the package name @param resourceName the resource name @param content the content @throws GenerationException if an {@code IOException occurs} """ try { FileObject mf = filer.createResource(StandardLocation.SOURCE_OUTPUT, packageName, resourceName); Writer w = mf.openWriter(); BufferedWriter bw = new BufferedWriter(w); bw.append(content); bw.close(); w.close(); } catch (IOException e) { throw new GenerationException(String.format("Error writing content for %s.%s: %s", packageName, resourceName, e.getMessage())); } }
java
protected void writeResource(final String packageName, final String resourceName, final StringBuffer content) { try { FileObject mf = filer.createResource(StandardLocation.SOURCE_OUTPUT, packageName, resourceName); Writer w = mf.openWriter(); BufferedWriter bw = new BufferedWriter(w); bw.append(content); bw.close(); w.close(); } catch (IOException e) { throw new GenerationException(String.format("Error writing content for %s.%s: %s", packageName, resourceName, e.getMessage())); } }
[ "protected", "void", "writeResource", "(", "final", "String", "packageName", ",", "final", "String", "resourceName", ",", "final", "StringBuffer", "content", ")", "{", "try", "{", "FileObject", "mf", "=", "filer", ".", "createResource", "(", "StandardLocation", ".", "SOURCE_OUTPUT", ",", "packageName", ",", "resourceName", ")", ";", "Writer", "w", "=", "mf", ".", "openWriter", "(", ")", ";", "BufferedWriter", "bw", "=", "new", "BufferedWriter", "(", "w", ")", ";", "bw", ".", "append", "(", "content", ")", ";", "bw", ".", "close", "(", ")", ";", "w", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "GenerationException", "(", "String", ".", "format", "(", "\"Error writing content for %s.%s: %s\"", ",", "packageName", ",", "resourceName", ",", "e", ".", "getMessage", "(", ")", ")", ")", ";", "}", "}" ]
Writes the specified resource and wraps any {@code IOException} as {@link GenerationException}. @param packageName the package name @param resourceName the resource name @param content the content @throws GenerationException if an {@code IOException occurs}
[ "Writes", "the", "specified", "resource", "and", "wraps", "any", "{", "@code", "IOException", "}", "as", "{", "@link", "GenerationException", "}", "." ]
train
https://github.com/hal/core/blob/d6d03f0bb128dc0470f5dc75fdb1ea1014400602/processors/src/main/java/org/jboss/hal/processors/AbstractHalProcessor.java#L271-L283
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectInverseOfImpl_CustomFieldSerializer.java
OWLObjectInverseOfImpl_CustomFieldSerializer.deserializeInstance
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLObjectInverseOfImpl instance) throws SerializationException { """ Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful """ deserialize(streamReader, instance); }
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLObjectInverseOfImpl instance) throws SerializationException { deserialize(streamReader, instance); }
[ "@", "Override", "public", "void", "deserializeInstance", "(", "SerializationStreamReader", "streamReader", ",", "OWLObjectInverseOfImpl", "instance", ")", "throws", "SerializationException", "{", "deserialize", "(", "streamReader", ",", "instance", ")", ";", "}" ]
Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful
[ "Deserializes", "the", "content", "of", "the", "object", "from", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamReader", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectInverseOfImpl_CustomFieldSerializer.java#L90-L93
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/coll/CollationBuilder.java
CollationBuilder.insertTailoredNodeAfter
private int insertTailoredNodeAfter(int index, int strength) { """ Makes and inserts a new tailored node into the list, after the one at index. Skips over nodes of weaker strength to maintain collation order ("postpone insertion"). @return the new node's index """ assert(0 <= index && index < nodes.size()); if(strength >= Collator.SECONDARY) { index = findCommonNode(index, Collator.SECONDARY); if(strength >= Collator.TERTIARY) { index = findCommonNode(index, Collator.TERTIARY); } } // Postpone insertion: // Insert the new node before the next one with a strength at least as strong. long node = nodes.elementAti(index); int nextIndex; while((nextIndex = nextIndexFromNode(node)) != 0) { node = nodes.elementAti(nextIndex); if(strengthFromNode(node) <= strength) { break; } // Skip the next node which has a weaker (larger) strength than the new one. index = nextIndex; } node = IS_TAILORED | nodeFromStrength(strength); return insertNodeBetween(index, nextIndex, node); }
java
private int insertTailoredNodeAfter(int index, int strength) { assert(0 <= index && index < nodes.size()); if(strength >= Collator.SECONDARY) { index = findCommonNode(index, Collator.SECONDARY); if(strength >= Collator.TERTIARY) { index = findCommonNode(index, Collator.TERTIARY); } } // Postpone insertion: // Insert the new node before the next one with a strength at least as strong. long node = nodes.elementAti(index); int nextIndex; while((nextIndex = nextIndexFromNode(node)) != 0) { node = nodes.elementAti(nextIndex); if(strengthFromNode(node) <= strength) { break; } // Skip the next node which has a weaker (larger) strength than the new one. index = nextIndex; } node = IS_TAILORED | nodeFromStrength(strength); return insertNodeBetween(index, nextIndex, node); }
[ "private", "int", "insertTailoredNodeAfter", "(", "int", "index", ",", "int", "strength", ")", "{", "assert", "(", "0", "<=", "index", "&&", "index", "<", "nodes", ".", "size", "(", ")", ")", ";", "if", "(", "strength", ">=", "Collator", ".", "SECONDARY", ")", "{", "index", "=", "findCommonNode", "(", "index", ",", "Collator", ".", "SECONDARY", ")", ";", "if", "(", "strength", ">=", "Collator", ".", "TERTIARY", ")", "{", "index", "=", "findCommonNode", "(", "index", ",", "Collator", ".", "TERTIARY", ")", ";", "}", "}", "// Postpone insertion:", "// Insert the new node before the next one with a strength at least as strong.", "long", "node", "=", "nodes", ".", "elementAti", "(", "index", ")", ";", "int", "nextIndex", ";", "while", "(", "(", "nextIndex", "=", "nextIndexFromNode", "(", "node", ")", ")", "!=", "0", ")", "{", "node", "=", "nodes", ".", "elementAti", "(", "nextIndex", ")", ";", "if", "(", "strengthFromNode", "(", "node", ")", "<=", "strength", ")", "{", "break", ";", "}", "// Skip the next node which has a weaker (larger) strength than the new one.", "index", "=", "nextIndex", ";", "}", "node", "=", "IS_TAILORED", "|", "nodeFromStrength", "(", "strength", ")", ";", "return", "insertNodeBetween", "(", "index", ",", "nextIndex", ",", "node", ")", ";", "}" ]
Makes and inserts a new tailored node into the list, after the one at index. Skips over nodes of weaker strength to maintain collation order ("postpone insertion"). @return the new node's index
[ "Makes", "and", "inserts", "a", "new", "tailored", "node", "into", "the", "list", "after", "the", "one", "at", "index", ".", "Skips", "over", "nodes", "of", "weaker", "strength", "to", "maintain", "collation", "order", "(", "postpone", "insertion", ")", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/coll/CollationBuilder.java#L701-L721
junit-team/junit4
src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java
FailOnTimeout.getResult
private Throwable getResult(FutureTask<Throwable> task, Thread thread) { """ Wait for the test task, returning the exception thrown by the test if the test failed, an exception indicating a timeout if the test timed out, or {@code null} if the test passed. """ try { if (timeout > 0) { return task.get(timeout, timeUnit); } else { return task.get(); } } catch (InterruptedException e) { return e; // caller will re-throw; no need to call Thread.interrupt() } catch (ExecutionException e) { // test failed; have caller re-throw the exception thrown by the test return e.getCause(); } catch (TimeoutException e) { return createTimeoutException(thread); } }
java
private Throwable getResult(FutureTask<Throwable> task, Thread thread) { try { if (timeout > 0) { return task.get(timeout, timeUnit); } else { return task.get(); } } catch (InterruptedException e) { return e; // caller will re-throw; no need to call Thread.interrupt() } catch (ExecutionException e) { // test failed; have caller re-throw the exception thrown by the test return e.getCause(); } catch (TimeoutException e) { return createTimeoutException(thread); } }
[ "private", "Throwable", "getResult", "(", "FutureTask", "<", "Throwable", ">", "task", ",", "Thread", "thread", ")", "{", "try", "{", "if", "(", "timeout", ">", "0", ")", "{", "return", "task", ".", "get", "(", "timeout", ",", "timeUnit", ")", ";", "}", "else", "{", "return", "task", ".", "get", "(", ")", ";", "}", "}", "catch", "(", "InterruptedException", "e", ")", "{", "return", "e", ";", "// caller will re-throw; no need to call Thread.interrupt()", "}", "catch", "(", "ExecutionException", "e", ")", "{", "// test failed; have caller re-throw the exception thrown by the test", "return", "e", ".", "getCause", "(", ")", ";", "}", "catch", "(", "TimeoutException", "e", ")", "{", "return", "createTimeoutException", "(", "thread", ")", ";", "}", "}" ]
Wait for the test task, returning the exception thrown by the test if the test failed, an exception indicating a timeout if the test timed out, or {@code null} if the test passed.
[ "Wait", "for", "the", "test", "task", "returning", "the", "exception", "thrown", "by", "the", "test", "if", "the", "test", "failed", "an", "exception", "indicating", "a", "timeout", "if", "the", "test", "timed", "out", "or", "{" ]
train
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java#L153-L168
jenetics/jenetics
jenetics/src/main/java/io/jenetics/internal/math/random.java
random.nextInt
public static int nextInt(final IntRange range, final Random random) { """ Returns a pseudo-random, uniformly distributed int value between origin (included) and bound (excluded). @param range the allowed integer range @param random the random engine to use for calculating the random int value @return a random integer greater than or equal to {@code min} and less than or equal to {@code max} @throws IllegalArgumentException if {@code range.getMin() >= range.getMax()} """ return range.size() == 1 ? range.getMin() : nextInt(range.getMin(), range.getMax(), random); }
java
public static int nextInt(final IntRange range, final Random random) { return range.size() == 1 ? range.getMin() : nextInt(range.getMin(), range.getMax(), random); }
[ "public", "static", "int", "nextInt", "(", "final", "IntRange", "range", ",", "final", "Random", "random", ")", "{", "return", "range", ".", "size", "(", ")", "==", "1", "?", "range", ".", "getMin", "(", ")", ":", "nextInt", "(", "range", ".", "getMin", "(", ")", ",", "range", ".", "getMax", "(", ")", ",", "random", ")", ";", "}" ]
Returns a pseudo-random, uniformly distributed int value between origin (included) and bound (excluded). @param range the allowed integer range @param random the random engine to use for calculating the random int value @return a random integer greater than or equal to {@code min} and less than or equal to {@code max} @throws IllegalArgumentException if {@code range.getMin() >= range.getMax()}
[ "Returns", "a", "pseudo", "-", "random", "uniformly", "distributed", "int", "value", "between", "origin", "(", "included", ")", "and", "bound", "(", "excluded", ")", "." ]
train
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/internal/math/random.java#L112-L116
mbaechler/proxy-servlet
src/main/java/com/woonoz/proxy/servlet/UrlRewriterImpl.java
UrlRewriterImpl.copyPathFragment
private static int copyPathFragment(char[] input, int beginIndex, StringBuilder output) { """ Copy path fragment @param input input string @param beginIndex character index from which we look for '/' in input @param output where path fragments are appended @return last character in fragment + 1 """ int inputCharIndex = beginIndex; while (inputCharIndex < input.length) { final char inputChar = input[inputCharIndex]; if (inputChar == '/') { break; } output.append(inputChar); inputCharIndex += 1; } return inputCharIndex; }
java
private static int copyPathFragment(char[] input, int beginIndex, StringBuilder output) { int inputCharIndex = beginIndex; while (inputCharIndex < input.length) { final char inputChar = input[inputCharIndex]; if (inputChar == '/') { break; } output.append(inputChar); inputCharIndex += 1; } return inputCharIndex; }
[ "private", "static", "int", "copyPathFragment", "(", "char", "[", "]", "input", ",", "int", "beginIndex", ",", "StringBuilder", "output", ")", "{", "int", "inputCharIndex", "=", "beginIndex", ";", "while", "(", "inputCharIndex", "<", "input", ".", "length", ")", "{", "final", "char", "inputChar", "=", "input", "[", "inputCharIndex", "]", ";", "if", "(", "inputChar", "==", "'", "'", ")", "{", "break", ";", "}", "output", ".", "append", "(", "inputChar", ")", ";", "inputCharIndex", "+=", "1", ";", "}", "return", "inputCharIndex", ";", "}" ]
Copy path fragment @param input input string @param beginIndex character index from which we look for '/' in input @param output where path fragments are appended @return last character in fragment + 1
[ "Copy", "path", "fragment" ]
train
https://github.com/mbaechler/proxy-servlet/blob/0aa56fbf41b356222d4e2e257e92f2dd8ce0c6af/src/main/java/com/woonoz/proxy/servlet/UrlRewriterImpl.java#L266-L282
deeplearning4j/deeplearning4j
arbiter/arbiter-deeplearning4j/src/main/java/org/deeplearning4j/arbiter/scoring/util/ScoreUtil.java
ScoreUtil.score
public static double score(ComputationGraph model, DataSetIterator testSet, RegressionValue regressionValue) { """ Run a {@link RegressionEvaluation} over a {@link DataSetIterator} @param model the model to use @param testSet the test set iterator @param regressionValue the regression type to use @return """ RegressionEvaluation evaluation = model.evaluateRegression(testSet); return getScoreFromRegressionEval(evaluation, regressionValue); }
java
public static double score(ComputationGraph model, DataSetIterator testSet, RegressionValue regressionValue) { RegressionEvaluation evaluation = model.evaluateRegression(testSet); return getScoreFromRegressionEval(evaluation, regressionValue); }
[ "public", "static", "double", "score", "(", "ComputationGraph", "model", ",", "DataSetIterator", "testSet", ",", "RegressionValue", "regressionValue", ")", "{", "RegressionEvaluation", "evaluation", "=", "model", ".", "evaluateRegression", "(", "testSet", ")", ";", "return", "getScoreFromRegressionEval", "(", "evaluation", ",", "regressionValue", ")", ";", "}" ]
Run a {@link RegressionEvaluation} over a {@link DataSetIterator} @param model the model to use @param testSet the test set iterator @param regressionValue the regression type to use @return
[ "Run", "a", "{" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/arbiter/arbiter-deeplearning4j/src/main/java/org/deeplearning4j/arbiter/scoring/util/ScoreUtil.java#L252-L255
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/api/JMapperAPI.java
JMapperAPI.localAttribute
public static LocalAttribute localAttribute(String name, String customGet, String customSet) { """ Permits to define a local attribute. @param name local attribute name @param customGet custom get method @param customSet custom set method @return an instance of LocalAttribute """ return new LocalAttribute(name, customGet, customSet); }
java
public static LocalAttribute localAttribute(String name, String customGet, String customSet){ return new LocalAttribute(name, customGet, customSet); }
[ "public", "static", "LocalAttribute", "localAttribute", "(", "String", "name", ",", "String", "customGet", ",", "String", "customSet", ")", "{", "return", "new", "LocalAttribute", "(", "name", ",", "customGet", ",", "customSet", ")", ";", "}" ]
Permits to define a local attribute. @param name local attribute name @param customGet custom get method @param customSet custom set method @return an instance of LocalAttribute
[ "Permits", "to", "define", "a", "local", "attribute", "." ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/api/JMapperAPI.java#L127-L129
CubeEngine/Dirigent
src/main/java/org/cubeengine/dirigent/context/Arguments.java
Arguments.getOrElse
public String getOrElse(String name, String def) { """ Returns the parameter value for the given name or the given default if not found. @param name the name of the parameter @param def the default value @return the value of the argument by name or the default value. """ String val = get(name); if (val == null) { return def; } return val; }
java
public String getOrElse(String name, String def) { String val = get(name); if (val == null) { return def; } return val; }
[ "public", "String", "getOrElse", "(", "String", "name", ",", "String", "def", ")", "{", "String", "val", "=", "get", "(", "name", ")", ";", "if", "(", "val", "==", "null", ")", "{", "return", "def", ";", "}", "return", "val", ";", "}" ]
Returns the parameter value for the given name or the given default if not found. @param name the name of the parameter @param def the default value @return the value of the argument by name or the default value.
[ "Returns", "the", "parameter", "value", "for", "the", "given", "name", "or", "the", "given", "default", "if", "not", "found", "." ]
train
https://github.com/CubeEngine/Dirigent/blob/68587a8202754a6a6b629cc15e14c516806badaa/src/main/java/org/cubeengine/dirigent/context/Arguments.java#L88-L96
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/InstanceFailoverGroupsInner.java
InstanceFailoverGroupsInner.forceFailoverAllowDataLossAsync
public Observable<InstanceFailoverGroupInner> forceFailoverAllowDataLossAsync(String resourceGroupName, String locationName, String failoverGroupName) { """ Fails over from the current primary managed instance to this managed instance. This operation might result in data loss. @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 locationName The name of the region where the resource is located. @param failoverGroupName The name of the failover group. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return forceFailoverAllowDataLossWithServiceResponseAsync(resourceGroupName, locationName, failoverGroupName).map(new Func1<ServiceResponse<InstanceFailoverGroupInner>, InstanceFailoverGroupInner>() { @Override public InstanceFailoverGroupInner call(ServiceResponse<InstanceFailoverGroupInner> response) { return response.body(); } }); }
java
public Observable<InstanceFailoverGroupInner> forceFailoverAllowDataLossAsync(String resourceGroupName, String locationName, String failoverGroupName) { return forceFailoverAllowDataLossWithServiceResponseAsync(resourceGroupName, locationName, failoverGroupName).map(new Func1<ServiceResponse<InstanceFailoverGroupInner>, InstanceFailoverGroupInner>() { @Override public InstanceFailoverGroupInner call(ServiceResponse<InstanceFailoverGroupInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "InstanceFailoverGroupInner", ">", "forceFailoverAllowDataLossAsync", "(", "String", "resourceGroupName", ",", "String", "locationName", ",", "String", "failoverGroupName", ")", "{", "return", "forceFailoverAllowDataLossWithServiceResponseAsync", "(", "resourceGroupName", ",", "locationName", ",", "failoverGroupName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "InstanceFailoverGroupInner", ">", ",", "InstanceFailoverGroupInner", ">", "(", ")", "{", "@", "Override", "public", "InstanceFailoverGroupInner", "call", "(", "ServiceResponse", "<", "InstanceFailoverGroupInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Fails over from the current primary managed instance to this managed instance. This operation might result in data loss. @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 locationName The name of the region where the resource is located. @param failoverGroupName The name of the failover group. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Fails", "over", "from", "the", "current", "primary", "managed", "instance", "to", "this", "managed", "instance", ".", "This", "operation", "might", "result", "in", "data", "loss", "." ]
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/InstanceFailoverGroupsInner.java#L891-L898
Steveice10/OpenNBT
src/main/java/com/github/steveice10/opennbt/NBTIO.java
NBTIO.readTag
public static Tag readTag(InputStream in, boolean littleEndian) throws IOException { """ Reads an NBT tag. @param in Input stream to read from. @param littleEndian Whether to read little endian NBT. @return The read tag, or null if the tag is an end tag. @throws java.io.IOException If an I/O error occurs. """ return readTag((DataInput) (littleEndian ? new LittleEndianDataInputStream(in) : new DataInputStream(in))); }
java
public static Tag readTag(InputStream in, boolean littleEndian) throws IOException { return readTag((DataInput) (littleEndian ? new LittleEndianDataInputStream(in) : new DataInputStream(in))); }
[ "public", "static", "Tag", "readTag", "(", "InputStream", "in", ",", "boolean", "littleEndian", ")", "throws", "IOException", "{", "return", "readTag", "(", "(", "DataInput", ")", "(", "littleEndian", "?", "new", "LittleEndianDataInputStream", "(", "in", ")", ":", "new", "DataInputStream", "(", "in", ")", ")", ")", ";", "}" ]
Reads an NBT tag. @param in Input stream to read from. @param littleEndian Whether to read little endian NBT. @return The read tag, or null if the tag is an end tag. @throws java.io.IOException If an I/O error occurs.
[ "Reads", "an", "NBT", "tag", "." ]
train
https://github.com/Steveice10/OpenNBT/blob/9bf4adb2afd206a21bc4309c85d642494d1fb536/src/main/java/com/github/steveice10/opennbt/NBTIO.java#L167-L169
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/StringUtils.java
StringUtils.appendIfMissing
private static String appendIfMissing(final String str, final CharSequence suffix, final boolean ignoreCase, final CharSequence... suffixes) { """ Appends the suffix to the end of the string if the string does not already end with the suffix. @param str The string. @param suffix The suffix to append to the end of the string. @param ignoreCase Indicates whether the compare should ignore case. @param suffixes Additional suffixes that are valid terminators (optional). @return A new String if suffix was appended, the same string otherwise. """ if (str == null || isEmpty(suffix) || endsWith(str, suffix, ignoreCase)) { return str; } if (suffixes != null && suffixes.length > 0) { for (final CharSequence s : suffixes) { if (endsWith(str, s, ignoreCase)) { return str; } } } return str + suffix.toString(); }
java
private static String appendIfMissing(final String str, final CharSequence suffix, final boolean ignoreCase, final CharSequence... suffixes) { if (str == null || isEmpty(suffix) || endsWith(str, suffix, ignoreCase)) { return str; } if (suffixes != null && suffixes.length > 0) { for (final CharSequence s : suffixes) { if (endsWith(str, s, ignoreCase)) { return str; } } } return str + suffix.toString(); }
[ "private", "static", "String", "appendIfMissing", "(", "final", "String", "str", ",", "final", "CharSequence", "suffix", ",", "final", "boolean", "ignoreCase", ",", "final", "CharSequence", "...", "suffixes", ")", "{", "if", "(", "str", "==", "null", "||", "isEmpty", "(", "suffix", ")", "||", "endsWith", "(", "str", ",", "suffix", ",", "ignoreCase", ")", ")", "{", "return", "str", ";", "}", "if", "(", "suffixes", "!=", "null", "&&", "suffixes", ".", "length", ">", "0", ")", "{", "for", "(", "final", "CharSequence", "s", ":", "suffixes", ")", "{", "if", "(", "endsWith", "(", "str", ",", "s", ",", "ignoreCase", ")", ")", "{", "return", "str", ";", "}", "}", "}", "return", "str", "+", "suffix", ".", "toString", "(", ")", ";", "}" ]
Appends the suffix to the end of the string if the string does not already end with the suffix. @param str The string. @param suffix The suffix to append to the end of the string. @param ignoreCase Indicates whether the compare should ignore case. @param suffixes Additional suffixes that are valid terminators (optional). @return A new String if suffix was appended, the same string otherwise.
[ "Appends", "the", "suffix", "to", "the", "end", "of", "the", "string", "if", "the", "string", "does", "not", "already", "end", "with", "the", "suffix", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L8766-L8778
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-classloader/xwiki-commons-classloader-api/src/main/java/org/xwiki/classloader/internal/ResourceLoader.java
ResourceLoader.findResource
public URL findResource(URL[] sources, String name) { """ Finds resource with given name at the given search path. The path is searched iteratively, one URL at a time. If the URL points to a directory, the name is the file path relative to this directory. If the URL points to the JAR file, the name identifies an entry in that JAR file. If the URL points to the JAR file, the resource is not found in that JAR file, and the JAR file has Class-Path attribute, the JAR files identified in the Class-Path are also searched for the resource. @param sources the source URL path @param name the resource name @return URL of the resource, or null if not found """ Set<URL> visited = new HashSet<>(); for (URL source : sources) { URL url = findResource(source, name, visited, null); if (url != null) { return url; } } return null; }
java
public URL findResource(URL[] sources, String name) { Set<URL> visited = new HashSet<>(); for (URL source : sources) { URL url = findResource(source, name, visited, null); if (url != null) { return url; } } return null; }
[ "public", "URL", "findResource", "(", "URL", "[", "]", "sources", ",", "String", "name", ")", "{", "Set", "<", "URL", ">", "visited", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "URL", "source", ":", "sources", ")", "{", "URL", "url", "=", "findResource", "(", "source", ",", "name", ",", "visited", ",", "null", ")", ";", "if", "(", "url", "!=", "null", ")", "{", "return", "url", ";", "}", "}", "return", "null", ";", "}" ]
Finds resource with given name at the given search path. The path is searched iteratively, one URL at a time. If the URL points to a directory, the name is the file path relative to this directory. If the URL points to the JAR file, the name identifies an entry in that JAR file. If the URL points to the JAR file, the resource is not found in that JAR file, and the JAR file has Class-Path attribute, the JAR files identified in the Class-Path are also searched for the resource. @param sources the source URL path @param name the resource name @return URL of the resource, or null if not found
[ "Finds", "resource", "with", "given", "name", "at", "the", "given", "search", "path", ".", "The", "path", "is", "searched", "iteratively", "one", "URL", "at", "a", "time", ".", "If", "the", "URL", "points", "to", "a", "directory", "the", "name", "is", "the", "file", "path", "relative", "to", "this", "directory", ".", "If", "the", "URL", "points", "to", "the", "JAR", "file", "the", "name", "identifies", "an", "entry", "in", "that", "JAR", "file", ".", "If", "the", "URL", "points", "to", "the", "JAR", "file", "the", "resource", "is", "not", "found", "in", "that", "JAR", "file", "and", "the", "JAR", "file", "has", "Class", "-", "Path", "attribute", "the", "JAR", "files", "identified", "in", "the", "Class", "-", "Path", "are", "also", "searched", "for", "the", "resource", "." ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-classloader/xwiki-commons-classloader-api/src/main/java/org/xwiki/classloader/internal/ResourceLoader.java#L283-L293
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/PersistentResourceXMLDescription.java
PersistentResourceXMLDescription.persistDecorator
private void persistDecorator(XMLExtendedStreamWriter writer, ModelNode model) throws XMLStreamException { """ persist decorator and than continue to children without touching the model """ if (shouldWriteDecoratorAndElements(model)) { writer.writeStartElement(decoratorElement); persistChildren(writer, model); writer.writeEndElement(); } }
java
private void persistDecorator(XMLExtendedStreamWriter writer, ModelNode model) throws XMLStreamException { if (shouldWriteDecoratorAndElements(model)) { writer.writeStartElement(decoratorElement); persistChildren(writer, model); writer.writeEndElement(); } }
[ "private", "void", "persistDecorator", "(", "XMLExtendedStreamWriter", "writer", ",", "ModelNode", "model", ")", "throws", "XMLStreamException", "{", "if", "(", "shouldWriteDecoratorAndElements", "(", "model", ")", ")", "{", "writer", ".", "writeStartElement", "(", "decoratorElement", ")", ";", "persistChildren", "(", "writer", ",", "model", ")", ";", "writer", ".", "writeEndElement", "(", ")", ";", "}", "}" ]
persist decorator and than continue to children without touching the model
[ "persist", "decorator", "and", "than", "continue", "to", "children", "without", "touching", "the", "model" ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/PersistentResourceXMLDescription.java#L366-L372
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ExpressRouteConnectionsInner.java
ExpressRouteConnectionsInner.listAsync
public Observable<ExpressRouteConnectionListInner> listAsync(String resourceGroupName, String expressRouteGatewayName) { """ Lists ExpressRouteConnections. @param resourceGroupName The name of the resource group. @param expressRouteGatewayName The name of the ExpressRoute gateway. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ExpressRouteConnectionListInner object """ return listWithServiceResponseAsync(resourceGroupName, expressRouteGatewayName).map(new Func1<ServiceResponse<ExpressRouteConnectionListInner>, ExpressRouteConnectionListInner>() { @Override public ExpressRouteConnectionListInner call(ServiceResponse<ExpressRouteConnectionListInner> response) { return response.body(); } }); }
java
public Observable<ExpressRouteConnectionListInner> listAsync(String resourceGroupName, String expressRouteGatewayName) { return listWithServiceResponseAsync(resourceGroupName, expressRouteGatewayName).map(new Func1<ServiceResponse<ExpressRouteConnectionListInner>, ExpressRouteConnectionListInner>() { @Override public ExpressRouteConnectionListInner call(ServiceResponse<ExpressRouteConnectionListInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ExpressRouteConnectionListInner", ">", "listAsync", "(", "String", "resourceGroupName", ",", "String", "expressRouteGatewayName", ")", "{", "return", "listWithServiceResponseAsync", "(", "resourceGroupName", ",", "expressRouteGatewayName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ExpressRouteConnectionListInner", ">", ",", "ExpressRouteConnectionListInner", ">", "(", ")", "{", "@", "Override", "public", "ExpressRouteConnectionListInner", "call", "(", "ServiceResponse", "<", "ExpressRouteConnectionListInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Lists ExpressRouteConnections. @param resourceGroupName The name of the resource group. @param expressRouteGatewayName The name of the ExpressRoute gateway. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ExpressRouteConnectionListInner object
[ "Lists", "ExpressRouteConnections", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ExpressRouteConnectionsInner.java#L557-L564
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java
JBBPBitOutputStream.writeStringArray
public void writeStringArray(final String[] value, final JBBPByteOrder order) throws IOException { """ Write array of strings in stream in UTF8 format <b>the byte order in saved char data will be BIG_ENDIAN</b> @param value array to be written, must not be null but can contain null values @throws IOException it will be thrown for transport errors @see #writeString(String, JBBPByteOrder) @since 1.4.0 """ for (final String s : value) { this.writeString(s, order); } }
java
public void writeStringArray(final String[] value, final JBBPByteOrder order) throws IOException { for (final String s : value) { this.writeString(s, order); } }
[ "public", "void", "writeStringArray", "(", "final", "String", "[", "]", "value", ",", "final", "JBBPByteOrder", "order", ")", "throws", "IOException", "{", "for", "(", "final", "String", "s", ":", "value", ")", "{", "this", ".", "writeString", "(", "s", ",", "order", ")", ";", "}", "}" ]
Write array of strings in stream in UTF8 format <b>the byte order in saved char data will be BIG_ENDIAN</b> @param value array to be written, must not be null but can contain null values @throws IOException it will be thrown for transport errors @see #writeString(String, JBBPByteOrder) @since 1.4.0
[ "Write", "array", "of", "strings", "in", "stream", "in", "UTF8", "format", "<b", ">", "the", "byte", "order", "in", "saved", "char", "data", "will", "be", "BIG_ENDIAN<", "/", "b", ">" ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java#L425-L429
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/api/TagsApi.java
TagsApi.getClusterPhotos
public Photos getClusterPhotos(String tag, List<String> clusterId) throws JinxException { """ Returns the first 24 photos for a given tag cluster This method does not require authentication. This method will combine the Strings in the clusterId list. @param tag the tag that the cluster belongs to. Required. @param clusterId top three tags for the cluster. Required. @return first 24 photos for a given tag cluster. @throws JinxException if required parameters are missing, or if there are any errors. @see <a href="https://www.flickr.com/services/api/flickr.tags.getClusterPhotos.html">flickr.tags.getClusterPhotos</a> """ JinxUtils.validateParams(tag, clusterId); StringBuilder sb = new StringBuilder(); for (String s : clusterId) { sb.append(s).append("-"); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } return getClusterPhotos(tag, sb.toString()); }
java
public Photos getClusterPhotos(String tag, List<String> clusterId) throws JinxException { JinxUtils.validateParams(tag, clusterId); StringBuilder sb = new StringBuilder(); for (String s : clusterId) { sb.append(s).append("-"); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } return getClusterPhotos(tag, sb.toString()); }
[ "public", "Photos", "getClusterPhotos", "(", "String", "tag", ",", "List", "<", "String", ">", "clusterId", ")", "throws", "JinxException", "{", "JinxUtils", ".", "validateParams", "(", "tag", ",", "clusterId", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "String", "s", ":", "clusterId", ")", "{", "sb", ".", "append", "(", "s", ")", ".", "append", "(", "\"-\"", ")", ";", "}", "if", "(", "sb", ".", "length", "(", ")", ">", "0", ")", "{", "sb", ".", "deleteCharAt", "(", "sb", ".", "length", "(", ")", "-", "1", ")", ";", "}", "return", "getClusterPhotos", "(", "tag", ",", "sb", ".", "toString", "(", ")", ")", ";", "}" ]
Returns the first 24 photos for a given tag cluster This method does not require authentication. This method will combine the Strings in the clusterId list. @param tag the tag that the cluster belongs to. Required. @param clusterId top three tags for the cluster. Required. @return first 24 photos for a given tag cluster. @throws JinxException if required parameters are missing, or if there are any errors. @see <a href="https://www.flickr.com/services/api/flickr.tags.getClusterPhotos.html">flickr.tags.getClusterPhotos</a>
[ "Returns", "the", "first", "24", "photos", "for", "a", "given", "tag", "cluster" ]
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/TagsApi.java#L85-L95
google/closure-compiler
src/com/google/javascript/jscomp/ProcessClosurePrimitives.java
ProcessClosurePrimitives.verifyLastArgumentIsString
private boolean verifyLastArgumentIsString(Node methodName, Node arg) { """ Verifies that a method call has exactly one argument, and that it's a string literal. Reports a compile error if it doesn't. @return Whether the argument checked out okay """ return verifyNotNull(methodName, arg) && verifyOfType(methodName, arg, Token.STRING) && verifyIsLast(methodName, arg); }
java
private boolean verifyLastArgumentIsString(Node methodName, Node arg) { return verifyNotNull(methodName, arg) && verifyOfType(methodName, arg, Token.STRING) && verifyIsLast(methodName, arg); }
[ "private", "boolean", "verifyLastArgumentIsString", "(", "Node", "methodName", ",", "Node", "arg", ")", "{", "return", "verifyNotNull", "(", "methodName", ",", "arg", ")", "&&", "verifyOfType", "(", "methodName", ",", "arg", ",", "Token", ".", "STRING", ")", "&&", "verifyIsLast", "(", "methodName", ",", "arg", ")", ";", "}" ]
Verifies that a method call has exactly one argument, and that it's a string literal. Reports a compile error if it doesn't. @return Whether the argument checked out okay
[ "Verifies", "that", "a", "method", "call", "has", "exactly", "one", "argument", "and", "that", "it", "s", "a", "string", "literal", ".", "Reports", "a", "compile", "error", "if", "it", "doesn", "t", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosurePrimitives.java#L956-L960
vincentk/joptimizer
src/main/java/com/joptimizer/util/Utils.java
Utils.calculateScaledResidual
public static double calculateScaledResidual(DoubleMatrix2D A, DoubleMatrix2D X, DoubleMatrix2D B) { """ Calculate the scaled residual <br> ||Ax-b||_oo/( ||A||_oo . ||x||_oo + ||b||_oo ), with <br> ||x||_oo = max(||x[i]||) """ double residual = -Double.MAX_VALUE; double niX = Algebra.DEFAULT.normInfinity(X); double niB = Algebra.DEFAULT.normInfinity(B); if(Double.compare(niX, 0.)==0 && Double.compare(niB, 0.)==0){ return 0; }else{ double num = Algebra.DEFAULT.normInfinity(Algebra.DEFAULT.mult(A, X).assign(B, Functions.minus)); double den = Algebra.DEFAULT.normInfinity(A) * niX + niB; residual = num / den; //log.debug("scaled residual: " + residual); return residual; } }
java
public static double calculateScaledResidual(DoubleMatrix2D A, DoubleMatrix2D X, DoubleMatrix2D B){ double residual = -Double.MAX_VALUE; double niX = Algebra.DEFAULT.normInfinity(X); double niB = Algebra.DEFAULT.normInfinity(B); if(Double.compare(niX, 0.)==0 && Double.compare(niB, 0.)==0){ return 0; }else{ double num = Algebra.DEFAULT.normInfinity(Algebra.DEFAULT.mult(A, X).assign(B, Functions.minus)); double den = Algebra.DEFAULT.normInfinity(A) * niX + niB; residual = num / den; //log.debug("scaled residual: " + residual); return residual; } }
[ "public", "static", "double", "calculateScaledResidual", "(", "DoubleMatrix2D", "A", ",", "DoubleMatrix2D", "X", ",", "DoubleMatrix2D", "B", ")", "{", "double", "residual", "=", "-", "Double", ".", "MAX_VALUE", ";", "double", "niX", "=", "Algebra", ".", "DEFAULT", ".", "normInfinity", "(", "X", ")", ";", "double", "niB", "=", "Algebra", ".", "DEFAULT", ".", "normInfinity", "(", "B", ")", ";", "if", "(", "Double", ".", "compare", "(", "niX", ",", "0.", ")", "==", "0", "&&", "Double", ".", "compare", "(", "niB", ",", "0.", ")", "==", "0", ")", "{", "return", "0", ";", "}", "else", "{", "double", "num", "=", "Algebra", ".", "DEFAULT", ".", "normInfinity", "(", "Algebra", ".", "DEFAULT", ".", "mult", "(", "A", ",", "X", ")", ".", "assign", "(", "B", ",", "Functions", ".", "minus", ")", ")", ";", "double", "den", "=", "Algebra", ".", "DEFAULT", ".", "normInfinity", "(", "A", ")", "*", "niX", "+", "niB", ";", "residual", "=", "num", "/", "den", ";", "//log.debug(\"scaled residual: \" + residual);\r", "return", "residual", ";", "}", "}" ]
Calculate the scaled residual <br> ||Ax-b||_oo/( ||A||_oo . ||x||_oo + ||b||_oo ), with <br> ||x||_oo = max(||x[i]||)
[ "Calculate", "the", "scaled", "residual", "<br", ">", "||Ax", "-", "b||_oo", "/", "(", "||A||_oo", ".", "||x||_oo", "+", "||b||_oo", ")", "with", "<br", ">", "||x||_oo", "=", "max", "(", "||x", "[", "i", "]", "||", ")" ]
train
https://github.com/vincentk/joptimizer/blob/65064c1bb0b26c7261358021e4c93d06dd43564f/src/main/java/com/joptimizer/util/Utils.java#L113-L127
ThreeTen/threetenbp
src/main/java/org/threeten/bp/chrono/Chronology.java
Chronology.ensureChronoZonedDateTime
<D extends ChronoLocalDate> ChronoZonedDateTimeImpl<D> ensureChronoZonedDateTime(Temporal temporal) { """ Casts the {@code Temporal} to {@code ChronoZonedDateTimeImpl} with the same chronology. @param temporal a date-time to cast, not null @return the date-time checked and cast to {@code ChronoZonedDateTimeImpl}, not null @throws ClassCastException if the date-time cannot be cast to ChronoZonedDateTimeImpl or the chronology is not equal this Chrono """ @SuppressWarnings("unchecked") ChronoZonedDateTimeImpl<D> other = (ChronoZonedDateTimeImpl<D>) temporal; if (this.equals(other.toLocalDate().getChronology()) == false) { throw new ClassCastException("Chrono mismatch, required: " + getId() + ", supplied: " + other.toLocalDate().getChronology().getId()); } return other; }
java
<D extends ChronoLocalDate> ChronoZonedDateTimeImpl<D> ensureChronoZonedDateTime(Temporal temporal) { @SuppressWarnings("unchecked") ChronoZonedDateTimeImpl<D> other = (ChronoZonedDateTimeImpl<D>) temporal; if (this.equals(other.toLocalDate().getChronology()) == false) { throw new ClassCastException("Chrono mismatch, required: " + getId() + ", supplied: " + other.toLocalDate().getChronology().getId()); } return other; }
[ "<", "D", "extends", "ChronoLocalDate", ">", "ChronoZonedDateTimeImpl", "<", "D", ">", "ensureChronoZonedDateTime", "(", "Temporal", "temporal", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "ChronoZonedDateTimeImpl", "<", "D", ">", "other", "=", "(", "ChronoZonedDateTimeImpl", "<", "D", ">", ")", "temporal", ";", "if", "(", "this", ".", "equals", "(", "other", ".", "toLocalDate", "(", ")", ".", "getChronology", "(", ")", ")", "==", "false", ")", "{", "throw", "new", "ClassCastException", "(", "\"Chrono mismatch, required: \"", "+", "getId", "(", ")", "+", "\", supplied: \"", "+", "other", ".", "toLocalDate", "(", ")", ".", "getChronology", "(", ")", ".", "getId", "(", ")", ")", ";", "}", "return", "other", ";", "}" ]
Casts the {@code Temporal} to {@code ChronoZonedDateTimeImpl} with the same chronology. @param temporal a date-time to cast, not null @return the date-time checked and cast to {@code ChronoZonedDateTimeImpl}, not null @throws ClassCastException if the date-time cannot be cast to ChronoZonedDateTimeImpl or the chronology is not equal this Chrono
[ "Casts", "the", "{", "@code", "Temporal", "}", "to", "{", "@code", "ChronoZonedDateTimeImpl", "}", "with", "the", "same", "chronology", "." ]
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/chrono/Chronology.java#L392-L400
csc19601128/Phynixx
phynixx/phynixx-logger/src/main/java/org/csc/phynixx/loggersystem/logrecord/PhynixxXADataRecorder.java
PhynixxXADataRecorder.recoverDataRecorder
static PhynixxXADataRecorder recoverDataRecorder(XADataLogger xaDataLogger, IXADataRecorderLifecycleListener dataRecorderLifycycleListner) { """ opens an Recorder for read. If no recorder with the given ID exists recorder with no data is returned @param xaDataLogger Strategy to persist the records @return @throws IOException @throws InterruptedException """ try { PhynixxXADataRecorder dataRecorder = new PhynixxXADataRecorder(-1, xaDataLogger, dataRecorderLifycycleListner); dataRecorder.recover(); return dataRecorder; } catch (Exception e) { throw new DelegatedRuntimeException(e); } }
java
static PhynixxXADataRecorder recoverDataRecorder(XADataLogger xaDataLogger, IXADataRecorderLifecycleListener dataRecorderLifycycleListner) { try { PhynixxXADataRecorder dataRecorder = new PhynixxXADataRecorder(-1, xaDataLogger, dataRecorderLifycycleListner); dataRecorder.recover(); return dataRecorder; } catch (Exception e) { throw new DelegatedRuntimeException(e); } }
[ "static", "PhynixxXADataRecorder", "recoverDataRecorder", "(", "XADataLogger", "xaDataLogger", ",", "IXADataRecorderLifecycleListener", "dataRecorderLifycycleListner", ")", "{", "try", "{", "PhynixxXADataRecorder", "dataRecorder", "=", "new", "PhynixxXADataRecorder", "(", "-", "1", ",", "xaDataLogger", ",", "dataRecorderLifycycleListner", ")", ";", "dataRecorder", ".", "recover", "(", ")", ";", "return", "dataRecorder", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "DelegatedRuntimeException", "(", "e", ")", ";", "}", "}" ]
opens an Recorder for read. If no recorder with the given ID exists recorder with no data is returned @param xaDataLogger Strategy to persist the records @return @throws IOException @throws InterruptedException
[ "opens", "an", "Recorder", "for", "read", ".", "If", "no", "recorder", "with", "the", "given", "ID", "exists", "recorder", "with", "no", "data", "is", "returned" ]
train
https://github.com/csc19601128/Phynixx/blob/a26c03bc229a8882c647799834115bec6bdc0ac8/phynixx/phynixx-logger/src/main/java/org/csc/phynixx/loggersystem/logrecord/PhynixxXADataRecorder.java#L73-L82
alkacon/opencms-core
src/org/opencms/main/OpenCmsSolrHandler.java
OpenCmsSolrHandler.initializeRequest
protected Context initializeRequest(HttpServletRequest req, HttpServletResponse res) throws CmsException, Exception, CmsSearchException, IOException { """ Initialized the search request and sets the local parameter.<p> @param req the servlet request @param res the servlet response @return the generated context @throws CmsException if something goes wrong @throws Exception if something goes wrong @throws CmsSearchException if something goes wrong @throws IOException if something goes wrong """ Context context = new Context(); context.m_cms = getCmsObject(req); context.m_params = CmsRequestUtil.createParameterMap(req.getParameterMap()); context.m_index = CmsSearchManager.getIndexSolr(context.m_cms, context.m_params); if (context.m_index != null) { context.m_query = new CmsSolrQuery(context.m_cms, context.m_params); } else { res.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (LOG.isInfoEnabled()) { String indexName = context.m_params.get(PARAM_CORE) != null ? context.m_params.get(PARAM_CORE)[0] : (context.m_params.get(PARAM_INDEX) != null ? context.m_params.get(PARAM_INDEX)[0] : null); LOG.info(Messages.get().getBundle().key(Messages.GUI_SOLR_INDEX_NOT_FOUND_1, indexName)); } } return context; }
java
protected Context initializeRequest(HttpServletRequest req, HttpServletResponse res) throws CmsException, Exception, CmsSearchException, IOException { Context context = new Context(); context.m_cms = getCmsObject(req); context.m_params = CmsRequestUtil.createParameterMap(req.getParameterMap()); context.m_index = CmsSearchManager.getIndexSolr(context.m_cms, context.m_params); if (context.m_index != null) { context.m_query = new CmsSolrQuery(context.m_cms, context.m_params); } else { res.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (LOG.isInfoEnabled()) { String indexName = context.m_params.get(PARAM_CORE) != null ? context.m_params.get(PARAM_CORE)[0] : (context.m_params.get(PARAM_INDEX) != null ? context.m_params.get(PARAM_INDEX)[0] : null); LOG.info(Messages.get().getBundle().key(Messages.GUI_SOLR_INDEX_NOT_FOUND_1, indexName)); } } return context; }
[ "protected", "Context", "initializeRequest", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ")", "throws", "CmsException", ",", "Exception", ",", "CmsSearchException", ",", "IOException", "{", "Context", "context", "=", "new", "Context", "(", ")", ";", "context", ".", "m_cms", "=", "getCmsObject", "(", "req", ")", ";", "context", ".", "m_params", "=", "CmsRequestUtil", ".", "createParameterMap", "(", "req", ".", "getParameterMap", "(", ")", ")", ";", "context", ".", "m_index", "=", "CmsSearchManager", ".", "getIndexSolr", "(", "context", ".", "m_cms", ",", "context", ".", "m_params", ")", ";", "if", "(", "context", ".", "m_index", "!=", "null", ")", "{", "context", ".", "m_query", "=", "new", "CmsSolrQuery", "(", "context", ".", "m_cms", ",", "context", ".", "m_params", ")", ";", "}", "else", "{", "res", ".", "setStatus", "(", "HttpServletResponse", ".", "SC_BAD_REQUEST", ")", ";", "if", "(", "LOG", ".", "isInfoEnabled", "(", ")", ")", "{", "String", "indexName", "=", "context", ".", "m_params", ".", "get", "(", "PARAM_CORE", ")", "!=", "null", "?", "context", ".", "m_params", ".", "get", "(", "PARAM_CORE", ")", "[", "0", "]", ":", "(", "context", ".", "m_params", ".", "get", "(", "PARAM_INDEX", ")", "!=", "null", "?", "context", ".", "m_params", ".", "get", "(", "PARAM_INDEX", ")", "[", "0", "]", ":", "null", ")", ";", "LOG", ".", "info", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "key", "(", "Messages", ".", "GUI_SOLR_INDEX_NOT_FOUND_1", ",", "indexName", ")", ")", ";", "}", "}", "return", "context", ";", "}" ]
Initialized the search request and sets the local parameter.<p> @param req the servlet request @param res the servlet response @return the generated context @throws CmsException if something goes wrong @throws Exception if something goes wrong @throws CmsSearchException if something goes wrong @throws IOException if something goes wrong
[ "Initialized", "the", "search", "request", "and", "sets", "the", "local", "parameter", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/OpenCmsSolrHandler.java#L218-L239
UrielCh/ovh-java-sdk
ovh-java-sdk-kube/src/main/java/net/minidev/ovh/api/ApiOvhKube.java
ApiOvhKube.serviceName_publiccloud_node_nodeId_GET
public OvhNode serviceName_publiccloud_node_nodeId_GET(String serviceName, String nodeId) throws IOException { """ Get information on a specific node on your cluster REST: GET /kube/{serviceName}/publiccloud/node/{nodeId} @param nodeId [required] Node ID @param serviceName [required] Cluster ID API beta """ String qPath = "/kube/{serviceName}/publiccloud/node/{nodeId}"; StringBuilder sb = path(qPath, serviceName, nodeId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhNode.class); }
java
public OvhNode serviceName_publiccloud_node_nodeId_GET(String serviceName, String nodeId) throws IOException { String qPath = "/kube/{serviceName}/publiccloud/node/{nodeId}"; StringBuilder sb = path(qPath, serviceName, nodeId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhNode.class); }
[ "public", "OvhNode", "serviceName_publiccloud_node_nodeId_GET", "(", "String", "serviceName", ",", "String", "nodeId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/kube/{serviceName}/publiccloud/node/{nodeId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "nodeId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhNode", ".", "class", ")", ";", "}" ]
Get information on a specific node on your cluster REST: GET /kube/{serviceName}/publiccloud/node/{nodeId} @param nodeId [required] Node ID @param serviceName [required] Cluster ID API beta
[ "Get", "information", "on", "a", "specific", "node", "on", "your", "cluster" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-kube/src/main/java/net/minidev/ovh/api/ApiOvhKube.java#L233-L238
alkacon/opencms-core
src/org/opencms/ui/apps/resourcetypes/CmsNewResourceTypeDialog.java
CmsNewResourceTypeDialog.createParentXmlElements
protected void createParentXmlElements(CmsXmlContent xmlContent, String xmlPath, Locale l) { """ Creates the parents of nested XML elements if necessary. @param xmlContent the XML content that is edited. @param xmlPath the path of the (nested) element, for which the parents should be created @param l the locale for which the XML content is edited. """ if (CmsXmlUtils.isDeepXpath(xmlPath)) { String parentPath = CmsXmlUtils.removeLastXpathElement(xmlPath); if (null == xmlContent.getValue(parentPath, l)) { createParentXmlElements(xmlContent, parentPath, l); xmlContent.addValue(m_cms, parentPath, l, CmsXmlUtils.getXpathIndexInt(parentPath) - 1); } } }
java
protected void createParentXmlElements(CmsXmlContent xmlContent, String xmlPath, Locale l) { if (CmsXmlUtils.isDeepXpath(xmlPath)) { String parentPath = CmsXmlUtils.removeLastXpathElement(xmlPath); if (null == xmlContent.getValue(parentPath, l)) { createParentXmlElements(xmlContent, parentPath, l); xmlContent.addValue(m_cms, parentPath, l, CmsXmlUtils.getXpathIndexInt(parentPath) - 1); } } }
[ "protected", "void", "createParentXmlElements", "(", "CmsXmlContent", "xmlContent", ",", "String", "xmlPath", ",", "Locale", "l", ")", "{", "if", "(", "CmsXmlUtils", ".", "isDeepXpath", "(", "xmlPath", ")", ")", "{", "String", "parentPath", "=", "CmsXmlUtils", ".", "removeLastXpathElement", "(", "xmlPath", ")", ";", "if", "(", "null", "==", "xmlContent", ".", "getValue", "(", "parentPath", ",", "l", ")", ")", "{", "createParentXmlElements", "(", "xmlContent", ",", "parentPath", ",", "l", ")", ";", "xmlContent", ".", "addValue", "(", "m_cms", ",", "parentPath", ",", "l", ",", "CmsXmlUtils", ".", "getXpathIndexInt", "(", "parentPath", ")", "-", "1", ")", ";", "}", "}", "}" ]
Creates the parents of nested XML elements if necessary. @param xmlContent the XML content that is edited. @param xmlPath the path of the (nested) element, for which the parents should be created @param l the locale for which the XML content is edited.
[ "Creates", "the", "parents", "of", "nested", "XML", "elements", "if", "necessary", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/resourcetypes/CmsNewResourceTypeDialog.java#L395-L405
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/validation/RelsValidator.java
RelsValidator.checkBadAssertion
private void checkBadAssertion(String nsURI, String localName, String qName) throws SAXException { """ checkBadAssertion: checks that the DC and fedora-view namespace are not being used in RELS-EXT, and that if fedora-model is used, the localName is hasService, hasModel, isDeploymentOf, or isContractorOf. Also ensures that fedora-model:hasContentModel is only used once. @param nsURI the namespace URI of the predicate being evaluated @param localName the local name of the predicate being evaluated @param qName the qualified name of the predicate being evaluated """ if (m_dsId.equals(RELS_EXT) && (nsURI.equals(DC.uri) || nsURI.equals(OAI_DC.uri))) { throw new SAXException("RelsExtValidator:" + " The RELS-EXT datastream has improper" + " relationship assertion: " + qName + ".\n" + " No Dublin Core assertions allowed" + " in Fedora relationship metadata."); } else if (nsURI.equals(MODEL.uri)) { if ((m_dsId.equals(RELS_INT) && !localName.equals(MODEL.DOWNLOAD_FILENAME.localName) ) || (m_dsId.equals(RELS_EXT) && !localName.equals(MODEL.HAS_SERVICE.localName) && !localName.equals(MODEL.IS_CONTRACTOR_OF.localName) && !localName.equals(MODEL.HAS_MODEL.localName) && !localName.equals(MODEL.IS_DEPLOYMENT_OF.localName) )) { throw new SAXException("RelsExtValidator:" + " Disallowed predicate in " + m_dsId + ": " + qName + "\n" + " The only predicates from the fedora-model namespace" + " allowed in RELS-EXT are " + MODEL.HAS_SERVICE.localName + ", " + MODEL.IS_CONTRACTOR_OF.localName + ", " + MODEL.HAS_MODEL.localName + ", " + MODEL.IS_DEPLOYMENT_OF.localName + ". The only predicate allowed " + "in RELS-INT is " + MODEL.DOWNLOAD_FILENAME.localName +"." ); } } else if (nsURI.equals(VIEW.uri)) { throw new SAXException("RelsExtValidator:" + " Disallowed predicate in RELS-EXT: " + qName + "\n" + " The fedora-view namespace is reserved by Fedora."); } }
java
private void checkBadAssertion(String nsURI, String localName, String qName) throws SAXException { if (m_dsId.equals(RELS_EXT) && (nsURI.equals(DC.uri) || nsURI.equals(OAI_DC.uri))) { throw new SAXException("RelsExtValidator:" + " The RELS-EXT datastream has improper" + " relationship assertion: " + qName + ".\n" + " No Dublin Core assertions allowed" + " in Fedora relationship metadata."); } else if (nsURI.equals(MODEL.uri)) { if ((m_dsId.equals(RELS_INT) && !localName.equals(MODEL.DOWNLOAD_FILENAME.localName) ) || (m_dsId.equals(RELS_EXT) && !localName.equals(MODEL.HAS_SERVICE.localName) && !localName.equals(MODEL.IS_CONTRACTOR_OF.localName) && !localName.equals(MODEL.HAS_MODEL.localName) && !localName.equals(MODEL.IS_DEPLOYMENT_OF.localName) )) { throw new SAXException("RelsExtValidator:" + " Disallowed predicate in " + m_dsId + ": " + qName + "\n" + " The only predicates from the fedora-model namespace" + " allowed in RELS-EXT are " + MODEL.HAS_SERVICE.localName + ", " + MODEL.IS_CONTRACTOR_OF.localName + ", " + MODEL.HAS_MODEL.localName + ", " + MODEL.IS_DEPLOYMENT_OF.localName + ". The only predicate allowed " + "in RELS-INT is " + MODEL.DOWNLOAD_FILENAME.localName +"." ); } } else if (nsURI.equals(VIEW.uri)) { throw new SAXException("RelsExtValidator:" + " Disallowed predicate in RELS-EXT: " + qName + "\n" + " The fedora-view namespace is reserved by Fedora."); } }
[ "private", "void", "checkBadAssertion", "(", "String", "nsURI", ",", "String", "localName", ",", "String", "qName", ")", "throws", "SAXException", "{", "if", "(", "m_dsId", ".", "equals", "(", "RELS_EXT", ")", "&&", "(", "nsURI", ".", "equals", "(", "DC", ".", "uri", ")", "||", "nsURI", ".", "equals", "(", "OAI_DC", ".", "uri", ")", ")", ")", "{", "throw", "new", "SAXException", "(", "\"RelsExtValidator:\"", "+", "\" The RELS-EXT datastream has improper\"", "+", "\" relationship assertion: \"", "+", "qName", "+", "\".\\n\"", "+", "\" No Dublin Core assertions allowed\"", "+", "\" in Fedora relationship metadata.\"", ")", ";", "}", "else", "if", "(", "nsURI", ".", "equals", "(", "MODEL", ".", "uri", ")", ")", "{", "if", "(", "(", "m_dsId", ".", "equals", "(", "RELS_INT", ")", "&&", "!", "localName", ".", "equals", "(", "MODEL", ".", "DOWNLOAD_FILENAME", ".", "localName", ")", ")", "||", "(", "m_dsId", ".", "equals", "(", "RELS_EXT", ")", "&&", "!", "localName", ".", "equals", "(", "MODEL", ".", "HAS_SERVICE", ".", "localName", ")", "&&", "!", "localName", ".", "equals", "(", "MODEL", ".", "IS_CONTRACTOR_OF", ".", "localName", ")", "&&", "!", "localName", ".", "equals", "(", "MODEL", ".", "HAS_MODEL", ".", "localName", ")", "&&", "!", "localName", ".", "equals", "(", "MODEL", ".", "IS_DEPLOYMENT_OF", ".", "localName", ")", ")", ")", "{", "throw", "new", "SAXException", "(", "\"RelsExtValidator:\"", "+", "\" Disallowed predicate in \"", "+", "m_dsId", "+", "\": \"", "+", "qName", "+", "\"\\n\"", "+", "\" The only predicates from the fedora-model namespace\"", "+", "\" allowed in RELS-EXT are \"", "+", "MODEL", ".", "HAS_SERVICE", ".", "localName", "+", "\", \"", "+", "MODEL", ".", "IS_CONTRACTOR_OF", ".", "localName", "+", "\", \"", "+", "MODEL", ".", "HAS_MODEL", ".", "localName", "+", "\", \"", "+", "MODEL", ".", "IS_DEPLOYMENT_OF", ".", "localName", "+", "\". The only predicate allowed \"", "+", "\"in RELS-INT is \"", "+", "MODEL", ".", "DOWNLOAD_FILENAME", ".", "localName", "+", "\".\"", ")", ";", "}", "}", "else", "if", "(", "nsURI", ".", "equals", "(", "VIEW", ".", "uri", ")", ")", "{", "throw", "new", "SAXException", "(", "\"RelsExtValidator:\"", "+", "\" Disallowed predicate in RELS-EXT: \"", "+", "qName", "+", "\"\\n\"", "+", "\" The fedora-view namespace is reserved by Fedora.\"", ")", ";", "}", "}" ]
checkBadAssertion: checks that the DC and fedora-view namespace are not being used in RELS-EXT, and that if fedora-model is used, the localName is hasService, hasModel, isDeploymentOf, or isContractorOf. Also ensures that fedora-model:hasContentModel is only used once. @param nsURI the namespace URI of the predicate being evaluated @param localName the local name of the predicate being evaluated @param qName the qualified name of the predicate being evaluated
[ "checkBadAssertion", ":", "checks", "that", "the", "DC", "and", "fedora", "-", "view", "namespace", "are", "not", "being", "used", "in", "RELS", "-", "EXT", "and", "that", "if", "fedora", "-", "model", "is", "used", "the", "localName", "is", "hasService", "hasModel", "isDeploymentOf", "or", "isContractorOf", ".", "Also", "ensures", "that", "fedora", "-", "model", ":", "hasContentModel", "is", "only", "used", "once", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/validation/RelsValidator.java#L312-L351
bbottema/outlook-message-parser
src/main/java/org/simplejavamail/outlookmessageparser/OutlookMessageParser.java
OutlookMessageParser.checkRecipientDirectoryEntry
private void checkRecipientDirectoryEntry(final DirectoryEntry dir, final OutlookMessage msg) throws IOException { """ Parses a recipient directory entry which holds informations about one of possibly multiple recipients. The parsed information is put into the {@link OutlookMessage} object. @param dir The current node in the .msg file. @param msg The resulting {@link OutlookMessage} object. @throws IOException Thrown if the .msg file could not be parsed. """ final OutlookRecipient recipient = new OutlookRecipient(); // we iterate through all entries in the current directory for (final Iterator<?> iter = dir.getEntries(); iter.hasNext(); ) { final Entry entry = (Entry) iter.next(); // check whether the entry is either a directory entry // or a document entry, while we are just interested in document entries on this level if (!entry.isDirectoryEntry() && entry.isDocumentEntry()) { // a document entry contains information about the mail (e.g, from, to, subject, ...) checkRecipientDocumentEntry((DocumentEntry) entry, recipient); } } //after all properties are set -> add recipient to msg object msg.addRecipient(recipient); }
java
private void checkRecipientDirectoryEntry(final DirectoryEntry dir, final OutlookMessage msg) throws IOException { final OutlookRecipient recipient = new OutlookRecipient(); // we iterate through all entries in the current directory for (final Iterator<?> iter = dir.getEntries(); iter.hasNext(); ) { final Entry entry = (Entry) iter.next(); // check whether the entry is either a directory entry // or a document entry, while we are just interested in document entries on this level if (!entry.isDirectoryEntry() && entry.isDocumentEntry()) { // a document entry contains information about the mail (e.g, from, to, subject, ...) checkRecipientDocumentEntry((DocumentEntry) entry, recipient); } } //after all properties are set -> add recipient to msg object msg.addRecipient(recipient); }
[ "private", "void", "checkRecipientDirectoryEntry", "(", "final", "DirectoryEntry", "dir", ",", "final", "OutlookMessage", "msg", ")", "throws", "IOException", "{", "final", "OutlookRecipient", "recipient", "=", "new", "OutlookRecipient", "(", ")", ";", "// we iterate through all entries in the current directory", "for", "(", "final", "Iterator", "<", "?", ">", "iter", "=", "dir", ".", "getEntries", "(", ")", ";", "iter", ".", "hasNext", "(", ")", ";", ")", "{", "final", "Entry", "entry", "=", "(", "Entry", ")", "iter", ".", "next", "(", ")", ";", "// check whether the entry is either a directory entry", "// or a document entry, while we are just interested in document entries on this level\t\t\t", "if", "(", "!", "entry", ".", "isDirectoryEntry", "(", ")", "&&", "entry", ".", "isDocumentEntry", "(", ")", ")", "{", "// a document entry contains information about the mail (e.g, from, to, subject, ...)", "checkRecipientDocumentEntry", "(", "(", "DocumentEntry", ")", "entry", ",", "recipient", ")", ";", "}", "}", "//after all properties are set -> add recipient to msg object", "msg", ".", "addRecipient", "(", "recipient", ")", ";", "}" ]
Parses a recipient directory entry which holds informations about one of possibly multiple recipients. The parsed information is put into the {@link OutlookMessage} object. @param dir The current node in the .msg file. @param msg The resulting {@link OutlookMessage} object. @throws IOException Thrown if the .msg file could not be parsed.
[ "Parses", "a", "recipient", "directory", "entry", "which", "holds", "informations", "about", "one", "of", "possibly", "multiple", "recipients", ".", "The", "parsed", "information", "is", "put", "into", "the", "{", "@link", "OutlookMessage", "}", "object", "." ]
train
https://github.com/bbottema/outlook-message-parser/blob/ea7d59da33c8a62dfc2e0aa64d2f8f7c903ccb0e/src/main/java/org/simplejavamail/outlookmessageparser/OutlookMessageParser.java#L181-L199
icode/ameba
src/main/java/ameba/lib/Fibers.java
Fibers.runInFiberRuntime
public static <V> V runInFiberRuntime(FiberScheduler scheduler, SuspendableCallable<V> target) throws InterruptedException { """ Runs an action in a new fiber, awaits the fiber's termination, and returns its result. Unlike {@link #runInFiber(FiberScheduler, SuspendableCallable) runInFiber} this method does not throw {@link ExecutionException}, but wraps any checked exception thrown by the operation in a {@link RuntimeException}. @param <V> @param scheduler the {@link FiberScheduler} to use when scheduling the fiber. @param target the operation @return the operations return value @throws InterruptedException """ return FiberUtil.runInFiberRuntime(scheduler, target); }
java
public static <V> V runInFiberRuntime(FiberScheduler scheduler, SuspendableCallable<V> target) throws InterruptedException { return FiberUtil.runInFiberRuntime(scheduler, target); }
[ "public", "static", "<", "V", ">", "V", "runInFiberRuntime", "(", "FiberScheduler", "scheduler", ",", "SuspendableCallable", "<", "V", ">", "target", ")", "throws", "InterruptedException", "{", "return", "FiberUtil", ".", "runInFiberRuntime", "(", "scheduler", ",", "target", ")", ";", "}" ]
Runs an action in a new fiber, awaits the fiber's termination, and returns its result. Unlike {@link #runInFiber(FiberScheduler, SuspendableCallable) runInFiber} this method does not throw {@link ExecutionException}, but wraps any checked exception thrown by the operation in a {@link RuntimeException}. @param <V> @param scheduler the {@link FiberScheduler} to use when scheduling the fiber. @param target the operation @return the operations return value @throws InterruptedException
[ "Runs", "an", "action", "in", "a", "new", "fiber", "awaits", "the", "fiber", "s", "termination", "and", "returns", "its", "result", ".", "Unlike", "{", "@link", "#runInFiber", "(", "FiberScheduler", "SuspendableCallable", ")", "runInFiber", "}", "this", "method", "does", "not", "throw", "{", "@link", "ExecutionException", "}", "but", "wraps", "any", "checked", "exception", "thrown", "by", "the", "operation", "in", "a", "{", "@link", "RuntimeException", "}", "." ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/lib/Fibers.java#L317-L319
rubenlagus/TelegramBots
telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMedia.java
InputMedia.setMedia
public T setMedia(InputStream mediaStream, String fileName) { """ Use this setter to send new file as stream. @param mediaStream File to send @return This object """ this.newMediaStream = mediaStream; this.isNewMedia = true; this.mediaName = fileName; this.media = "attach://" + fileName; return (T) this; }
java
public T setMedia(InputStream mediaStream, String fileName) { this.newMediaStream = mediaStream; this.isNewMedia = true; this.mediaName = fileName; this.media = "attach://" + fileName; return (T) this; }
[ "public", "T", "setMedia", "(", "InputStream", "mediaStream", ",", "String", "fileName", ")", "{", "this", ".", "newMediaStream", "=", "mediaStream", ";", "this", ".", "isNewMedia", "=", "true", ";", "this", ".", "mediaName", "=", "fileName", ";", "this", ".", "media", "=", "\"attach://\"", "+", "fileName", ";", "return", "(", "T", ")", "this", ";", "}" ]
Use this setter to send new file as stream. @param mediaStream File to send @return This object
[ "Use", "this", "setter", "to", "send", "new", "file", "as", "stream", "." ]
train
https://github.com/rubenlagus/TelegramBots/blob/d62354915d7664597a40fd9858f16bce67ef1478/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMedia.java#L104-L110
biojava/biojava
biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java
LocationHelper.modulateCircularIndex
public static int modulateCircularIndex(int index, int seqLength) { """ Takes a point on a circular location and moves it left until it falls at the earliest possible point that represents the same base. @param index Index of the position to work with @param seqLength Length of the Sequence @return The shifted point """ // Dummy case if (seqLength == 0) { return index; } // Modulate while (index > seqLength) { index -= seqLength; } return index; }
java
public static int modulateCircularIndex(int index, int seqLength) { // Dummy case if (seqLength == 0) { return index; } // Modulate while (index > seqLength) { index -= seqLength; } return index; }
[ "public", "static", "int", "modulateCircularIndex", "(", "int", "index", ",", "int", "seqLength", ")", "{", "// Dummy case", "if", "(", "seqLength", "==", "0", ")", "{", "return", "index", ";", "}", "// Modulate", "while", "(", "index", ">", "seqLength", ")", "{", "index", "-=", "seqLength", ";", "}", "return", "index", ";", "}" ]
Takes a point on a circular location and moves it left until it falls at the earliest possible point that represents the same base. @param index Index of the position to work with @param seqLength Length of the Sequence @return The shifted point
[ "Takes", "a", "point", "on", "a", "circular", "location", "and", "moves", "it", "left", "until", "it", "falls", "at", "the", "earliest", "possible", "point", "that", "represents", "the", "same", "base", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java#L226-L236
mebigfatguy/fb-contrib
src/main/java/com/mebigfatguy/fbcontrib/detect/BloatedAssignmentScope.java
BloatedAssignmentScope.sawMonitorEnter
private void sawMonitorEnter(int pc) { """ processes a monitor enter call to create a scope block @param pc the current program counter """ monitorSyncPCs.add(Integer.valueOf(pc)); ScopeBlock sb = new ScopeBlock(pc, Integer.MAX_VALUE); sb.setSync(); rootScopeBlock.addChild(sb); }
java
private void sawMonitorEnter(int pc) { monitorSyncPCs.add(Integer.valueOf(pc)); ScopeBlock sb = new ScopeBlock(pc, Integer.MAX_VALUE); sb.setSync(); rootScopeBlock.addChild(sb); }
[ "private", "void", "sawMonitorEnter", "(", "int", "pc", ")", "{", "monitorSyncPCs", ".", "add", "(", "Integer", ".", "valueOf", "(", "pc", ")", ")", ";", "ScopeBlock", "sb", "=", "new", "ScopeBlock", "(", "pc", ",", "Integer", ".", "MAX_VALUE", ")", ";", "sb", ".", "setSync", "(", ")", ";", "rootScopeBlock", ".", "addChild", "(", "sb", ")", ";", "}" ]
processes a monitor enter call to create a scope block @param pc the current program counter
[ "processes", "a", "monitor", "enter", "call", "to", "create", "a", "scope", "block" ]
train
https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/BloatedAssignmentScope.java#L555-L561
classgraph/classgraph
src/main/java/io/github/classgraph/ClassInfo.java
ClassInfo.getClassesWithFieldOrMethodAnnotation
private ClassInfoList getClassesWithFieldOrMethodAnnotation(final RelType relType) { """ Get the classes that have this class as a field, method or method parameter annotation. @param relType One of {@link RelType#CLASSES_WITH_FIELD_ANNOTATION}, {@link RelType#CLASSES_WITH_METHOD_ANNOTATION} or {@link RelType#CLASSES_WITH_METHOD_PARAMETER_ANNOTATION}. @return A list of classes that have a declared method with this annotation or meta-annotation, or the empty list if none. """ final boolean isField = relType == RelType.CLASSES_WITH_FIELD_ANNOTATION; if (!(isField ? scanResult.scanSpec.enableFieldInfo : scanResult.scanSpec.enableMethodInfo) || !scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enable" + (isField ? "Field" : "Method") + "Info() and " + "#enableAnnotationInfo() before #scan()"); } final ReachableAndDirectlyRelatedClasses classesWithDirectlyAnnotatedFieldsOrMethods = this .filterClassInfo(relType, /* strictWhitelist = */ !isExternalClass); final ReachableAndDirectlyRelatedClasses annotationsWithThisMetaAnnotation = this.filterClassInfo( RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass, ClassType.ANNOTATION); if (annotationsWithThisMetaAnnotation.reachableClasses.isEmpty()) { // This annotation does not meta-annotate another annotation that annotates a method return new ClassInfoList(classesWithDirectlyAnnotatedFieldsOrMethods, /* sortByName = */ true); } else { // Take the union of all classes with fields or methods directly annotated by this annotation, // and classes with fields or methods meta-annotated by this annotation final Set<ClassInfo> allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods = new LinkedHashSet<>( classesWithDirectlyAnnotatedFieldsOrMethods.reachableClasses); for (final ClassInfo metaAnnotatedAnnotation : annotationsWithThisMetaAnnotation.reachableClasses) { allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods .addAll(metaAnnotatedAnnotation.filterClassInfo(relType, /* strictWhitelist = */ !metaAnnotatedAnnotation.isExternalClass).reachableClasses); } return new ClassInfoList(allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods, classesWithDirectlyAnnotatedFieldsOrMethods.directlyRelatedClasses, /* sortByName = */ true); } }
java
private ClassInfoList getClassesWithFieldOrMethodAnnotation(final RelType relType) { final boolean isField = relType == RelType.CLASSES_WITH_FIELD_ANNOTATION; if (!(isField ? scanResult.scanSpec.enableFieldInfo : scanResult.scanSpec.enableMethodInfo) || !scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enable" + (isField ? "Field" : "Method") + "Info() and " + "#enableAnnotationInfo() before #scan()"); } final ReachableAndDirectlyRelatedClasses classesWithDirectlyAnnotatedFieldsOrMethods = this .filterClassInfo(relType, /* strictWhitelist = */ !isExternalClass); final ReachableAndDirectlyRelatedClasses annotationsWithThisMetaAnnotation = this.filterClassInfo( RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass, ClassType.ANNOTATION); if (annotationsWithThisMetaAnnotation.reachableClasses.isEmpty()) { // This annotation does not meta-annotate another annotation that annotates a method return new ClassInfoList(classesWithDirectlyAnnotatedFieldsOrMethods, /* sortByName = */ true); } else { // Take the union of all classes with fields or methods directly annotated by this annotation, // and classes with fields or methods meta-annotated by this annotation final Set<ClassInfo> allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods = new LinkedHashSet<>( classesWithDirectlyAnnotatedFieldsOrMethods.reachableClasses); for (final ClassInfo metaAnnotatedAnnotation : annotationsWithThisMetaAnnotation.reachableClasses) { allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods .addAll(metaAnnotatedAnnotation.filterClassInfo(relType, /* strictWhitelist = */ !metaAnnotatedAnnotation.isExternalClass).reachableClasses); } return new ClassInfoList(allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods, classesWithDirectlyAnnotatedFieldsOrMethods.directlyRelatedClasses, /* sortByName = */ true); } }
[ "private", "ClassInfoList", "getClassesWithFieldOrMethodAnnotation", "(", "final", "RelType", "relType", ")", "{", "final", "boolean", "isField", "=", "relType", "==", "RelType", ".", "CLASSES_WITH_FIELD_ANNOTATION", ";", "if", "(", "!", "(", "isField", "?", "scanResult", ".", "scanSpec", ".", "enableFieldInfo", ":", "scanResult", ".", "scanSpec", ".", "enableMethodInfo", ")", "||", "!", "scanResult", ".", "scanSpec", ".", "enableAnnotationInfo", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Please call ClassGraph#enable\"", "+", "(", "isField", "?", "\"Field\"", ":", "\"Method\"", ")", "+", "\"Info() and \"", "+", "\"#enableAnnotationInfo() before #scan()\"", ")", ";", "}", "final", "ReachableAndDirectlyRelatedClasses", "classesWithDirectlyAnnotatedFieldsOrMethods", "=", "this", ".", "filterClassInfo", "(", "relType", ",", "/* strictWhitelist = */", "!", "isExternalClass", ")", ";", "final", "ReachableAndDirectlyRelatedClasses", "annotationsWithThisMetaAnnotation", "=", "this", ".", "filterClassInfo", "(", "RelType", ".", "CLASSES_WITH_ANNOTATION", ",", "/* strictWhitelist = */", "!", "isExternalClass", ",", "ClassType", ".", "ANNOTATION", ")", ";", "if", "(", "annotationsWithThisMetaAnnotation", ".", "reachableClasses", ".", "isEmpty", "(", ")", ")", "{", "// This annotation does not meta-annotate another annotation that annotates a method", "return", "new", "ClassInfoList", "(", "classesWithDirectlyAnnotatedFieldsOrMethods", ",", "/* sortByName = */", "true", ")", ";", "}", "else", "{", "// Take the union of all classes with fields or methods directly annotated by this annotation,", "// and classes with fields or methods meta-annotated by this annotation", "final", "Set", "<", "ClassInfo", ">", "allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods", "=", "new", "LinkedHashSet", "<>", "(", "classesWithDirectlyAnnotatedFieldsOrMethods", ".", "reachableClasses", ")", ";", "for", "(", "final", "ClassInfo", "metaAnnotatedAnnotation", ":", "annotationsWithThisMetaAnnotation", ".", "reachableClasses", ")", "{", "allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods", ".", "addAll", "(", "metaAnnotatedAnnotation", ".", "filterClassInfo", "(", "relType", ",", "/* strictWhitelist = */", "!", "metaAnnotatedAnnotation", ".", "isExternalClass", ")", ".", "reachableClasses", ")", ";", "}", "return", "new", "ClassInfoList", "(", "allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods", ",", "classesWithDirectlyAnnotatedFieldsOrMethods", ".", "directlyRelatedClasses", ",", "/* sortByName = */", "true", ")", ";", "}", "}" ]
Get the classes that have this class as a field, method or method parameter annotation. @param relType One of {@link RelType#CLASSES_WITH_FIELD_ANNOTATION}, {@link RelType#CLASSES_WITH_METHOD_ANNOTATION} or {@link RelType#CLASSES_WITH_METHOD_PARAMETER_ANNOTATION}. @return A list of classes that have a declared method with this annotation or meta-annotation, or the empty list if none.
[ "Get", "the", "classes", "that", "have", "this", "class", "as", "a", "field", "method", "or", "method", "parameter", "annotation", "." ]
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/io/github/classgraph/ClassInfo.java#L1571-L1598
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/TemplateList.java
TemplateList.addObjectIfNotFound
private void addObjectIfNotFound(Object obj, Vector v) { """ Add object to vector if not already there. @param obj @param v """ int n = v.size(); boolean addIt = true; for (int i = 0; i < n; i++) { if (v.elementAt(i) == obj) { addIt = false; break; } } if (addIt) { v.addElement(obj); } }
java
private void addObjectIfNotFound(Object obj, Vector v) { int n = v.size(); boolean addIt = true; for (int i = 0; i < n; i++) { if (v.elementAt(i) == obj) { addIt = false; break; } } if (addIt) { v.addElement(obj); } }
[ "private", "void", "addObjectIfNotFound", "(", "Object", "obj", ",", "Vector", "v", ")", "{", "int", "n", "=", "v", ".", "size", "(", ")", ";", "boolean", "addIt", "=", "true", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "if", "(", "v", ".", "elementAt", "(", "i", ")", "==", "obj", ")", "{", "addIt", "=", "false", ";", "break", ";", "}", "}", "if", "(", "addIt", ")", "{", "v", ".", "addElement", "(", "obj", ")", ";", "}", "}" ]
Add object to vector if not already there. @param obj @param v
[ "Add", "object", "to", "vector", "if", "not", "already", "there", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/TemplateList.java#L739-L759
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MultiIndex.java
MultiIndex.createIndex
private long createIndex(NodeDataIndexingIterator iterator, NodeData rootNode) throws IOException, RepositoryException { """ Create index. @param iterator the NodeDataIndexing iterator @param rootNode the root node of the index @return the total amount of indexed nodes @throws IOException if an error occurs while writing to the index. @throws RepositoryException if any other error occurs """ MultithreadedIndexing indexing = new MultithreadedIndexing(iterator, rootNode); return indexing.launch(false); }
java
private long createIndex(NodeDataIndexingIterator iterator, NodeData rootNode) throws IOException, RepositoryException { MultithreadedIndexing indexing = new MultithreadedIndexing(iterator, rootNode); return indexing.launch(false); }
[ "private", "long", "createIndex", "(", "NodeDataIndexingIterator", "iterator", ",", "NodeData", "rootNode", ")", "throws", "IOException", ",", "RepositoryException", "{", "MultithreadedIndexing", "indexing", "=", "new", "MultithreadedIndexing", "(", "iterator", ",", "rootNode", ")", ";", "return", "indexing", ".", "launch", "(", "false", ")", ";", "}" ]
Create index. @param iterator the NodeDataIndexing iterator @param rootNode the root node of the index @return the total amount of indexed nodes @throws IOException if an error occurs while writing to the index. @throws RepositoryException if any other error occurs
[ "Create", "index", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MultiIndex.java#L2115-L2120
Javacord/Javacord
javacord-core/src/main/java/org/javacord/core/entity/server/ServerImpl.java
ServerImpl.setDeafened
public void setDeafened(long userId, boolean deafened) { """ Sets the deafened state of the user with the given id. @param userId The id of the user. @param deafened Whether the user with the given id is deafened or not. """ if (deafened) { this.deafened.add(userId); } else { this.deafened.remove(userId); } }
java
public void setDeafened(long userId, boolean deafened) { if (deafened) { this.deafened.add(userId); } else { this.deafened.remove(userId); } }
[ "public", "void", "setDeafened", "(", "long", "userId", ",", "boolean", "deafened", ")", "{", "if", "(", "deafened", ")", "{", "this", ".", "deafened", ".", "add", "(", "userId", ")", ";", "}", "else", "{", "this", ".", "deafened", ".", "remove", "(", "userId", ")", ";", "}", "}" ]
Sets the deafened state of the user with the given id. @param userId The id of the user. @param deafened Whether the user with the given id is deafened or not.
[ "Sets", "the", "deafened", "state", "of", "the", "user", "with", "the", "given", "id", "." ]
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-core/src/main/java/org/javacord/core/entity/server/ServerImpl.java#L772-L778
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/TupleMRConfigBuilder.java
TupleMRConfigBuilder.initializeComparators
public static void initializeComparators(Configuration conf, TupleMRConfig groupConfig) { """ Initializes the custom comparator instances inside the given config criterias, calling the {@link Configurable#setConf(Configuration)} method. """ TupleMRConfigBuilder.initializeComparators(conf, groupConfig.getCommonCriteria()); for (Criteria criteria : groupConfig.getSpecificOrderBys()) { if (criteria != null) { TupleMRConfigBuilder.initializeComparators(conf, criteria); } } }
java
public static void initializeComparators(Configuration conf, TupleMRConfig groupConfig) { TupleMRConfigBuilder.initializeComparators(conf, groupConfig.getCommonCriteria()); for (Criteria criteria : groupConfig.getSpecificOrderBys()) { if (criteria != null) { TupleMRConfigBuilder.initializeComparators(conf, criteria); } } }
[ "public", "static", "void", "initializeComparators", "(", "Configuration", "conf", ",", "TupleMRConfig", "groupConfig", ")", "{", "TupleMRConfigBuilder", ".", "initializeComparators", "(", "conf", ",", "groupConfig", ".", "getCommonCriteria", "(", ")", ")", ";", "for", "(", "Criteria", "criteria", ":", "groupConfig", ".", "getSpecificOrderBys", "(", ")", ")", "{", "if", "(", "criteria", "!=", "null", ")", "{", "TupleMRConfigBuilder", ".", "initializeComparators", "(", "conf", ",", "criteria", ")", ";", "}", "}", "}" ]
Initializes the custom comparator instances inside the given config criterias, calling the {@link Configurable#setConf(Configuration)} method.
[ "Initializes", "the", "custom", "comparator", "instances", "inside", "the", "given", "config", "criterias", "calling", "the", "{" ]
train
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/TupleMRConfigBuilder.java#L434-L441
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/las/index/strtree/BoundablePair.java
BoundablePair.expandToQueue
public void expandToQueue( PriorityQueue priQ, double minDistance ) { """ For a pair which is not a leaf (i.e. has at least one composite boundable) computes a list of new pairs from the expansion of the larger boundable. """ boolean isComp1 = isComposite(boundable1); boolean isComp2 = isComposite(boundable2); /** * HEURISTIC: If both boundable are composite, * choose the one with largest area to expand. * Otherwise, simply expand whichever is composite. */ if (isComp1 && isComp2) { if (area(boundable1) > area(boundable2)) { expand(boundable1, boundable2, priQ, minDistance); return; } else { expand(boundable2, boundable1, priQ, minDistance); return; } } else if (isComp1) { expand(boundable1, boundable2, priQ, minDistance); return; } else if (isComp2) { expand(boundable2, boundable1, priQ, minDistance); return; } throw new IllegalArgumentException("neither boundable is composite"); }
java
public void expandToQueue( PriorityQueue priQ, double minDistance ) { boolean isComp1 = isComposite(boundable1); boolean isComp2 = isComposite(boundable2); /** * HEURISTIC: If both boundable are composite, * choose the one with largest area to expand. * Otherwise, simply expand whichever is composite. */ if (isComp1 && isComp2) { if (area(boundable1) > area(boundable2)) { expand(boundable1, boundable2, priQ, minDistance); return; } else { expand(boundable2, boundable1, priQ, minDistance); return; } } else if (isComp1) { expand(boundable1, boundable2, priQ, minDistance); return; } else if (isComp2) { expand(boundable2, boundable1, priQ, minDistance); return; } throw new IllegalArgumentException("neither boundable is composite"); }
[ "public", "void", "expandToQueue", "(", "PriorityQueue", "priQ", ",", "double", "minDistance", ")", "{", "boolean", "isComp1", "=", "isComposite", "(", "boundable1", ")", ";", "boolean", "isComp2", "=", "isComposite", "(", "boundable2", ")", ";", "/**\n * HEURISTIC: If both boundable are composite,\n * choose the one with largest area to expand.\n * Otherwise, simply expand whichever is composite.\n */", "if", "(", "isComp1", "&&", "isComp2", ")", "{", "if", "(", "area", "(", "boundable1", ")", ">", "area", "(", "boundable2", ")", ")", "{", "expand", "(", "boundable1", ",", "boundable2", ",", "priQ", ",", "minDistance", ")", ";", "return", ";", "}", "else", "{", "expand", "(", "boundable2", ",", "boundable1", ",", "priQ", ",", "minDistance", ")", ";", "return", ";", "}", "}", "else", "if", "(", "isComp1", ")", "{", "expand", "(", "boundable1", ",", "boundable2", ",", "priQ", ",", "minDistance", ")", ";", "return", ";", "}", "else", "if", "(", "isComp2", ")", "{", "expand", "(", "boundable2", ",", "boundable1", ",", "priQ", ",", "minDistance", ")", ";", "return", ";", "}", "throw", "new", "IllegalArgumentException", "(", "\"neither boundable is composite\"", ")", ";", "}" ]
For a pair which is not a leaf (i.e. has at least one composite boundable) computes a list of new pairs from the expansion of the larger boundable.
[ "For", "a", "pair", "which", "is", "not", "a", "leaf", "(", "i", ".", "e", ".", "has", "at", "least", "one", "composite", "boundable", ")", "computes", "a", "list", "of", "new", "pairs", "from", "the", "expansion", "of", "the", "larger", "boundable", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/las/index/strtree/BoundablePair.java#L167-L193
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java
ApiOvhHostingprivateDatabase.serviceName_changeVersion_POST
public OvhTask serviceName_changeVersion_POST(String serviceName, OvhAvailableVersionEnum version) throws IOException { """ Change the private database engine version REST: POST /hosting/privateDatabase/{serviceName}/changeVersion @param version [required] Private database versions @param serviceName [required] The internal name of your private database """ String qPath = "/hosting/privateDatabase/{serviceName}/changeVersion"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "version", version); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask serviceName_changeVersion_POST(String serviceName, OvhAvailableVersionEnum version) throws IOException { String qPath = "/hosting/privateDatabase/{serviceName}/changeVersion"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "version", version); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "serviceName_changeVersion_POST", "(", "String", "serviceName", ",", "OvhAvailableVersionEnum", "version", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/hosting/privateDatabase/{serviceName}/changeVersion\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"version\"", ",", "version", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhTask", ".", "class", ")", ";", "}" ]
Change the private database engine version REST: POST /hosting/privateDatabase/{serviceName}/changeVersion @param version [required] Private database versions @param serviceName [required] The internal name of your private database
[ "Change", "the", "private", "database", "engine", "version" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java#L90-L97
keenon/loglinear
src/main/java/com/github/keenon/loglinear/model/GraphicalModel.java
GraphicalModel.addFactor
public VectorFactor addFactor(int[] neighborIndices, int[] neighborDimensions, Function<int[], ConcatVector> assignmentFeaturizer) { """ This is the preferred way to add factors to a graphical model. Specify the neighbors, their dimensions, and a function that maps from variable assignments to ConcatVector's of features, and this function will handle the data flow of constructing and populating a factor matching those specifications. <p> IMPORTANT: assignmentFeaturizer must be REPEATABLE and NOT HAVE SIDE EFFECTS This is because it is actually stored as a lazy closure until the full featurized vector is needed, and then it is created, used, and discarded. It CAN BE CALLED MULTIPLE TIMES, and must always return the same value in order for behavior of downstream systems to be defined. @param neighborIndices the names of the variables, as indices @param neighborDimensions the sizes of the neighbor variables, corresponding to the order in neighborIndices @param assignmentFeaturizer a function that maps from an assignment to the variables, represented as an array of assignments in the same order as presented in neighborIndices, to a ConcatVector of features for that assignment. @return a reference to the created factor. This can be safely ignored, as the factor is already saved in the model """ ConcatVectorTable features = new ConcatVectorTable(neighborDimensions); for (int[] assignment : features) { features.setAssignmentValue(assignment, () -> assignmentFeaturizer.apply(assignment)); } return addFactor(features, neighborIndices); }
java
public VectorFactor addFactor(int[] neighborIndices, int[] neighborDimensions, Function<int[], ConcatVector> assignmentFeaturizer) { ConcatVectorTable features = new ConcatVectorTable(neighborDimensions); for (int[] assignment : features) { features.setAssignmentValue(assignment, () -> assignmentFeaturizer.apply(assignment)); } return addFactor(features, neighborIndices); }
[ "public", "VectorFactor", "addFactor", "(", "int", "[", "]", "neighborIndices", ",", "int", "[", "]", "neighborDimensions", ",", "Function", "<", "int", "[", "]", ",", "ConcatVector", ">", "assignmentFeaturizer", ")", "{", "ConcatVectorTable", "features", "=", "new", "ConcatVectorTable", "(", "neighborDimensions", ")", ";", "for", "(", "int", "[", "]", "assignment", ":", "features", ")", "{", "features", ".", "setAssignmentValue", "(", "assignment", ",", "(", ")", "->", "assignmentFeaturizer", ".", "apply", "(", "assignment", ")", ")", ";", "}", "return", "addFactor", "(", "features", ",", "neighborIndices", ")", ";", "}" ]
This is the preferred way to add factors to a graphical model. Specify the neighbors, their dimensions, and a function that maps from variable assignments to ConcatVector's of features, and this function will handle the data flow of constructing and populating a factor matching those specifications. <p> IMPORTANT: assignmentFeaturizer must be REPEATABLE and NOT HAVE SIDE EFFECTS This is because it is actually stored as a lazy closure until the full featurized vector is needed, and then it is created, used, and discarded. It CAN BE CALLED MULTIPLE TIMES, and must always return the same value in order for behavior of downstream systems to be defined. @param neighborIndices the names of the variables, as indices @param neighborDimensions the sizes of the neighbor variables, corresponding to the order in neighborIndices @param assignmentFeaturizer a function that maps from an assignment to the variables, represented as an array of assignments in the same order as presented in neighborIndices, to a ConcatVector of features for that assignment. @return a reference to the created factor. This can be safely ignored, as the factor is already saved in the model
[ "This", "is", "the", "preferred", "way", "to", "add", "factors", "to", "a", "graphical", "model", ".", "Specify", "the", "neighbors", "their", "dimensions", "and", "a", "function", "that", "maps", "from", "variable", "assignments", "to", "ConcatVector", "s", "of", "features", "and", "this", "function", "will", "handle", "the", "data", "flow", "of", "constructing", "and", "populating", "a", "factor", "matching", "those", "specifications", ".", "<p", ">", "IMPORTANT", ":", "assignmentFeaturizer", "must", "be", "REPEATABLE", "and", "NOT", "HAVE", "SIDE", "EFFECTS", "This", "is", "because", "it", "is", "actually", "stored", "as", "a", "lazy", "closure", "until", "the", "full", "featurized", "vector", "is", "needed", "and", "then", "it", "is", "created", "used", "and", "discarded", ".", "It", "CAN", "BE", "CALLED", "MULTIPLE", "TIMES", "and", "must", "always", "return", "the", "same", "value", "in", "order", "for", "behavior", "of", "downstream", "systems", "to", "be", "defined", "." ]
train
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/model/GraphicalModel.java#L419-L426
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabasesInner.java
DatabasesInner.getAsync
public Observable<DatabaseInner> getAsync(String resourceGroupName, String serverName, String databaseName, String expand) { """ Gets a database. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database to be retrieved. @param expand A comma separated list of child objects to expand in the response. Possible properties: serviceTierAdvisors, transparentDataEncryption. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DatabaseInner object """ return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName, expand).map(new Func1<ServiceResponse<DatabaseInner>, DatabaseInner>() { @Override public DatabaseInner call(ServiceResponse<DatabaseInner> response) { return response.body(); } }); }
java
public Observable<DatabaseInner> getAsync(String resourceGroupName, String serverName, String databaseName, String expand) { return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName, expand).map(new Func1<ServiceResponse<DatabaseInner>, DatabaseInner>() { @Override public DatabaseInner call(ServiceResponse<DatabaseInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DatabaseInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "databaseName", ",", "String", "expand", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "databaseName", ",", "expand", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "DatabaseInner", ">", ",", "DatabaseInner", ">", "(", ")", "{", "@", "Override", "public", "DatabaseInner", "call", "(", "ServiceResponse", "<", "DatabaseInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets a database. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database to be retrieved. @param expand A comma separated list of child objects to expand in the response. Possible properties: serviceTierAdvisors, transparentDataEncryption. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DatabaseInner object
[ "Gets", "a", "database", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabasesInner.java#L1089-L1096
graphhopper/graphhopper
core/src/main/java/com/graphhopper/geohash/LinearKeyAlgo.java
LinearKeyAlgo.decode
@Override public final void decode(long linearKey, GHPoint latLon) { """ This method returns latitude and longitude via latLon - calculated from specified linearKey <p> @param linearKey is the input """ double lat = linearKey / lonUnits * latDelta + bounds.minLat; double lon = linearKey % lonUnits * lonDelta + bounds.minLon; latLon.lat = lat + latDelta / 2; latLon.lon = lon + lonDelta / 2; }
java
@Override public final void decode(long linearKey, GHPoint latLon) { double lat = linearKey / lonUnits * latDelta + bounds.minLat; double lon = linearKey % lonUnits * lonDelta + bounds.minLon; latLon.lat = lat + latDelta / 2; latLon.lon = lon + lonDelta / 2; }
[ "@", "Override", "public", "final", "void", "decode", "(", "long", "linearKey", ",", "GHPoint", "latLon", ")", "{", "double", "lat", "=", "linearKey", "/", "lonUnits", "*", "latDelta", "+", "bounds", ".", "minLat", ";", "double", "lon", "=", "linearKey", "%", "lonUnits", "*", "lonDelta", "+", "bounds", ".", "minLon", ";", "latLon", ".", "lat", "=", "lat", "+", "latDelta", "/", "2", ";", "latLon", ".", "lon", "=", "lon", "+", "lonDelta", "/", "2", ";", "}" ]
This method returns latitude and longitude via latLon - calculated from specified linearKey <p> @param linearKey is the input
[ "This", "method", "returns", "latitude", "and", "longitude", "via", "latLon", "-", "calculated", "from", "specified", "linearKey", "<p", ">" ]
train
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/geohash/LinearKeyAlgo.java#L96-L102
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworkGatewayConnectionsInner.java
VirtualNetworkGatewayConnectionsInner.beginResetSharedKey
public ConnectionResetSharedKeyInner beginResetSharedKey(String resourceGroupName, String virtualNetworkGatewayConnectionName, int keyLength) { """ The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayConnectionName The virtual network gateway connection reset shared key Name. @param keyLength The virtual network connection reset shared key length, should between 1 and 128. @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 ConnectionResetSharedKeyInner object if successful. """ return beginResetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, keyLength).toBlocking().single().body(); }
java
public ConnectionResetSharedKeyInner beginResetSharedKey(String resourceGroupName, String virtualNetworkGatewayConnectionName, int keyLength) { return beginResetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, keyLength).toBlocking().single().body(); }
[ "public", "ConnectionResetSharedKeyInner", "beginResetSharedKey", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayConnectionName", ",", "int", "keyLength", ")", "{", "return", "beginResetSharedKeyWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkGatewayConnectionName", ",", "keyLength", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayConnectionName The virtual network gateway connection reset shared key Name. @param keyLength The virtual network connection reset shared key length, should between 1 and 128. @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 ConnectionResetSharedKeyInner object if successful.
[ "The", "VirtualNetworkGatewayConnectionResetSharedKey", "operation", "resets", "the", "virtual", "network", "gateway", "connection", "shared", "key", "for", "passed", "virtual", "network", "gateway", "connection", "in", "the", "specified", "resource", "group", "through", "Network", "resource", "provider", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworkGatewayConnectionsInner.java#L1296-L1298
powermock/powermock
powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java
PowerMock.mockStaticPartialNice
public static synchronized void mockStaticPartialNice(Class<?> clazz, String... methodNames) { """ A utility method that may be used to mock several <b>static</b> methods (nice) in an easy way (by just passing in the method names of the method you wish to mock). Note that you cannot uniquely specify a method to mock using this method if there are several methods with the same name in {@code type}. This method will mock ALL methods that match the supplied name regardless of parameter types and signature. If this is the case you should fall-back on using the {@link #mockStaticStrict(Class, Method...)} method instead. @param clazz The class that contains the static methods that should be mocked. @param methodNames The names of the methods that should be mocked. If {@code null}, then this method will have the same effect as just calling {@link #mockStatic(Class, Method...)} with the second parameter as {@code new Method[0]} (i.e. all methods in that class will be mocked). """ mockStaticNice(clazz, Whitebox.getMethods(clazz, methodNames)); }
java
public static synchronized void mockStaticPartialNice(Class<?> clazz, String... methodNames) { mockStaticNice(clazz, Whitebox.getMethods(clazz, methodNames)); }
[ "public", "static", "synchronized", "void", "mockStaticPartialNice", "(", "Class", "<", "?", ">", "clazz", ",", "String", "...", "methodNames", ")", "{", "mockStaticNice", "(", "clazz", ",", "Whitebox", ".", "getMethods", "(", "clazz", ",", "methodNames", ")", ")", ";", "}" ]
A utility method that may be used to mock several <b>static</b> methods (nice) in an easy way (by just passing in the method names of the method you wish to mock). Note that you cannot uniquely specify a method to mock using this method if there are several methods with the same name in {@code type}. This method will mock ALL methods that match the supplied name regardless of parameter types and signature. If this is the case you should fall-back on using the {@link #mockStaticStrict(Class, Method...)} method instead. @param clazz The class that contains the static methods that should be mocked. @param methodNames The names of the methods that should be mocked. If {@code null}, then this method will have the same effect as just calling {@link #mockStatic(Class, Method...)} with the second parameter as {@code new Method[0]} (i.e. all methods in that class will be mocked).
[ "A", "utility", "method", "that", "may", "be", "used", "to", "mock", "several", "<b", ">", "static<", "/", "b", ">", "methods", "(", "nice", ")", "in", "an", "easy", "way", "(", "by", "just", "passing", "in", "the", "method", "names", "of", "the", "method", "you", "wish", "to", "mock", ")", ".", "Note", "that", "you", "cannot", "uniquely", "specify", "a", "method", "to", "mock", "using", "this", "method", "if", "there", "are", "several", "methods", "with", "the", "same", "name", "in", "{", "@code", "type", "}", ".", "This", "method", "will", "mock", "ALL", "methods", "that", "match", "the", "supplied", "name", "regardless", "of", "parameter", "types", "and", "signature", ".", "If", "this", "is", "the", "case", "you", "should", "fall", "-", "back", "on", "using", "the", "{", "@link", "#mockStaticStrict", "(", "Class", "Method", "...", ")", "}", "method", "instead", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L613-L615
CubeEngine/Dirigent
src/main/java/org/cubeengine/dirigent/formatter/NumberFormatter.java
NumberFormatter.parseNumberToString
protected String parseNumberToString(Number number, Context context, Arguments args) { """ Parses the given number to a string depending on the context. @param number The number to parse. @param context The context to use. @param args The arguments of the macro. @return The number as a string. """ final NumberFormat numberFormat = parseFormatter(context, args); final Currency currency = context.get(Contexts.CURRENCY); if (currency != null) { numberFormat.setCurrency(currency); } return numberFormat.format(number); }
java
protected String parseNumberToString(Number number, Context context, Arguments args) { final NumberFormat numberFormat = parseFormatter(context, args); final Currency currency = context.get(Contexts.CURRENCY); if (currency != null) { numberFormat.setCurrency(currency); } return numberFormat.format(number); }
[ "protected", "String", "parseNumberToString", "(", "Number", "number", ",", "Context", "context", ",", "Arguments", "args", ")", "{", "final", "NumberFormat", "numberFormat", "=", "parseFormatter", "(", "context", ",", "args", ")", ";", "final", "Currency", "currency", "=", "context", ".", "get", "(", "Contexts", ".", "CURRENCY", ")", ";", "if", "(", "currency", "!=", "null", ")", "{", "numberFormat", ".", "setCurrency", "(", "currency", ")", ";", "}", "return", "numberFormat", ".", "format", "(", "number", ")", ";", "}" ]
Parses the given number to a string depending on the context. @param number The number to parse. @param context The context to use. @param args The arguments of the macro. @return The number as a string.
[ "Parses", "the", "given", "number", "to", "a", "string", "depending", "on", "the", "context", "." ]
train
https://github.com/CubeEngine/Dirigent/blob/68587a8202754a6a6b629cc15e14c516806badaa/src/main/java/org/cubeengine/dirigent/formatter/NumberFormatter.java#L113-L124
abego/treelayout
org.abego.treelayout/src/main/java/org/abego/treelayout/TreeLayout.java
TreeLayout.dumpTree
public void dumpTree(PrintStream printStream, DumpConfiguration dumpConfiguration) { """ Prints a dump of the tree to the given printStream, using the node's "toString" method. @param printStream &nbsp; @param dumpConfiguration [default: new DumpConfiguration()] """ dumpTree(printStream,tree.getRoot(),0, dumpConfiguration); }
java
public void dumpTree(PrintStream printStream, DumpConfiguration dumpConfiguration) { dumpTree(printStream,tree.getRoot(),0, dumpConfiguration); }
[ "public", "void", "dumpTree", "(", "PrintStream", "printStream", ",", "DumpConfiguration", "dumpConfiguration", ")", "{", "dumpTree", "(", "printStream", ",", "tree", ".", "getRoot", "(", ")", ",", "0", ",", "dumpConfiguration", ")", ";", "}" ]
Prints a dump of the tree to the given printStream, using the node's "toString" method. @param printStream &nbsp; @param dumpConfiguration [default: new DumpConfiguration()]
[ "Prints", "a", "dump", "of", "the", "tree", "to", "the", "given", "printStream", "using", "the", "node", "s", "toString", "method", "." ]
train
https://github.com/abego/treelayout/blob/aa73af5803c6ec30db0b4ad192c7cba55d0862d2/org.abego.treelayout/src/main/java/org/abego/treelayout/TreeLayout.java#L894-L896
wellner/jcarafe
jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java
ObjectArrayList.binarySearchFromTo
public int binarySearchFromTo(Object key, int from, int to) { """ Searches the receiver for the specified value using the binary search algorithm. The receiver must be sorted into ascending order according to the <i>natural ordering</i> of its elements (as by the sort method) prior to making this call. If it is not sorted, the results are undefined: in particular, the call may enter an infinite loop. If the receiver contains multiple elements equal to the specified object, there is no guarantee which instance will be found. @param key the value to be searched for. @param from the leftmost search position, inclusive. @param to the rightmost search position, inclusive. @return index of the search key, if it is contained in the receiver; otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The <i>insertion point</i> is defined as the the point at which the value would be inserted into the receiver: the index of the first element greater than the key, or <tt>receiver.size()</tt>, if all elements in the receiver are less than the specified key. Note that this guarantees that the return value will be &gt;= 0 if and only if the key is found. @see Comparable @see java.util.Arrays """ int low = from; int high = to; while (low <= high) { int mid =(low + high)/2; Object midVal = elements[mid]; int cmp = ((Comparable)midVal).compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. }
java
public int binarySearchFromTo(Object key, int from, int to) { int low = from; int high = to; while (low <= high) { int mid =(low + high)/2; Object midVal = elements[mid]; int cmp = ((Comparable)midVal).compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. }
[ "public", "int", "binarySearchFromTo", "(", "Object", "key", ",", "int", "from", ",", "int", "to", ")", "{", "int", "low", "=", "from", ";", "int", "high", "=", "to", ";", "while", "(", "low", "<=", "high", ")", "{", "int", "mid", "=", "(", "low", "+", "high", ")", "/", "2", ";", "Object", "midVal", "=", "elements", "[", "mid", "]", ";", "int", "cmp", "=", "(", "(", "Comparable", ")", "midVal", ")", ".", "compareTo", "(", "key", ")", ";", "if", "(", "cmp", "<", "0", ")", "low", "=", "mid", "+", "1", ";", "else", "if", "(", "cmp", ">", "0", ")", "high", "=", "mid", "-", "1", ";", "else", "return", "mid", ";", "// key found\r", "}", "return", "-", "(", "low", "+", "1", ")", ";", "// key not found.\r", "}" ]
Searches the receiver for the specified value using the binary search algorithm. The receiver must be sorted into ascending order according to the <i>natural ordering</i> of its elements (as by the sort method) prior to making this call. If it is not sorted, the results are undefined: in particular, the call may enter an infinite loop. If the receiver contains multiple elements equal to the specified object, there is no guarantee which instance will be found. @param key the value to be searched for. @param from the leftmost search position, inclusive. @param to the rightmost search position, inclusive. @return index of the search key, if it is contained in the receiver; otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The <i>insertion point</i> is defined as the the point at which the value would be inserted into the receiver: the index of the first element greater than the key, or <tt>receiver.size()</tt>, if all elements in the receiver are less than the specified key. Note that this guarantees that the return value will be &gt;= 0 if and only if the key is found. @see Comparable @see java.util.Arrays
[ "Searches", "the", "receiver", "for", "the", "specified", "value", "using", "the", "binary", "search", "algorithm", ".", "The", "receiver", "must", "be", "sorted", "into", "ascending", "order", "according", "to", "the", "<i", ">", "natural", "ordering<", "/", "i", ">", "of", "its", "elements", "(", "as", "by", "the", "sort", "method", ")", "prior", "to", "making", "this", "call", ".", "If", "it", "is", "not", "sorted", "the", "results", "are", "undefined", ":", "in", "particular", "the", "call", "may", "enter", "an", "infinite", "loop", ".", "If", "the", "receiver", "contains", "multiple", "elements", "equal", "to", "the", "specified", "object", "there", "is", "no", "guarantee", "which", "instance", "will", "be", "found", "." ]
train
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java#L178-L192
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/system/systemcmdpolicy.java
systemcmdpolicy.get
public static systemcmdpolicy get(nitro_service service, String policyname) throws Exception { """ Use this API to fetch systemcmdpolicy resource of given name . """ systemcmdpolicy obj = new systemcmdpolicy(); obj.set_policyname(policyname); systemcmdpolicy response = (systemcmdpolicy) obj.get_resource(service); return response; }
java
public static systemcmdpolicy get(nitro_service service, String policyname) throws Exception{ systemcmdpolicy obj = new systemcmdpolicy(); obj.set_policyname(policyname); systemcmdpolicy response = (systemcmdpolicy) obj.get_resource(service); return response; }
[ "public", "static", "systemcmdpolicy", "get", "(", "nitro_service", "service", ",", "String", "policyname", ")", "throws", "Exception", "{", "systemcmdpolicy", "obj", "=", "new", "systemcmdpolicy", "(", ")", ";", "obj", ".", "set_policyname", "(", "policyname", ")", ";", "systemcmdpolicy", "response", "=", "(", "systemcmdpolicy", ")", "obj", ".", "get_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch systemcmdpolicy resource of given name .
[ "Use", "this", "API", "to", "fetch", "systemcmdpolicy", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/system/systemcmdpolicy.java#L272-L277
ModeShape/modeshape
sequencers/modeshape-sequencer-ddl/src/main/java/org/modeshape/sequencer/ddl/dialect/derby/DerbyDdlParser.java
DerbyDdlParser.parseColumns
protected void parseColumns( DdlTokenStream tokens, AstNode tableNode, boolean isAlterTable ) throws ParsingException { """ Utility method designed to parse columns within an ALTER TABLE ADD statement. @param tokens the tokenized {@link DdlTokenStream} of the DDL input content; may not be null @param tableNode @param isAlterTable @throws ParsingException """ String tableElementString = getTableElementsString(tokens, false); DdlTokenStream localTokens = new DdlTokenStream(tableElementString, DdlTokenStream.ddlTokenizer(false), false); localTokens.start(); StringBuilder unusedTokensSB = new StringBuilder(); do { if (isColumnDefinitionStart(localTokens)) { parseColumnDefinition(localTokens, tableNode, isAlterTable); } else { // THIS IS AN ERROR. NOTHING FOUND. // NEED TO absorb tokens unusedTokensSB.append(SPACE).append(localTokens.consume()); } } while (localTokens.canConsume(COMMA)); if (unusedTokensSB.length() > 0) { String msg = DdlSequencerI18n.unusedTokensParsingColumnDefinition.text(tableNode.getName()); DdlParserProblem problem = new DdlParserProblem(Problems.WARNING, getCurrentMarkedPosition(), msg); problem.setUnusedSource(unusedTokensSB.toString()); addProblem(problem, tableNode); } }
java
protected void parseColumns( DdlTokenStream tokens, AstNode tableNode, boolean isAlterTable ) throws ParsingException { String tableElementString = getTableElementsString(tokens, false); DdlTokenStream localTokens = new DdlTokenStream(tableElementString, DdlTokenStream.ddlTokenizer(false), false); localTokens.start(); StringBuilder unusedTokensSB = new StringBuilder(); do { if (isColumnDefinitionStart(localTokens)) { parseColumnDefinition(localTokens, tableNode, isAlterTable); } else { // THIS IS AN ERROR. NOTHING FOUND. // NEED TO absorb tokens unusedTokensSB.append(SPACE).append(localTokens.consume()); } } while (localTokens.canConsume(COMMA)); if (unusedTokensSB.length() > 0) { String msg = DdlSequencerI18n.unusedTokensParsingColumnDefinition.text(tableNode.getName()); DdlParserProblem problem = new DdlParserProblem(Problems.WARNING, getCurrentMarkedPosition(), msg); problem.setUnusedSource(unusedTokensSB.toString()); addProblem(problem, tableNode); } }
[ "protected", "void", "parseColumns", "(", "DdlTokenStream", "tokens", ",", "AstNode", "tableNode", ",", "boolean", "isAlterTable", ")", "throws", "ParsingException", "{", "String", "tableElementString", "=", "getTableElementsString", "(", "tokens", ",", "false", ")", ";", "DdlTokenStream", "localTokens", "=", "new", "DdlTokenStream", "(", "tableElementString", ",", "DdlTokenStream", ".", "ddlTokenizer", "(", "false", ")", ",", "false", ")", ";", "localTokens", ".", "start", "(", ")", ";", "StringBuilder", "unusedTokensSB", "=", "new", "StringBuilder", "(", ")", ";", "do", "{", "if", "(", "isColumnDefinitionStart", "(", "localTokens", ")", ")", "{", "parseColumnDefinition", "(", "localTokens", ",", "tableNode", ",", "isAlterTable", ")", ";", "}", "else", "{", "// THIS IS AN ERROR. NOTHING FOUND.", "// NEED TO absorb tokens", "unusedTokensSB", ".", "append", "(", "SPACE", ")", ".", "append", "(", "localTokens", ".", "consume", "(", ")", ")", ";", "}", "}", "while", "(", "localTokens", ".", "canConsume", "(", "COMMA", ")", ")", ";", "if", "(", "unusedTokensSB", ".", "length", "(", ")", ">", "0", ")", "{", "String", "msg", "=", "DdlSequencerI18n", ".", "unusedTokensParsingColumnDefinition", ".", "text", "(", "tableNode", ".", "getName", "(", ")", ")", ";", "DdlParserProblem", "problem", "=", "new", "DdlParserProblem", "(", "Problems", ".", "WARNING", ",", "getCurrentMarkedPosition", "(", ")", ",", "msg", ")", ";", "problem", ".", "setUnusedSource", "(", "unusedTokensSB", ".", "toString", "(", ")", ")", ";", "addProblem", "(", "problem", ",", "tableNode", ")", ";", "}", "}" ]
Utility method designed to parse columns within an ALTER TABLE ADD statement. @param tokens the tokenized {@link DdlTokenStream} of the DDL input content; may not be null @param tableNode @param isAlterTable @throws ParsingException
[ "Utility", "method", "designed", "to", "parse", "columns", "within", "an", "ALTER", "TABLE", "ADD", "statement", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/sequencers/modeshape-sequencer-ddl/src/main/java/org/modeshape/sequencer/ddl/dialect/derby/DerbyDdlParser.java#L887-L914
rhuss/jolokia
agent/core/src/main/java/org/jolokia/discovery/MulticastUtil.java
MulticastUtil.sendDiscoveryRequests
private static List<Future<List<DiscoveryIncomingMessage>>> sendDiscoveryRequests(DiscoveryOutgoingMessage pOutMsg, int pTimeout, LogHandler pLogHandler) throws SocketException, UnknownHostException { """ Send requests in parallel threads, return the futures for getting the result """ // Note for Ipv6 support: If there are two local addresses, one with IpV6 and one with IpV4 then two discovery request // should be sent, on each interface respectively. Currently, only IpV4 is supported. List<InetAddress> addresses = getMulticastAddresses(); ExecutorService executor = Executors.newFixedThreadPool(addresses.size()); final List<Future<List<DiscoveryIncomingMessage>>> futures = new ArrayList<Future<List<DiscoveryIncomingMessage>>>(addresses.size()); for (InetAddress address : addresses) { // Discover UDP packet send to multicast address DatagramPacket out = pOutMsg.createDatagramPacket(InetAddress.getByName(JOLOKIA_MULTICAST_GROUP), JOLOKIA_MULTICAST_PORT); Callable<List<DiscoveryIncomingMessage>> findAgentsCallable = new FindAgentsCallable(address, out, pTimeout, pLogHandler); futures.add(executor.submit(findAgentsCallable)); } executor.shutdownNow(); return futures; }
java
private static List<Future<List<DiscoveryIncomingMessage>>> sendDiscoveryRequests(DiscoveryOutgoingMessage pOutMsg, int pTimeout, LogHandler pLogHandler) throws SocketException, UnknownHostException { // Note for Ipv6 support: If there are two local addresses, one with IpV6 and one with IpV4 then two discovery request // should be sent, on each interface respectively. Currently, only IpV4 is supported. List<InetAddress> addresses = getMulticastAddresses(); ExecutorService executor = Executors.newFixedThreadPool(addresses.size()); final List<Future<List<DiscoveryIncomingMessage>>> futures = new ArrayList<Future<List<DiscoveryIncomingMessage>>>(addresses.size()); for (InetAddress address : addresses) { // Discover UDP packet send to multicast address DatagramPacket out = pOutMsg.createDatagramPacket(InetAddress.getByName(JOLOKIA_MULTICAST_GROUP), JOLOKIA_MULTICAST_PORT); Callable<List<DiscoveryIncomingMessage>> findAgentsCallable = new FindAgentsCallable(address, out, pTimeout, pLogHandler); futures.add(executor.submit(findAgentsCallable)); } executor.shutdownNow(); return futures; }
[ "private", "static", "List", "<", "Future", "<", "List", "<", "DiscoveryIncomingMessage", ">", ">", ">", "sendDiscoveryRequests", "(", "DiscoveryOutgoingMessage", "pOutMsg", ",", "int", "pTimeout", ",", "LogHandler", "pLogHandler", ")", "throws", "SocketException", ",", "UnknownHostException", "{", "// Note for Ipv6 support: If there are two local addresses, one with IpV6 and one with IpV4 then two discovery request", "// should be sent, on each interface respectively. Currently, only IpV4 is supported.", "List", "<", "InetAddress", ">", "addresses", "=", "getMulticastAddresses", "(", ")", ";", "ExecutorService", "executor", "=", "Executors", ".", "newFixedThreadPool", "(", "addresses", ".", "size", "(", ")", ")", ";", "final", "List", "<", "Future", "<", "List", "<", "DiscoveryIncomingMessage", ">", ">", ">", "futures", "=", "new", "ArrayList", "<", "Future", "<", "List", "<", "DiscoveryIncomingMessage", ">", ">", ">", "(", "addresses", ".", "size", "(", ")", ")", ";", "for", "(", "InetAddress", "address", ":", "addresses", ")", "{", "// Discover UDP packet send to multicast address", "DatagramPacket", "out", "=", "pOutMsg", ".", "createDatagramPacket", "(", "InetAddress", ".", "getByName", "(", "JOLOKIA_MULTICAST_GROUP", ")", ",", "JOLOKIA_MULTICAST_PORT", ")", ";", "Callable", "<", "List", "<", "DiscoveryIncomingMessage", ">", ">", "findAgentsCallable", "=", "new", "FindAgentsCallable", "(", "address", ",", "out", ",", "pTimeout", ",", "pLogHandler", ")", ";", "futures", ".", "add", "(", "executor", ".", "submit", "(", "findAgentsCallable", ")", ")", ";", "}", "executor", ".", "shutdownNow", "(", ")", ";", "return", "futures", ";", "}" ]
Send requests in parallel threads, return the futures for getting the result
[ "Send", "requests", "in", "parallel", "threads", "return", "the", "futures", "for", "getting", "the", "result" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/discovery/MulticastUtil.java#L76-L92
moparisthebest/beehive
beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/databinding/datagrid/ImageAnchorCell.java
ImageAnchorCell.addParameter
public void addParameter(String name, Object value, String facet) throws JspException { """ <p> Implementation of the {@link IUrlParams} interface. This allows this tag to accept &lt;netui:parameter&gt; and &lt;netui:parameterMap&gt; in order to add URL parameters onto the rendered anchor. For example: <pre> <netui-data:imageAnchorCell href="foo.jsp" src="foo.png"> <netui:parameter name="paramKey" value="paramValue"/> </netui-data:anchorCell> </pre> will render an HTML image anchor as: <pre> <a href="foo.jsp?paramKey=paramValue><img src="foo.png"/></a> </pre> </p> @param name the name of the parameter @param value the value of the parameter @param facet the facet for the parameter @throws JspException thrown when the facet is unsupported """ ParamHelper.addParam(_imageAnchorCellModel.getParams(), name, value); }
java
public void addParameter(String name, Object value, String facet) throws JspException { ParamHelper.addParam(_imageAnchorCellModel.getParams(), name, value); }
[ "public", "void", "addParameter", "(", "String", "name", ",", "Object", "value", ",", "String", "facet", ")", "throws", "JspException", "{", "ParamHelper", ".", "addParam", "(", "_imageAnchorCellModel", ".", "getParams", "(", ")", ",", "name", ",", "value", ")", ";", "}" ]
<p> Implementation of the {@link IUrlParams} interface. This allows this tag to accept &lt;netui:parameter&gt; and &lt;netui:parameterMap&gt; in order to add URL parameters onto the rendered anchor. For example: <pre> <netui-data:imageAnchorCell href="foo.jsp" src="foo.png"> <netui:parameter name="paramKey" value="paramValue"/> </netui-data:anchorCell> </pre> will render an HTML image anchor as: <pre> <a href="foo.jsp?paramKey=paramValue><img src="foo.png"/></a> </pre> </p> @param name the name of the parameter @param value the value of the parameter @param facet the facet for the parameter @throws JspException thrown when the facet is unsupported
[ "<p", ">", "Implementation", "of", "the", "{" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/databinding/datagrid/ImageAnchorCell.java#L657-L660
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Utility.java
Utility.parseChar
public static boolean parseChar(String id, int[] pos, char ch) { """ Parse a single non-whitespace character 'ch', optionally preceded by whitespace. @param id the string to be parsed @param pos INPUT-OUTPUT parameter. On input, pos[0] is the offset of the first character to be parsed. On output, pos[0] is the index after the last parsed character. If the parse fails, pos[0] will be unchanged. @param ch the non-whitespace character to be parsed. @return true if 'ch' is seen preceded by zero or more whitespace characters. """ int start = pos[0]; pos[0] = PatternProps.skipWhiteSpace(id, pos[0]); if (pos[0] == id.length() || id.charAt(pos[0]) != ch) { pos[0] = start; return false; } ++pos[0]; return true; }
java
public static boolean parseChar(String id, int[] pos, char ch) { int start = pos[0]; pos[0] = PatternProps.skipWhiteSpace(id, pos[0]); if (pos[0] == id.length() || id.charAt(pos[0]) != ch) { pos[0] = start; return false; } ++pos[0]; return true; }
[ "public", "static", "boolean", "parseChar", "(", "String", "id", ",", "int", "[", "]", "pos", ",", "char", "ch", ")", "{", "int", "start", "=", "pos", "[", "0", "]", ";", "pos", "[", "0", "]", "=", "PatternProps", ".", "skipWhiteSpace", "(", "id", ",", "pos", "[", "0", "]", ")", ";", "if", "(", "pos", "[", "0", "]", "==", "id", ".", "length", "(", ")", "||", "id", ".", "charAt", "(", "pos", "[", "0", "]", ")", "!=", "ch", ")", "{", "pos", "[", "0", "]", "=", "start", ";", "return", "false", ";", "}", "++", "pos", "[", "0", "]", ";", "return", "true", ";", "}" ]
Parse a single non-whitespace character 'ch', optionally preceded by whitespace. @param id the string to be parsed @param pos INPUT-OUTPUT parameter. On input, pos[0] is the offset of the first character to be parsed. On output, pos[0] is the index after the last parsed character. If the parse fails, pos[0] will be unchanged. @param ch the non-whitespace character to be parsed. @return true if 'ch' is seen preceded by zero or more whitespace characters.
[ "Parse", "a", "single", "non", "-", "whitespace", "character", "ch", "optionally", "preceded", "by", "whitespace", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Utility.java#L1131-L1141
Alluxio/alluxio
core/common/src/main/java/alluxio/concurrent/jsr/CompletableFuture.java
CompletableFuture.encodeThrowable
static Object encodeThrowable(Throwable x, Object r) { """ Returns the encoding of the given (non-null) exception as a wrapped CompletionException unless it is one already. May return the given Object r (which must have been the result of a source future) if it is equivalent, i.e. if this is a simple relay of an existing CompletionException. """ if (!(x instanceof CompletionException)) x = new CompletionException(x); else if (r instanceof AltResult && x == ((AltResult) r).ex) return r; return new AltResult(x); }
java
static Object encodeThrowable(Throwable x, Object r) { if (!(x instanceof CompletionException)) x = new CompletionException(x); else if (r instanceof AltResult && x == ((AltResult) r).ex) return r; return new AltResult(x); }
[ "static", "Object", "encodeThrowable", "(", "Throwable", "x", ",", "Object", "r", ")", "{", "if", "(", "!", "(", "x", "instanceof", "CompletionException", ")", ")", "x", "=", "new", "CompletionException", "(", "x", ")", ";", "else", "if", "(", "r", "instanceof", "AltResult", "&&", "x", "==", "(", "(", "AltResult", ")", "r", ")", ".", "ex", ")", "return", "r", ";", "return", "new", "AltResult", "(", "x", ")", ";", "}" ]
Returns the encoding of the given (non-null) exception as a wrapped CompletionException unless it is one already. May return the given Object r (which must have been the result of a source future) if it is equivalent, i.e. if this is a simple relay of an existing CompletionException.
[ "Returns", "the", "encoding", "of", "the", "given", "(", "non", "-", "null", ")", "exception", "as", "a", "wrapped", "CompletionException", "unless", "it", "is", "one", "already", ".", "May", "return", "the", "given", "Object", "r", "(", "which", "must", "have", "been", "the", "result", "of", "a", "source", "future", ")", "if", "it", "is", "equivalent", "i", ".", "e", ".", "if", "this", "is", "a", "simple", "relay", "of", "an", "existing", "CompletionException", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/concurrent/jsr/CompletableFuture.java#L261-L267
onelogin/onelogin-java-sdk
src/main/java/com/onelogin/sdk/conn/Client.java
Client.sendInviteLink
public Boolean sendInviteLink(String email) throws OAuthSystemException, OAuthProblemException, URISyntaxException { """ Send an invite link to a user that you have already created in your OneLogin account. @param email Set to the email address of the user that you want to send an invite link for. @return True if the mail with the link was sent @throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection @throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled @throws URISyntaxException - if there is an error when generating the target URL at the URIBuilder constructor @see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/invite-links/send-invite-link">Send Invite Link documentation</a> """ return sendInviteLink(email, null); }
java
public Boolean sendInviteLink(String email) throws OAuthSystemException, OAuthProblemException, URISyntaxException { return sendInviteLink(email, null); }
[ "public", "Boolean", "sendInviteLink", "(", "String", "email", ")", "throws", "OAuthSystemException", ",", "OAuthProblemException", ",", "URISyntaxException", "{", "return", "sendInviteLink", "(", "email", ",", "null", ")", ";", "}" ]
Send an invite link to a user that you have already created in your OneLogin account. @param email Set to the email address of the user that you want to send an invite link for. @return True if the mail with the link was sent @throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection @throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled @throws URISyntaxException - if there is an error when generating the target URL at the URIBuilder constructor @see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/invite-links/send-invite-link">Send Invite Link documentation</a>
[ "Send", "an", "invite", "link", "to", "a", "user", "that", "you", "have", "already", "created", "in", "your", "OneLogin", "account", "." ]
train
https://github.com/onelogin/onelogin-java-sdk/blob/1570b78033dcc1c7387099e77fe41b6b0638df8c/src/main/java/com/onelogin/sdk/conn/Client.java#L3086-L3088
javalite/activejdbc
activejdbc/src/main/java/org/javalite/activejdbc/LazyList.java
LazyList.toXml
@Deprecated public String toXml(int spaces, boolean declaration, String... attrs) { """ Generates a XML document from content of this list. @param spaces by how many spaces to indent. @param declaration true to include XML declaration at the top @param attrs list of attributes to include. No arguments == include all attributes. @return generated XML. @deprecated Use {@link #toXml(boolean, boolean, String...)} instead """ return toXml(spaces > 0, declaration, attrs); }
java
@Deprecated public String toXml(int spaces, boolean declaration, String... attrs) { return toXml(spaces > 0, declaration, attrs); }
[ "@", "Deprecated", "public", "String", "toXml", "(", "int", "spaces", ",", "boolean", "declaration", ",", "String", "...", "attrs", ")", "{", "return", "toXml", "(", "spaces", ">", "0", ",", "declaration", ",", "attrs", ")", ";", "}" ]
Generates a XML document from content of this list. @param spaces by how many spaces to indent. @param declaration true to include XML declaration at the top @param attrs list of attributes to include. No arguments == include all attributes. @return generated XML. @deprecated Use {@link #toXml(boolean, boolean, String...)} instead
[ "Generates", "a", "XML", "document", "from", "content", "of", "this", "list", "." ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/LazyList.java#L233-L236
otto-de/edison-hal
src/main/java/de/otto/edison/hal/traverson/Traverson.java
Traverson.getResource
private <T extends HalRepresentation> T getResource(final Link link, final Class<T> resultType, final EmbeddedTypeInfo embeddedTypeInfo) throws IOException { """ Retrieve the HAL resource identified by {@code uri} and return the representation as a HalRepresentation. @param link the Link of the resource to retrieve, or null, if the contextUrl should be resolved. @throws IllegalArgumentException if resolving URLs is failing @param resultType the Class of the returned HalRepresentation. @param embeddedTypeInfo type information about embedded items @param <T> type parameter of the returned HalRepresentation @return list of zero or more HalRepresentations. """ return getResource(link, resultType, singletonList(embeddedTypeInfo)); }
java
private <T extends HalRepresentation> T getResource(final Link link, final Class<T> resultType, final EmbeddedTypeInfo embeddedTypeInfo) throws IOException { return getResource(link, resultType, singletonList(embeddedTypeInfo)); }
[ "private", "<", "T", "extends", "HalRepresentation", ">", "T", "getResource", "(", "final", "Link", "link", ",", "final", "Class", "<", "T", ">", "resultType", ",", "final", "EmbeddedTypeInfo", "embeddedTypeInfo", ")", "throws", "IOException", "{", "return", "getResource", "(", "link", ",", "resultType", ",", "singletonList", "(", "embeddedTypeInfo", ")", ")", ";", "}" ]
Retrieve the HAL resource identified by {@code uri} and return the representation as a HalRepresentation. @param link the Link of the resource to retrieve, or null, if the contextUrl should be resolved. @throws IllegalArgumentException if resolving URLs is failing @param resultType the Class of the returned HalRepresentation. @param embeddedTypeInfo type information about embedded items @param <T> type parameter of the returned HalRepresentation @return list of zero or more HalRepresentations.
[ "Retrieve", "the", "HAL", "resource", "identified", "by", "{", "@code", "uri", "}", "and", "return", "the", "representation", "as", "a", "HalRepresentation", "." ]
train
https://github.com/otto-de/edison-hal/blob/1582d2b49d1f0d9103e03bf742f18afa9d166992/src/main/java/de/otto/edison/hal/traverson/Traverson.java#L1367-L1371