repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_instance_group_groupId_DELETE
public void project_serviceName_instance_group_groupId_DELETE(String serviceName, String groupId) throws IOException { """ Delete a group REST: DELETE /cloud/project/{serviceName}/instance/group/{groupId} @param groupId [required] Group id @param serviceName [required] Project name """ String qPath = "/cloud/project/{serviceName}/instance/group/{groupId}"; StringBuilder sb = path(qPath, serviceName, groupId); exec(qPath, "DELETE", sb.toString(), null); }
java
public void project_serviceName_instance_group_groupId_DELETE(String serviceName, String groupId) throws IOException { String qPath = "/cloud/project/{serviceName}/instance/group/{groupId}"; StringBuilder sb = path(qPath, serviceName, groupId); exec(qPath, "DELETE", sb.toString(), null); }
[ "public", "void", "project_serviceName_instance_group_groupId_DELETE", "(", "String", "serviceName", ",", "String", "groupId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/instance/group/{groupId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "groupId", ")", ";", "exec", "(", "qPath", ",", "\"DELETE\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "}" ]
Delete a group REST: DELETE /cloud/project/{serviceName}/instance/group/{groupId} @param groupId [required] Group id @param serviceName [required] Project name
[ "Delete", "a", "group" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L2152-L2156
joniles/mpxj
src/main/java/net/sf/mpxj/ProjectCalendar.java
ProjectCalendar.getDuration
public Duration getDuration(Date startDate, Date endDate) { """ This method is provided to allow an absolute period of time represented by start and end dates into a duration in working days based on this calendar instance. This method takes account of any exceptions defined for this calendar. @param startDate start of the period @param endDate end of the period @return new Duration object """ Calendar cal = DateHelper.popCalendar(startDate); int days = getDaysInRange(startDate, endDate); int duration = 0; Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK)); while (days > 0) { if (isWorkingDate(cal.getTime(), day) == true) { ++duration; } --days; day = day.getNextDay(); cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1); } DateHelper.pushCalendar(cal); return (Duration.getInstance(duration, TimeUnit.DAYS)); }
java
public Duration getDuration(Date startDate, Date endDate) { Calendar cal = DateHelper.popCalendar(startDate); int days = getDaysInRange(startDate, endDate); int duration = 0; Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK)); while (days > 0) { if (isWorkingDate(cal.getTime(), day) == true) { ++duration; } --days; day = day.getNextDay(); cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1); } DateHelper.pushCalendar(cal); return (Duration.getInstance(duration, TimeUnit.DAYS)); }
[ "public", "Duration", "getDuration", "(", "Date", "startDate", ",", "Date", "endDate", ")", "{", "Calendar", "cal", "=", "DateHelper", ".", "popCalendar", "(", "startDate", ")", ";", "int", "days", "=", "getDaysInRange", "(", "startDate", ",", "endDate", ")", ";", "int", "duration", "=", "0", ";", "Day", "day", "=", "Day", ".", "getInstance", "(", "cal", ".", "get", "(", "Calendar", ".", "DAY_OF_WEEK", ")", ")", ";", "while", "(", "days", ">", "0", ")", "{", "if", "(", "isWorkingDate", "(", "cal", ".", "getTime", "(", ")", ",", "day", ")", "==", "true", ")", "{", "++", "duration", ";", "}", "--", "days", ";", "day", "=", "day", ".", "getNextDay", "(", ")", ";", "cal", ".", "set", "(", "Calendar", ".", "DAY_OF_YEAR", ",", "cal", ".", "get", "(", "Calendar", ".", "DAY_OF_YEAR", ")", "+", "1", ")", ";", "}", "DateHelper", ".", "pushCalendar", "(", "cal", ")", ";", "return", "(", "Duration", ".", "getInstance", "(", "duration", ",", "TimeUnit", ".", "DAYS", ")", ")", ";", "}" ]
This method is provided to allow an absolute period of time represented by start and end dates into a duration in working days based on this calendar instance. This method takes account of any exceptions defined for this calendar. @param startDate start of the period @param endDate end of the period @return new Duration object
[ "This", "method", "is", "provided", "to", "allow", "an", "absolute", "period", "of", "time", "represented", "by", "start", "and", "end", "dates", "into", "a", "duration", "in", "working", "days", "based", "on", "this", "calendar", "instance", ".", "This", "method", "takes", "account", "of", "any", "exceptions", "defined", "for", "this", "calendar", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ProjectCalendar.java#L327-L348
duracloud/snapshot
snapshot-service-impl/src/main/java/org/duracloud/snapshot/service/impl/StepExecutionSupport.java
StepExecutionSupport.addToLong
protected void addToLong(String key, long value) { """ Adds the specified value to the existing key. @param key @param value """ synchronized (this.stepExecution) { long currentValue = getLongValue(key); getExecutionContext().putLong(key, currentValue + value); } }
java
protected void addToLong(String key, long value) { synchronized (this.stepExecution) { long currentValue = getLongValue(key); getExecutionContext().putLong(key, currentValue + value); } }
[ "protected", "void", "addToLong", "(", "String", "key", ",", "long", "value", ")", "{", "synchronized", "(", "this", ".", "stepExecution", ")", "{", "long", "currentValue", "=", "getLongValue", "(", "key", ")", ";", "getExecutionContext", "(", ")", ".", "putLong", "(", "key", ",", "currentValue", "+", "value", ")", ";", "}", "}" ]
Adds the specified value to the existing key. @param key @param value
[ "Adds", "the", "specified", "value", "to", "the", "existing", "key", "." ]
train
https://github.com/duracloud/snapshot/blob/7cb387b22fd4a9425087f654276138727c2c0b73/snapshot-service-impl/src/main/java/org/duracloud/snapshot/service/impl/StepExecutionSupport.java#L141-L147
apereo/cas
support/cas-server-support-saml-core-api/src/main/java/org/apereo/cas/support/saml/SamlUtils.java
SamlUtils.transformSamlObject
public static <T extends XMLObject> T transformSamlObject(final OpenSamlConfigBean configBean, final String xml, final Class<T> clazz) { """ Transform saml object t. @param <T> the type parameter @param configBean the config bean @param xml the xml @param clazz the clazz @return the t """ return transformSamlObject(configBean, xml.getBytes(StandardCharsets.UTF_8), clazz); }
java
public static <T extends XMLObject> T transformSamlObject(final OpenSamlConfigBean configBean, final String xml, final Class<T> clazz) { return transformSamlObject(configBean, xml.getBytes(StandardCharsets.UTF_8), clazz); }
[ "public", "static", "<", "T", "extends", "XMLObject", ">", "T", "transformSamlObject", "(", "final", "OpenSamlConfigBean", "configBean", ",", "final", "String", "xml", ",", "final", "Class", "<", "T", ">", "clazz", ")", "{", "return", "transformSamlObject", "(", "configBean", ",", "xml", ".", "getBytes", "(", "StandardCharsets", ".", "UTF_8", ")", ",", "clazz", ")", ";", "}" ]
Transform saml object t. @param <T> the type parameter @param configBean the config bean @param xml the xml @param clazz the clazz @return the t
[ "Transform", "saml", "object", "t", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-core-api/src/main/java/org/apereo/cas/support/saml/SamlUtils.java#L84-L87
square/wire
wire-schema/src/main/java/com/squareup/wire/schema/internal/parser/SyntaxReader.java
SyntaxReader.readDataType
public String readDataType(String name) { """ Reads a scalar, map, or type name with {@code name} as a prefix word. """ if (name.equals("map")) { if (readChar() != '<') throw unexpected("expected '<'"); String keyType = readDataType(); if (readChar() != ',') throw unexpected("expected ','"); String valueType = readDataType(); if (readChar() != '>') throw unexpected("expected '>'"); return String.format("map<%s, %s>", keyType, valueType); } else { return name; } }
java
public String readDataType(String name) { if (name.equals("map")) { if (readChar() != '<') throw unexpected("expected '<'"); String keyType = readDataType(); if (readChar() != ',') throw unexpected("expected ','"); String valueType = readDataType(); if (readChar() != '>') throw unexpected("expected '>'"); return String.format("map<%s, %s>", keyType, valueType); } else { return name; } }
[ "public", "String", "readDataType", "(", "String", "name", ")", "{", "if", "(", "name", ".", "equals", "(", "\"map\"", ")", ")", "{", "if", "(", "readChar", "(", ")", "!=", "'", "'", ")", "throw", "unexpected", "(", "\"expected '<'\"", ")", ";", "String", "keyType", "=", "readDataType", "(", ")", ";", "if", "(", "readChar", "(", ")", "!=", "'", "'", ")", "throw", "unexpected", "(", "\"expected ','\"", ")", ";", "String", "valueType", "=", "readDataType", "(", ")", ";", "if", "(", "readChar", "(", ")", "!=", "'", "'", ")", "throw", "unexpected", "(", "\"expected '>'\"", ")", ";", "return", "String", ".", "format", "(", "\"map<%s, %s>\"", ",", "keyType", ",", "valueType", ")", ";", "}", "else", "{", "return", "name", ";", "}", "}" ]
Reads a scalar, map, or type name with {@code name} as a prefix word.
[ "Reads", "a", "scalar", "map", "or", "type", "name", "with", "{" ]
train
https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-schema/src/main/java/com/squareup/wire/schema/internal/parser/SyntaxReader.java#L177-L188
jboss/jboss-servlet-api_spec
src/main/java/javax/servlet/http/HttpServletResponseWrapper.java
HttpServletResponseWrapper.setTrailerFields
@Override public void setTrailerFields(Supplier<Map<String, String>> supplier) { """ The default behaviour of this method is to call {@link HttpServletResponse#setTrailerFields} on the wrapped response object. @param supplier of trailer headers @since Servlet 4.0 """ _getHttpServletResponse().setTrailerFields(supplier); }
java
@Override public void setTrailerFields(Supplier<Map<String, String>> supplier) { _getHttpServletResponse().setTrailerFields(supplier); }
[ "@", "Override", "public", "void", "setTrailerFields", "(", "Supplier", "<", "Map", "<", "String", ",", "String", ">", ">", "supplier", ")", "{", "_getHttpServletResponse", "(", ")", ".", "setTrailerFields", "(", "supplier", ")", ";", "}" ]
The default behaviour of this method is to call {@link HttpServletResponse#setTrailerFields} on the wrapped response object. @param supplier of trailer headers @since Servlet 4.0
[ "The", "default", "behaviour", "of", "this", "method", "is", "to", "call", "{", "@link", "HttpServletResponse#setTrailerFields", "}", "on", "the", "wrapped", "response", "object", "." ]
train
https://github.com/jboss/jboss-servlet-api_spec/blob/5bc96f2b833c072baff6eb8ae49bc7b5e503e9b2/src/main/java/javax/servlet/http/HttpServletResponseWrapper.java#L340-L343
SeleniumHQ/selenium
java/client/src/org/openqa/selenium/remote/BaseAugmenter.java
BaseAugmenter.augment
public WebDriver augment(WebDriver driver) { """ Enhance the interfaces implemented by this instance of WebDriver iff that instance is a {@link org.openqa.selenium.remote.RemoteWebDriver}. The WebDriver that is returned may well be a dynamic proxy. You cannot rely on the concrete implementing class to remain constant. @param driver The driver to enhance @return A class implementing the described interfaces. """ RemoteWebDriver remoteDriver = extractRemoteWebDriver(driver); if (remoteDriver == null) { return driver; } return create(remoteDriver, driverAugmentors, driver); }
java
public WebDriver augment(WebDriver driver) { RemoteWebDriver remoteDriver = extractRemoteWebDriver(driver); if (remoteDriver == null) { return driver; } return create(remoteDriver, driverAugmentors, driver); }
[ "public", "WebDriver", "augment", "(", "WebDriver", "driver", ")", "{", "RemoteWebDriver", "remoteDriver", "=", "extractRemoteWebDriver", "(", "driver", ")", ";", "if", "(", "remoteDriver", "==", "null", ")", "{", "return", "driver", ";", "}", "return", "create", "(", "remoteDriver", ",", "driverAugmentors", ",", "driver", ")", ";", "}" ]
Enhance the interfaces implemented by this instance of WebDriver iff that instance is a {@link org.openqa.selenium.remote.RemoteWebDriver}. The WebDriver that is returned may well be a dynamic proxy. You cannot rely on the concrete implementing class to remain constant. @param driver The driver to enhance @return A class implementing the described interfaces.
[ "Enhance", "the", "interfaces", "implemented", "by", "this", "instance", "of", "WebDriver", "iff", "that", "instance", "is", "a", "{", "@link", "org", ".", "openqa", ".", "selenium", ".", "remote", ".", "RemoteWebDriver", "}", "." ]
train
https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/client/src/org/openqa/selenium/remote/BaseAugmenter.java#L92-L98
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/SerializedFormBuilder.java
SerializedFormBuilder.buildFieldSubHeader
public void buildFieldSubHeader(XMLNode node, Content fieldsContentTree) { """ Build the field sub header. @param node the XML element that specifies which components to document @param fieldsContentTree content tree to which the documentation will be added """ if (!currentClass.definesSerializableFields()) { FieldDoc field = (FieldDoc) currentMember; fieldWriter.addMemberHeader(field.type().asClassDoc(), field.type().typeName(), field.type().dimension(), field.name(), fieldsContentTree); } }
java
public void buildFieldSubHeader(XMLNode node, Content fieldsContentTree) { if (!currentClass.definesSerializableFields()) { FieldDoc field = (FieldDoc) currentMember; fieldWriter.addMemberHeader(field.type().asClassDoc(), field.type().typeName(), field.type().dimension(), field.name(), fieldsContentTree); } }
[ "public", "void", "buildFieldSubHeader", "(", "XMLNode", "node", ",", "Content", "fieldsContentTree", ")", "{", "if", "(", "!", "currentClass", ".", "definesSerializableFields", "(", ")", ")", "{", "FieldDoc", "field", "=", "(", "FieldDoc", ")", "currentMember", ";", "fieldWriter", ".", "addMemberHeader", "(", "field", ".", "type", "(", ")", ".", "asClassDoc", "(", ")", ",", "field", ".", "type", "(", ")", ".", "typeName", "(", ")", ",", "field", ".", "type", "(", ")", ".", "dimension", "(", ")", ",", "field", ".", "name", "(", ")", ",", "fieldsContentTree", ")", ";", "}", "}" ]
Build the field sub header. @param node the XML element that specifies which components to document @param fieldsContentTree content tree to which the documentation will be added
[ "Build", "the", "field", "sub", "header", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/SerializedFormBuilder.java#L441-L448
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/WorkflowTriggersInner.java
WorkflowTriggersInner.getSchemaJsonAsync
public Observable<JsonSchemaInner> getSchemaJsonAsync(String resourceGroupName, String workflowName, String triggerName) { """ Get the trigger schema as JSON. @param resourceGroupName The resource group name. @param workflowName The workflow name. @param triggerName The workflow trigger name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the JsonSchemaInner object """ return getSchemaJsonWithServiceResponseAsync(resourceGroupName, workflowName, triggerName).map(new Func1<ServiceResponse<JsonSchemaInner>, JsonSchemaInner>() { @Override public JsonSchemaInner call(ServiceResponse<JsonSchemaInner> response) { return response.body(); } }); }
java
public Observable<JsonSchemaInner> getSchemaJsonAsync(String resourceGroupName, String workflowName, String triggerName) { return getSchemaJsonWithServiceResponseAsync(resourceGroupName, workflowName, triggerName).map(new Func1<ServiceResponse<JsonSchemaInner>, JsonSchemaInner>() { @Override public JsonSchemaInner call(ServiceResponse<JsonSchemaInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "JsonSchemaInner", ">", "getSchemaJsonAsync", "(", "String", "resourceGroupName", ",", "String", "workflowName", ",", "String", "triggerName", ")", "{", "return", "getSchemaJsonWithServiceResponseAsync", "(", "resourceGroupName", ",", "workflowName", ",", "triggerName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "JsonSchemaInner", ">", ",", "JsonSchemaInner", ">", "(", ")", "{", "@", "Override", "public", "JsonSchemaInner", "call", "(", "ServiceResponse", "<", "JsonSchemaInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Get the trigger schema as JSON. @param resourceGroupName The resource group name. @param workflowName The workflow name. @param triggerName The workflow trigger name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the JsonSchemaInner object
[ "Get", "the", "trigger", "schema", "as", "JSON", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/WorkflowTriggersInner.java#L665-L672
phax/ph-oton
ph-oton-app/src/main/java/com/helger/photon/app/url/LinkHelper.java
LinkHelper.getURLWithContext
@Nonnull public static SimpleURL getURLWithContext (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final String sHRef) { """ Prefix the passed href with the relative context path in case the passed href has no protocol yet. @param aRequestScope The request web scope to be used. Required for cookie-less handling. May not be <code>null</code>. @param sHRef The href to be extended. May not be <code>null</code>. @return Either the original href if already absolute or <code>/webapp-context/<i>href</i></code> otherwise. Never <code>null</code>. """ return new SimpleURL (getURIWithContext (aRequestScope, sHRef)); }
java
@Nonnull public static SimpleURL getURLWithContext (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final String sHRef) { return new SimpleURL (getURIWithContext (aRequestScope, sHRef)); }
[ "@", "Nonnull", "public", "static", "SimpleURL", "getURLWithContext", "(", "@", "Nonnull", "final", "IRequestWebScopeWithoutResponse", "aRequestScope", ",", "@", "Nonnull", "final", "String", "sHRef", ")", "{", "return", "new", "SimpleURL", "(", "getURIWithContext", "(", "aRequestScope", ",", "sHRef", ")", ")", ";", "}" ]
Prefix the passed href with the relative context path in case the passed href has no protocol yet. @param aRequestScope The request web scope to be used. Required for cookie-less handling. May not be <code>null</code>. @param sHRef The href to be extended. May not be <code>null</code>. @return Either the original href if already absolute or <code>/webapp-context/<i>href</i></code> otherwise. Never <code>null</code>.
[ "Prefix", "the", "passed", "href", "with", "the", "relative", "context", "path", "in", "case", "the", "passed", "href", "has", "no", "protocol", "yet", "." ]
train
https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-app/src/main/java/com/helger/photon/app/url/LinkHelper.java#L214-L219
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlDateTimeUtils.java
SqlDateTimeUtils.convertTz
public static String convertTz(String dateStr, String format, String tzFrom, String tzTo) { """ Convert datetime string from a time zone to another time zone. @param dateStr the date time string @param format the date time format @param tzFrom the original time zone @param tzTo the target time zone """ return dateFormatTz(toTimestampTz(dateStr, format, tzFrom), tzTo); }
java
public static String convertTz(String dateStr, String format, String tzFrom, String tzTo) { return dateFormatTz(toTimestampTz(dateStr, format, tzFrom), tzTo); }
[ "public", "static", "String", "convertTz", "(", "String", "dateStr", ",", "String", "format", ",", "String", "tzFrom", ",", "String", "tzTo", ")", "{", "return", "dateFormatTz", "(", "toTimestampTz", "(", "dateStr", ",", "format", ",", "tzFrom", ")", ",", "tzTo", ")", ";", "}" ]
Convert datetime string from a time zone to another time zone. @param dateStr the date time string @param format the date time format @param tzFrom the original time zone @param tzTo the target time zone
[ "Convert", "datetime", "string", "from", "a", "time", "zone", "to", "another", "time", "zone", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlDateTimeUtils.java#L376-L378
spring-projects/spring-mobile
spring-mobile-device/src/main/java/org/springframework/mobile/device/switcher/SiteSwitcherRequestFilter.java
SiteSwitcherRequestFilter.urlPath
private void urlPath() throws ServletException { """ Configures a site switcher that redirects to a path on the current domain for normal site requests that either originate from a mobile or tablet device, or indicate a mobile or tablet site preference. Uses a {@link CookieSitePreferenceRepository} that saves a cookie that is stored on the root path. """ SiteUrlFactory normalSiteUrlFactory = new NormalSitePathUrlFactory(mobilePath, tabletPath, rootPath); SiteUrlFactory mobileSiteUrlFactory = null; SiteUrlFactory tabletSiteUrlFactory = null; if (mobilePath != null) { mobileSiteUrlFactory = new MobileSitePathUrlFactory(mobilePath, tabletPath, rootPath); } if (tabletPath != null) { tabletSiteUrlFactory = new TabletSitePathUrlFactory(tabletPath, mobilePath, rootPath); } this.siteSwitcherHandler = new StandardSiteSwitcherHandler(normalSiteUrlFactory, mobileSiteUrlFactory, tabletSiteUrlFactory, new StandardSitePreferenceHandler(new CookieSitePreferenceRepository()), null); }
java
private void urlPath() throws ServletException { SiteUrlFactory normalSiteUrlFactory = new NormalSitePathUrlFactory(mobilePath, tabletPath, rootPath); SiteUrlFactory mobileSiteUrlFactory = null; SiteUrlFactory tabletSiteUrlFactory = null; if (mobilePath != null) { mobileSiteUrlFactory = new MobileSitePathUrlFactory(mobilePath, tabletPath, rootPath); } if (tabletPath != null) { tabletSiteUrlFactory = new TabletSitePathUrlFactory(tabletPath, mobilePath, rootPath); } this.siteSwitcherHandler = new StandardSiteSwitcherHandler(normalSiteUrlFactory, mobileSiteUrlFactory, tabletSiteUrlFactory, new StandardSitePreferenceHandler(new CookieSitePreferenceRepository()), null); }
[ "private", "void", "urlPath", "(", ")", "throws", "ServletException", "{", "SiteUrlFactory", "normalSiteUrlFactory", "=", "new", "NormalSitePathUrlFactory", "(", "mobilePath", ",", "tabletPath", ",", "rootPath", ")", ";", "SiteUrlFactory", "mobileSiteUrlFactory", "=", "null", ";", "SiteUrlFactory", "tabletSiteUrlFactory", "=", "null", ";", "if", "(", "mobilePath", "!=", "null", ")", "{", "mobileSiteUrlFactory", "=", "new", "MobileSitePathUrlFactory", "(", "mobilePath", ",", "tabletPath", ",", "rootPath", ")", ";", "}", "if", "(", "tabletPath", "!=", "null", ")", "{", "tabletSiteUrlFactory", "=", "new", "TabletSitePathUrlFactory", "(", "tabletPath", ",", "mobilePath", ",", "rootPath", ")", ";", "}", "this", ".", "siteSwitcherHandler", "=", "new", "StandardSiteSwitcherHandler", "(", "normalSiteUrlFactory", ",", "mobileSiteUrlFactory", ",", "tabletSiteUrlFactory", ",", "new", "StandardSitePreferenceHandler", "(", "new", "CookieSitePreferenceRepository", "(", ")", ")", ",", "null", ")", ";", "}" ]
Configures a site switcher that redirects to a path on the current domain for normal site requests that either originate from a mobile or tablet device, or indicate a mobile or tablet site preference. Uses a {@link CookieSitePreferenceRepository} that saves a cookie that is stored on the root path.
[ "Configures", "a", "site", "switcher", "that", "redirects", "to", "a", "path", "on", "the", "current", "domain", "for", "normal", "site", "requests", "that", "either", "originate", "from", "a", "mobile", "or", "tablet", "device", "or", "indicate", "a", "mobile", "or", "tablet", "site", "preference", ".", "Uses", "a", "{" ]
train
https://github.com/spring-projects/spring-mobile/blob/a402cbcaf208e24288b957f44c9984bd6e8bf064/spring-mobile-device/src/main/java/org/springframework/mobile/device/switcher/SiteSwitcherRequestFilter.java#L283-L295
Metatavu/edelphi
edelphi/src/main/java/fi/metatavu/edelphi/utils/GoogleDriveUtils.java
GoogleDriveUtils.downloadFile
public static DownloadResponse downloadFile(Drive drive, File file) throws IOException { """ Downloads file from Google Drive @param drive drive client @param file file to be downloaded @return file content @throws IOException an IOException """ if (file == null) { return null; } return downloadFile(drive, file.getId()); }
java
public static DownloadResponse downloadFile(Drive drive, File file) throws IOException { if (file == null) { return null; } return downloadFile(drive, file.getId()); }
[ "public", "static", "DownloadResponse", "downloadFile", "(", "Drive", "drive", ",", "File", "file", ")", "throws", "IOException", "{", "if", "(", "file", "==", "null", ")", "{", "return", "null", ";", "}", "return", "downloadFile", "(", "drive", ",", "file", ".", "getId", "(", ")", ")", ";", "}" ]
Downloads file from Google Drive @param drive drive client @param file file to be downloaded @return file content @throws IOException an IOException
[ "Downloads", "file", "from", "Google", "Drive" ]
train
https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/utils/GoogleDriveUtils.java#L351-L357
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/DestinationManager.java
DestinationManager.getDestination
public DestinationHandler getDestination(SIBUuid12 destinationUuid, boolean includeInvisible) throws SITemporaryDestinationNotFoundException, SINotPossibleInCurrentConfigurationException { """ Method getDestination. @param destinationUuid @return Destination @throws SIDestinationNotFoundException <p>This method provides lookup of a destination by its uuid. If the destination is not found, it throws SIDestinationNotFoundException.</p> """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getDestination", destinationUuid); // Get the destination, include invisible dests DestinationHandler destinationHandler = getDestinationInternal(destinationUuid, includeInvisible); checkDestinationHandlerExists( destinationHandler != null, destinationUuid.toString(), messageProcessor.getMessagingEngineName()); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getDestination", destinationHandler); return destinationHandler; }
java
public DestinationHandler getDestination(SIBUuid12 destinationUuid, boolean includeInvisible) throws SITemporaryDestinationNotFoundException, SINotPossibleInCurrentConfigurationException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getDestination", destinationUuid); // Get the destination, include invisible dests DestinationHandler destinationHandler = getDestinationInternal(destinationUuid, includeInvisible); checkDestinationHandlerExists( destinationHandler != null, destinationUuid.toString(), messageProcessor.getMessagingEngineName()); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getDestination", destinationHandler); return destinationHandler; }
[ "public", "DestinationHandler", "getDestination", "(", "SIBUuid12", "destinationUuid", ",", "boolean", "includeInvisible", ")", "throws", "SITemporaryDestinationNotFoundException", ",", "SINotPossibleInCurrentConfigurationException", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "tc", ",", "\"getDestination\"", ",", "destinationUuid", ")", ";", "// Get the destination, include invisible dests", "DestinationHandler", "destinationHandler", "=", "getDestinationInternal", "(", "destinationUuid", ",", "includeInvisible", ")", ";", "checkDestinationHandlerExists", "(", "destinationHandler", "!=", "null", ",", "destinationUuid", ".", "toString", "(", ")", ",", "messageProcessor", ".", "getMessagingEngineName", "(", ")", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "exit", "(", "tc", ",", "\"getDestination\"", ",", "destinationHandler", ")", ";", "return", "destinationHandler", ";", "}" ]
Method getDestination. @param destinationUuid @return Destination @throws SIDestinationNotFoundException <p>This method provides lookup of a destination by its uuid. If the destination is not found, it throws SIDestinationNotFoundException.</p>
[ "Method", "getDestination", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/DestinationManager.java#L5184-L5201
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java
ComputeNodeOperations.getComputeNodeRemoteLoginSettings
public ComputeNodeGetRemoteLoginSettingsResult getComputeNodeRemoteLoginSettings(String poolId, String nodeId) throws BatchErrorException, IOException { """ Gets the settings required for remote login to a compute node. @param poolId The ID of the pool that contains the compute node. @param nodeId The ID of the compute node for which to get a remote login settings. @return The remote settings for the specified compute node. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. """ return getComputeNodeRemoteLoginSettings(poolId, nodeId, null); }
java
public ComputeNodeGetRemoteLoginSettingsResult getComputeNodeRemoteLoginSettings(String poolId, String nodeId) throws BatchErrorException, IOException { return getComputeNodeRemoteLoginSettings(poolId, nodeId, null); }
[ "public", "ComputeNodeGetRemoteLoginSettingsResult", "getComputeNodeRemoteLoginSettings", "(", "String", "poolId", ",", "String", "nodeId", ")", "throws", "BatchErrorException", ",", "IOException", "{", "return", "getComputeNodeRemoteLoginSettings", "(", "poolId", ",", "nodeId", ",", "null", ")", ";", "}" ]
Gets the settings required for remote login to a compute node. @param poolId The ID of the pool that contains the compute node. @param nodeId The ID of the compute node for which to get a remote login settings. @return The remote settings for the specified compute node. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Gets", "the", "settings", "required", "for", "remote", "login", "to", "a", "compute", "node", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java#L476-L478
xsonorg/xson
src/main/java/org/xson/core/asm/ClassWriter.java
ClassWriter.newDouble
Item newDouble(final double value) { """ Adds a double to the constant pool of the class being build. Does nothing if the constant pool already contains a similar item. @param value the double value. @return a new or already existing double item. """ key.set(value); Item result = get(key); if (result == null) { pool.putByte(DOUBLE).putLong(key.longVal); result = new Item(index, key); put(result); index += 2; } return result; }
java
Item newDouble(final double value) { key.set(value); Item result = get(key); if (result == null) { pool.putByte(DOUBLE).putLong(key.longVal); result = new Item(index, key); put(result); index += 2; } return result; }
[ "Item", "newDouble", "(", "final", "double", "value", ")", "{", "key", ".", "set", "(", "value", ")", ";", "Item", "result", "=", "get", "(", "key", ")", ";", "if", "(", "result", "==", "null", ")", "{", "pool", ".", "putByte", "(", "DOUBLE", ")", ".", "putLong", "(", "key", ".", "longVal", ")", ";", "result", "=", "new", "Item", "(", "index", ",", "key", ")", ";", "put", "(", "result", ")", ";", "index", "+=", "2", ";", "}", "return", "result", ";", "}" ]
Adds a double to the constant pool of the class being build. Does nothing if the constant pool already contains a similar item. @param value the double value. @return a new or already existing double item.
[ "Adds", "a", "double", "to", "the", "constant", "pool", "of", "the", "class", "being", "build", ".", "Does", "nothing", "if", "the", "constant", "pool", "already", "contains", "a", "similar", "item", "." ]
train
https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/ClassWriter.java#L1113-L1123
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/transform/description/AbstractTransformationDescriptionBuilder.java
AbstractTransformationDescriptionBuilder.buildDefault
protected TransformationDescription buildDefault(final DiscardPolicy discardPolicy, boolean inherited, final AttributeTransformationDescriptionBuilderImpl.AttributeTransformationDescriptionBuilderRegistry registry, List<String> discardedOperations) { """ Build the default transformation description. @param discardPolicy the discard policy to use @param inherited whether the definition is inherited @param registry the attribute transformation rules for the resource @param discardedOperations the discarded operations @return the transformation description """ // Build attribute rules final Map<String, AttributeTransformationDescription> attributes = registry.buildAttributes(); // Create operation transformers final Map<String, OperationTransformer> operations = buildOperationTransformers(registry); // Process children final List<TransformationDescription> children = buildChildren(); if (discardPolicy == DiscardPolicy.NEVER) { // TODO override more global operations? if(! operations.containsKey(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION)) { operations.put(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION, OperationTransformationRules.createWriteOperation(attributes)); } if(! operations.containsKey(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION)) { operations.put(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION, OperationTransformationRules.createUndefinedOperation(attributes)); } } // Create the description Set<String> discarded = new HashSet<>(); discarded.addAll(discardedOperations); return new TransformingDescription(pathElement, pathAddressTransformer, discardPolicy, inherited, resourceTransformer, attributes, operations, children, discarded, dynamicDiscardPolicy); }
java
protected TransformationDescription buildDefault(final DiscardPolicy discardPolicy, boolean inherited, final AttributeTransformationDescriptionBuilderImpl.AttributeTransformationDescriptionBuilderRegistry registry, List<String> discardedOperations) { // Build attribute rules final Map<String, AttributeTransformationDescription> attributes = registry.buildAttributes(); // Create operation transformers final Map<String, OperationTransformer> operations = buildOperationTransformers(registry); // Process children final List<TransformationDescription> children = buildChildren(); if (discardPolicy == DiscardPolicy.NEVER) { // TODO override more global operations? if(! operations.containsKey(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION)) { operations.put(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION, OperationTransformationRules.createWriteOperation(attributes)); } if(! operations.containsKey(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION)) { operations.put(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION, OperationTransformationRules.createUndefinedOperation(attributes)); } } // Create the description Set<String> discarded = new HashSet<>(); discarded.addAll(discardedOperations); return new TransformingDescription(pathElement, pathAddressTransformer, discardPolicy, inherited, resourceTransformer, attributes, operations, children, discarded, dynamicDiscardPolicy); }
[ "protected", "TransformationDescription", "buildDefault", "(", "final", "DiscardPolicy", "discardPolicy", ",", "boolean", "inherited", ",", "final", "AttributeTransformationDescriptionBuilderImpl", ".", "AttributeTransformationDescriptionBuilderRegistry", "registry", ",", "List", "<", "String", ">", "discardedOperations", ")", "{", "// Build attribute rules", "final", "Map", "<", "String", ",", "AttributeTransformationDescription", ">", "attributes", "=", "registry", ".", "buildAttributes", "(", ")", ";", "// Create operation transformers", "final", "Map", "<", "String", ",", "OperationTransformer", ">", "operations", "=", "buildOperationTransformers", "(", "registry", ")", ";", "// Process children", "final", "List", "<", "TransformationDescription", ">", "children", "=", "buildChildren", "(", ")", ";", "if", "(", "discardPolicy", "==", "DiscardPolicy", ".", "NEVER", ")", "{", "// TODO override more global operations?", "if", "(", "!", "operations", ".", "containsKey", "(", "ModelDescriptionConstants", ".", "WRITE_ATTRIBUTE_OPERATION", ")", ")", "{", "operations", ".", "put", "(", "ModelDescriptionConstants", ".", "WRITE_ATTRIBUTE_OPERATION", ",", "OperationTransformationRules", ".", "createWriteOperation", "(", "attributes", ")", ")", ";", "}", "if", "(", "!", "operations", ".", "containsKey", "(", "ModelDescriptionConstants", ".", "UNDEFINE_ATTRIBUTE_OPERATION", ")", ")", "{", "operations", ".", "put", "(", "ModelDescriptionConstants", ".", "UNDEFINE_ATTRIBUTE_OPERATION", ",", "OperationTransformationRules", ".", "createUndefinedOperation", "(", "attributes", ")", ")", ";", "}", "}", "// Create the description", "Set", "<", "String", ">", "discarded", "=", "new", "HashSet", "<>", "(", ")", ";", "discarded", ".", "addAll", "(", "discardedOperations", ")", ";", "return", "new", "TransformingDescription", "(", "pathElement", ",", "pathAddressTransformer", ",", "discardPolicy", ",", "inherited", ",", "resourceTransformer", ",", "attributes", ",", "operations", ",", "children", ",", "discarded", ",", "dynamicDiscardPolicy", ")", ";", "}" ]
Build the default transformation description. @param discardPolicy the discard policy to use @param inherited whether the definition is inherited @param registry the attribute transformation rules for the resource @param discardedOperations the discarded operations @return the transformation description
[ "Build", "the", "default", "transformation", "description", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/transform/description/AbstractTransformationDescriptionBuilder.java#L87-L109
advantageous/boon
reflekt/src/main/java/io/advantageous/boon/core/reflection/MapperComplex.java
MapperComplex.fromValueMap
@Override @SuppressWarnings("unchecked") public Object fromValueMap(final Map<String, Value> valueMap ) { """ Creates an object from a value map. This does some special handling to take advantage of us using the value map so it avoids creating a bunch of array objects and collections. Things you have to worry about when writing a high-speed JSON serializer. @return new object from value map """ try { String className = valueMap.get( "class" ).toString(); Class<?> cls = Reflection.loadClass( className ); return fromValueMap( valueMap, cls ); } catch ( Exception ex ) { return handle(Object.class, Str.sputs("fromValueMap", "map", valueMap, "fieldAccessor", fieldsAccessor), ex); } }
java
@Override @SuppressWarnings("unchecked") public Object fromValueMap(final Map<String, Value> valueMap ) { try { String className = valueMap.get( "class" ).toString(); Class<?> cls = Reflection.loadClass( className ); return fromValueMap( valueMap, cls ); } catch ( Exception ex ) { return handle(Object.class, Str.sputs("fromValueMap", "map", valueMap, "fieldAccessor", fieldsAccessor), ex); } }
[ "@", "Override", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "Object", "fromValueMap", "(", "final", "Map", "<", "String", ",", "Value", ">", "valueMap", ")", "{", "try", "{", "String", "className", "=", "valueMap", ".", "get", "(", "\"class\"", ")", ".", "toString", "(", ")", ";", "Class", "<", "?", ">", "cls", "=", "Reflection", ".", "loadClass", "(", "className", ")", ";", "return", "fromValueMap", "(", "valueMap", ",", "cls", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "return", "handle", "(", "Object", ".", "class", ",", "Str", ".", "sputs", "(", "\"fromValueMap\"", ",", "\"map\"", ",", "valueMap", ",", "\"fieldAccessor\"", ",", "fieldsAccessor", ")", ",", "ex", ")", ";", "}", "}" ]
Creates an object from a value map. This does some special handling to take advantage of us using the value map so it avoids creating a bunch of array objects and collections. Things you have to worry about when writing a high-speed JSON serializer. @return new object from value map
[ "Creates", "an", "object", "from", "a", "value", "map", "." ]
train
https://github.com/advantageous/boon/blob/12712d376761aa3b33223a9f1716720ddb67cb5e/reflekt/src/main/java/io/advantageous/boon/core/reflection/MapperComplex.java#L1145-L1158
Azure/azure-sdk-for-java
datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/StorageAccountsInner.java
StorageAccountsInner.listByAccountWithServiceResponseAsync
public Observable<ServiceResponse<Page<StorageAccountInformationInner>>> listByAccountWithServiceResponseAsync(final String resourceGroupName, final String accountName, final String filter, final Integer top, final Integer skip, final String select, final String orderby, final Boolean count) { """ Gets the first page of Azure Storage accounts, if any, linked to the specified Data Lake Analytics account. The response includes a link to the next page, if any. @param resourceGroupName The name of the Azure resource group. @param accountName The name of the Data Lake Analytics account. @param filter The OData filter. Optional. @param top The number of items to return. Optional. @param skip The number of items to skip over before returning elements. Optional. @param select OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. @param orderby OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional. @param count The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;StorageAccountInformationInner&gt; object """ return listByAccountSinglePageAsync(resourceGroupName, accountName, filter, top, skip, select, orderby, count) .concatMap(new Func1<ServiceResponse<Page<StorageAccountInformationInner>>, Observable<ServiceResponse<Page<StorageAccountInformationInner>>>>() { @Override public Observable<ServiceResponse<Page<StorageAccountInformationInner>>> call(ServiceResponse<Page<StorageAccountInformationInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByAccountNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<StorageAccountInformationInner>>> listByAccountWithServiceResponseAsync(final String resourceGroupName, final String accountName, final String filter, final Integer top, final Integer skip, final String select, final String orderby, final Boolean count) { return listByAccountSinglePageAsync(resourceGroupName, accountName, filter, top, skip, select, orderby, count) .concatMap(new Func1<ServiceResponse<Page<StorageAccountInformationInner>>, Observable<ServiceResponse<Page<StorageAccountInformationInner>>>>() { @Override public Observable<ServiceResponse<Page<StorageAccountInformationInner>>> call(ServiceResponse<Page<StorageAccountInformationInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByAccountNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "StorageAccountInformationInner", ">", ">", ">", "listByAccountWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "accountName", ",", "final", "String", "filter", ",", "final", "Integer", "top", ",", "final", "Integer", "skip", ",", "final", "String", "select", ",", "final", "String", "orderby", ",", "final", "Boolean", "count", ")", "{", "return", "listByAccountSinglePageAsync", "(", "resourceGroupName", ",", "accountName", ",", "filter", ",", "top", ",", "skip", ",", "select", ",", "orderby", ",", "count", ")", ".", "concatMap", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "StorageAccountInformationInner", ">", ">", ",", "Observable", "<", "ServiceResponse", "<", "Page", "<", "StorageAccountInformationInner", ">", ">", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "StorageAccountInformationInner", ">", ">", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "StorageAccountInformationInner", ">", ">", "page", ")", "{", "String", "nextPageLink", "=", "page", ".", "body", "(", ")", ".", "nextPageLink", "(", ")", ";", "if", "(", "nextPageLink", "==", "null", ")", "{", "return", "Observable", ".", "just", "(", "page", ")", ";", "}", "return", "Observable", ".", "just", "(", "page", ")", ".", "concatWith", "(", "listByAccountNextWithServiceResponseAsync", "(", "nextPageLink", ")", ")", ";", "}", "}", ")", ";", "}" ]
Gets the first page of Azure Storage accounts, if any, linked to the specified Data Lake Analytics account. The response includes a link to the next page, if any. @param resourceGroupName The name of the Azure resource group. @param accountName The name of the Data Lake Analytics account. @param filter The OData filter. Optional. @param top The number of items to return. Optional. @param skip The number of items to skip over before returning elements. Optional. @param select OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. @param orderby OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional. @param count The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;StorageAccountInformationInner&gt; object
[ "Gets", "the", "first", "page", "of", "Azure", "Storage", "accounts", "if", "any", "linked", "to", "the", "specified", "Data", "Lake", "Analytics", "account", ".", "The", "response", "includes", "a", "link", "to", "the", "next", "page", "if", "any", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/StorageAccountsInner.java#L327-L339
powermock/powermock
powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java
PowerMock.createNiceMockAndExpectNew
public static synchronized <T> T createNiceMockAndExpectNew(Class<T> type, Object... arguments) throws Exception { """ Convenience method for createNiceMock followed by expectNew. @param type The class that should be mocked. @param arguments The constructor arguments. @return A mock object of the same type as the mock. @throws Exception """ T mock = createNiceMock(type); IExpectationSetters<T> expectationSetters = expectNiceNew(type, arguments); if (expectationSetters != null) { expectationSetters.andReturn(mock); } return mock; }
java
public static synchronized <T> T createNiceMockAndExpectNew(Class<T> type, Object... arguments) throws Exception { T mock = createNiceMock(type); IExpectationSetters<T> expectationSetters = expectNiceNew(type, arguments); if (expectationSetters != null) { expectationSetters.andReturn(mock); } return mock; }
[ "public", "static", "synchronized", "<", "T", ">", "T", "createNiceMockAndExpectNew", "(", "Class", "<", "T", ">", "type", ",", "Object", "...", "arguments", ")", "throws", "Exception", "{", "T", "mock", "=", "createNiceMock", "(", "type", ")", ";", "IExpectationSetters", "<", "T", ">", "expectationSetters", "=", "expectNiceNew", "(", "type", ",", "arguments", ")", ";", "if", "(", "expectationSetters", "!=", "null", ")", "{", "expectationSetters", ".", "andReturn", "(", "mock", ")", ";", "}", "return", "mock", ";", "}" ]
Convenience method for createNiceMock followed by expectNew. @param type The class that should be mocked. @param arguments The constructor arguments. @return A mock object of the same type as the mock. @throws Exception
[ "Convenience", "method", "for", "createNiceMock", "followed", "by", "expectNew", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L1538-L1545
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/fit/MapColumnFixture.java
MapColumnFixture.getSymbolArrayValue
private Object getSymbolArrayValue(Object arraySymbol, int index) { """ Fetch the value from arraySymbol on specified index. @param arraySymbol symbol from Fixture that is array @param index to find element from array @return the element from the symbol array """ Object result = null; if (index > -1 && index < ((Object[]) arraySymbol).length) { result = ((Object[]) arraySymbol)[index]; } return result; }
java
private Object getSymbolArrayValue(Object arraySymbol, int index) { Object result = null; if (index > -1 && index < ((Object[]) arraySymbol).length) { result = ((Object[]) arraySymbol)[index]; } return result; }
[ "private", "Object", "getSymbolArrayValue", "(", "Object", "arraySymbol", ",", "int", "index", ")", "{", "Object", "result", "=", "null", ";", "if", "(", "index", ">", "-", "1", "&&", "index", "<", "(", "(", "Object", "[", "]", ")", "arraySymbol", ")", ".", "length", ")", "{", "result", "=", "(", "(", "Object", "[", "]", ")", "arraySymbol", ")", "[", "index", "]", ";", "}", "return", "result", ";", "}" ]
Fetch the value from arraySymbol on specified index. @param arraySymbol symbol from Fixture that is array @param index to find element from array @return the element from the symbol array
[ "Fetch", "the", "value", "from", "arraySymbol", "on", "specified", "index", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/fit/MapColumnFixture.java#L496-L502
perwendel/spark
src/main/java/spark/utils/MimeParse.java
MimeParse.bestMatch
public static String bestMatch(Collection<String> supported, String header) { """ Finds best match @param supported the supported types @param header the header @return the best match """ List<ParseResults> parseResults = new LinkedList<>(); List<FitnessAndQuality> weightedMatches = new LinkedList<>(); for (String r : header.split(",")) { parseResults.add(parseMediaRange(r)); } for (String s : supported) { FitnessAndQuality fitnessAndQuality = fitnessAndQualityParsed(s, parseResults); fitnessAndQuality.mimeType = s; weightedMatches.add(fitnessAndQuality); } Collections.sort(weightedMatches); FitnessAndQuality lastOne = weightedMatches.get(weightedMatches.size() - 1); return Float.compare(lastOne.quality, 0) != 0 ? lastOne.mimeType : NO_MIME_TYPE; }
java
public static String bestMatch(Collection<String> supported, String header) { List<ParseResults> parseResults = new LinkedList<>(); List<FitnessAndQuality> weightedMatches = new LinkedList<>(); for (String r : header.split(",")) { parseResults.add(parseMediaRange(r)); } for (String s : supported) { FitnessAndQuality fitnessAndQuality = fitnessAndQualityParsed(s, parseResults); fitnessAndQuality.mimeType = s; weightedMatches.add(fitnessAndQuality); } Collections.sort(weightedMatches); FitnessAndQuality lastOne = weightedMatches.get(weightedMatches.size() - 1); return Float.compare(lastOne.quality, 0) != 0 ? lastOne.mimeType : NO_MIME_TYPE; }
[ "public", "static", "String", "bestMatch", "(", "Collection", "<", "String", ">", "supported", ",", "String", "header", ")", "{", "List", "<", "ParseResults", ">", "parseResults", "=", "new", "LinkedList", "<>", "(", ")", ";", "List", "<", "FitnessAndQuality", ">", "weightedMatches", "=", "new", "LinkedList", "<>", "(", ")", ";", "for", "(", "String", "r", ":", "header", ".", "split", "(", "\",\"", ")", ")", "{", "parseResults", ".", "add", "(", "parseMediaRange", "(", "r", ")", ")", ";", "}", "for", "(", "String", "s", ":", "supported", ")", "{", "FitnessAndQuality", "fitnessAndQuality", "=", "fitnessAndQualityParsed", "(", "s", ",", "parseResults", ")", ";", "fitnessAndQuality", ".", "mimeType", "=", "s", ";", "weightedMatches", ".", "add", "(", "fitnessAndQuality", ")", ";", "}", "Collections", ".", "sort", "(", "weightedMatches", ")", ";", "FitnessAndQuality", "lastOne", "=", "weightedMatches", ".", "get", "(", "weightedMatches", ".", "size", "(", ")", "-", "1", ")", ";", "return", "Float", ".", "compare", "(", "lastOne", ".", "quality", ",", "0", ")", "!=", "0", "?", "lastOne", ".", "mimeType", ":", "NO_MIME_TYPE", ";", "}" ]
Finds best match @param supported the supported types @param header the header @return the best match
[ "Finds", "best", "match" ]
train
https://github.com/perwendel/spark/blob/080fb1f9d6e580f6742e9589044c7420d3157b8b/src/main/java/spark/utils/MimeParse.java#L173-L189
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/BoundedOverlay.java
BoundedOverlay.hasTile
public boolean hasTile(int x, int y, int zoom) { """ Determine if there is a tile for the x, y, and zoom @param x x coordinate @param y y coordinate @param zoom zoom value @return true if there is a tile @since 1.2.6 """ // Check if generating tiles for the zoom level and is within the bounding box boolean hasTile = isWithinBounds(x, y, zoom); if (hasTile) { // Check if there is a tile to retrieve hasTile = hasTileToRetrieve(x, y, zoom); } return hasTile; }
java
public boolean hasTile(int x, int y, int zoom) { // Check if generating tiles for the zoom level and is within the bounding box boolean hasTile = isWithinBounds(x, y, zoom); if (hasTile) { // Check if there is a tile to retrieve hasTile = hasTileToRetrieve(x, y, zoom); } return hasTile; }
[ "public", "boolean", "hasTile", "(", "int", "x", ",", "int", "y", ",", "int", "zoom", ")", "{", "// Check if generating tiles for the zoom level and is within the bounding box", "boolean", "hasTile", "=", "isWithinBounds", "(", "x", ",", "y", ",", "zoom", ")", ";", "if", "(", "hasTile", ")", "{", "// Check if there is a tile to retrieve", "hasTile", "=", "hasTileToRetrieve", "(", "x", ",", "y", ",", "zoom", ")", ";", "}", "return", "hasTile", ";", "}" ]
Determine if there is a tile for the x, y, and zoom @param x x coordinate @param y y coordinate @param zoom zoom value @return true if there is a tile @since 1.2.6
[ "Determine", "if", "there", "is", "a", "tile", "for", "the", "x", "y", "and", "zoom" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/BoundedOverlay.java#L151-L161
EsotericSoftware/kryo
src/com/esotericsoftware/kryo/Kryo.java
Kryo.addDefaultSerializer
public void addDefaultSerializer (Class type, SerializerFactory serializerFactory) { """ Instances of the specified class will use the specified factory to create a serializer when {@link #register(Class)} or {@link #register(Class, int)} are called. @see #setDefaultSerializer(Class) """ if (type == null) throw new IllegalArgumentException("type cannot be null."); if (serializerFactory == null) throw new IllegalArgumentException("serializerFactory cannot be null."); insertDefaultSerializer(type, serializerFactory); }
java
public void addDefaultSerializer (Class type, SerializerFactory serializerFactory) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (serializerFactory == null) throw new IllegalArgumentException("serializerFactory cannot be null."); insertDefaultSerializer(type, serializerFactory); }
[ "public", "void", "addDefaultSerializer", "(", "Class", "type", ",", "SerializerFactory", "serializerFactory", ")", "{", "if", "(", "type", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"type cannot be null.\"", ")", ";", "if", "(", "serializerFactory", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"serializerFactory cannot be null.\"", ")", ";", "insertDefaultSerializer", "(", "type", ",", "serializerFactory", ")", ";", "}" ]
Instances of the specified class will use the specified factory to create a serializer when {@link #register(Class)} or {@link #register(Class, int)} are called. @see #setDefaultSerializer(Class)
[ "Instances", "of", "the", "specified", "class", "will", "use", "the", "specified", "factory", "to", "create", "a", "serializer", "when", "{" ]
train
https://github.com/EsotericSoftware/kryo/blob/a8be1ab26f347f299a3c3f7171d6447dd5390845/src/com/esotericsoftware/kryo/Kryo.java#L269-L273
baratine/baratine
framework/src/main/java/com/caucho/v5/ramp/db/DatabaseServiceRamp.java
DatabaseServiceRamp.find
public void find(ResultStream<Cursor> result, String sql, Object ...args) { """ Queries the database, returning values to a result sink. @param sql the select query for the search @param result callback for the result iterator @param args arguments to the sql """ _kraken.findStream(sql, args, result); }
java
public void find(ResultStream<Cursor> result, String sql, Object ...args) { _kraken.findStream(sql, args, result); }
[ "public", "void", "find", "(", "ResultStream", "<", "Cursor", ">", "result", ",", "String", "sql", ",", "Object", "...", "args", ")", "{", "_kraken", ".", "findStream", "(", "sql", ",", "args", ",", "result", ")", ";", "}" ]
Queries the database, returning values to a result sink. @param sql the select query for the search @param result callback for the result iterator @param args arguments to the sql
[ "Queries", "the", "database", "returning", "values", "to", "a", "result", "sink", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/ramp/db/DatabaseServiceRamp.java#L157-L160
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/GraphGenerator.java
GraphGenerator.setLink
void setLink(Node node, Relation relation, Node childNode, NodeLink nodeLink) { """ Set link property @param node node @param relation relation @param childNode target node @param nodeLink node link(bridge) """ nodeLink.setMultiplicity(relation.getType()); EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(node.getPersistenceDelegator() .getKunderaMetadata(), node.getDataClass()); nodeLink.setLinkProperties(getLinkProperties(metadata, relation, node.getPersistenceDelegator() .getKunderaMetadata())); // Add Parent node to this child childNode.addParentNode(nodeLink, node); // Add child node to this node node.addChildNode(nodeLink, childNode); }
java
void setLink(Node node, Relation relation, Node childNode, NodeLink nodeLink) { nodeLink.setMultiplicity(relation.getType()); EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(node.getPersistenceDelegator() .getKunderaMetadata(), node.getDataClass()); nodeLink.setLinkProperties(getLinkProperties(metadata, relation, node.getPersistenceDelegator() .getKunderaMetadata())); // Add Parent node to this child childNode.addParentNode(nodeLink, node); // Add child node to this node node.addChildNode(nodeLink, childNode); }
[ "void", "setLink", "(", "Node", "node", ",", "Relation", "relation", ",", "Node", "childNode", ",", "NodeLink", "nodeLink", ")", "{", "nodeLink", ".", "setMultiplicity", "(", "relation", ".", "getType", "(", ")", ")", ";", "EntityMetadata", "metadata", "=", "KunderaMetadataManager", ".", "getEntityMetadata", "(", "node", ".", "getPersistenceDelegator", "(", ")", ".", "getKunderaMetadata", "(", ")", ",", "node", ".", "getDataClass", "(", ")", ")", ";", "nodeLink", ".", "setLinkProperties", "(", "getLinkProperties", "(", "metadata", ",", "relation", ",", "node", ".", "getPersistenceDelegator", "(", ")", ".", "getKunderaMetadata", "(", ")", ")", ")", ";", "// Add Parent node to this child", "childNode", ".", "addParentNode", "(", "nodeLink", ",", "node", ")", ";", "// Add child node to this node", "node", ".", "addChildNode", "(", "nodeLink", ",", "childNode", ")", ";", "}" ]
Set link property @param node node @param relation relation @param childNode target node @param nodeLink node link(bridge)
[ "Set", "link", "property" ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/GraphGenerator.java#L297-L311
grpc/grpc-java
examples/android/clientcache/app/src/main/java/io/grpc/clientcacheexample/SafeMethodCachingInterceptor.java
SafeMethodCachingInterceptor.newLruCache
public static Cache newLruCache(final int cacheSizeInBytes) { """ Obtain a new cache with a least-recently used eviction policy and the specified size limit. The backing caching implementation is provided by {@link LruCache}. It is safe for a single cache to be shared across multiple {@link SafeMethodCachingInterceptor}s without synchronization. """ return new Cache() { private final LruCache<Key, Value> lruCache = new LruCache<Key, Value>(cacheSizeInBytes) { protected int sizeOf(Key key, Value value) { return value.response.getSerializedSize(); } }; @Override public void put(Key key, Value value) { lruCache.put(key, value); } @Override public Value get(Key key) { return lruCache.get(key); } @Override public void remove(Key key) { lruCache.remove(key); } @Override public void clear() { lruCache.evictAll(); } }; }
java
public static Cache newLruCache(final int cacheSizeInBytes) { return new Cache() { private final LruCache<Key, Value> lruCache = new LruCache<Key, Value>(cacheSizeInBytes) { protected int sizeOf(Key key, Value value) { return value.response.getSerializedSize(); } }; @Override public void put(Key key, Value value) { lruCache.put(key, value); } @Override public Value get(Key key) { return lruCache.get(key); } @Override public void remove(Key key) { lruCache.remove(key); } @Override public void clear() { lruCache.evictAll(); } }; }
[ "public", "static", "Cache", "newLruCache", "(", "final", "int", "cacheSizeInBytes", ")", "{", "return", "new", "Cache", "(", ")", "{", "private", "final", "LruCache", "<", "Key", ",", "Value", ">", "lruCache", "=", "new", "LruCache", "<", "Key", ",", "Value", ">", "(", "cacheSizeInBytes", ")", "{", "protected", "int", "sizeOf", "(", "Key", "key", ",", "Value", "value", ")", "{", "return", "value", ".", "response", ".", "getSerializedSize", "(", ")", ";", "}", "}", ";", "@", "Override", "public", "void", "put", "(", "Key", "key", ",", "Value", "value", ")", "{", "lruCache", ".", "put", "(", "key", ",", "value", ")", ";", "}", "@", "Override", "public", "Value", "get", "(", "Key", "key", ")", "{", "return", "lruCache", ".", "get", "(", "key", ")", ";", "}", "@", "Override", "public", "void", "remove", "(", "Key", "key", ")", "{", "lruCache", ".", "remove", "(", "key", ")", ";", "}", "@", "Override", "public", "void", "clear", "(", ")", "{", "lruCache", ".", "evictAll", "(", ")", ";", "}", "}", ";", "}" ]
Obtain a new cache with a least-recently used eviction policy and the specified size limit. The backing caching implementation is provided by {@link LruCache}. It is safe for a single cache to be shared across multiple {@link SafeMethodCachingInterceptor}s without synchronization.
[ "Obtain", "a", "new", "cache", "with", "a", "least", "-", "recently", "used", "eviction", "policy", "and", "the", "specified", "size", "limit", ".", "The", "backing", "caching", "implementation", "is", "provided", "by", "{" ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/examples/android/clientcache/app/src/main/java/io/grpc/clientcacheexample/SafeMethodCachingInterceptor.java#L107-L136
teatrove/teatrove
trove/src/main/java/org/teatrove/trove/classfile/ConstantDoubleInfo.java
ConstantDoubleInfo.make
static ConstantDoubleInfo make(ConstantPool cp, double value) { """ Will return either a new ConstantDoubleInfo object or one already in the constant pool. If it is a new ConstantDoubleInfo, it will be inserted into the pool. """ ConstantInfo ci = new ConstantDoubleInfo(value); return (ConstantDoubleInfo)cp.addConstant(ci); }
java
static ConstantDoubleInfo make(ConstantPool cp, double value) { ConstantInfo ci = new ConstantDoubleInfo(value); return (ConstantDoubleInfo)cp.addConstant(ci); }
[ "static", "ConstantDoubleInfo", "make", "(", "ConstantPool", "cp", ",", "double", "value", ")", "{", "ConstantInfo", "ci", "=", "new", "ConstantDoubleInfo", "(", "value", ")", ";", "return", "(", "ConstantDoubleInfo", ")", "cp", ".", "addConstant", "(", "ci", ")", ";", "}" ]
Will return either a new ConstantDoubleInfo object or one already in the constant pool. If it is a new ConstantDoubleInfo, it will be inserted into the pool.
[ "Will", "return", "either", "a", "new", "ConstantDoubleInfo", "object", "or", "one", "already", "in", "the", "constant", "pool", ".", "If", "it", "is", "a", "new", "ConstantDoubleInfo", "it", "will", "be", "inserted", "into", "the", "pool", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/ConstantDoubleInfo.java#L35-L38
looly/hutool
hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java
ImgUtil.pressImage
public static BufferedImage pressImage(Image srcImage, Image pressImg, Rectangle rectangle, float alpha) { """ 给图片添加图片水印<br> 此方法并不关闭流 @param srcImage 源图像流 @param pressImg 水印图片,可以使用{@link ImageIO#read(File)}方法读取文件 @param rectangle 矩形对象,表示矩形区域的x,y,width,height,x,y从背景图片中心计算 @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字 @return 结果图片 @since 4.1.14 """ return Img.from(srcImage).pressImage(pressImg, rectangle, alpha).getImg(); }
java
public static BufferedImage pressImage(Image srcImage, Image pressImg, Rectangle rectangle, float alpha) { return Img.from(srcImage).pressImage(pressImg, rectangle, alpha).getImg(); }
[ "public", "static", "BufferedImage", "pressImage", "(", "Image", "srcImage", ",", "Image", "pressImg", ",", "Rectangle", "rectangle", ",", "float", "alpha", ")", "{", "return", "Img", ".", "from", "(", "srcImage", ")", ".", "pressImage", "(", "pressImg", ",", "rectangle", ",", "alpha", ")", ".", "getImg", "(", ")", ";", "}" ]
给图片添加图片水印<br> 此方法并不关闭流 @param srcImage 源图像流 @param pressImg 水印图片,可以使用{@link ImageIO#read(File)}方法读取文件 @param rectangle 矩形对象,表示矩形区域的x,y,width,height,x,y从背景图片中心计算 @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字 @return 结果图片 @since 4.1.14
[ "给图片添加图片水印<br", ">", "此方法并不关闭流" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L987-L989
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/link/ComponentEnhancer.java
ComponentEnhancer.manageUniqueWaveTypeAction
private static void manageUniqueWaveTypeAction(final Component<?> component, final String waveActionName, final Method method) { """ Manage unique {@link WaveType} subscription (from value field of {@link OnWave} annotation). @param component the wave ready @param waveActionName the {@link WaveType} unique name @param method the wave handler method """ // Get the WaveType from the WaveType registry final WaveType wt = WaveTypeRegistry.getWaveType(waveActionName); if (wt == null) { throw new CoreRuntimeException("WaveType '" + waveActionName + "' not found into WaveTypeRegistry."); } else { // Method is not defined or is the default fallback one if (method == null || AbstractComponent.PROCESS_WAVE_METHOD_NAME.equals(method.getName())) { // Just listen the WaveType component.listen(wt); } else { // Listen the WaveType and specify the right method handler component.listen(null, method, wt); } } }
java
private static void manageUniqueWaveTypeAction(final Component<?> component, final String waveActionName, final Method method) { // Get the WaveType from the WaveType registry final WaveType wt = WaveTypeRegistry.getWaveType(waveActionName); if (wt == null) { throw new CoreRuntimeException("WaveType '" + waveActionName + "' not found into WaveTypeRegistry."); } else { // Method is not defined or is the default fallback one if (method == null || AbstractComponent.PROCESS_WAVE_METHOD_NAME.equals(method.getName())) { // Just listen the WaveType component.listen(wt); } else { // Listen the WaveType and specify the right method handler component.listen(null, method, wt); } } }
[ "private", "static", "void", "manageUniqueWaveTypeAction", "(", "final", "Component", "<", "?", ">", "component", ",", "final", "String", "waveActionName", ",", "final", "Method", "method", ")", "{", "// Get the WaveType from the WaveType registry", "final", "WaveType", "wt", "=", "WaveTypeRegistry", ".", "getWaveType", "(", "waveActionName", ")", ";", "if", "(", "wt", "==", "null", ")", "{", "throw", "new", "CoreRuntimeException", "(", "\"WaveType '\"", "+", "waveActionName", "+", "\"' not found into WaveTypeRegistry.\"", ")", ";", "}", "else", "{", "// Method is not defined or is the default fallback one", "if", "(", "method", "==", "null", "||", "AbstractComponent", ".", "PROCESS_WAVE_METHOD_NAME", ".", "equals", "(", "method", ".", "getName", "(", ")", ")", ")", "{", "// Just listen the WaveType", "component", ".", "listen", "(", "wt", ")", ";", "}", "else", "{", "// Listen the WaveType and specify the right method handler", "component", ".", "listen", "(", "null", ",", "method", ",", "wt", ")", ";", "}", "}", "}" ]
Manage unique {@link WaveType} subscription (from value field of {@link OnWave} annotation). @param component the wave ready @param waveActionName the {@link WaveType} unique name @param method the wave handler method
[ "Manage", "unique", "{", "@link", "WaveType", "}", "subscription", "(", "from", "value", "field", "of", "{", "@link", "OnWave", "}", "annotation", ")", "." ]
train
https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/link/ComponentEnhancer.java#L249-L265
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.groupBy
public static Map<Object, Map> groupBy(Map self, List<Closure> closures) { """ Groups the members of a map into sub maps determined by the supplied mapping closures. Each closure will be passed a Map.Entry or key and value (depending on the number of parameters the closure accepts) and should return the key that each item should be grouped under. The resulting map will have an entry for each 'group path' returned by all closures, with values being the map members from the original map that belong to each such 'group path'. If the <code>self</code> map is one of TreeMap, Hashtable, or Properties, the returned Map will preserve that type, otherwise a LinkedHashMap will be returned. <pre class="groovyTestCase">def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy([{ it.value % 2 }, { it.key.next() }]) assert result == [1:[b:[a:1], d:[c:3], f:[e:5]], 0:[c:[b:2], e:[d:4], g:[f:6]]]</pre> If an empty list of closures is supplied the IDENTITY Closure will be used. @param self a map to group @param closures a list of closures that map entries on keys @return a new map grouped by keys on each criterion @since 1.8.1 @see Closure#IDENTITY """ return groupBy(self, closures.toArray()); }
java
public static Map<Object, Map> groupBy(Map self, List<Closure> closures) { return groupBy(self, closures.toArray()); }
[ "public", "static", "Map", "<", "Object", ",", "Map", ">", "groupBy", "(", "Map", "self", ",", "List", "<", "Closure", ">", "closures", ")", "{", "return", "groupBy", "(", "self", ",", "closures", ".", "toArray", "(", ")", ")", ";", "}" ]
Groups the members of a map into sub maps determined by the supplied mapping closures. Each closure will be passed a Map.Entry or key and value (depending on the number of parameters the closure accepts) and should return the key that each item should be grouped under. The resulting map will have an entry for each 'group path' returned by all closures, with values being the map members from the original map that belong to each such 'group path'. If the <code>self</code> map is one of TreeMap, Hashtable, or Properties, the returned Map will preserve that type, otherwise a LinkedHashMap will be returned. <pre class="groovyTestCase">def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy([{ it.value % 2 }, { it.key.next() }]) assert result == [1:[b:[a:1], d:[c:3], f:[e:5]], 0:[c:[b:2], e:[d:4], g:[f:6]]]</pre> If an empty list of closures is supplied the IDENTITY Closure will be used. @param self a map to group @param closures a list of closures that map entries on keys @return a new map grouped by keys on each criterion @since 1.8.1 @see Closure#IDENTITY
[ "Groups", "the", "members", "of", "a", "map", "into", "sub", "maps", "determined", "by", "the", "supplied", "mapping", "closures", ".", "Each", "closure", "will", "be", "passed", "a", "Map", ".", "Entry", "or", "key", "and", "value", "(", "depending", "on", "the", "number", "of", "parameters", "the", "closure", "accepts", ")", "and", "should", "return", "the", "key", "that", "each", "item", "should", "be", "grouped", "under", ".", "The", "resulting", "map", "will", "have", "an", "entry", "for", "each", "group", "path", "returned", "by", "all", "closures", "with", "values", "being", "the", "map", "members", "from", "the", "original", "map", "that", "belong", "to", "each", "such", "group", "path", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L5882-L5884
pmwmedia/tinylog
tinylog-impl/src/main/java/org/tinylog/core/MessageFormatter.java
MessageFormatter.getFormatter
private Format getFormatter(final String pattern, final Object argument) { """ Gets the format object for a pattern of a placeholder. {@link ChoiceFormat} and {@link DecimalFormat} are supported. @param pattern Pattern of placeholder @param argument Replacement for placeholder @return Format object """ if (pattern.indexOf('|') != -1) { int start = pattern.indexOf('{'); if (start >= 0 && start < pattern.lastIndexOf('}')) { return new ChoiceFormat(format(pattern, new Object[] { argument })); } else { return new ChoiceFormat(pattern); } } else { return new DecimalFormat(pattern, symbols); } }
java
private Format getFormatter(final String pattern, final Object argument) { if (pattern.indexOf('|') != -1) { int start = pattern.indexOf('{'); if (start >= 0 && start < pattern.lastIndexOf('}')) { return new ChoiceFormat(format(pattern, new Object[] { argument })); } else { return new ChoiceFormat(pattern); } } else { return new DecimalFormat(pattern, symbols); } }
[ "private", "Format", "getFormatter", "(", "final", "String", "pattern", ",", "final", "Object", "argument", ")", "{", "if", "(", "pattern", ".", "indexOf", "(", "'", "'", ")", "!=", "-", "1", ")", "{", "int", "start", "=", "pattern", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "start", ">=", "0", "&&", "start", "<", "pattern", ".", "lastIndexOf", "(", "'", "'", ")", ")", "{", "return", "new", "ChoiceFormat", "(", "format", "(", "pattern", ",", "new", "Object", "[", "]", "{", "argument", "}", ")", ")", ";", "}", "else", "{", "return", "new", "ChoiceFormat", "(", "pattern", ")", ";", "}", "}", "else", "{", "return", "new", "DecimalFormat", "(", "pattern", ",", "symbols", ")", ";", "}", "}" ]
Gets the format object for a pattern of a placeholder. {@link ChoiceFormat} and {@link DecimalFormat} are supported. @param pattern Pattern of placeholder @param argument Replacement for placeholder @return Format object
[ "Gets", "the", "format", "object", "for", "a", "pattern", "of", "a", "placeholder", ".", "{", "@link", "ChoiceFormat", "}", "and", "{", "@link", "DecimalFormat", "}", "are", "supported", "." ]
train
https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/tinylog-impl/src/main/java/org/tinylog/core/MessageFormatter.java#L132-L143
JetBrains/xodus
entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentEntityStoreImpl.java
PersistentEntityStoreImpl.getLinkId
public int getLinkId(@NotNull final PersistentStoreTransaction txn, @NotNull final String linkName, final boolean allowCreate) { """ Gets id of a link and creates the new one if necessary. @param linkName name of the link. @param allowCreate if set to true and if there is no link named as linkName, create the new id for the linkName. @return < 0 if there is no such link and create=false, else id of the link """ return allowCreate ? linkIds.getOrAllocateId(txn, linkName) : linkIds.getId(txn, linkName); }
java
public int getLinkId(@NotNull final PersistentStoreTransaction txn, @NotNull final String linkName, final boolean allowCreate) { return allowCreate ? linkIds.getOrAllocateId(txn, linkName) : linkIds.getId(txn, linkName); }
[ "public", "int", "getLinkId", "(", "@", "NotNull", "final", "PersistentStoreTransaction", "txn", ",", "@", "NotNull", "final", "String", "linkName", ",", "final", "boolean", "allowCreate", ")", "{", "return", "allowCreate", "?", "linkIds", ".", "getOrAllocateId", "(", "txn", ",", "linkName", ")", ":", "linkIds", ".", "getId", "(", "txn", ",", "linkName", ")", ";", "}" ]
Gets id of a link and creates the new one if necessary. @param linkName name of the link. @param allowCreate if set to true and if there is no link named as linkName, create the new id for the linkName. @return < 0 if there is no such link and create=false, else id of the link
[ "Gets", "id", "of", "a", "link", "and", "creates", "the", "new", "one", "if", "necessary", "." ]
train
https://github.com/JetBrains/xodus/blob/7b3476c4e81db66f9c7529148c761605cc8eea6d/entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentEntityStoreImpl.java#L1751-L1753
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/StructureIO.java
StructureIO.getBiologicalAssemblies
public static List<Structure> getBiologicalAssemblies(String pdbId) throws IOException, StructureException { """ Returns all biological assemblies for the given PDB id, using multiModel={@value AtomCache#DEFAULT_BIOASSEMBLY_STYLE} <p> If only one biological assembly is required use {@link #getBiologicalAssembly(String)} or {@link #getBiologicalAssembly(String, int)} instead. @param pdbId @return @throws IOException @throws StructureException @since 5.0 """ return getBiologicalAssemblies(pdbId, AtomCache.DEFAULT_BIOASSEMBLY_STYLE); }
java
public static List<Structure> getBiologicalAssemblies(String pdbId) throws IOException, StructureException { return getBiologicalAssemblies(pdbId, AtomCache.DEFAULT_BIOASSEMBLY_STYLE); }
[ "public", "static", "List", "<", "Structure", ">", "getBiologicalAssemblies", "(", "String", "pdbId", ")", "throws", "IOException", ",", "StructureException", "{", "return", "getBiologicalAssemblies", "(", "pdbId", ",", "AtomCache", ".", "DEFAULT_BIOASSEMBLY_STYLE", ")", ";", "}" ]
Returns all biological assemblies for the given PDB id, using multiModel={@value AtomCache#DEFAULT_BIOASSEMBLY_STYLE} <p> If only one biological assembly is required use {@link #getBiologicalAssembly(String)} or {@link #getBiologicalAssembly(String, int)} instead. @param pdbId @return @throws IOException @throws StructureException @since 5.0
[ "Returns", "all", "biological", "assemblies", "for", "the", "given", "PDB", "id", "using", "multiModel", "=", "{" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureIO.java#L265-L267
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/parser/XPathParser.java
XPathParser.parseOccuranceIndicator
private char parseOccuranceIndicator() { """ Parses the the rule OccuranceIndicator according to the following production rule: <p> [50] OccurrenceIndicator ::= "?" | "*" | "+" . </p> @return wildcard """ char wildcard; if (is(TokenType.STAR, true)) { wildcard = '*'; } else if (is(TokenType.PLUS, true)) { wildcard = '+'; } else { consume(TokenType.INTERROGATION, true); wildcard = '?'; } return wildcard; }
java
private char parseOccuranceIndicator() { char wildcard; if (is(TokenType.STAR, true)) { wildcard = '*'; } else if (is(TokenType.PLUS, true)) { wildcard = '+'; } else { consume(TokenType.INTERROGATION, true); wildcard = '?'; } return wildcard; }
[ "private", "char", "parseOccuranceIndicator", "(", ")", "{", "char", "wildcard", ";", "if", "(", "is", "(", "TokenType", ".", "STAR", ",", "true", ")", ")", "{", "wildcard", "=", "'", "'", ";", "}", "else", "if", "(", "is", "(", "TokenType", ".", "PLUS", ",", "true", ")", ")", "{", "wildcard", "=", "'", "'", ";", "}", "else", "{", "consume", "(", "TokenType", ".", "INTERROGATION", ",", "true", ")", ";", "wildcard", "=", "'", "'", ";", "}", "return", "wildcard", ";", "}" ]
Parses the the rule OccuranceIndicator according to the following production rule: <p> [50] OccurrenceIndicator ::= "?" | "*" | "+" . </p> @return wildcard
[ "Parses", "the", "the", "rule", "OccuranceIndicator", "according", "to", "the", "following", "production", "rule", ":", "<p", ">", "[", "50", "]", "OccurrenceIndicator", "::", "=", "?", "|", "*", "|", "+", ".", "<", "/", "p", ">" ]
train
https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/parser/XPathParser.java#L1373-L1388
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.buildIntervalMethod
private MethodSpec buildIntervalMethod(Map<String, Map<String, String>> intervalFormats, String fallback) { """ Build methods to format date time intervals using the field of greatest difference. """ MethodSpec.Builder method = MethodSpec.methodBuilder("formatInterval") .addAnnotation(Override.class) .addModifiers(PUBLIC) .addParameter(ZonedDateTime.class, "s") .addParameter(ZonedDateTime.class, "e") .addParameter(String.class, "k") .addParameter(DateTimeField.class, "f") .addParameter(StringBuilder.class, "b"); // Only enter the switches if both params are non-null. method.beginControlFlow("if (k != null && f != null)"); // BEGIN switch (k) method.beginControlFlow("switch (k)"); for (Map.Entry<String, Map<String, String>> format : intervalFormats.entrySet()) { String skeleton = format.getKey(); // BEGIN "case skeleton:" method.beginControlFlow("case $S:", skeleton); method.beginControlFlow("switch (f)"); for (Map.Entry<String, String> entry : format.getValue().entrySet()) { String field = entry.getKey(); // Split the interval pattern on the boundary. We end up with two patterns, one for // start and end respectively. Pair<List<Node>, List<Node>> patterns = DATETIME_PARSER.splitIntervalPattern(entry.getValue()); // BEGIN "case field:" // Render this pair of patterns when the given field matches. method.beginControlFlow("case $L:", DateTimeField.fromString(field)); method.addComment("$S", DateTimePatternParser.render(patterns._1)); addIntervalPattern(method, patterns._1, "s"); method.addComment("$S", DateTimePatternParser.render(patterns._2)); addIntervalPattern(method, patterns._2, "e"); method.addStatement("return"); method.endControlFlow(); // END "case field:" } method.addStatement("default: break"); method.endControlFlow(); // switch (f) method.addStatement("break"); method.endControlFlow(); // END "case skeleton:" } method.addStatement("default: break"); method.endControlFlow(); // END switch (k) // One of the parameters was null, or nothing matched, so render the // fallback, e.g. format the start / end separately as "{0} - {1}" addIntervalFallback(method, fallback); method.endControlFlow(); return method.build(); }
java
private MethodSpec buildIntervalMethod(Map<String, Map<String, String>> intervalFormats, String fallback) { MethodSpec.Builder method = MethodSpec.methodBuilder("formatInterval") .addAnnotation(Override.class) .addModifiers(PUBLIC) .addParameter(ZonedDateTime.class, "s") .addParameter(ZonedDateTime.class, "e") .addParameter(String.class, "k") .addParameter(DateTimeField.class, "f") .addParameter(StringBuilder.class, "b"); // Only enter the switches if both params are non-null. method.beginControlFlow("if (k != null && f != null)"); // BEGIN switch (k) method.beginControlFlow("switch (k)"); for (Map.Entry<String, Map<String, String>> format : intervalFormats.entrySet()) { String skeleton = format.getKey(); // BEGIN "case skeleton:" method.beginControlFlow("case $S:", skeleton); method.beginControlFlow("switch (f)"); for (Map.Entry<String, String> entry : format.getValue().entrySet()) { String field = entry.getKey(); // Split the interval pattern on the boundary. We end up with two patterns, one for // start and end respectively. Pair<List<Node>, List<Node>> patterns = DATETIME_PARSER.splitIntervalPattern(entry.getValue()); // BEGIN "case field:" // Render this pair of patterns when the given field matches. method.beginControlFlow("case $L:", DateTimeField.fromString(field)); method.addComment("$S", DateTimePatternParser.render(patterns._1)); addIntervalPattern(method, patterns._1, "s"); method.addComment("$S", DateTimePatternParser.render(patterns._2)); addIntervalPattern(method, patterns._2, "e"); method.addStatement("return"); method.endControlFlow(); // END "case field:" } method.addStatement("default: break"); method.endControlFlow(); // switch (f) method.addStatement("break"); method.endControlFlow(); // END "case skeleton:" } method.addStatement("default: break"); method.endControlFlow(); // END switch (k) // One of the parameters was null, or nothing matched, so render the // fallback, e.g. format the start / end separately as "{0} - {1}" addIntervalFallback(method, fallback); method.endControlFlow(); return method.build(); }
[ "private", "MethodSpec", "buildIntervalMethod", "(", "Map", "<", "String", ",", "Map", "<", "String", ",", "String", ">", ">", "intervalFormats", ",", "String", "fallback", ")", "{", "MethodSpec", ".", "Builder", "method", "=", "MethodSpec", ".", "methodBuilder", "(", "\"formatInterval\"", ")", ".", "addAnnotation", "(", "Override", ".", "class", ")", ".", "addModifiers", "(", "PUBLIC", ")", ".", "addParameter", "(", "ZonedDateTime", ".", "class", ",", "\"s\"", ")", ".", "addParameter", "(", "ZonedDateTime", ".", "class", ",", "\"e\"", ")", ".", "addParameter", "(", "String", ".", "class", ",", "\"k\"", ")", ".", "addParameter", "(", "DateTimeField", ".", "class", ",", "\"f\"", ")", ".", "addParameter", "(", "StringBuilder", ".", "class", ",", "\"b\"", ")", ";", "// Only enter the switches if both params are non-null.", "method", ".", "beginControlFlow", "(", "\"if (k != null && f != null)\"", ")", ";", "// BEGIN switch (k)", "method", ".", "beginControlFlow", "(", "\"switch (k)\"", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Map", "<", "String", ",", "String", ">", ">", "format", ":", "intervalFormats", ".", "entrySet", "(", ")", ")", "{", "String", "skeleton", "=", "format", ".", "getKey", "(", ")", ";", "// BEGIN \"case skeleton:\"", "method", ".", "beginControlFlow", "(", "\"case $S:\"", ",", "skeleton", ")", ";", "method", ".", "beginControlFlow", "(", "\"switch (f)\"", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "format", ".", "getValue", "(", ")", ".", "entrySet", "(", ")", ")", "{", "String", "field", "=", "entry", ".", "getKey", "(", ")", ";", "// Split the interval pattern on the boundary. We end up with two patterns, one for", "// start and end respectively.", "Pair", "<", "List", "<", "Node", ">", ",", "List", "<", "Node", ">", ">", "patterns", "=", "DATETIME_PARSER", ".", "splitIntervalPattern", "(", "entry", ".", "getValue", "(", ")", ")", ";", "// BEGIN \"case field:\"", "// Render this pair of patterns when the given field matches.", "method", ".", "beginControlFlow", "(", "\"case $L:\"", ",", "DateTimeField", ".", "fromString", "(", "field", ")", ")", ";", "method", ".", "addComment", "(", "\"$S\"", ",", "DateTimePatternParser", ".", "render", "(", "patterns", ".", "_1", ")", ")", ";", "addIntervalPattern", "(", "method", ",", "patterns", ".", "_1", ",", "\"s\"", ")", ";", "method", ".", "addComment", "(", "\"$S\"", ",", "DateTimePatternParser", ".", "render", "(", "patterns", ".", "_2", ")", ")", ";", "addIntervalPattern", "(", "method", ",", "patterns", ".", "_2", ",", "\"e\"", ")", ";", "method", ".", "addStatement", "(", "\"return\"", ")", ";", "method", ".", "endControlFlow", "(", ")", ";", "// END \"case field:\"", "}", "method", ".", "addStatement", "(", "\"default: break\"", ")", ";", "method", ".", "endControlFlow", "(", ")", ";", "// switch (f)", "method", ".", "addStatement", "(", "\"break\"", ")", ";", "method", ".", "endControlFlow", "(", ")", ";", "// END \"case skeleton:\"", "}", "method", ".", "addStatement", "(", "\"default: break\"", ")", ";", "method", ".", "endControlFlow", "(", ")", ";", "// END switch (k)", "// One of the parameters was null, or nothing matched, so render the", "// fallback, e.g. format the start / end separately as \"{0} - {1}\"", "addIntervalFallback", "(", "method", ",", "fallback", ")", ";", "method", ".", "endControlFlow", "(", ")", ";", "return", "method", ".", "build", "(", ")", ";", "}" ]
Build methods to format date time intervals using the field of greatest difference.
[ "Build", "methods", "to", "format", "date", "time", "intervals", "using", "the", "field", "of", "greatest", "difference", "." ]
train
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L416-L474
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/Counters.java
Counters.findCounter
public synchronized Counter findCounter(String group, String name) { """ Find a counter given the group and the name. @param group the name of the group @param name the internal name of the counter @return the counter for that name """ return getGroup(group).getCounterForName(name); }
java
public synchronized Counter findCounter(String group, String name) { return getGroup(group).getCounterForName(name); }
[ "public", "synchronized", "Counter", "findCounter", "(", "String", "group", ",", "String", "name", ")", "{", "return", "getGroup", "(", "group", ")", ".", "getCounterForName", "(", "name", ")", ";", "}" ]
Find a counter given the group and the name. @param group the name of the group @param name the internal name of the counter @return the counter for that name
[ "Find", "a", "counter", "given", "the", "group", "and", "the", "name", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/Counters.java#L390-L392
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/CapsuleLauncher.java
CapsuleLauncher.setJavaHomes
public CapsuleLauncher setJavaHomes(Map<String, List<Path>> javaHomes) { """ Sets the Java homes that will be used by the capsules created by {@code newCapsule}. @param javaHomes a map from Java version strings to their respective JVM installation paths @return {@code this} """ final Field homes = getCapsuleField("JAVA_HOMES"); if (homes != null) set(null, homes, javaHomes); return this; }
java
public CapsuleLauncher setJavaHomes(Map<String, List<Path>> javaHomes) { final Field homes = getCapsuleField("JAVA_HOMES"); if (homes != null) set(null, homes, javaHomes); return this; }
[ "public", "CapsuleLauncher", "setJavaHomes", "(", "Map", "<", "String", ",", "List", "<", "Path", ">", ">", "javaHomes", ")", "{", "final", "Field", "homes", "=", "getCapsuleField", "(", "\"JAVA_HOMES\"", ")", ";", "if", "(", "homes", "!=", "null", ")", "set", "(", "null", ",", "homes", ",", "javaHomes", ")", ";", "return", "this", ";", "}" ]
Sets the Java homes that will be used by the capsules created by {@code newCapsule}. @param javaHomes a map from Java version strings to their respective JVM installation paths @return {@code this}
[ "Sets", "the", "Java", "homes", "that", "will", "be", "used", "by", "the", "capsules", "created", "by", "{", "@code", "newCapsule", "}", "." ]
train
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/CapsuleLauncher.java#L56-L61
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/zookeeper/FlinkZooKeeperQuorumPeer.java
FlinkZooKeeperQuorumPeer.runFlinkZkQuorumPeer
public static void runFlinkZkQuorumPeer(String zkConfigFile, int peerId) throws Exception { """ Runs a ZooKeeper {@link QuorumPeer} if further peers are configured or a single {@link ZooKeeperServer} if no further peers are configured. @param zkConfigFile ZooKeeper config file 'zoo.cfg' @param peerId ID for the 'myid' file """ Properties zkProps = new Properties(); try (InputStream inStream = new FileInputStream(new File(zkConfigFile))) { zkProps.load(inStream); } LOG.info("Configuration: " + zkProps); // Set defaults for required properties setRequiredProperties(zkProps); // Write peer id to myid file writeMyIdToDataDir(zkProps, peerId); // The myid file needs to be written before creating the instance. Otherwise, this // will fail. QuorumPeerConfig conf = new QuorumPeerConfig(); conf.parseProperties(zkProps); if (conf.isDistributed()) { // Run quorum peer LOG.info("Running distributed ZooKeeper quorum peer (total peers: {}).", conf.getServers().size()); QuorumPeerMain qp = new QuorumPeerMain(); qp.runFromConfig(conf); } else { // Run standalone LOG.info("Running standalone ZooKeeper quorum peer."); ZooKeeperServerMain zk = new ZooKeeperServerMain(); ServerConfig sc = new ServerConfig(); sc.readFrom(conf); zk.runFromConfig(sc); } }
java
public static void runFlinkZkQuorumPeer(String zkConfigFile, int peerId) throws Exception { Properties zkProps = new Properties(); try (InputStream inStream = new FileInputStream(new File(zkConfigFile))) { zkProps.load(inStream); } LOG.info("Configuration: " + zkProps); // Set defaults for required properties setRequiredProperties(zkProps); // Write peer id to myid file writeMyIdToDataDir(zkProps, peerId); // The myid file needs to be written before creating the instance. Otherwise, this // will fail. QuorumPeerConfig conf = new QuorumPeerConfig(); conf.parseProperties(zkProps); if (conf.isDistributed()) { // Run quorum peer LOG.info("Running distributed ZooKeeper quorum peer (total peers: {}).", conf.getServers().size()); QuorumPeerMain qp = new QuorumPeerMain(); qp.runFromConfig(conf); } else { // Run standalone LOG.info("Running standalone ZooKeeper quorum peer."); ZooKeeperServerMain zk = new ZooKeeperServerMain(); ServerConfig sc = new ServerConfig(); sc.readFrom(conf); zk.runFromConfig(sc); } }
[ "public", "static", "void", "runFlinkZkQuorumPeer", "(", "String", "zkConfigFile", ",", "int", "peerId", ")", "throws", "Exception", "{", "Properties", "zkProps", "=", "new", "Properties", "(", ")", ";", "try", "(", "InputStream", "inStream", "=", "new", "FileInputStream", "(", "new", "File", "(", "zkConfigFile", ")", ")", ")", "{", "zkProps", ".", "load", "(", "inStream", ")", ";", "}", "LOG", ".", "info", "(", "\"Configuration: \"", "+", "zkProps", ")", ";", "// Set defaults for required properties", "setRequiredProperties", "(", "zkProps", ")", ";", "// Write peer id to myid file", "writeMyIdToDataDir", "(", "zkProps", ",", "peerId", ")", ";", "// The myid file needs to be written before creating the instance. Otherwise, this", "// will fail.", "QuorumPeerConfig", "conf", "=", "new", "QuorumPeerConfig", "(", ")", ";", "conf", ".", "parseProperties", "(", "zkProps", ")", ";", "if", "(", "conf", ".", "isDistributed", "(", ")", ")", "{", "// Run quorum peer", "LOG", ".", "info", "(", "\"Running distributed ZooKeeper quorum peer (total peers: {}).\"", ",", "conf", ".", "getServers", "(", ")", ".", "size", "(", ")", ")", ";", "QuorumPeerMain", "qp", "=", "new", "QuorumPeerMain", "(", ")", ";", "qp", ".", "runFromConfig", "(", "conf", ")", ";", "}", "else", "{", "// Run standalone", "LOG", ".", "info", "(", "\"Running standalone ZooKeeper quorum peer.\"", ")", ";", "ZooKeeperServerMain", "zk", "=", "new", "ZooKeeperServerMain", "(", ")", ";", "ServerConfig", "sc", "=", "new", "ServerConfig", "(", ")", ";", "sc", ".", "readFrom", "(", "conf", ")", ";", "zk", ".", "runFromConfig", "(", "sc", ")", ";", "}", "}" ]
Runs a ZooKeeper {@link QuorumPeer} if further peers are configured or a single {@link ZooKeeperServer} if no further peers are configured. @param zkConfigFile ZooKeeper config file 'zoo.cfg' @param peerId ID for the 'myid' file
[ "Runs", "a", "ZooKeeper", "{", "@link", "QuorumPeer", "}", "if", "further", "peers", "are", "configured", "or", "a", "single", "{", "@link", "ZooKeeperServer", "}", "if", "no", "further", "peers", "are", "configured", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/zookeeper/FlinkZooKeeperQuorumPeer.java#L96-L134
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/crypto/openssl/OpenSSLPKCS12.java
OpenSSLPKCS12.filterP12
public static void filterP12(File p12, String p12Password) throws IOException { """ Recreates a PKCS12 KeyStore using OpenSSL; this is a workaround a BouncyCastle-Firefox compatibility bug @param p12 The PKCS12 Keystore to filter @param p12Password The password for the keystore @throws IOException if a catastrophic unexpected failure occurs during execution @throws IllegalArgumentException if the PKCS12 keystore doesn't exist @throws IllegalStateException if openssl exits with a failure condition """ if (!p12.exists()) throw new IllegalArgumentException("p12 file does not exist: " + p12.getPath()); final File pem; if (USE_GENERIC_TEMP_DIRECTORY) pem = File.createTempFile(UUID.randomUUID().toString(), ""); else pem = new File(p12.getAbsolutePath() + ".pem.tmp"); final String pemPassword = UUID.randomUUID().toString(); try { P12toPEM(p12, p12Password, pem, pemPassword); PEMtoP12(pem, pemPassword, p12, p12Password); } finally { if (pem.exists()) if (!pem.delete()) log.warn("[OpenSSLPKCS12] {filterP12} Could not delete temporary PEM file " + pem); } }
java
public static void filterP12(File p12, String p12Password) throws IOException { if (!p12.exists()) throw new IllegalArgumentException("p12 file does not exist: " + p12.getPath()); final File pem; if (USE_GENERIC_TEMP_DIRECTORY) pem = File.createTempFile(UUID.randomUUID().toString(), ""); else pem = new File(p12.getAbsolutePath() + ".pem.tmp"); final String pemPassword = UUID.randomUUID().toString(); try { P12toPEM(p12, p12Password, pem, pemPassword); PEMtoP12(pem, pemPassword, p12, p12Password); } finally { if (pem.exists()) if (!pem.delete()) log.warn("[OpenSSLPKCS12] {filterP12} Could not delete temporary PEM file " + pem); } }
[ "public", "static", "void", "filterP12", "(", "File", "p12", ",", "String", "p12Password", ")", "throws", "IOException", "{", "if", "(", "!", "p12", ".", "exists", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"p12 file does not exist: \"", "+", "p12", ".", "getPath", "(", ")", ")", ";", "final", "File", "pem", ";", "if", "(", "USE_GENERIC_TEMP_DIRECTORY", ")", "pem", "=", "File", ".", "createTempFile", "(", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ",", "\"\"", ")", ";", "else", "pem", "=", "new", "File", "(", "p12", ".", "getAbsolutePath", "(", ")", "+", "\".pem.tmp\"", ")", ";", "final", "String", "pemPassword", "=", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ";", "try", "{", "P12toPEM", "(", "p12", ",", "p12Password", ",", "pem", ",", "pemPassword", ")", ";", "PEMtoP12", "(", "pem", ",", "pemPassword", ",", "p12", ",", "p12Password", ")", ";", "}", "finally", "{", "if", "(", "pem", ".", "exists", "(", ")", ")", "if", "(", "!", "pem", ".", "delete", "(", ")", ")", "log", ".", "warn", "(", "\"[OpenSSLPKCS12] {filterP12} Could not delete temporary PEM file \"", "+", "pem", ")", ";", "}", "}" ]
Recreates a PKCS12 KeyStore using OpenSSL; this is a workaround a BouncyCastle-Firefox compatibility bug @param p12 The PKCS12 Keystore to filter @param p12Password The password for the keystore @throws IOException if a catastrophic unexpected failure occurs during execution @throws IllegalArgumentException if the PKCS12 keystore doesn't exist @throws IllegalStateException if openssl exits with a failure condition
[ "Recreates", "a", "PKCS12", "KeyStore", "using", "OpenSSL", ";", "this", "is", "a", "workaround", "a", "BouncyCastle", "-", "Firefox", "compatibility", "bug" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/crypto/openssl/OpenSSLPKCS12.java#L34-L59
tvesalainen/util
util/src/main/java/org/vesalainen/math/CubicSplineCurve.java
CubicSplineCurve.get141Matrix
public static final DenseMatrix64F get141Matrix(int order) { """ Creates a 1 4 1 matrix eg. |4 1 0| |1 4 1| |0 1 4| @param order Matrix dimension > 1 @return 1 4 1 matrix """ if (order < 2) { throw new IllegalArgumentException("order has to be at least 2 for 1 4 1 matrix"); } double[] data = new double[order*order]; for (int row=0;row<order;row++) { for (int col=0;col<order;col++) { int index = row*order+col; if (row == col) { data[index] = 4; } else { if (Math.abs(row-col) == 1) { data[index] = 1; } else { data[index] = 0; } } } } return new DenseMatrix64F(order, order, true, data); }
java
public static final DenseMatrix64F get141Matrix(int order) { if (order < 2) { throw new IllegalArgumentException("order has to be at least 2 for 1 4 1 matrix"); } double[] data = new double[order*order]; for (int row=0;row<order;row++) { for (int col=0;col<order;col++) { int index = row*order+col; if (row == col) { data[index] = 4; } else { if (Math.abs(row-col) == 1) { data[index] = 1; } else { data[index] = 0; } } } } return new DenseMatrix64F(order, order, true, data); }
[ "public", "static", "final", "DenseMatrix64F", "get141Matrix", "(", "int", "order", ")", "{", "if", "(", "order", "<", "2", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"order has to be at least 2 for 1 4 1 matrix\"", ")", ";", "}", "double", "[", "]", "data", "=", "new", "double", "[", "order", "*", "order", "]", ";", "for", "(", "int", "row", "=", "0", ";", "row", "<", "order", ";", "row", "++", ")", "{", "for", "(", "int", "col", "=", "0", ";", "col", "<", "order", ";", "col", "++", ")", "{", "int", "index", "=", "row", "*", "order", "+", "col", ";", "if", "(", "row", "==", "col", ")", "{", "data", "[", "index", "]", "=", "4", ";", "}", "else", "{", "if", "(", "Math", ".", "abs", "(", "row", "-", "col", ")", "==", "1", ")", "{", "data", "[", "index", "]", "=", "1", ";", "}", "else", "{", "data", "[", "index", "]", "=", "0", ";", "}", "}", "}", "}", "return", "new", "DenseMatrix64F", "(", "order", ",", "order", ",", "true", ",", "data", ")", ";", "}" ]
Creates a 1 4 1 matrix eg. |4 1 0| |1 4 1| |0 1 4| @param order Matrix dimension > 1 @return 1 4 1 matrix
[ "Creates", "a", "1", "4", "1", "matrix", "eg", ".", "|4", "1", "0|", "|1", "4", "1|", "|0", "1", "4|" ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/math/CubicSplineCurve.java#L172-L202
chhh/MSFTBX
MSFileToolbox/src/main/java/umich/ms/util/base64/Base64Slow.java
Base64Slow.encodeToString
public static String encodeToString(byte[] bytes, boolean lineBreaks) { """ Encode bytes in Base64. @param bytes The data to encode. @param lineBreaks Whether to insert line breaks every 76 characters in the output. @return String with Base64 encoded data. @since ostermillerutils 1.04.00 """ try { return new String(encode(bytes, lineBreaks), "ASCII"); } catch (UnsupportedEncodingException iex) { // ASCII should be supported throw new RuntimeException(iex); } }
java
public static String encodeToString(byte[] bytes, boolean lineBreaks) { try { return new String(encode(bytes, lineBreaks), "ASCII"); } catch (UnsupportedEncodingException iex) { // ASCII should be supported throw new RuntimeException(iex); } }
[ "public", "static", "String", "encodeToString", "(", "byte", "[", "]", "bytes", ",", "boolean", "lineBreaks", ")", "{", "try", "{", "return", "new", "String", "(", "encode", "(", "bytes", ",", "lineBreaks", ")", ",", "\"ASCII\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "iex", ")", "{", "// ASCII should be supported", "throw", "new", "RuntimeException", "(", "iex", ")", ";", "}", "}" ]
Encode bytes in Base64. @param bytes The data to encode. @param lineBreaks Whether to insert line breaks every 76 characters in the output. @return String with Base64 encoded data. @since ostermillerutils 1.04.00
[ "Encode", "bytes", "in", "Base64", "." ]
train
https://github.com/chhh/MSFTBX/blob/e53ae6be982e2de3123292be7d5297715bec70bb/MSFileToolbox/src/main/java/umich/ms/util/base64/Base64Slow.java#L278-L285
lucee/Lucee
core/src/main/java/lucee/runtime/schedule/StorageUtil.java
StorageUtil.toDateTime
public DateTime toDateTime(Element el, String attributeName, DateTime defaultValue) { """ reads a XML Element Attribute ans cast it to a DateTime @param el XML Element to read Attribute from it @param attributeName Name of the Attribute to read @param defaultValue if attribute doesn't exist return default value @return Attribute Value """ String value = el.getAttribute(attributeName); if (value == null) return defaultValue; DateTime dtValue = Caster.toDate(value, false, null, null); if (dtValue == null) return defaultValue; return dtValue; }
java
public DateTime toDateTime(Element el, String attributeName, DateTime defaultValue) { String value = el.getAttribute(attributeName); if (value == null) return defaultValue; DateTime dtValue = Caster.toDate(value, false, null, null); if (dtValue == null) return defaultValue; return dtValue; }
[ "public", "DateTime", "toDateTime", "(", "Element", "el", ",", "String", "attributeName", ",", "DateTime", "defaultValue", ")", "{", "String", "value", "=", "el", ".", "getAttribute", "(", "attributeName", ")", ";", "if", "(", "value", "==", "null", ")", "return", "defaultValue", ";", "DateTime", "dtValue", "=", "Caster", ".", "toDate", "(", "value", ",", "false", ",", "null", ",", "null", ")", ";", "if", "(", "dtValue", "==", "null", ")", "return", "defaultValue", ";", "return", "dtValue", ";", "}" ]
reads a XML Element Attribute ans cast it to a DateTime @param el XML Element to read Attribute from it @param attributeName Name of the Attribute to read @param defaultValue if attribute doesn't exist return default value @return Attribute Value
[ "reads", "a", "XML", "Element", "Attribute", "ans", "cast", "it", "to", "a", "DateTime" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/schedule/StorageUtil.java#L257-L264
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/SpiderSession.java
SpiderSession.addObject
public ObjectResult addObject(String tableName, DBObject dbObj) { """ Add the given object to the given table, which must be defined for a table that belongs to this session's application. This is a convenience method that bundles the DBObject in a {@link DBObjectBatch} and calls {@link #addBatch(String, DBObjectBatch)}. The {@link ObjectResult} from the batch result is returned. @param tableName Name of table to add object to. @param dbObj {@link DBObject} of object to add to the database. @return {@link ObjectResult} of the add request. The result can be used to determine the ID of the object if it was added by the system. """ Utils.require(!Utils.isEmpty(tableName), "tableName"); Utils.require(dbObj != null, "dbObj"); TableDefinition tableDef = m_appDef.getTableDef(tableName); Utils.require(tableDef != null, "Unknown table for application '%s': %s", m_appDef.getAppName(), tableName); try { // Send single-object batch to "POST /{application}/{table}" DBObjectBatch dbObjBatch = new DBObjectBatch(); dbObjBatch.addObject(dbObj); byte[] body = Utils.toBytes(dbObjBatch.toDoc().toJSON()); StringBuilder uri = new StringBuilder(Utils.isEmpty(m_restClient.getApiPrefix()) ? "" : "/" + m_restClient.getApiPrefix()); uri.append("/"); uri.append(Utils.urlEncode(m_appDef.getAppName())); uri.append("/"); uri.append(Utils.urlEncode(tableName)); RESTResponse response = m_restClient.sendRequest(HttpMethod.POST, uri.toString(), ContentType.APPLICATION_JSON, body); m_logger.debug("addBatch() response: {}", response.toString()); BatchResult batchResult = createBatchResult(response, dbObjBatch); ObjectResult objResult = null; if (batchResult.isFailed()) { objResult = ObjectResult.newErrorResult(batchResult.getErrorMessage(), dbObj.getObjectID()); } else { objResult = batchResult.getResultObjects().iterator().next(); if (Utils.isEmpty(dbObj.getObjectID())) { dbObj.setObjectID(objResult.getObjectID()); } } return objResult; } catch (Exception e) { throw new RuntimeException(e); } }
java
public ObjectResult addObject(String tableName, DBObject dbObj) { Utils.require(!Utils.isEmpty(tableName), "tableName"); Utils.require(dbObj != null, "dbObj"); TableDefinition tableDef = m_appDef.getTableDef(tableName); Utils.require(tableDef != null, "Unknown table for application '%s': %s", m_appDef.getAppName(), tableName); try { // Send single-object batch to "POST /{application}/{table}" DBObjectBatch dbObjBatch = new DBObjectBatch(); dbObjBatch.addObject(dbObj); byte[] body = Utils.toBytes(dbObjBatch.toDoc().toJSON()); StringBuilder uri = new StringBuilder(Utils.isEmpty(m_restClient.getApiPrefix()) ? "" : "/" + m_restClient.getApiPrefix()); uri.append("/"); uri.append(Utils.urlEncode(m_appDef.getAppName())); uri.append("/"); uri.append(Utils.urlEncode(tableName)); RESTResponse response = m_restClient.sendRequest(HttpMethod.POST, uri.toString(), ContentType.APPLICATION_JSON, body); m_logger.debug("addBatch() response: {}", response.toString()); BatchResult batchResult = createBatchResult(response, dbObjBatch); ObjectResult objResult = null; if (batchResult.isFailed()) { objResult = ObjectResult.newErrorResult(batchResult.getErrorMessage(), dbObj.getObjectID()); } else { objResult = batchResult.getResultObjects().iterator().next(); if (Utils.isEmpty(dbObj.getObjectID())) { dbObj.setObjectID(objResult.getObjectID()); } } return objResult; } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "ObjectResult", "addObject", "(", "String", "tableName", ",", "DBObject", "dbObj", ")", "{", "Utils", ".", "require", "(", "!", "Utils", ".", "isEmpty", "(", "tableName", ")", ",", "\"tableName\"", ")", ";", "Utils", ".", "require", "(", "dbObj", "!=", "null", ",", "\"dbObj\"", ")", ";", "TableDefinition", "tableDef", "=", "m_appDef", ".", "getTableDef", "(", "tableName", ")", ";", "Utils", ".", "require", "(", "tableDef", "!=", "null", ",", "\"Unknown table for application '%s': %s\"", ",", "m_appDef", ".", "getAppName", "(", ")", ",", "tableName", ")", ";", "try", "{", "// Send single-object batch to \"POST /{application}/{table}\"\r", "DBObjectBatch", "dbObjBatch", "=", "new", "DBObjectBatch", "(", ")", ";", "dbObjBatch", ".", "addObject", "(", "dbObj", ")", ";", "byte", "[", "]", "body", "=", "Utils", ".", "toBytes", "(", "dbObjBatch", ".", "toDoc", "(", ")", ".", "toJSON", "(", ")", ")", ";", "StringBuilder", "uri", "=", "new", "StringBuilder", "(", "Utils", ".", "isEmpty", "(", "m_restClient", ".", "getApiPrefix", "(", ")", ")", "?", "\"\"", ":", "\"/\"", "+", "m_restClient", ".", "getApiPrefix", "(", ")", ")", ";", "uri", ".", "append", "(", "\"/\"", ")", ";", "uri", ".", "append", "(", "Utils", ".", "urlEncode", "(", "m_appDef", ".", "getAppName", "(", ")", ")", ")", ";", "uri", ".", "append", "(", "\"/\"", ")", ";", "uri", ".", "append", "(", "Utils", ".", "urlEncode", "(", "tableName", ")", ")", ";", "RESTResponse", "response", "=", "m_restClient", ".", "sendRequest", "(", "HttpMethod", ".", "POST", ",", "uri", ".", "toString", "(", ")", ",", "ContentType", ".", "APPLICATION_JSON", ",", "body", ")", ";", "m_logger", ".", "debug", "(", "\"addBatch() response: {}\"", ",", "response", ".", "toString", "(", ")", ")", ";", "BatchResult", "batchResult", "=", "createBatchResult", "(", "response", ",", "dbObjBatch", ")", ";", "ObjectResult", "objResult", "=", "null", ";", "if", "(", "batchResult", ".", "isFailed", "(", ")", ")", "{", "objResult", "=", "ObjectResult", ".", "newErrorResult", "(", "batchResult", ".", "getErrorMessage", "(", ")", ",", "dbObj", ".", "getObjectID", "(", ")", ")", ";", "}", "else", "{", "objResult", "=", "batchResult", ".", "getResultObjects", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "if", "(", "Utils", ".", "isEmpty", "(", "dbObj", ".", "getObjectID", "(", ")", ")", ")", "{", "dbObj", ".", "setObjectID", "(", "objResult", ".", "getObjectID", "(", ")", ")", ";", "}", "}", "return", "objResult", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Add the given object to the given table, which must be defined for a table that belongs to this session's application. This is a convenience method that bundles the DBObject in a {@link DBObjectBatch} and calls {@link #addBatch(String, DBObjectBatch)}. The {@link ObjectResult} from the batch result is returned. @param tableName Name of table to add object to. @param dbObj {@link DBObject} of object to add to the database. @return {@link ObjectResult} of the add request. The result can be used to determine the ID of the object if it was added by the system.
[ "Add", "the", "given", "object", "to", "the", "given", "table", "which", "must", "be", "defined", "for", "a", "table", "that", "belongs", "to", "this", "session", "s", "application", ".", "This", "is", "a", "convenience", "method", "that", "bundles", "the", "DBObject", "in", "a", "{", "@link", "DBObjectBatch", "}", "and", "calls", "{", "@link", "#addBatch", "(", "String", "DBObjectBatch", ")", "}", ".", "The", "{", "@link", "ObjectResult", "}", "from", "the", "batch", "result", "is", "returned", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/SpiderSession.java#L102-L137
belaban/JGroups
src/org/jgroups/util/RingBuffer.java
RingBuffer.drainTo
public int drainTo(Collection<? super T> c, int max_elements) { """ Removes a number of messages and adds them to c. Same semantics as {@link java.util.concurrent.BlockingQueue#drainTo(Collection,int)}. @param c The collection to which to add the removed messages. @param max_elements The max number of messages to remove. The actual number of messages removed may be smaller if the buffer has fewer elements @return The number of messages removed @throws NullPointerException If c is null """ int num=Math.min(count, max_elements); // count may increase in the mean time, but that's ok if(num == 0) return num; int read_index=ri; // no lock as we're the only reader for(int i=0; i < num; i++) { int real_index=realIndex(read_index +i); c.add(buf[real_index]); buf[real_index]=null; } publishReadIndex(num); return num; }
java
public int drainTo(Collection<? super T> c, int max_elements) { int num=Math.min(count, max_elements); // count may increase in the mean time, but that's ok if(num == 0) return num; int read_index=ri; // no lock as we're the only reader for(int i=0; i < num; i++) { int real_index=realIndex(read_index +i); c.add(buf[real_index]); buf[real_index]=null; } publishReadIndex(num); return num; }
[ "public", "int", "drainTo", "(", "Collection", "<", "?", "super", "T", ">", "c", ",", "int", "max_elements", ")", "{", "int", "num", "=", "Math", ".", "min", "(", "count", ",", "max_elements", ")", ";", "// count may increase in the mean time, but that's ok", "if", "(", "num", "==", "0", ")", "return", "num", ";", "int", "read_index", "=", "ri", ";", "// no lock as we're the only reader", "for", "(", "int", "i", "=", "0", ";", "i", "<", "num", ";", "i", "++", ")", "{", "int", "real_index", "=", "realIndex", "(", "read_index", "+", "i", ")", ";", "c", ".", "add", "(", "buf", "[", "real_index", "]", ")", ";", "buf", "[", "real_index", "]", "=", "null", ";", "}", "publishReadIndex", "(", "num", ")", ";", "return", "num", ";", "}" ]
Removes a number of messages and adds them to c. Same semantics as {@link java.util.concurrent.BlockingQueue#drainTo(Collection,int)}. @param c The collection to which to add the removed messages. @param max_elements The max number of messages to remove. The actual number of messages removed may be smaller if the buffer has fewer elements @return The number of messages removed @throws NullPointerException If c is null
[ "Removes", "a", "number", "of", "messages", "and", "adds", "them", "to", "c", ".", "Same", "semantics", "as", "{" ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/util/RingBuffer.java#L173-L185
googleads/googleads-java-lib
examples/admanager_axis/src/main/java/admanager/axis/v201808/producttemplateservice/GetAllProductTemplates.java
GetAllProductTemplates.runExample
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { """ Runs the example. @param adManagerServices the services factory. @param session the session. @throws ApiException if the API request failed with one or more service errors. @throws RemoteException if the API request failed due to other errors. """ // Get the ProductTemplateService. ProductTemplateServiceInterface productTemplateService = adManagerServices.get(session, ProductTemplateServiceInterface.class); // Create a statement to select all product templates. StatementBuilder statementBuilder = new StatementBuilder() .orderBy("id ASC") .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); // Default for total result set size. int totalResultSetSize = 0; do { // Get product templates by statement. ProductTemplatePage page = productTemplateService.getProductTemplatesByStatement(statementBuilder.toStatement()); if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); int i = page.getStartIndex(); for (ProductTemplate productTemplate : page.getResults()) { System.out.printf( "%d) Product template with ID %d and name '%s' was found.%n", i++, productTemplate.getId(), productTemplate.getName()); } } statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.getOffset() < totalResultSetSize); System.out.printf("Number of results found: %d%n", totalResultSetSize); }
java
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the ProductTemplateService. ProductTemplateServiceInterface productTemplateService = adManagerServices.get(session, ProductTemplateServiceInterface.class); // Create a statement to select all product templates. StatementBuilder statementBuilder = new StatementBuilder() .orderBy("id ASC") .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); // Default for total result set size. int totalResultSetSize = 0; do { // Get product templates by statement. ProductTemplatePage page = productTemplateService.getProductTemplatesByStatement(statementBuilder.toStatement()); if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); int i = page.getStartIndex(); for (ProductTemplate productTemplate : page.getResults()) { System.out.printf( "%d) Product template with ID %d and name '%s' was found.%n", i++, productTemplate.getId(), productTemplate.getName()); } } statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.getOffset() < totalResultSetSize); System.out.printf("Number of results found: %d%n", totalResultSetSize); }
[ "public", "static", "void", "runExample", "(", "AdManagerServices", "adManagerServices", ",", "AdManagerSession", "session", ")", "throws", "RemoteException", "{", "// Get the ProductTemplateService.", "ProductTemplateServiceInterface", "productTemplateService", "=", "adManagerServices", ".", "get", "(", "session", ",", "ProductTemplateServiceInterface", ".", "class", ")", ";", "// Create a statement to select all product templates.", "StatementBuilder", "statementBuilder", "=", "new", "StatementBuilder", "(", ")", ".", "orderBy", "(", "\"id ASC\"", ")", ".", "limit", "(", "StatementBuilder", ".", "SUGGESTED_PAGE_LIMIT", ")", ";", "// Default for total result set size.", "int", "totalResultSetSize", "=", "0", ";", "do", "{", "// Get product templates by statement.", "ProductTemplatePage", "page", "=", "productTemplateService", ".", "getProductTemplatesByStatement", "(", "statementBuilder", ".", "toStatement", "(", ")", ")", ";", "if", "(", "page", ".", "getResults", "(", ")", "!=", "null", ")", "{", "totalResultSetSize", "=", "page", ".", "getTotalResultSetSize", "(", ")", ";", "int", "i", "=", "page", ".", "getStartIndex", "(", ")", ";", "for", "(", "ProductTemplate", "productTemplate", ":", "page", ".", "getResults", "(", ")", ")", "{", "System", ".", "out", ".", "printf", "(", "\"%d) Product template with ID %d and name '%s' was found.%n\"", ",", "i", "++", ",", "productTemplate", ".", "getId", "(", ")", ",", "productTemplate", ".", "getName", "(", ")", ")", ";", "}", "}", "statementBuilder", ".", "increaseOffsetBy", "(", "StatementBuilder", ".", "SUGGESTED_PAGE_LIMIT", ")", ";", "}", "while", "(", "statementBuilder", ".", "getOffset", "(", ")", "<", "totalResultSetSize", ")", ";", "System", ".", "out", ".", "printf", "(", "\"Number of results found: %d%n\"", ",", "totalResultSetSize", ")", ";", "}" ]
Runs the example. @param adManagerServices the services factory. @param session the session. @throws ApiException if the API request failed with one or more service errors. @throws RemoteException if the API request failed due to other errors.
[ "Runs", "the", "example", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201808/producttemplateservice/GetAllProductTemplates.java#L52-L85
docusign/docusign-java-client
src/main/java/com/docusign/esign/api/CloudStorageApi.java
CloudStorageApi.getProvider
public CloudStorageProviders getProvider(String accountId, String userId, String serviceId) throws ApiException { """ Gets the specified Cloud Storage Provider configuration for the User. Retrieves the list of cloud storage providers enabled for the account and the configuration information for the user. @param accountId The external account number (int) or account ID Guid. (required) @param userId The user ID of the user being accessed. Generally this is the user ID of the authenticated user, but if the authenticated user is an Admin on the account, this may be another user the Admin user is accessing. (required) @param serviceId The ID of the service to access. Valid values are the service name (\&quot;Box\&quot;) or the numerical serviceId (\&quot;4136\&quot;). (required) @return CloudStorageProviders """ return getProvider(accountId, userId, serviceId, null); }
java
public CloudStorageProviders getProvider(String accountId, String userId, String serviceId) throws ApiException { return getProvider(accountId, userId, serviceId, null); }
[ "public", "CloudStorageProviders", "getProvider", "(", "String", "accountId", ",", "String", "userId", ",", "String", "serviceId", ")", "throws", "ApiException", "{", "return", "getProvider", "(", "accountId", ",", "userId", ",", "serviceId", ",", "null", ")", ";", "}" ]
Gets the specified Cloud Storage Provider configuration for the User. Retrieves the list of cloud storage providers enabled for the account and the configuration information for the user. @param accountId The external account number (int) or account ID Guid. (required) @param userId The user ID of the user being accessed. Generally this is the user ID of the authenticated user, but if the authenticated user is an Admin on the account, this may be another user the Admin user is accessing. (required) @param serviceId The ID of the service to access. Valid values are the service name (\&quot;Box\&quot;) or the numerical serviceId (\&quot;4136\&quot;). (required) @return CloudStorageProviders
[ "Gets", "the", "specified", "Cloud", "Storage", "Provider", "configuration", "for", "the", "User", ".", "Retrieves", "the", "list", "of", "cloud", "storage", "providers", "enabled", "for", "the", "account", "and", "the", "configuration", "information", "for", "the", "user", "." ]
train
https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/CloudStorageApi.java#L221-L223
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/topography/ST_Drape.java
ST_Drape.drapePolygon
public static Geometry drapePolygon(Polygon p, Geometry triangles, STRtree sTRtree) { """ Drape a polygon on a set of triangles @param p @param triangles @param sTRtree @return """ GeometryFactory factory = p.getFactory(); //Split the triangles in lines to perform all intersections Geometry triangleLines = LinearComponentExtracter.getGeometry(triangles, true); Polygon splittedP = processPolygon(p, triangleLines, factory); CoordinateSequenceFilter drapeFilter = new DrapeFilter(sTRtree); splittedP.apply(drapeFilter); return splittedP; }
java
public static Geometry drapePolygon(Polygon p, Geometry triangles, STRtree sTRtree) { GeometryFactory factory = p.getFactory(); //Split the triangles in lines to perform all intersections Geometry triangleLines = LinearComponentExtracter.getGeometry(triangles, true); Polygon splittedP = processPolygon(p, triangleLines, factory); CoordinateSequenceFilter drapeFilter = new DrapeFilter(sTRtree); splittedP.apply(drapeFilter); return splittedP; }
[ "public", "static", "Geometry", "drapePolygon", "(", "Polygon", "p", ",", "Geometry", "triangles", ",", "STRtree", "sTRtree", ")", "{", "GeometryFactory", "factory", "=", "p", ".", "getFactory", "(", ")", ";", "//Split the triangles in lines to perform all intersections", "Geometry", "triangleLines", "=", "LinearComponentExtracter", ".", "getGeometry", "(", "triangles", ",", "true", ")", ";", "Polygon", "splittedP", "=", "processPolygon", "(", "p", ",", "triangleLines", ",", "factory", ")", ";", "CoordinateSequenceFilter", "drapeFilter", "=", "new", "DrapeFilter", "(", "sTRtree", ")", ";", "splittedP", ".", "apply", "(", "drapeFilter", ")", ";", "return", "splittedP", ";", "}" ]
Drape a polygon on a set of triangles @param p @param triangles @param sTRtree @return
[ "Drape", "a", "polygon", "on", "a", "set", "of", "triangles" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/topography/ST_Drape.java#L167-L175
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/crdt/pncounter/PNCounterImpl.java
PNCounterImpl.subtractAndGet
public CRDTTimestampedLong subtractAndGet(long delta, VectorClock observedTimestamps) { """ Subtracts the given value from the current value. <p> The method can throw a {@link ConsistencyLostException} when the state of this CRDT is not causally related to the observed timestamps. This means that it cannot provide the session guarantees of RYW (read your writes) and monotonic read. @param delta the value to subtract @param observedTimestamps the vector clock last observed by the client of this counter @return the current counter value with the current counter vector clock @throws ConsistencyLostException if this replica cannot provide the session guarantees """ checkSessionConsistency(observedTimestamps); stateWriteLock.lock(); try { checkNotMigrated(); if (delta < 0) { return addAndGet(-delta, observedTimestamps); } return updateAndGet(delta, observedTimestamps, false); } finally { stateWriteLock.unlock(); } }
java
public CRDTTimestampedLong subtractAndGet(long delta, VectorClock observedTimestamps) { checkSessionConsistency(observedTimestamps); stateWriteLock.lock(); try { checkNotMigrated(); if (delta < 0) { return addAndGet(-delta, observedTimestamps); } return updateAndGet(delta, observedTimestamps, false); } finally { stateWriteLock.unlock(); } }
[ "public", "CRDTTimestampedLong", "subtractAndGet", "(", "long", "delta", ",", "VectorClock", "observedTimestamps", ")", "{", "checkSessionConsistency", "(", "observedTimestamps", ")", ";", "stateWriteLock", ".", "lock", "(", ")", ";", "try", "{", "checkNotMigrated", "(", ")", ";", "if", "(", "delta", "<", "0", ")", "{", "return", "addAndGet", "(", "-", "delta", ",", "observedTimestamps", ")", ";", "}", "return", "updateAndGet", "(", "delta", ",", "observedTimestamps", ",", "false", ")", ";", "}", "finally", "{", "stateWriteLock", ".", "unlock", "(", ")", ";", "}", "}" ]
Subtracts the given value from the current value. <p> The method can throw a {@link ConsistencyLostException} when the state of this CRDT is not causally related to the observed timestamps. This means that it cannot provide the session guarantees of RYW (read your writes) and monotonic read. @param delta the value to subtract @param observedTimestamps the vector clock last observed by the client of this counter @return the current counter value with the current counter vector clock @throws ConsistencyLostException if this replica cannot provide the session guarantees
[ "Subtracts", "the", "given", "value", "from", "the", "current", "value", ".", "<p", ">", "The", "method", "can", "throw", "a", "{", "@link", "ConsistencyLostException", "}", "when", "the", "state", "of", "this", "CRDT", "is", "not", "causally", "related", "to", "the", "observed", "timestamps", ".", "This", "means", "that", "it", "cannot", "provide", "the", "session", "guarantees", "of", "RYW", "(", "read", "your", "writes", ")", "and", "monotonic", "read", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/crdt/pncounter/PNCounterImpl.java#L198-L210
finmath/finmath-lib
src/main/java6/net/finmath/montecarlo/interestrate/products/components/Numeraire.java
Numeraire.getValue
@Override public RandomVariableInterface getValue(double evaluationTime, LIBORModelMonteCarloSimulationInterface model) throws CalculationException { """ This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime. Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time. cash-flows prior evaluationTime are not considered. @param evaluationTime The time on which this products value should be observed. @param model The model used to price the product. @return The random variable representing the value of the product discounted to evaluation time @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. """ return model.getNumeraire(evaluationTime); }
java
@Override public RandomVariableInterface getValue(double evaluationTime, LIBORModelMonteCarloSimulationInterface model) throws CalculationException { return model.getNumeraire(evaluationTime); }
[ "@", "Override", "public", "RandomVariableInterface", "getValue", "(", "double", "evaluationTime", ",", "LIBORModelMonteCarloSimulationInterface", "model", ")", "throws", "CalculationException", "{", "return", "model", ".", "getNumeraire", "(", "evaluationTime", ")", ";", "}" ]
This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime. Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time. cash-flows prior evaluationTime are not considered. @param evaluationTime The time on which this products value should be observed. @param model The model used to price the product. @return The random variable representing the value of the product discounted to evaluation time @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
[ "This", "method", "returns", "the", "value", "random", "variable", "of", "the", "product", "within", "the", "specified", "model", "evaluated", "at", "a", "given", "evalutationTime", ".", "Note", ":", "For", "a", "lattice", "this", "is", "often", "the", "value", "conditional", "to", "evalutationTime", "for", "a", "Monte", "-", "Carlo", "simulation", "this", "is", "the", "(", "sum", "of", ")", "value", "discounted", "to", "evaluation", "time", ".", "cash", "-", "flows", "prior", "evaluationTime", "are", "not", "considered", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/interestrate/products/components/Numeraire.java#L44-L49
Wikidata/Wikidata-Toolkit
wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/DataObjectFactoryImpl.java
DataObjectFactoryImpl.getValueSnak
@Override public ValueSnak getValueSnak(PropertyIdValue propertyId, Value value) { """ Creates a {@link ValueSnakImpl}. Value snaks in JSON need to know the datatype of their property, which is not given in the parameters of this method. The snak that will be returned will use a default type based on the kind of value that is used (usually the "simplest" type for that value). This may not be desired. @see DataObjectFactory#getValueSnak(PropertyIdValue, Value) """ return new ValueSnakImpl(propertyId, value); }
java
@Override public ValueSnak getValueSnak(PropertyIdValue propertyId, Value value) { return new ValueSnakImpl(propertyId, value); }
[ "@", "Override", "public", "ValueSnak", "getValueSnak", "(", "PropertyIdValue", "propertyId", ",", "Value", "value", ")", "{", "return", "new", "ValueSnakImpl", "(", "propertyId", ",", "value", ")", ";", "}" ]
Creates a {@link ValueSnakImpl}. Value snaks in JSON need to know the datatype of their property, which is not given in the parameters of this method. The snak that will be returned will use a default type based on the kind of value that is used (usually the "simplest" type for that value). This may not be desired. @see DataObjectFactory#getValueSnak(PropertyIdValue, Value)
[ "Creates", "a", "{", "@link", "ValueSnakImpl", "}", ".", "Value", "snaks", "in", "JSON", "need", "to", "know", "the", "datatype", "of", "their", "property", "which", "is", "not", "given", "in", "the", "parameters", "of", "this", "method", ".", "The", "snak", "that", "will", "be", "returned", "will", "use", "a", "default", "type", "based", "on", "the", "kind", "of", "value", "that", "is", "used", "(", "usually", "the", "simplest", "type", "for", "that", "value", ")", ".", "This", "may", "not", "be", "desired", "." ]
train
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/DataObjectFactoryImpl.java#L137-L140
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/ListLayoutExample.java
ListLayoutExample.addExample
private void addExample(final String heading, final ListLayout layout) { """ Adds an example to the set of examples. @param heading the heading for the example @param layout the layout for the panel """ add(new WHeading(HeadingLevel.H2, heading)); WPanel panel = new WPanel(); panel.setLayout(layout); add(panel); for (String item : EXAMPLE_ITEMS) { panel.add(new WText(item)); } add(new WHorizontalRule()); }
java
private void addExample(final String heading, final ListLayout layout) { add(new WHeading(HeadingLevel.H2, heading)); WPanel panel = new WPanel(); panel.setLayout(layout); add(panel); for (String item : EXAMPLE_ITEMS) { panel.add(new WText(item)); } add(new WHorizontalRule()); }
[ "private", "void", "addExample", "(", "final", "String", "heading", ",", "final", "ListLayout", "layout", ")", "{", "add", "(", "new", "WHeading", "(", "HeadingLevel", ".", "H2", ",", "heading", ")", ")", ";", "WPanel", "panel", "=", "new", "WPanel", "(", ")", ";", "panel", ".", "setLayout", "(", "layout", ")", ";", "add", "(", "panel", ")", ";", "for", "(", "String", "item", ":", "EXAMPLE_ITEMS", ")", "{", "panel", ".", "add", "(", "new", "WText", "(", "item", ")", ")", ";", "}", "add", "(", "new", "WHorizontalRule", "(", ")", ")", ";", "}" ]
Adds an example to the set of examples. @param heading the heading for the example @param layout the layout for the panel
[ "Adds", "an", "example", "to", "the", "set", "of", "examples", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/ListLayoutExample.java#L55-L64
jronrun/benayn
benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Retryer.java
Retryer.exponentialWait
public Retryer<R> exponentialWait(long multiplier, long maximumTime, TimeUnit maximumUnit) { """ Sets the wait strategy which sleeps for an exponential amount of time after the first failed attempt @see Retryer#exponentialWait(long, long) @param multiplier @param maximumTime @param maximumUnit @return """ return exponentialWait(multiplier, checkNotNull(maximumUnit).toMillis(maximumTime)); }
java
public Retryer<R> exponentialWait(long multiplier, long maximumTime, TimeUnit maximumUnit) { return exponentialWait(multiplier, checkNotNull(maximumUnit).toMillis(maximumTime)); }
[ "public", "Retryer", "<", "R", ">", "exponentialWait", "(", "long", "multiplier", ",", "long", "maximumTime", ",", "TimeUnit", "maximumUnit", ")", "{", "return", "exponentialWait", "(", "multiplier", ",", "checkNotNull", "(", "maximumUnit", ")", ".", "toMillis", "(", "maximumTime", ")", ")", ";", "}" ]
Sets the wait strategy which sleeps for an exponential amount of time after the first failed attempt @see Retryer#exponentialWait(long, long) @param multiplier @param maximumTime @param maximumUnit @return
[ "Sets", "the", "wait", "strategy", "which", "sleeps", "for", "an", "exponential", "amount", "of", "time", "after", "the", "first", "failed", "attempt" ]
train
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Retryer.java#L492-L494
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRAvatar.java
GVRAvatar.loadModel
public void loadModel(GVRAndroidResource avatarResource) { """ Load the avatar base model @param avatarResource resource with avatar model """ EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION)); GVRContext ctx = mAvatarRoot.getGVRContext(); GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource); GVRSceneObject modelRoot = new GVRSceneObject(ctx); mAvatarRoot.addChildObject(modelRoot); ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler); }
java
public void loadModel(GVRAndroidResource avatarResource) { EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION)); GVRContext ctx = mAvatarRoot.getGVRContext(); GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource); GVRSceneObject modelRoot = new GVRSceneObject(ctx); mAvatarRoot.addChildObject(modelRoot); ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler); }
[ "public", "void", "loadModel", "(", "GVRAndroidResource", "avatarResource", ")", "{", "EnumSet", "<", "GVRImportSettings", ">", "settings", "=", "GVRImportSettings", ".", "getRecommendedSettingsWith", "(", "EnumSet", ".", "of", "(", "GVRImportSettings", ".", "OPTIMIZE_GRAPH", ",", "GVRImportSettings", ".", "NO_ANIMATION", ")", ")", ";", "GVRContext", "ctx", "=", "mAvatarRoot", ".", "getGVRContext", "(", ")", ";", "GVRResourceVolume", "volume", "=", "new", "GVRResourceVolume", "(", "ctx", ",", "avatarResource", ")", ";", "GVRSceneObject", "modelRoot", "=", "new", "GVRSceneObject", "(", "ctx", ")", ";", "mAvatarRoot", ".", "addChildObject", "(", "modelRoot", ")", ";", "ctx", ".", "getAssetLoader", "(", ")", ".", "loadModel", "(", "volume", ",", "modelRoot", ",", "settings", ",", "false", ",", "mLoadModelHandler", ")", ";", "}" ]
Load the avatar base model @param avatarResource resource with avatar model
[ "Load", "the", "avatar", "base", "model" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRAvatar.java#L191-L200
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/Database.java
Database.findOptionalLong
public @NotNull OptionalLong findOptionalLong(@NotNull @SQL String sql, Object... args) { """ Finds a unique result from database, converting the database row to long using default mechanisms. Returns empty if there are no results or if single null result is returned. @throws NonUniqueResultException if there are multiple result rows """ return findOptionalLong(SqlQuery.query(sql, args)); }
java
public @NotNull OptionalLong findOptionalLong(@NotNull @SQL String sql, Object... args) { return findOptionalLong(SqlQuery.query(sql, args)); }
[ "public", "@", "NotNull", "OptionalLong", "findOptionalLong", "(", "@", "NotNull", "@", "SQL", "String", "sql", ",", "Object", "...", "args", ")", "{", "return", "findOptionalLong", "(", "SqlQuery", ".", "query", "(", "sql", ",", "args", ")", ")", ";", "}" ]
Finds a unique result from database, converting the database row to long using default mechanisms. Returns empty if there are no results or if single null result is returned. @throws NonUniqueResultException if there are multiple result rows
[ "Finds", "a", "unique", "result", "from", "database", "converting", "the", "database", "row", "to", "long", "using", "default", "mechanisms", ".", "Returns", "empty", "if", "there", "are", "no", "results", "or", "if", "single", "null", "result", "is", "returned", "." ]
train
https://github.com/EvidentSolutions/dalesbred/blob/713f5b6e152d97e1672ca68b9ff9c7c6c288ceb1/dalesbred/src/main/java/org/dalesbred/Database.java#L433-L435
aws/aws-sdk-java
aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/APNSMessage.java
APNSMessage.withData
public APNSMessage withData(java.util.Map<String, String> data) { """ The data payload used for a silent push. This payload is added to the notifications' data.pinpoint.jsonBody' object @param data The data payload used for a silent push. This payload is added to the notifications' data.pinpoint.jsonBody' object @return Returns a reference to this object so that method calls can be chained together. """ setData(data); return this; }
java
public APNSMessage withData(java.util.Map<String, String> data) { setData(data); return this; }
[ "public", "APNSMessage", "withData", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "data", ")", "{", "setData", "(", "data", ")", ";", "return", "this", ";", "}" ]
The data payload used for a silent push. This payload is added to the notifications' data.pinpoint.jsonBody' object @param data The data payload used for a silent push. This payload is added to the notifications' data.pinpoint.jsonBody' object @return Returns a reference to this object so that method calls can be chained together.
[ "The", "data", "payload", "used", "for", "a", "silent", "push", ".", "This", "payload", "is", "added", "to", "the", "notifications", "data", ".", "pinpoint", ".", "jsonBody", "object" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/APNSMessage.java#L412-L415
BotMill/fb-botmill
src/main/java/co/aurasphere/botmill/fb/model/outcoming/factory/PassengerSegmentInfoBuilder.java
PassengerSegmentInfoBuilder.addProductInfo
public PassengerSegmentInfoBuilder addProductInfo(String title, String value) { """ Adds a {@link ProductInfo} object to the list of products the passenger purchased in the current {@link PassengerSegmentInfo}. This field is mandatory and there must be at least one element. @param title the product title. It can't be empty. @param value the product description. It can't be empty. @return this builder. """ ProductInfo productInfo = new ProductInfo(title, value); segmentInfo.addProductInfo(productInfo); return this; }
java
public PassengerSegmentInfoBuilder addProductInfo(String title, String value) { ProductInfo productInfo = new ProductInfo(title, value); segmentInfo.addProductInfo(productInfo); return this; }
[ "public", "PassengerSegmentInfoBuilder", "addProductInfo", "(", "String", "title", ",", "String", "value", ")", "{", "ProductInfo", "productInfo", "=", "new", "ProductInfo", "(", "title", ",", "value", ")", ";", "segmentInfo", ".", "addProductInfo", "(", "productInfo", ")", ";", "return", "this", ";", "}" ]
Adds a {@link ProductInfo} object to the list of products the passenger purchased in the current {@link PassengerSegmentInfo}. This field is mandatory and there must be at least one element. @param title the product title. It can't be empty. @param value the product description. It can't be empty. @return this builder.
[ "Adds", "a", "{", "@link", "ProductInfo", "}", "object", "to", "the", "list", "of", "products", "the", "passenger", "purchased", "in", "the", "current", "{", "@link", "PassengerSegmentInfo", "}", ".", "This", "field", "is", "mandatory", "and", "there", "must", "be", "at", "least", "one", "element", "." ]
train
https://github.com/BotMill/fb-botmill/blob/d94da3615a7339822c137ef75c92a03d791ee969/src/main/java/co/aurasphere/botmill/fb/model/outcoming/factory/PassengerSegmentInfoBuilder.java#L86-L90
JodaOrg/joda-convert
src/main/java/org/joda/convert/MethodsStringConverter.java
MethodsStringConverter.convertFromString
@Override public T convertFromString(Class<? extends T> cls, String str) { """ Converts the {@code String} to an object. @param cls the class to convert to, not null @param str the string to convert, not null @return the converted object, may be null but generally not """ try { return cls.cast(fromString.invoke(null, str)); } catch (IllegalAccessException ex) { throw new IllegalStateException("Method is not accessible: " + fromString); } catch (InvocationTargetException ex) { if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw new RuntimeException(ex.getMessage(), ex.getCause()); } }
java
@Override public T convertFromString(Class<? extends T> cls, String str) { try { return cls.cast(fromString.invoke(null, str)); } catch (IllegalAccessException ex) { throw new IllegalStateException("Method is not accessible: " + fromString); } catch (InvocationTargetException ex) { if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw new RuntimeException(ex.getMessage(), ex.getCause()); } }
[ "@", "Override", "public", "T", "convertFromString", "(", "Class", "<", "?", "extends", "T", ">", "cls", ",", "String", "str", ")", "{", "try", "{", "return", "cls", ".", "cast", "(", "fromString", ".", "invoke", "(", "null", ",", "str", ")", ")", ";", "}", "catch", "(", "IllegalAccessException", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Method is not accessible: \"", "+", "fromString", ")", ";", "}", "catch", "(", "InvocationTargetException", "ex", ")", "{", "if", "(", "ex", ".", "getCause", "(", ")", "instanceof", "RuntimeException", ")", "{", "throw", "(", "RuntimeException", ")", "ex", ".", "getCause", "(", ")", ";", "}", "throw", "new", "RuntimeException", "(", "ex", ".", "getMessage", "(", ")", ",", "ex", ".", "getCause", "(", ")", ")", ";", "}", "}" ]
Converts the {@code String} to an object. @param cls the class to convert to, not null @param str the string to convert, not null @return the converted object, may be null but generally not
[ "Converts", "the", "{" ]
train
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/MethodsStringConverter.java#L75-L87
jboss-integration/fuse-bxms-integ
quickstarts/switchyard-demo-library/src/main/java/org/switchyard/quickstarts/demos/library/Library.java
Library.attemptLoan
public Loan attemptLoan(String isbn, String loanId) { """ Attempt loan. @param isbn the isbn @param loanId the loan id @return the loan """ Loan loan = new Loan(); loan.setId(loanId); Book book = getBook(isbn); if (book != null) { synchronized (librarian) { int quantity = getQuantity(book); if (quantity > 0) { quantity--; isbns_to_quantities.put(isbn, quantity); loan.setApproved(true); loan.setNotes("Happy reading! Remaining copies: " + quantity); loan.setBook(book); } else { loan.setApproved(false); loan.setNotes("Book has no copies available."); } } } else { loan.setApproved(false); loan.setNotes("No book matching isbn: " + isbn); } return loan; }
java
public Loan attemptLoan(String isbn, String loanId) { Loan loan = new Loan(); loan.setId(loanId); Book book = getBook(isbn); if (book != null) { synchronized (librarian) { int quantity = getQuantity(book); if (quantity > 0) { quantity--; isbns_to_quantities.put(isbn, quantity); loan.setApproved(true); loan.setNotes("Happy reading! Remaining copies: " + quantity); loan.setBook(book); } else { loan.setApproved(false); loan.setNotes("Book has no copies available."); } } } else { loan.setApproved(false); loan.setNotes("No book matching isbn: " + isbn); } return loan; }
[ "public", "Loan", "attemptLoan", "(", "String", "isbn", ",", "String", "loanId", ")", "{", "Loan", "loan", "=", "new", "Loan", "(", ")", ";", "loan", ".", "setId", "(", "loanId", ")", ";", "Book", "book", "=", "getBook", "(", "isbn", ")", ";", "if", "(", "book", "!=", "null", ")", "{", "synchronized", "(", "librarian", ")", "{", "int", "quantity", "=", "getQuantity", "(", "book", ")", ";", "if", "(", "quantity", ">", "0", ")", "{", "quantity", "--", ";", "isbns_to_quantities", ".", "put", "(", "isbn", ",", "quantity", ")", ";", "loan", ".", "setApproved", "(", "true", ")", ";", "loan", ".", "setNotes", "(", "\"Happy reading! Remaining copies: \"", "+", "quantity", ")", ";", "loan", ".", "setBook", "(", "book", ")", ";", "}", "else", "{", "loan", ".", "setApproved", "(", "false", ")", ";", "loan", ".", "setNotes", "(", "\"Book has no copies available.\"", ")", ";", "}", "}", "}", "else", "{", "loan", ".", "setApproved", "(", "false", ")", ";", "loan", ".", "setNotes", "(", "\"No book matching isbn: \"", "+", "isbn", ")", ";", "}", "return", "loan", ";", "}" ]
Attempt loan. @param isbn the isbn @param loanId the loan id @return the loan
[ "Attempt", "loan", "." ]
train
https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/quickstarts/switchyard-demo-library/src/main/java/org/switchyard/quickstarts/demos/library/Library.java#L159-L182
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/IDNA.java
IDNA.convertToASCII
@Deprecated public static StringBuffer convertToASCII(UCharacterIterator src, int options) throws StringPrepParseException { """ IDNA2003: This function implements the ToASCII operation as defined in the IDNA RFC. This operation is done on <b>single labels</b> before sending it to something that expects ASCII names. A label is an individual part of a domain name. Labels are usually separated by dots; e.g." "www.example.com" is composed of 3 labels "www","example", and "com". @param src The input string as UCharacterIterator to be processed @param options A bit set of options: - IDNA.DEFAULT Use default options, i.e., do not process unassigned code points and do not use STD3 ASCII rules If unassigned code points are found the operation fails with ParseException. - IDNA.ALLOW_UNASSIGNED Unassigned values can be converted to ASCII for query operations If this option is set, the unassigned code points are in the input are treated as normal Unicode code points. - IDNA.USE_STD3_RULES Use STD3 ASCII rules for host name syntax restrictions If this option is set and the input does not satisfy STD3 rules, the operation will fail with ParseException @return StringBuffer the converted String @deprecated ICU 55 Use UTS 46 instead via {@link #getUTS46Instance(int)}. @hide original deprecated declaration """ return IDNA2003.convertToASCII(src, options); }
java
@Deprecated public static StringBuffer convertToASCII(UCharacterIterator src, int options) throws StringPrepParseException{ return IDNA2003.convertToASCII(src, options); }
[ "@", "Deprecated", "public", "static", "StringBuffer", "convertToASCII", "(", "UCharacterIterator", "src", ",", "int", "options", ")", "throws", "StringPrepParseException", "{", "return", "IDNA2003", ".", "convertToASCII", "(", "src", ",", "options", ")", ";", "}" ]
IDNA2003: This function implements the ToASCII operation as defined in the IDNA RFC. This operation is done on <b>single labels</b> before sending it to something that expects ASCII names. A label is an individual part of a domain name. Labels are usually separated by dots; e.g." "www.example.com" is composed of 3 labels "www","example", and "com". @param src The input string as UCharacterIterator to be processed @param options A bit set of options: - IDNA.DEFAULT Use default options, i.e., do not process unassigned code points and do not use STD3 ASCII rules If unassigned code points are found the operation fails with ParseException. - IDNA.ALLOW_UNASSIGNED Unassigned values can be converted to ASCII for query operations If this option is set, the unassigned code points are in the input are treated as normal Unicode code points. - IDNA.USE_STD3_RULES Use STD3 ASCII rules for host name syntax restrictions If this option is set and the input does not satisfy STD3 rules, the operation will fail with ParseException @return StringBuffer the converted String @deprecated ICU 55 Use UTS 46 instead via {@link #getUTS46Instance(int)}. @hide original deprecated declaration
[ "IDNA2003", ":", "This", "function", "implements", "the", "ToASCII", "operation", "as", "defined", "in", "the", "IDNA", "RFC", ".", "This", "operation", "is", "done", "on", "<b", ">", "single", "labels<", "/", "b", ">", "before", "sending", "it", "to", "something", "that", "expects", "ASCII", "names", ".", "A", "label", "is", "an", "individual", "part", "of", "a", "domain", "name", ".", "Labels", "are", "usually", "separated", "by", "dots", ";", "e", ".", "g", ".", "www", ".", "example", ".", "com", "is", "composed", "of", "3", "labels", "www", "example", "and", "com", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/IDNA.java#L543-L547
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/sjavac/Main.java
Main.verifyImplicitOption
private static String[] verifyImplicitOption(String[] args) throws ProblemException { """ Check if -implicit is supplied, if so check that it is none. If -implicit is not supplied, supply -implicit:none Only implicit:none is allowed because otherwise the multicore compilations and dependency tracking will be tangled up. """ boolean foundImplicit = false; for (String a : args) { if (a.startsWith("-implicit:")) { foundImplicit = true; if (!a.equals("-implicit:none")) { throw new ProblemException("The only allowed setting for sjavac is -implicit:none, it is also the default."); } } } if (foundImplicit) { return args; } // -implicit:none not found lets add it. String[] newargs = new String[args.length+1]; System.arraycopy(args,0, newargs, 0, args.length); newargs[args.length] = "-implicit:none"; return newargs; }
java
private static String[] verifyImplicitOption(String[] args) throws ProblemException { boolean foundImplicit = false; for (String a : args) { if (a.startsWith("-implicit:")) { foundImplicit = true; if (!a.equals("-implicit:none")) { throw new ProblemException("The only allowed setting for sjavac is -implicit:none, it is also the default."); } } } if (foundImplicit) { return args; } // -implicit:none not found lets add it. String[] newargs = new String[args.length+1]; System.arraycopy(args,0, newargs, 0, args.length); newargs[args.length] = "-implicit:none"; return newargs; }
[ "private", "static", "String", "[", "]", "verifyImplicitOption", "(", "String", "[", "]", "args", ")", "throws", "ProblemException", "{", "boolean", "foundImplicit", "=", "false", ";", "for", "(", "String", "a", ":", "args", ")", "{", "if", "(", "a", ".", "startsWith", "(", "\"-implicit:\"", ")", ")", "{", "foundImplicit", "=", "true", ";", "if", "(", "!", "a", ".", "equals", "(", "\"-implicit:none\"", ")", ")", "{", "throw", "new", "ProblemException", "(", "\"The only allowed setting for sjavac is -implicit:none, it is also the default.\"", ")", ";", "}", "}", "}", "if", "(", "foundImplicit", ")", "{", "return", "args", ";", "}", "// -implicit:none not found lets add it.", "String", "[", "]", "newargs", "=", "new", "String", "[", "args", ".", "length", "+", "1", "]", ";", "System", ".", "arraycopy", "(", "args", ",", "0", ",", "newargs", ",", "0", ",", "args", ".", "length", ")", ";", "newargs", "[", "args", ".", "length", "]", "=", "\"-implicit:none\"", ";", "return", "newargs", ";", "}" ]
Check if -implicit is supplied, if so check that it is none. If -implicit is not supplied, supply -implicit:none Only implicit:none is allowed because otherwise the multicore compilations and dependency tracking will be tangled up.
[ "Check", "if", "-", "implicit", "is", "supplied", "if", "so", "check", "that", "it", "is", "none", ".", "If", "-", "implicit", "is", "not", "supplied", "supply", "-", "implicit", ":", "none", "Only", "implicit", ":", "none", "is", "allowed", "because", "otherwise", "the", "multicore", "compilations", "and", "dependency", "tracking", "will", "be", "tangled", "up", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/sjavac/Main.java#L578-L598
xmlunit/xmlunit
xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/XMLUnit.java
XMLUnit.buildDocument
public static Document buildDocument(DocumentBuilder withBuilder, Reader fromReader) throws SAXException, IOException { """ Utility method to build a Document using a specific DocumentBuilder and reading characters from a specific Reader. @param withBuilder @param fromReader @return Document built @throws SAXException @throws IOException """ return buildDocument(withBuilder, new InputSource(fromReader)); }
java
public static Document buildDocument(DocumentBuilder withBuilder, Reader fromReader) throws SAXException, IOException { return buildDocument(withBuilder, new InputSource(fromReader)); }
[ "public", "static", "Document", "buildDocument", "(", "DocumentBuilder", "withBuilder", ",", "Reader", "fromReader", ")", "throws", "SAXException", ",", "IOException", "{", "return", "buildDocument", "(", "withBuilder", ",", "new", "InputSource", "(", "fromReader", ")", ")", ";", "}" ]
Utility method to build a Document using a specific DocumentBuilder and reading characters from a specific Reader. @param withBuilder @param fromReader @return Document built @throws SAXException @throws IOException
[ "Utility", "method", "to", "build", "a", "Document", "using", "a", "specific", "DocumentBuilder", "and", "reading", "characters", "from", "a", "specific", "Reader", "." ]
train
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/XMLUnit.java#L359-L362
Cleveroad/AdaptiveTableLayout
library/src/main/java/com/cleveroad/adaptivetablelayout/BaseDataAdaptiveTableLayoutAdapter.java
BaseDataAdaptiveTableLayoutAdapter.switchTwoColumnHeaders
void switchTwoColumnHeaders(int columnIndex, int columnToIndex) { """ Switch 2 columns headers with data @param columnIndex column header from @param columnToIndex column header to """ Object cellData = getColumnHeaders()[columnToIndex]; getColumnHeaders()[columnToIndex] = getColumnHeaders()[columnIndex]; getColumnHeaders()[columnIndex] = cellData; }
java
void switchTwoColumnHeaders(int columnIndex, int columnToIndex) { Object cellData = getColumnHeaders()[columnToIndex]; getColumnHeaders()[columnToIndex] = getColumnHeaders()[columnIndex]; getColumnHeaders()[columnIndex] = cellData; }
[ "void", "switchTwoColumnHeaders", "(", "int", "columnIndex", ",", "int", "columnToIndex", ")", "{", "Object", "cellData", "=", "getColumnHeaders", "(", ")", "[", "columnToIndex", "]", ";", "getColumnHeaders", "(", ")", "[", "columnToIndex", "]", "=", "getColumnHeaders", "(", ")", "[", "columnIndex", "]", ";", "getColumnHeaders", "(", ")", "[", "columnIndex", "]", "=", "cellData", ";", "}" ]
Switch 2 columns headers with data @param columnIndex column header from @param columnToIndex column header to
[ "Switch", "2", "columns", "headers", "with", "data" ]
train
https://github.com/Cleveroad/AdaptiveTableLayout/blob/188213b35e05e635497b03fe741799782dde7208/library/src/main/java/com/cleveroad/adaptivetablelayout/BaseDataAdaptiveTableLayoutAdapter.java#L49-L53
google/closure-templates
java/src/com/google/template/soy/passes/ResolveExpressionTypesPass.java
ResolveExpressionTypesPass.getElementType
private SoyType getElementType(SoyType collectionType, ForNonemptyNode node) { """ Given a collection type, compute the element type. @param collectionType The base type. @param node The ForNonemptyNode being iterated. @return The type of the elements of the collection. """ Preconditions.checkNotNull(collectionType); switch (collectionType.getKind()) { case UNKNOWN: // If we don't know anything about the base type, then make no assumptions // about the field type. return UnknownType.getInstance(); case LIST: if (collectionType == ListType.EMPTY_LIST) { errorReporter.report(node.getParent().getSourceLocation(), EMPTY_LIST_FOREACH); return ErrorType.getInstance(); } return ((ListType) collectionType).getElementType(); case UNION: { // If it's a union, then do the field type calculation for each member of // the union and combine the result. UnionType unionType = (UnionType) collectionType; List<SoyType> fieldTypes = new ArrayList<>(unionType.getMembers().size()); for (SoyType unionMember : unionType.getMembers()) { SoyType elementType = getElementType(unionMember, node); if (elementType.getKind() == SoyType.Kind.ERROR) { return ErrorType.getInstance(); } fieldTypes.add(elementType); } return SoyTypes.computeLowestCommonType(typeRegistry, fieldTypes); } default: errorReporter.report( node.getParent().getSourceLocation(), BAD_FOREACH_TYPE, node.getExpr().toSourceString(), node.getExpr().getType()); // Report the outermost union type in the error. return ErrorType.getInstance(); } }
java
private SoyType getElementType(SoyType collectionType, ForNonemptyNode node) { Preconditions.checkNotNull(collectionType); switch (collectionType.getKind()) { case UNKNOWN: // If we don't know anything about the base type, then make no assumptions // about the field type. return UnknownType.getInstance(); case LIST: if (collectionType == ListType.EMPTY_LIST) { errorReporter.report(node.getParent().getSourceLocation(), EMPTY_LIST_FOREACH); return ErrorType.getInstance(); } return ((ListType) collectionType).getElementType(); case UNION: { // If it's a union, then do the field type calculation for each member of // the union and combine the result. UnionType unionType = (UnionType) collectionType; List<SoyType> fieldTypes = new ArrayList<>(unionType.getMembers().size()); for (SoyType unionMember : unionType.getMembers()) { SoyType elementType = getElementType(unionMember, node); if (elementType.getKind() == SoyType.Kind.ERROR) { return ErrorType.getInstance(); } fieldTypes.add(elementType); } return SoyTypes.computeLowestCommonType(typeRegistry, fieldTypes); } default: errorReporter.report( node.getParent().getSourceLocation(), BAD_FOREACH_TYPE, node.getExpr().toSourceString(), node.getExpr().getType()); // Report the outermost union type in the error. return ErrorType.getInstance(); } }
[ "private", "SoyType", "getElementType", "(", "SoyType", "collectionType", ",", "ForNonemptyNode", "node", ")", "{", "Preconditions", ".", "checkNotNull", "(", "collectionType", ")", ";", "switch", "(", "collectionType", ".", "getKind", "(", ")", ")", "{", "case", "UNKNOWN", ":", "// If we don't know anything about the base type, then make no assumptions", "// about the field type.", "return", "UnknownType", ".", "getInstance", "(", ")", ";", "case", "LIST", ":", "if", "(", "collectionType", "==", "ListType", ".", "EMPTY_LIST", ")", "{", "errorReporter", ".", "report", "(", "node", ".", "getParent", "(", ")", ".", "getSourceLocation", "(", ")", ",", "EMPTY_LIST_FOREACH", ")", ";", "return", "ErrorType", ".", "getInstance", "(", ")", ";", "}", "return", "(", "(", "ListType", ")", "collectionType", ")", ".", "getElementType", "(", ")", ";", "case", "UNION", ":", "{", "// If it's a union, then do the field type calculation for each member of", "// the union and combine the result.", "UnionType", "unionType", "=", "(", "UnionType", ")", "collectionType", ";", "List", "<", "SoyType", ">", "fieldTypes", "=", "new", "ArrayList", "<>", "(", "unionType", ".", "getMembers", "(", ")", ".", "size", "(", ")", ")", ";", "for", "(", "SoyType", "unionMember", ":", "unionType", ".", "getMembers", "(", ")", ")", "{", "SoyType", "elementType", "=", "getElementType", "(", "unionMember", ",", "node", ")", ";", "if", "(", "elementType", ".", "getKind", "(", ")", "==", "SoyType", ".", "Kind", ".", "ERROR", ")", "{", "return", "ErrorType", ".", "getInstance", "(", ")", ";", "}", "fieldTypes", ".", "add", "(", "elementType", ")", ";", "}", "return", "SoyTypes", ".", "computeLowestCommonType", "(", "typeRegistry", ",", "fieldTypes", ")", ";", "}", "default", ":", "errorReporter", ".", "report", "(", "node", ".", "getParent", "(", ")", ".", "getSourceLocation", "(", ")", ",", "BAD_FOREACH_TYPE", ",", "node", ".", "getExpr", "(", ")", ".", "toSourceString", "(", ")", ",", "node", ".", "getExpr", "(", ")", ".", "getType", "(", ")", ")", ";", "// Report the outermost union type in the error.", "return", "ErrorType", ".", "getInstance", "(", ")", ";", "}", "}" ]
Given a collection type, compute the element type. @param collectionType The base type. @param node The ForNonemptyNode being iterated. @return The type of the elements of the collection.
[ "Given", "a", "collection", "type", "compute", "the", "element", "type", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/ResolveExpressionTypesPass.java#L511-L550
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/lsh/RandomProjectionLSH.java
RandomProjectionLSH.rawBucketOf
INDArray rawBucketOf(INDArray query) { """ data elements in the same bucket as the query, without entropy """ INDArray pattern = hash(query); INDArray res = Nd4j.zeros(DataType.BOOL, index.shape()); Nd4j.getExecutioner().exec(new BroadcastEqualTo(index, pattern, res, -1)); return res.castTo(Nd4j.defaultFloatingPointType()).min(-1); }
java
INDArray rawBucketOf(INDArray query){ INDArray pattern = hash(query); INDArray res = Nd4j.zeros(DataType.BOOL, index.shape()); Nd4j.getExecutioner().exec(new BroadcastEqualTo(index, pattern, res, -1)); return res.castTo(Nd4j.defaultFloatingPointType()).min(-1); }
[ "INDArray", "rawBucketOf", "(", "INDArray", "query", ")", "{", "INDArray", "pattern", "=", "hash", "(", "query", ")", ";", "INDArray", "res", "=", "Nd4j", ".", "zeros", "(", "DataType", ".", "BOOL", ",", "index", ".", "shape", "(", ")", ")", ";", "Nd4j", ".", "getExecutioner", "(", ")", ".", "exec", "(", "new", "BroadcastEqualTo", "(", "index", ",", "pattern", ",", "res", ",", "-", "1", ")", ")", ";", "return", "res", ".", "castTo", "(", "Nd4j", ".", "defaultFloatingPointType", "(", ")", ")", ".", "min", "(", "-", "1", ")", ";", "}" ]
data elements in the same bucket as the query, without entropy
[ "data", "elements", "in", "the", "same", "bucket", "as", "the", "query", "without", "entropy" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/lsh/RandomProjectionLSH.java#L163-L169
openbase/jul
exception/src/main/java/org/openbase/jul/exception/StackTracePrinter.java
StackTracePrinter.printStackTrace
public static void printStackTrace(final String message, final StackTraceElement[] stackTraces, final Logger logger, final LogLevel logLevel) { """ Method prints the given stack trace in a human readable way. @param message the reason for printing the stack trace. @param stackTraces the stack trace to print. @param logger the logger used for printing. @param logLevel the log level used for logging the stack trace. """ String stackTraceString = ""; for (final StackTraceElement stackTrace : stackTraces) { stackTraceString += stackTrace.toString() + "\n"; } Printer.print((message == null ? "" : message) + "\n=== Stacktrace ===\n" + stackTraceString + "==================", logLevel, logger); }
java
public static void printStackTrace(final String message, final StackTraceElement[] stackTraces, final Logger logger, final LogLevel logLevel) { String stackTraceString = ""; for (final StackTraceElement stackTrace : stackTraces) { stackTraceString += stackTrace.toString() + "\n"; } Printer.print((message == null ? "" : message) + "\n=== Stacktrace ===\n" + stackTraceString + "==================", logLevel, logger); }
[ "public", "static", "void", "printStackTrace", "(", "final", "String", "message", ",", "final", "StackTraceElement", "[", "]", "stackTraces", ",", "final", "Logger", "logger", ",", "final", "LogLevel", "logLevel", ")", "{", "String", "stackTraceString", "=", "\"\"", ";", "for", "(", "final", "StackTraceElement", "stackTrace", ":", "stackTraces", ")", "{", "stackTraceString", "+=", "stackTrace", ".", "toString", "(", ")", "+", "\"\\n\"", ";", "}", "Printer", ".", "print", "(", "(", "message", "==", "null", "?", "\"\"", ":", "message", ")", "+", "\"\\n=== Stacktrace ===\\n\"", "+", "stackTraceString", "+", "\"==================\"", ",", "logLevel", ",", "logger", ")", ";", "}" ]
Method prints the given stack trace in a human readable way. @param message the reason for printing the stack trace. @param stackTraces the stack trace to print. @param logger the logger used for printing. @param logLevel the log level used for logging the stack trace.
[ "Method", "prints", "the", "given", "stack", "trace", "in", "a", "human", "readable", "way", "." ]
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/exception/src/main/java/org/openbase/jul/exception/StackTracePrinter.java#L101-L108
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deploymentoverlay/AffectedDeploymentOverlay.java
AffectedDeploymentOverlay.listDeployments
public static Set<String> listDeployments(Resource deploymentRootResource, Set<String> runtimeNames) { """ Returns the deployment names with the specified runtime names at the specified deploymentRootAddress. @param deploymentRootResource @param runtimeNames @return the deployment names with the specified runtime names at the specified deploymentRootAddress. """ Set<Pattern> set = new HashSet<>(); for (String wildcardExpr : runtimeNames) { Pattern pattern = DeploymentOverlayIndex.getPattern(wildcardExpr); set.add(pattern); } return listDeploymentNames(deploymentRootResource, set); }
java
public static Set<String> listDeployments(Resource deploymentRootResource, Set<String> runtimeNames) { Set<Pattern> set = new HashSet<>(); for (String wildcardExpr : runtimeNames) { Pattern pattern = DeploymentOverlayIndex.getPattern(wildcardExpr); set.add(pattern); } return listDeploymentNames(deploymentRootResource, set); }
[ "public", "static", "Set", "<", "String", ">", "listDeployments", "(", "Resource", "deploymentRootResource", ",", "Set", "<", "String", ">", "runtimeNames", ")", "{", "Set", "<", "Pattern", ">", "set", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "String", "wildcardExpr", ":", "runtimeNames", ")", "{", "Pattern", "pattern", "=", "DeploymentOverlayIndex", ".", "getPattern", "(", "wildcardExpr", ")", ";", "set", ".", "add", "(", "pattern", ")", ";", "}", "return", "listDeploymentNames", "(", "deploymentRootResource", ",", "set", ")", ";", "}" ]
Returns the deployment names with the specified runtime names at the specified deploymentRootAddress. @param deploymentRootResource @param runtimeNames @return the deployment names with the specified runtime names at the specified deploymentRootAddress.
[ "Returns", "the", "deployment", "names", "with", "the", "specified", "runtime", "names", "at", "the", "specified", "deploymentRootAddress", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deploymentoverlay/AffectedDeploymentOverlay.java#L225-L232
galan/verjson
src/main/java/de/galan/verjson/util/Transformations.java
Transformations.getObjAndRemove
public static ObjectNode getObjAndRemove(ObjectNode obj, String fieldName) { """ Removes the field from a ObjectNode and returns it as ObjectNode """ ObjectNode result = null; if (obj != null) { result = obj(remove(obj, fieldName)); } return result; }
java
public static ObjectNode getObjAndRemove(ObjectNode obj, String fieldName) { ObjectNode result = null; if (obj != null) { result = obj(remove(obj, fieldName)); } return result; }
[ "public", "static", "ObjectNode", "getObjAndRemove", "(", "ObjectNode", "obj", ",", "String", "fieldName", ")", "{", "ObjectNode", "result", "=", "null", ";", "if", "(", "obj", "!=", "null", ")", "{", "result", "=", "obj", "(", "remove", "(", "obj", ",", "fieldName", ")", ")", ";", "}", "return", "result", ";", "}" ]
Removes the field from a ObjectNode and returns it as ObjectNode
[ "Removes", "the", "field", "from", "a", "ObjectNode", "and", "returns", "it", "as", "ObjectNode" ]
train
https://github.com/galan/verjson/blob/4db610fb5198fde913114ed628234f957e1c19d5/src/main/java/de/galan/verjson/util/Transformations.java#L31-L37
jcuda/jcuda
JCudaJava/src/main/java/jcuda/runtime/JCuda.java
JCuda.cudaMallocArray
public static int cudaMallocArray(cudaArray array, cudaChannelFormatDesc desc, long width, long height) { """ Allocate an array on the device. <pre> cudaError_t cudaMallocArray ( cudaArray_t* array, const cudaChannelFormatDesc* desc, size_t width, size_t height = 0, unsigned int flags = 0 ) </pre> <div> <p>Allocate an array on the device. Allocates a CUDA array according to the cudaChannelFormatDesc structure <tt>desc</tt> and returns a handle to the new CUDA array in <tt>*array</tt>. </p> <p>The cudaChannelFormatDesc is defined as: <pre> struct cudaChannelFormatDesc { int x, y, z, w; enum cudaChannelFormatKind f; };</pre> where cudaChannelFormatKind is one of cudaChannelFormatKindSigned, cudaChannelFormatKindUnsigned, or cudaChannelFormatKindFloat. </p> <p>The <tt>flags</tt> parameter enables different options to be specified that affect the allocation, as follows. <ul> <li> <p>cudaArrayDefault: This flag's value is defined to be 0 and provides default array allocation </p> </li> <li> <p>cudaArraySurfaceLoadStore: Allocates an array that can be read from or written to using a surface reference </p> </li> <li> <p>cudaArrayTextureGather: This flag indicates that texture gather operations will be performed on the array. </p> </li> </ul> </p> <p><tt>width</tt> and <tt>height</tt> must meet certain size requirements. See cudaMalloc3DArray() for more details. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param array Pointer to allocated array in device memory @param desc Requested channel format @param width Requested array allocation width @param height Requested array allocation height @param flags Requested properties of allocated array @return cudaSuccess, cudaErrorMemoryAllocation @see JCuda#cudaMalloc @see JCuda#cudaMallocPitch @see JCuda#cudaFree @see JCuda#cudaFreeArray @see JCuda#cudaMallocHost @see JCuda#cudaFreeHost @see JCuda#cudaMalloc3D @see JCuda#cudaMalloc3DArray @see JCuda#cudaHostAlloc """ return cudaMallocArray(array, desc, width, height, 0); }
java
public static int cudaMallocArray(cudaArray array, cudaChannelFormatDesc desc, long width, long height) { return cudaMallocArray(array, desc, width, height, 0); }
[ "public", "static", "int", "cudaMallocArray", "(", "cudaArray", "array", ",", "cudaChannelFormatDesc", "desc", ",", "long", "width", ",", "long", "height", ")", "{", "return", "cudaMallocArray", "(", "array", ",", "desc", ",", "width", ",", "height", ",", "0", ")", ";", "}" ]
Allocate an array on the device. <pre> cudaError_t cudaMallocArray ( cudaArray_t* array, const cudaChannelFormatDesc* desc, size_t width, size_t height = 0, unsigned int flags = 0 ) </pre> <div> <p>Allocate an array on the device. Allocates a CUDA array according to the cudaChannelFormatDesc structure <tt>desc</tt> and returns a handle to the new CUDA array in <tt>*array</tt>. </p> <p>The cudaChannelFormatDesc is defined as: <pre> struct cudaChannelFormatDesc { int x, y, z, w; enum cudaChannelFormatKind f; };</pre> where cudaChannelFormatKind is one of cudaChannelFormatKindSigned, cudaChannelFormatKindUnsigned, or cudaChannelFormatKindFloat. </p> <p>The <tt>flags</tt> parameter enables different options to be specified that affect the allocation, as follows. <ul> <li> <p>cudaArrayDefault: This flag's value is defined to be 0 and provides default array allocation </p> </li> <li> <p>cudaArraySurfaceLoadStore: Allocates an array that can be read from or written to using a surface reference </p> </li> <li> <p>cudaArrayTextureGather: This flag indicates that texture gather operations will be performed on the array. </p> </li> </ul> </p> <p><tt>width</tt> and <tt>height</tt> must meet certain size requirements. See cudaMalloc3DArray() for more details. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param array Pointer to allocated array in device memory @param desc Requested channel format @param width Requested array allocation width @param height Requested array allocation height @param flags Requested properties of allocated array @return cudaSuccess, cudaErrorMemoryAllocation @see JCuda#cudaMalloc @see JCuda#cudaMallocPitch @see JCuda#cudaFree @see JCuda#cudaFreeArray @see JCuda#cudaMallocHost @see JCuda#cudaFreeHost @see JCuda#cudaMalloc3D @see JCuda#cudaMalloc3DArray @see JCuda#cudaHostAlloc
[ "Allocate", "an", "array", "on", "the", "device", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/runtime/JCuda.java#L4276-L4279
jnidzwetzki/bitfinex-v2-wss-api-java
src/main/java/com/github/jnidzwetzki/bitfinex/v2/BitfinexApiCallbackListeners.java
BitfinexApiCallbackListeners.onMyTradeEvent
public Closeable onMyTradeEvent(final BiConsumer<BitfinexAccountSymbol, BitfinexMyExecutedTrade> listener) { """ registers listener for user account related events - executed trades (against submitted order) events @param listener of event @return hook of this listener """ tradeConsumers.offer(listener); return () -> tradeConsumers.remove(listener); }
java
public Closeable onMyTradeEvent(final BiConsumer<BitfinexAccountSymbol, BitfinexMyExecutedTrade> listener) { tradeConsumers.offer(listener); return () -> tradeConsumers.remove(listener); }
[ "public", "Closeable", "onMyTradeEvent", "(", "final", "BiConsumer", "<", "BitfinexAccountSymbol", ",", "BitfinexMyExecutedTrade", ">", "listener", ")", "{", "tradeConsumers", ".", "offer", "(", "listener", ")", ";", "return", "(", ")", "->", "tradeConsumers", ".", "remove", "(", "listener", ")", ";", "}" ]
registers listener for user account related events - executed trades (against submitted order) events @param listener of event @return hook of this listener
[ "registers", "listener", "for", "user", "account", "related", "events", "-", "executed", "trades", "(", "against", "submitted", "order", ")", "events" ]
train
https://github.com/jnidzwetzki/bitfinex-v2-wss-api-java/blob/2e6adf1eb6f8cd4c8722f1619f78ab2cc3c600ee/src/main/java/com/github/jnidzwetzki/bitfinex/v2/BitfinexApiCallbackListeners.java#L128-L131
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/VoiceApi.java
VoiceApi.deleteFromConference
public ApiSuccessResponse deleteFromConference(String id, DeleteFromConferenceData deleteFromConferenceData) throws ApiException { """ Delete a party from a conference call Delete the specified DN from the conference call. This operation can only be performed by the owner of the conference call. @param id The connection ID of the conference call. (required) @param deleteFromConferenceData (required) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<ApiSuccessResponse> resp = deleteFromConferenceWithHttpInfo(id, deleteFromConferenceData); return resp.getData(); }
java
public ApiSuccessResponse deleteFromConference(String id, DeleteFromConferenceData deleteFromConferenceData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = deleteFromConferenceWithHttpInfo(id, deleteFromConferenceData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "deleteFromConference", "(", "String", "id", ",", "DeleteFromConferenceData", "deleteFromConferenceData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "deleteFromConferenceWithHttpInfo", "(", "id", ",", "deleteFromConferenceData", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Delete a party from a conference call Delete the specified DN from the conference call. This operation can only be performed by the owner of the conference call. @param id The connection ID of the conference call. (required) @param deleteFromConferenceData (required) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Delete", "a", "party", "from", "a", "conference", "call", "Delete", "the", "specified", "DN", "from", "the", "conference", "call", ".", "This", "operation", "can", "only", "be", "performed", "by", "the", "owner", "of", "the", "conference", "call", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/VoiceApi.java#L1211-L1214
FINRAOS/JTAF-ExtWebDriver
src/main/java/org/finra/jtaf/ewd/utils/ScreenshotUtils.java
ScreenshotUtils.takeScreenshotOfElement
public static void takeScreenshotOfElement(IElement element, File toSaveAs) throws IOException, WidgetException { """ * You can use this method to take your control pictures. Note that the file should be a png. @param element @param toSaveAs @throws IOException @throws WidgetException """ for(int i = 0; i < 10; i++) { //Loop up to 10x to ensure a clean screenshot was taken log.info("Taking screen shot of locator " + element.getByLocator() + " ... attempt #" + (i+1)); //Scroll to element element.scrollTo(); //Take picture of the page WebDriver wd = SessionManager.getInstance().getCurrentSession().getWrappedDriver(); File screenshot; boolean isRemote = false; if(!(wd instanceof RemoteWebDriver)) { screenshot = ((TakesScreenshot) wd).getScreenshotAs(OutputType.FILE); } else { Augmenter augmenter = new Augmenter(); screenshot = ((TakesScreenshot) augmenter.augment(wd)).getScreenshotAs(OutputType.FILE); isRemote = true; } BufferedImage fullImage = ImageIO.read(screenshot); WebElement ele = element.getWebElement(); //Parse out the picture of the element Point point = ele.getLocation(); int eleWidth = ele.getSize().getWidth(); int eleHeight = ele.getSize().getHeight(); int x; int y; if(isRemote) { x = ((Locatable)ele).getCoordinates().inViewPort().getX(); y = ((Locatable)ele).getCoordinates().inViewPort().getY(); } else { x = point.getX(); y = point.getY(); } log.debug("Screenshot coordinates x: "+x+", y: "+y); BufferedImage eleScreenshot = fullImage.getSubimage(x, y, eleWidth, eleHeight); ImageIO.write(eleScreenshot, "png", screenshot); //Ensure clean snapshot (sometimes WebDriver takes bad pictures and they turn out all black) if(!isBlack(ImageIO.read(screenshot))) { FileUtils.copyFile(screenshot, toSaveAs); break; } } }
java
public static void takeScreenshotOfElement(IElement element, File toSaveAs) throws IOException, WidgetException { for(int i = 0; i < 10; i++) { //Loop up to 10x to ensure a clean screenshot was taken log.info("Taking screen shot of locator " + element.getByLocator() + " ... attempt #" + (i+1)); //Scroll to element element.scrollTo(); //Take picture of the page WebDriver wd = SessionManager.getInstance().getCurrentSession().getWrappedDriver(); File screenshot; boolean isRemote = false; if(!(wd instanceof RemoteWebDriver)) { screenshot = ((TakesScreenshot) wd).getScreenshotAs(OutputType.FILE); } else { Augmenter augmenter = new Augmenter(); screenshot = ((TakesScreenshot) augmenter.augment(wd)).getScreenshotAs(OutputType.FILE); isRemote = true; } BufferedImage fullImage = ImageIO.read(screenshot); WebElement ele = element.getWebElement(); //Parse out the picture of the element Point point = ele.getLocation(); int eleWidth = ele.getSize().getWidth(); int eleHeight = ele.getSize().getHeight(); int x; int y; if(isRemote) { x = ((Locatable)ele).getCoordinates().inViewPort().getX(); y = ((Locatable)ele).getCoordinates().inViewPort().getY(); } else { x = point.getX(); y = point.getY(); } log.debug("Screenshot coordinates x: "+x+", y: "+y); BufferedImage eleScreenshot = fullImage.getSubimage(x, y, eleWidth, eleHeight); ImageIO.write(eleScreenshot, "png", screenshot); //Ensure clean snapshot (sometimes WebDriver takes bad pictures and they turn out all black) if(!isBlack(ImageIO.read(screenshot))) { FileUtils.copyFile(screenshot, toSaveAs); break; } } }
[ "public", "static", "void", "takeScreenshotOfElement", "(", "IElement", "element", ",", "File", "toSaveAs", ")", "throws", "IOException", ",", "WidgetException", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "10", ";", "i", "++", ")", "{", "//Loop up to 10x to ensure a clean screenshot was taken", "log", ".", "info", "(", "\"Taking screen shot of locator \"", "+", "element", ".", "getByLocator", "(", ")", "+", "\" ... attempt #\"", "+", "(", "i", "+", "1", ")", ")", ";", "//Scroll to element", "element", ".", "scrollTo", "(", ")", ";", "//Take picture of the page", "WebDriver", "wd", "=", "SessionManager", ".", "getInstance", "(", ")", ".", "getCurrentSession", "(", ")", ".", "getWrappedDriver", "(", ")", ";", "File", "screenshot", ";", "boolean", "isRemote", "=", "false", ";", "if", "(", "!", "(", "wd", "instanceof", "RemoteWebDriver", ")", ")", "{", "screenshot", "=", "(", "(", "TakesScreenshot", ")", "wd", ")", ".", "getScreenshotAs", "(", "OutputType", ".", "FILE", ")", ";", "}", "else", "{", "Augmenter", "augmenter", "=", "new", "Augmenter", "(", ")", ";", "screenshot", "=", "(", "(", "TakesScreenshot", ")", "augmenter", ".", "augment", "(", "wd", ")", ")", ".", "getScreenshotAs", "(", "OutputType", ".", "FILE", ")", ";", "isRemote", "=", "true", ";", "}", "BufferedImage", "fullImage", "=", "ImageIO", ".", "read", "(", "screenshot", ")", ";", "WebElement", "ele", "=", "element", ".", "getWebElement", "(", ")", ";", "//Parse out the picture of the element", "Point", "point", "=", "ele", ".", "getLocation", "(", ")", ";", "int", "eleWidth", "=", "ele", ".", "getSize", "(", ")", ".", "getWidth", "(", ")", ";", "int", "eleHeight", "=", "ele", ".", "getSize", "(", ")", ".", "getHeight", "(", ")", ";", "int", "x", ";", "int", "y", ";", "if", "(", "isRemote", ")", "{", "x", "=", "(", "(", "Locatable", ")", "ele", ")", ".", "getCoordinates", "(", ")", ".", "inViewPort", "(", ")", ".", "getX", "(", ")", ";", "y", "=", "(", "(", "Locatable", ")", "ele", ")", ".", "getCoordinates", "(", ")", ".", "inViewPort", "(", ")", ".", "getY", "(", ")", ";", "}", "else", "{", "x", "=", "point", ".", "getX", "(", ")", ";", "y", "=", "point", ".", "getY", "(", ")", ";", "}", "log", ".", "debug", "(", "\"Screenshot coordinates x: \"", "+", "x", "+", "\", y: \"", "+", "y", ")", ";", "BufferedImage", "eleScreenshot", "=", "fullImage", ".", "getSubimage", "(", "x", ",", "y", ",", "eleWidth", ",", "eleHeight", ")", ";", "ImageIO", ".", "write", "(", "eleScreenshot", ",", "\"png\"", ",", "screenshot", ")", ";", "//Ensure clean snapshot (sometimes WebDriver takes bad pictures and they turn out all black)", "if", "(", "!", "isBlack", "(", "ImageIO", ".", "read", "(", "screenshot", ")", ")", ")", "{", "FileUtils", ".", "copyFile", "(", "screenshot", ",", "toSaveAs", ")", ";", "break", ";", "}", "}", "}" ]
* You can use this method to take your control pictures. Note that the file should be a png. @param element @param toSaveAs @throws IOException @throws WidgetException
[ "*", "You", "can", "use", "this", "method", "to", "take", "your", "control", "pictures", ".", "Note", "that", "the", "file", "should", "be", "a", "png", "." ]
train
https://github.com/FINRAOS/JTAF-ExtWebDriver/blob/78d646def1bf0904f79b19a81df0241e07f2c73a/src/main/java/org/finra/jtaf/ewd/utils/ScreenshotUtils.java#L61-L108
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/apple/PropertyListSerialization.java
PropertyListSerialization.serializeMap
private static void serializeMap(final Map map, final ContentHandler handler) throws SAXException { """ Serialize a map as a dict element. @param map map to serialize. @param handler destination of serialization events. @throws SAXException if exception during serialization. """ final AttributesImpl attributes = new AttributesImpl(); handler.startElement(null, "dict", "dict", attributes); if (map.size() > 0) { // // need to output with sorted keys to maintain // reproducability // final Object[] keys = map.keySet().toArray(); Arrays.sort(keys); for (final Object key2 : keys) { final String key = String.valueOf(key2); handler.startElement(null, "key", "key", attributes); handler.characters(key.toCharArray(), 0, key.length()); handler.endElement(null, "key", "key"); serializeObject(map.get(key2), handler); } } handler.endElement(null, "dict", "dict"); }
java
private static void serializeMap(final Map map, final ContentHandler handler) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); handler.startElement(null, "dict", "dict", attributes); if (map.size() > 0) { // // need to output with sorted keys to maintain // reproducability // final Object[] keys = map.keySet().toArray(); Arrays.sort(keys); for (final Object key2 : keys) { final String key = String.valueOf(key2); handler.startElement(null, "key", "key", attributes); handler.characters(key.toCharArray(), 0, key.length()); handler.endElement(null, "key", "key"); serializeObject(map.get(key2), handler); } } handler.endElement(null, "dict", "dict"); }
[ "private", "static", "void", "serializeMap", "(", "final", "Map", "map", ",", "final", "ContentHandler", "handler", ")", "throws", "SAXException", "{", "final", "AttributesImpl", "attributes", "=", "new", "AttributesImpl", "(", ")", ";", "handler", ".", "startElement", "(", "null", ",", "\"dict\"", ",", "\"dict\"", ",", "attributes", ")", ";", "if", "(", "map", ".", "size", "(", ")", ">", "0", ")", "{", "//", "// need to output with sorted keys to maintain", "// reproducability", "//", "final", "Object", "[", "]", "keys", "=", "map", ".", "keySet", "(", ")", ".", "toArray", "(", ")", ";", "Arrays", ".", "sort", "(", "keys", ")", ";", "for", "(", "final", "Object", "key2", ":", "keys", ")", "{", "final", "String", "key", "=", "String", ".", "valueOf", "(", "key2", ")", ";", "handler", ".", "startElement", "(", "null", ",", "\"key\"", ",", "\"key\"", ",", "attributes", ")", ";", "handler", ".", "characters", "(", "key", ".", "toCharArray", "(", ")", ",", "0", ",", "key", ".", "length", "(", ")", ")", ";", "handler", ".", "endElement", "(", "null", ",", "\"key\"", ",", "\"key\"", ")", ";", "serializeObject", "(", "map", ".", "get", "(", "key2", ")", ",", "handler", ")", ";", "}", "}", "handler", ".", "endElement", "(", "null", ",", "\"dict\"", ",", "\"dict\"", ")", ";", "}" ]
Serialize a map as a dict element. @param map map to serialize. @param handler destination of serialization events. @throws SAXException if exception during serialization.
[ "Serialize", "a", "map", "as", "a", "dict", "element", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/apple/PropertyListSerialization.java#L164-L184
gallandarakhneorg/afc
core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java
XMLUtil.readXMLFragment
public static DocumentFragment readXMLFragment(URL file) throws IOException, SAXException, ParserConfigurationException { """ Read an XML fragment from an XML file. The XML file is well-formed. It means that the fragment will contains a single element: the root element within the input file. @param file is the file to read @return the fragment from the {@code file}. @throws IOException if the stream cannot be read. @throws SAXException if the stream does not contains valid XML data. @throws ParserConfigurationException if the parser cannot be configured. """ return readXMLFragment(file, false); }
java
public static DocumentFragment readXMLFragment(URL file) throws IOException, SAXException, ParserConfigurationException { return readXMLFragment(file, false); }
[ "public", "static", "DocumentFragment", "readXMLFragment", "(", "URL", "file", ")", "throws", "IOException", ",", "SAXException", ",", "ParserConfigurationException", "{", "return", "readXMLFragment", "(", "file", ",", "false", ")", ";", "}" ]
Read an XML fragment from an XML file. The XML file is well-formed. It means that the fragment will contains a single element: the root element within the input file. @param file is the file to read @return the fragment from the {@code file}. @throws IOException if the stream cannot be read. @throws SAXException if the stream does not contains valid XML data. @throws ParserConfigurationException if the parser cannot be configured.
[ "Read", "an", "XML", "fragment", "from", "an", "XML", "file", ".", "The", "XML", "file", "is", "well", "-", "formed", ".", "It", "means", "that", "the", "fragment", "will", "contains", "a", "single", "element", ":", "the", "root", "element", "within", "the", "input", "file", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java#L2137-L2139
nwillc/almost-functional
src/main/java/almost/functional/utils/Iterables.java
Iterables.contains
public static <T> boolean contains(final Iterable<T> iterable, final T value) { """ Does an iterable contain a value as determined by Object.isEqual(Object, Object). @param iterable the iterable @param value the value @param <T> the type of the iterable and object @return true if iterable contain a value as determined by Object.isEqual(Object, Object). """ return any(iterable, Predicates.isEqual(value)); }
java
public static <T> boolean contains(final Iterable<T> iterable, final T value) { return any(iterable, Predicates.isEqual(value)); }
[ "public", "static", "<", "T", ">", "boolean", "contains", "(", "final", "Iterable", "<", "T", ">", "iterable", ",", "final", "T", "value", ")", "{", "return", "any", "(", "iterable", ",", "Predicates", ".", "isEqual", "(", "value", ")", ")", ";", "}" ]
Does an iterable contain a value as determined by Object.isEqual(Object, Object). @param iterable the iterable @param value the value @param <T> the type of the iterable and object @return true if iterable contain a value as determined by Object.isEqual(Object, Object).
[ "Does", "an", "iterable", "contain", "a", "value", "as", "determined", "by", "Object", ".", "isEqual", "(", "Object", "Object", ")", "." ]
train
https://github.com/nwillc/almost-functional/blob/a6cc7c73b2be475ed1bce5128c24b2eb9c27d666/src/main/java/almost/functional/utils/Iterables.java#L115-L117
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/TaskTracker.java
TaskTracker.reportTaskFinished
void reportTaskFinished(TaskAttemptID taskid, boolean commitPending) { """ The task is no longer running. It may not have completed successfully """ TaskInProgress tip; synchronized (this) { tip = tasks.get(taskid); } if (tip != null) { tip.reportTaskFinished(commitPending); } else { LOG.warn("Unknown child task finished: "+taskid+". Ignored."); } }
java
void reportTaskFinished(TaskAttemptID taskid, boolean commitPending) { TaskInProgress tip; synchronized (this) { tip = tasks.get(taskid); } if (tip != null) { tip.reportTaskFinished(commitPending); } else { LOG.warn("Unknown child task finished: "+taskid+". Ignored."); } }
[ "void", "reportTaskFinished", "(", "TaskAttemptID", "taskid", ",", "boolean", "commitPending", ")", "{", "TaskInProgress", "tip", ";", "synchronized", "(", "this", ")", "{", "tip", "=", "tasks", ".", "get", "(", "taskid", ")", ";", "}", "if", "(", "tip", "!=", "null", ")", "{", "tip", ".", "reportTaskFinished", "(", "commitPending", ")", ";", "}", "else", "{", "LOG", ".", "warn", "(", "\"Unknown child task finished: \"", "+", "taskid", "+", "\". Ignored.\"", ")", ";", "}", "}" ]
The task is no longer running. It may not have completed successfully
[ "The", "task", "is", "no", "longer", "running", ".", "It", "may", "not", "have", "completed", "successfully" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/TaskTracker.java#L3772-L3782
synchronoss/cpo-api
cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/JdbcCpoAdapter.java
JdbcCpoAdapter.getReadConnection
protected Connection getReadConnection() throws CpoException { """ DOCUMENT ME! @return DOCUMENT ME! @throws CpoException DOCUMENT ME! """ Connection connection; try { if (!(invalidReadConnection_)) { connection = getReadDataSource().getConnection(); } else { connection = getWriteDataSource().getConnection(); } connection.setAutoCommit(false); } catch (Exception e) { invalidReadConnection_ = true; String msg = "getReadConnection(): failed"; logger.error(msg, e); try { connection = getWriteDataSource().getConnection(); connection.setAutoCommit(false); } catch (SQLException e2) { msg = "getWriteConnection(): failed"; logger.error(msg, e2); throw new CpoException(msg, e2); } } return connection; }
java
protected Connection getReadConnection() throws CpoException { Connection connection; try { if (!(invalidReadConnection_)) { connection = getReadDataSource().getConnection(); } else { connection = getWriteDataSource().getConnection(); } connection.setAutoCommit(false); } catch (Exception e) { invalidReadConnection_ = true; String msg = "getReadConnection(): failed"; logger.error(msg, e); try { connection = getWriteDataSource().getConnection(); connection.setAutoCommit(false); } catch (SQLException e2) { msg = "getWriteConnection(): failed"; logger.error(msg, e2); throw new CpoException(msg, e2); } } return connection; }
[ "protected", "Connection", "getReadConnection", "(", ")", "throws", "CpoException", "{", "Connection", "connection", ";", "try", "{", "if", "(", "!", "(", "invalidReadConnection_", ")", ")", "{", "connection", "=", "getReadDataSource", "(", ")", ".", "getConnection", "(", ")", ";", "}", "else", "{", "connection", "=", "getWriteDataSource", "(", ")", ".", "getConnection", "(", ")", ";", "}", "connection", ".", "setAutoCommit", "(", "false", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "invalidReadConnection_", "=", "true", ";", "String", "msg", "=", "\"getReadConnection(): failed\"", ";", "logger", ".", "error", "(", "msg", ",", "e", ")", ";", "try", "{", "connection", "=", "getWriteDataSource", "(", ")", ".", "getConnection", "(", ")", ";", "connection", ".", "setAutoCommit", "(", "false", ")", ";", "}", "catch", "(", "SQLException", "e2", ")", "{", "msg", "=", "\"getWriteConnection(): failed\"", ";", "logger", ".", "error", "(", "msg", ",", "e2", ")", ";", "throw", "new", "CpoException", "(", "msg", ",", "e2", ")", ";", "}", "}", "return", "connection", ";", "}" ]
DOCUMENT ME! @return DOCUMENT ME! @throws CpoException DOCUMENT ME!
[ "DOCUMENT", "ME!" ]
train
https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/JdbcCpoAdapter.java#L2044-L2071
rharter/auto-value-gson
auto-value-gson/src/main/java/com/ryanharter/auto/value/gson/AutoValueGsonExtension.java
AutoValueGsonExtension.getDefaultValue
private CodeBlock getDefaultValue(Property prop, FieldSpec field) { """ Returns a default value for initializing well-known types, or else {@code null}. """ if (field.type.isPrimitive()) { String defaultValue = getDefaultPrimitiveValue(field.type); if (defaultValue != null) { return CodeBlock.of("$L", defaultValue); } else { return CodeBlock.of("$T.valueOf(null)", field.type); } } if (prop.nullable()) { return null; } TypeMirror type = prop.element.getReturnType(); if (type.getKind() != TypeKind.DECLARED) { return null; } TypeElement typeElement = MoreTypes.asTypeElement(type); if (typeElement == null) { return null; } return null; }
java
private CodeBlock getDefaultValue(Property prop, FieldSpec field) { if (field.type.isPrimitive()) { String defaultValue = getDefaultPrimitiveValue(field.type); if (defaultValue != null) { return CodeBlock.of("$L", defaultValue); } else { return CodeBlock.of("$T.valueOf(null)", field.type); } } if (prop.nullable()) { return null; } TypeMirror type = prop.element.getReturnType(); if (type.getKind() != TypeKind.DECLARED) { return null; } TypeElement typeElement = MoreTypes.asTypeElement(type); if (typeElement == null) { return null; } return null; }
[ "private", "CodeBlock", "getDefaultValue", "(", "Property", "prop", ",", "FieldSpec", "field", ")", "{", "if", "(", "field", ".", "type", ".", "isPrimitive", "(", ")", ")", "{", "String", "defaultValue", "=", "getDefaultPrimitiveValue", "(", "field", ".", "type", ")", ";", "if", "(", "defaultValue", "!=", "null", ")", "{", "return", "CodeBlock", ".", "of", "(", "\"$L\"", ",", "defaultValue", ")", ";", "}", "else", "{", "return", "CodeBlock", ".", "of", "(", "\"$T.valueOf(null)\"", ",", "field", ".", "type", ")", ";", "}", "}", "if", "(", "prop", ".", "nullable", "(", ")", ")", "{", "return", "null", ";", "}", "TypeMirror", "type", "=", "prop", ".", "element", ".", "getReturnType", "(", ")", ";", "if", "(", "type", ".", "getKind", "(", ")", "!=", "TypeKind", ".", "DECLARED", ")", "{", "return", "null", ";", "}", "TypeElement", "typeElement", "=", "MoreTypes", ".", "asTypeElement", "(", "type", ")", ";", "if", "(", "typeElement", "==", "null", ")", "{", "return", "null", ";", "}", "return", "null", ";", "}" ]
Returns a default value for initializing well-known types, or else {@code null}.
[ "Returns", "a", "default", "value", "for", "initializing", "well", "-", "known", "types", "or", "else", "{" ]
train
https://github.com/rharter/auto-value-gson/blob/68be3b6a208d25ac0580164f6372a38c279cf4fc/auto-value-gson/src/main/java/com/ryanharter/auto/value/gson/AutoValueGsonExtension.java#L675-L697
s1ck/gdl
src/main/java/org/s1ck/gdl/GDLLoader.java
GDLLoader.addPredicates
private void addPredicates(List<Predicate> newPredicates) { """ Adds a list of predicates to the current predicates using AND conjunctions @param newPredicates predicates to be added """ for(Predicate newPredicate : newPredicates) { if(this.predicates == null) { this.predicates = newPredicate; } else { this.predicates = new And(this.predicates, newPredicate); } } }
java
private void addPredicates(List<Predicate> newPredicates) { for(Predicate newPredicate : newPredicates) { if(this.predicates == null) { this.predicates = newPredicate; } else { this.predicates = new And(this.predicates, newPredicate); } } }
[ "private", "void", "addPredicates", "(", "List", "<", "Predicate", ">", "newPredicates", ")", "{", "for", "(", "Predicate", "newPredicate", ":", "newPredicates", ")", "{", "if", "(", "this", ".", "predicates", "==", "null", ")", "{", "this", ".", "predicates", "=", "newPredicate", ";", "}", "else", "{", "this", ".", "predicates", "=", "new", "And", "(", "this", ".", "predicates", ",", "newPredicate", ")", ";", "}", "}", "}" ]
Adds a list of predicates to the current predicates using AND conjunctions @param newPredicates predicates to be added
[ "Adds", "a", "list", "of", "predicates", "to", "the", "current", "predicates", "using", "AND", "conjunctions" ]
train
https://github.com/s1ck/gdl/blob/c89b0f83526661823ad3392f338dbf7dc3e3f834/src/main/java/org/s1ck/gdl/GDLLoader.java#L825-L833
EsotericSoftware/kryonet
src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java
ObjectSpace.getRemoteObject
static public <T> T getRemoteObject (final Connection connection, int objectID, Class<T> iface) { """ Identical to {@link #getRemoteObject(Connection, int, Class...)} except returns the object cast to the specified interface type. The returned object still implements {@link RemoteObject}. """ return (T)getRemoteObject(connection, objectID, new Class[] {iface}); }
java
static public <T> T getRemoteObject (final Connection connection, int objectID, Class<T> iface) { return (T)getRemoteObject(connection, objectID, new Class[] {iface}); }
[ "static", "public", "<", "T", ">", "T", "getRemoteObject", "(", "final", "Connection", "connection", ",", "int", "objectID", ",", "Class", "<", "T", ">", "iface", ")", "{", "return", "(", "T", ")", "getRemoteObject", "(", "connection", ",", "objectID", ",", "new", "Class", "[", "]", "{", "iface", "}", ")", ";", "}" ]
Identical to {@link #getRemoteObject(Connection, int, Class...)} except returns the object cast to the specified interface type. The returned object still implements {@link RemoteObject}.
[ "Identical", "to", "{" ]
train
https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java#L270-L272
apache/flink
flink-core/src/main/java/org/apache/flink/api/common/io/FileInputFormat.java
FileInputFormat.registerInflaterInputStreamFactory
public static void registerInflaterInputStreamFactory(String fileExtension, InflaterInputStreamFactory<?> factory) { """ Registers a decompression algorithm through a {@link org.apache.flink.api.common.io.compression.InflaterInputStreamFactory} with a file extension for transparent decompression. @param fileExtension of the compressed files @param factory to create an {@link java.util.zip.InflaterInputStream} that handles the decompression format """ synchronized (INFLATER_INPUT_STREAM_FACTORIES) { if (INFLATER_INPUT_STREAM_FACTORIES.put(fileExtension, factory) != null) { LOG.warn("Overwriting an existing decompression algorithm for \"{}\" files.", fileExtension); } } }
java
public static void registerInflaterInputStreamFactory(String fileExtension, InflaterInputStreamFactory<?> factory) { synchronized (INFLATER_INPUT_STREAM_FACTORIES) { if (INFLATER_INPUT_STREAM_FACTORIES.put(fileExtension, factory) != null) { LOG.warn("Overwriting an existing decompression algorithm for \"{}\" files.", fileExtension); } } }
[ "public", "static", "void", "registerInflaterInputStreamFactory", "(", "String", "fileExtension", ",", "InflaterInputStreamFactory", "<", "?", ">", "factory", ")", "{", "synchronized", "(", "INFLATER_INPUT_STREAM_FACTORIES", ")", "{", "if", "(", "INFLATER_INPUT_STREAM_FACTORIES", ".", "put", "(", "fileExtension", ",", "factory", ")", "!=", "null", ")", "{", "LOG", ".", "warn", "(", "\"Overwriting an existing decompression algorithm for \\\"{}\\\" files.\"", ",", "fileExtension", ")", ";", "}", "}", "}" ]
Registers a decompression algorithm through a {@link org.apache.flink.api.common.io.compression.InflaterInputStreamFactory} with a file extension for transparent decompression. @param fileExtension of the compressed files @param factory to create an {@link java.util.zip.InflaterInputStream} that handles the decompression format
[ "Registers", "a", "decompression", "algorithm", "through", "a", "{" ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/common/io/FileInputFormat.java#L138-L144
Netflix/eureka
eureka-client/src/main/java/com/netflix/discovery/shared/Applications.java
Applications.addInstanceToMap
private void addInstanceToMap(InstanceInfo info, String vipAddresses, Map<String, VipIndexSupport> vipMap) { """ Add the instance to the given map based if the vip address matches with that of the instance. Note that an instance can be mapped to multiple vip addresses. """ if (vipAddresses != null) { String[] vipAddressArray = vipAddresses.toUpperCase(Locale.ROOT).split(","); for (String vipAddress : vipAddressArray) { VipIndexSupport vis = vipMap.computeIfAbsent(vipAddress, k -> new VipIndexSupport()); vis.instances.add(info); } } }
java
private void addInstanceToMap(InstanceInfo info, String vipAddresses, Map<String, VipIndexSupport> vipMap) { if (vipAddresses != null) { String[] vipAddressArray = vipAddresses.toUpperCase(Locale.ROOT).split(","); for (String vipAddress : vipAddressArray) { VipIndexSupport vis = vipMap.computeIfAbsent(vipAddress, k -> new VipIndexSupport()); vis.instances.add(info); } } }
[ "private", "void", "addInstanceToMap", "(", "InstanceInfo", "info", ",", "String", "vipAddresses", ",", "Map", "<", "String", ",", "VipIndexSupport", ">", "vipMap", ")", "{", "if", "(", "vipAddresses", "!=", "null", ")", "{", "String", "[", "]", "vipAddressArray", "=", "vipAddresses", ".", "toUpperCase", "(", "Locale", ".", "ROOT", ")", ".", "split", "(", "\",\"", ")", ";", "for", "(", "String", "vipAddress", ":", "vipAddressArray", ")", "{", "VipIndexSupport", "vis", "=", "vipMap", ".", "computeIfAbsent", "(", "vipAddress", ",", "k", "->", "new", "VipIndexSupport", "(", ")", ")", ";", "vis", ".", "instances", ".", "add", "(", "info", ")", ";", "}", "}", "}" ]
Add the instance to the given map based if the vip address matches with that of the instance. Note that an instance can be mapped to multiple vip addresses.
[ "Add", "the", "instance", "to", "the", "given", "map", "based", "if", "the", "vip", "address", "matches", "with", "that", "of", "the", "instance", ".", "Note", "that", "an", "instance", "can", "be", "mapped", "to", "multiple", "vip", "addresses", "." ]
train
https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-client/src/main/java/com/netflix/discovery/shared/Applications.java#L375-L383
tango-controls/JTango
dao/src/main/java/fr/esrf/TangoDs/Logging.java
Logging.add_logging_target
public void add_logging_target (Logger logger, String ttype, String tname) throws DevFailed { """ Adds a logging target to the specified logger (i.e. device). @param logger A lo4j logger to which the target will be added @param ttype The target type @param tname The target name """ add_logging_target(logger, ttype + LOGGING_SEPARATOR + tname); }
java
public void add_logging_target (Logger logger, String ttype, String tname) throws DevFailed { add_logging_target(logger, ttype + LOGGING_SEPARATOR + tname); }
[ "public", "void", "add_logging_target", "(", "Logger", "logger", ",", "String", "ttype", ",", "String", "tname", ")", "throws", "DevFailed", "{", "add_logging_target", "(", "logger", ",", "ttype", "+", "LOGGING_SEPARATOR", "+", "tname", ")", ";", "}" ]
Adds a logging target to the specified logger (i.e. device). @param logger A lo4j logger to which the target will be added @param ttype The target type @param tname The target name
[ "Adds", "a", "logging", "target", "to", "the", "specified", "logger", "(", "i", ".", "e", ".", "device", ")", "." ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/dao/src/main/java/fr/esrf/TangoDs/Logging.java#L345-L348
netty/netty
handler/src/main/java/io/netty/handler/ssl/SslUtils.java
SslUtils.toBase64
static ByteBuf toBase64(ByteBufAllocator allocator, ByteBuf src) { """ Same as {@link Base64#encode(ByteBuf, boolean)} but allows the use of a custom {@link ByteBufAllocator}. @see Base64#encode(ByteBuf, boolean) """ ByteBuf dst = Base64.encode(src, src.readerIndex(), src.readableBytes(), true, Base64Dialect.STANDARD, allocator); src.readerIndex(src.writerIndex()); return dst; }
java
static ByteBuf toBase64(ByteBufAllocator allocator, ByteBuf src) { ByteBuf dst = Base64.encode(src, src.readerIndex(), src.readableBytes(), true, Base64Dialect.STANDARD, allocator); src.readerIndex(src.writerIndex()); return dst; }
[ "static", "ByteBuf", "toBase64", "(", "ByteBufAllocator", "allocator", ",", "ByteBuf", "src", ")", "{", "ByteBuf", "dst", "=", "Base64", ".", "encode", "(", "src", ",", "src", ".", "readerIndex", "(", ")", ",", "src", ".", "readableBytes", "(", ")", ",", "true", ",", "Base64Dialect", ".", "STANDARD", ",", "allocator", ")", ";", "src", ".", "readerIndex", "(", "src", ".", "writerIndex", "(", ")", ")", ";", "return", "dst", ";", "}" ]
Same as {@link Base64#encode(ByteBuf, boolean)} but allows the use of a custom {@link ByteBufAllocator}. @see Base64#encode(ByteBuf, boolean)
[ "Same", "as", "{", "@link", "Base64#encode", "(", "ByteBuf", "boolean", ")", "}", "but", "allows", "the", "use", "of", "a", "custom", "{", "@link", "ByteBufAllocator", "}", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/SslUtils.java#L375-L380
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/ContainerTracker.java
ContainerTracker.registerContainer
public synchronized void registerContainer(String containerId, ImageConfiguration imageConfig, GavLabel gavLabel) { """ Register a started container to this tracker @param containerId container id to register @param imageConfig configuration of associated image @param gavLabel pom label to identifying the reactor project where the container was created """ ContainerShutdownDescriptor descriptor = new ContainerShutdownDescriptor(imageConfig, containerId); shutdownDescriptorPerContainerMap.put(containerId, descriptor); updatePomLabelMap(gavLabel, descriptor); updateImageToContainerMapping(imageConfig, containerId); }
java
public synchronized void registerContainer(String containerId, ImageConfiguration imageConfig, GavLabel gavLabel) { ContainerShutdownDescriptor descriptor = new ContainerShutdownDescriptor(imageConfig, containerId); shutdownDescriptorPerContainerMap.put(containerId, descriptor); updatePomLabelMap(gavLabel, descriptor); updateImageToContainerMapping(imageConfig, containerId); }
[ "public", "synchronized", "void", "registerContainer", "(", "String", "containerId", ",", "ImageConfiguration", "imageConfig", ",", "GavLabel", "gavLabel", ")", "{", "ContainerShutdownDescriptor", "descriptor", "=", "new", "ContainerShutdownDescriptor", "(", "imageConfig", ",", "containerId", ")", ";", "shutdownDescriptorPerContainerMap", ".", "put", "(", "containerId", ",", "descriptor", ")", ";", "updatePomLabelMap", "(", "gavLabel", ",", "descriptor", ")", ";", "updateImageToContainerMapping", "(", "imageConfig", ",", "containerId", ")", ";", "}" ]
Register a started container to this tracker @param containerId container id to register @param imageConfig configuration of associated image @param gavLabel pom label to identifying the reactor project where the container was created
[ "Register", "a", "started", "container", "to", "this", "tracker" ]
train
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/ContainerTracker.java#L34-L41
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/CoreJBossASClient.java
CoreJBossASClient.getAppServerDefaultDeploymentDir
public String getAppServerDefaultDeploymentDir() throws Exception { """ Returns the location where the default deployment scanner is pointing to. This is where EARs, WARs and the like are deployed to. @return the default deployments directory - null if there is no deployment scanner @throws Exception any error """ final String[] addressArr = { SUBSYSTEM, DEPLOYMENT_SCANNER, SCANNER, "default" }; final Address address = Address.root().add(addressArr); final ModelNode resourceAttributes = readResource(address); if (resourceAttributes == null) { return null; // there is no default scanner } final String path = resourceAttributes.get("path").asString(); String relativeTo = null; if (resourceAttributes.hasDefined("relative-to")) { relativeTo = resourceAttributes.get("relative-to").asString(); } // path = the actual filesystem path to be scanned. Treated as an absolute path, // unless 'relative-to' is specified, in which case value is treated as relative to that path. // relative-to = Reference to a filesystem path defined in the "paths" section of the server // configuration, or one of the system properties specified on startup. // NOTE: here we will assume that if specified, it is a system property name. if (relativeTo != null) { String syspropValue = System.getProperty(relativeTo); if (syspropValue == null) { throw new IllegalStateException("Cannot support relative-to that isn't a sysprop: " + relativeTo); } relativeTo = syspropValue; } final File dir = new File(relativeTo, path); return dir.getAbsolutePath(); }
java
public String getAppServerDefaultDeploymentDir() throws Exception { final String[] addressArr = { SUBSYSTEM, DEPLOYMENT_SCANNER, SCANNER, "default" }; final Address address = Address.root().add(addressArr); final ModelNode resourceAttributes = readResource(address); if (resourceAttributes == null) { return null; // there is no default scanner } final String path = resourceAttributes.get("path").asString(); String relativeTo = null; if (resourceAttributes.hasDefined("relative-to")) { relativeTo = resourceAttributes.get("relative-to").asString(); } // path = the actual filesystem path to be scanned. Treated as an absolute path, // unless 'relative-to' is specified, in which case value is treated as relative to that path. // relative-to = Reference to a filesystem path defined in the "paths" section of the server // configuration, or one of the system properties specified on startup. // NOTE: here we will assume that if specified, it is a system property name. if (relativeTo != null) { String syspropValue = System.getProperty(relativeTo); if (syspropValue == null) { throw new IllegalStateException("Cannot support relative-to that isn't a sysprop: " + relativeTo); } relativeTo = syspropValue; } final File dir = new File(relativeTo, path); return dir.getAbsolutePath(); }
[ "public", "String", "getAppServerDefaultDeploymentDir", "(", ")", "throws", "Exception", "{", "final", "String", "[", "]", "addressArr", "=", "{", "SUBSYSTEM", ",", "DEPLOYMENT_SCANNER", ",", "SCANNER", ",", "\"default\"", "}", ";", "final", "Address", "address", "=", "Address", ".", "root", "(", ")", ".", "add", "(", "addressArr", ")", ";", "final", "ModelNode", "resourceAttributes", "=", "readResource", "(", "address", ")", ";", "if", "(", "resourceAttributes", "==", "null", ")", "{", "return", "null", ";", "// there is no default scanner", "}", "final", "String", "path", "=", "resourceAttributes", ".", "get", "(", "\"path\"", ")", ".", "asString", "(", ")", ";", "String", "relativeTo", "=", "null", ";", "if", "(", "resourceAttributes", ".", "hasDefined", "(", "\"relative-to\"", ")", ")", "{", "relativeTo", "=", "resourceAttributes", ".", "get", "(", "\"relative-to\"", ")", ".", "asString", "(", ")", ";", "}", "// path = the actual filesystem path to be scanned. Treated as an absolute path,", "// unless 'relative-to' is specified, in which case value is treated as relative to that path.", "// relative-to = Reference to a filesystem path defined in the \"paths\" section of the server", "// configuration, or one of the system properties specified on startup.", "// NOTE: here we will assume that if specified, it is a system property name.", "if", "(", "relativeTo", "!=", "null", ")", "{", "String", "syspropValue", "=", "System", ".", "getProperty", "(", "relativeTo", ")", ";", "if", "(", "syspropValue", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Cannot support relative-to that isn't a sysprop: \"", "+", "relativeTo", ")", ";", "}", "relativeTo", "=", "syspropValue", ";", "}", "final", "File", "dir", "=", "new", "File", "(", "relativeTo", ",", "path", ")", ";", "return", "dir", ".", "getAbsolutePath", "(", ")", ";", "}" ]
Returns the location where the default deployment scanner is pointing to. This is where EARs, WARs and the like are deployed to. @return the default deployments directory - null if there is no deployment scanner @throws Exception any error
[ "Returns", "the", "location", "where", "the", "default", "deployment", "scanner", "is", "pointing", "to", ".", "This", "is", "where", "EARs", "WARs", "and", "the", "like", "are", "deployed", "to", "." ]
train
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/CoreJBossASClient.java#L200-L231
ben-manes/caffeine
simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/product/CollisionPolicy.java
CollisionPolicy.policies
public static Set<Policy> policies(Config config) { """ Returns all variations of this policy based on the configuration parameters. """ CollisionSettings settings = new CollisionSettings(config); return settings.density() .map(density -> new CollisionPolicy(settings, density)) .collect(toSet()); }
java
public static Set<Policy> policies(Config config) { CollisionSettings settings = new CollisionSettings(config); return settings.density() .map(density -> new CollisionPolicy(settings, density)) .collect(toSet()); }
[ "public", "static", "Set", "<", "Policy", ">", "policies", "(", "Config", "config", ")", "{", "CollisionSettings", "settings", "=", "new", "CollisionSettings", "(", "config", ")", ";", "return", "settings", ".", "density", "(", ")", ".", "map", "(", "density", "->", "new", "CollisionPolicy", "(", "settings", ",", "density", ")", ")", ".", "collect", "(", "toSet", "(", ")", ")", ";", "}" ]
Returns all variations of this policy based on the configuration parameters.
[ "Returns", "all", "variations", "of", "this", "policy", "based", "on", "the", "configuration", "parameters", "." ]
train
https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/product/CollisionPolicy.java#L67-L72
cojen/Cojen
src/main/java/org/cojen/classfile/ConstantPool.java
ConstantPool.addConstantClass
public ConstantClassInfo addConstantClass(String className, int dim) { """ Get or create a constant from the constant pool representing an array class. @param dim Number of array dimensions. """ return (ConstantClassInfo)addConstant(new ConstantClassInfo(this, className, dim)); }
java
public ConstantClassInfo addConstantClass(String className, int dim) { return (ConstantClassInfo)addConstant(new ConstantClassInfo(this, className, dim)); }
[ "public", "ConstantClassInfo", "addConstantClass", "(", "String", "className", ",", "int", "dim", ")", "{", "return", "(", "ConstantClassInfo", ")", "addConstant", "(", "new", "ConstantClassInfo", "(", "this", ",", "className", ",", "dim", ")", ")", ";", "}" ]
Get or create a constant from the constant pool representing an array class. @param dim Number of array dimensions.
[ "Get", "or", "create", "a", "constant", "from", "the", "constant", "pool", "representing", "an", "array", "class", "." ]
train
https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/ConstantPool.java#L128-L130
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/query/Criteria.java
Criteria.addColumnEqualTo
public void addColumnEqualTo(String column, Object value) { """ Adds and equals (=) criteria, CUST_ID = 10034 attribute will NOT be translated into column name @param column The column name to be used without translation @param value An object representing the value of the column """ // PAW // SelectionCriteria c = ValueCriteria.buildEqualToCriteria(column, value, getAlias()); SelectionCriteria c = ValueCriteria.buildEqualToCriteria(column, value, getUserAlias(column)); c.setTranslateAttribute(false); addSelectionCriteria(c); }
java
public void addColumnEqualTo(String column, Object value) { // PAW // SelectionCriteria c = ValueCriteria.buildEqualToCriteria(column, value, getAlias()); SelectionCriteria c = ValueCriteria.buildEqualToCriteria(column, value, getUserAlias(column)); c.setTranslateAttribute(false); addSelectionCriteria(c); }
[ "public", "void", "addColumnEqualTo", "(", "String", "column", ",", "Object", "value", ")", "{", "// PAW\r", "//\t\tSelectionCriteria c = ValueCriteria.buildEqualToCriteria(column, value, getAlias());\r", "SelectionCriteria", "c", "=", "ValueCriteria", ".", "buildEqualToCriteria", "(", "column", ",", "value", ",", "getUserAlias", "(", "column", ")", ")", ";", "c", ".", "setTranslateAttribute", "(", "false", ")", ";", "addSelectionCriteria", "(", "c", ")", ";", "}" ]
Adds and equals (=) criteria, CUST_ID = 10034 attribute will NOT be translated into column name @param column The column name to be used without translation @param value An object representing the value of the column
[ "Adds", "and", "equals", "(", "=", ")", "criteria", "CUST_ID", "=", "10034", "attribute", "will", "NOT", "be", "translated", "into", "column", "name" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L305-L312
qiujuer/Genius-Android
caprice/ui/src/main/java/net/qiujuer/genius/ui/compat/UiCompat.java
UiCompat.setTextDirection
public static void setTextDirection(TextView textView, int textDirection) { """ Sets the TextView text direction attribute when possible @param textView TextView @param textDirection Text Direction @see TextView#setTextDirection(int) """ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { UiCompatNotCrash.setTextDirection(textView, textDirection); } }
java
public static void setTextDirection(TextView textView, int textDirection) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { UiCompatNotCrash.setTextDirection(textView, textDirection); } }
[ "public", "static", "void", "setTextDirection", "(", "TextView", "textView", ",", "int", "textDirection", ")", "{", "if", "(", "Build", ".", "VERSION", ".", "SDK_INT", ">=", "Build", ".", "VERSION_CODES", ".", "JELLY_BEAN_MR1", ")", "{", "UiCompatNotCrash", ".", "setTextDirection", "(", "textView", ",", "textDirection", ")", ";", "}", "}" ]
Sets the TextView text direction attribute when possible @param textView TextView @param textDirection Text Direction @see TextView#setTextDirection(int)
[ "Sets", "the", "TextView", "text", "direction", "attribute", "when", "possible" ]
train
https://github.com/qiujuer/Genius-Android/blob/babefaf1321f5883a21cada582b6fa5104adc648/caprice/ui/src/main/java/net/qiujuer/genius/ui/compat/UiCompat.java#L93-L97
alkacon/opencms-core
src/org/opencms/pdftools/CmsPdfResourceHandler.java
CmsPdfResourceHandler.handleThumbnailLink
private void handleThumbnailLink( CmsObject cms, HttpServletRequest request, HttpServletResponse response, String uri) throws Exception { """ Handles a request for a PDF thumbnail.<p> @param cms the current CMS context @param request the servlet request @param response the servlet response @param uri the current uri @throws Exception if something goes wrong """ String options = request.getParameter(CmsPdfThumbnailLink.PARAM_OPTIONS); if (CmsStringUtil.isEmptyOrWhitespaceOnly(options)) { options = "w:64"; } CmsPdfThumbnailLink linkObj = new CmsPdfThumbnailLink(cms, uri, options); CmsResource pdf = linkObj.getPdfResource(); CmsFile pdfFile = cms.readFile(pdf); CmsPdfThumbnailGenerator thumbnailGenerator = new CmsPdfThumbnailGenerator(); // use a wrapped resource because we want the cache to store files with the correct (image file) extensions CmsWrappedResource wrapperWithImageExtension = new CmsWrappedResource(pdfFile); wrapperWithImageExtension.setRootPath(pdfFile.getRootPath() + "." + linkObj.getFormat()); String cacheName = m_thumbnailCache.getCacheName( wrapperWithImageExtension.getResource(), options + ";" + linkObj.getFormat()); byte[] imageData = m_thumbnailCache.getCacheContent(cacheName); if (imageData == null) { imageData = thumbnailGenerator.generateThumbnail( new ByteArrayInputStream(pdfFile.getContents()), linkObj.getWidth(), linkObj.getHeight(), linkObj.getFormat(), linkObj.getPage()); m_thumbnailCache.saveCacheFile(cacheName, imageData); } response.setContentType(IMAGE_MIMETYPES.get(linkObj.getFormat())); response.getOutputStream().write(imageData); CmsResourceInitException initEx = new CmsResourceInitException(CmsPdfResourceHandler.class); initEx.setClearErrors(true); throw initEx; }
java
private void handleThumbnailLink( CmsObject cms, HttpServletRequest request, HttpServletResponse response, String uri) throws Exception { String options = request.getParameter(CmsPdfThumbnailLink.PARAM_OPTIONS); if (CmsStringUtil.isEmptyOrWhitespaceOnly(options)) { options = "w:64"; } CmsPdfThumbnailLink linkObj = new CmsPdfThumbnailLink(cms, uri, options); CmsResource pdf = linkObj.getPdfResource(); CmsFile pdfFile = cms.readFile(pdf); CmsPdfThumbnailGenerator thumbnailGenerator = new CmsPdfThumbnailGenerator(); // use a wrapped resource because we want the cache to store files with the correct (image file) extensions CmsWrappedResource wrapperWithImageExtension = new CmsWrappedResource(pdfFile); wrapperWithImageExtension.setRootPath(pdfFile.getRootPath() + "." + linkObj.getFormat()); String cacheName = m_thumbnailCache.getCacheName( wrapperWithImageExtension.getResource(), options + ";" + linkObj.getFormat()); byte[] imageData = m_thumbnailCache.getCacheContent(cacheName); if (imageData == null) { imageData = thumbnailGenerator.generateThumbnail( new ByteArrayInputStream(pdfFile.getContents()), linkObj.getWidth(), linkObj.getHeight(), linkObj.getFormat(), linkObj.getPage()); m_thumbnailCache.saveCacheFile(cacheName, imageData); } response.setContentType(IMAGE_MIMETYPES.get(linkObj.getFormat())); response.getOutputStream().write(imageData); CmsResourceInitException initEx = new CmsResourceInitException(CmsPdfResourceHandler.class); initEx.setClearErrors(true); throw initEx; }
[ "private", "void", "handleThumbnailLink", "(", "CmsObject", "cms", ",", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ",", "String", "uri", ")", "throws", "Exception", "{", "String", "options", "=", "request", ".", "getParameter", "(", "CmsPdfThumbnailLink", ".", "PARAM_OPTIONS", ")", ";", "if", "(", "CmsStringUtil", ".", "isEmptyOrWhitespaceOnly", "(", "options", ")", ")", "{", "options", "=", "\"w:64\"", ";", "}", "CmsPdfThumbnailLink", "linkObj", "=", "new", "CmsPdfThumbnailLink", "(", "cms", ",", "uri", ",", "options", ")", ";", "CmsResource", "pdf", "=", "linkObj", ".", "getPdfResource", "(", ")", ";", "CmsFile", "pdfFile", "=", "cms", ".", "readFile", "(", "pdf", ")", ";", "CmsPdfThumbnailGenerator", "thumbnailGenerator", "=", "new", "CmsPdfThumbnailGenerator", "(", ")", ";", "// use a wrapped resource because we want the cache to store files with the correct (image file) extensions", "CmsWrappedResource", "wrapperWithImageExtension", "=", "new", "CmsWrappedResource", "(", "pdfFile", ")", ";", "wrapperWithImageExtension", ".", "setRootPath", "(", "pdfFile", ".", "getRootPath", "(", ")", "+", "\".\"", "+", "linkObj", ".", "getFormat", "(", ")", ")", ";", "String", "cacheName", "=", "m_thumbnailCache", ".", "getCacheName", "(", "wrapperWithImageExtension", ".", "getResource", "(", ")", ",", "options", "+", "\";\"", "+", "linkObj", ".", "getFormat", "(", ")", ")", ";", "byte", "[", "]", "imageData", "=", "m_thumbnailCache", ".", "getCacheContent", "(", "cacheName", ")", ";", "if", "(", "imageData", "==", "null", ")", "{", "imageData", "=", "thumbnailGenerator", ".", "generateThumbnail", "(", "new", "ByteArrayInputStream", "(", "pdfFile", ".", "getContents", "(", ")", ")", ",", "linkObj", ".", "getWidth", "(", ")", ",", "linkObj", ".", "getHeight", "(", ")", ",", "linkObj", ".", "getFormat", "(", ")", ",", "linkObj", ".", "getPage", "(", ")", ")", ";", "m_thumbnailCache", ".", "saveCacheFile", "(", "cacheName", ",", "imageData", ")", ";", "}", "response", ".", "setContentType", "(", "IMAGE_MIMETYPES", ".", "get", "(", "linkObj", ".", "getFormat", "(", ")", ")", ")", ";", "response", ".", "getOutputStream", "(", ")", ".", "write", "(", "imageData", ")", ";", "CmsResourceInitException", "initEx", "=", "new", "CmsResourceInitException", "(", "CmsPdfResourceHandler", ".", "class", ")", ";", "initEx", ".", "setClearErrors", "(", "true", ")", ";", "throw", "initEx", ";", "}" ]
Handles a request for a PDF thumbnail.<p> @param cms the current CMS context @param request the servlet request @param response the servlet response @param uri the current uri @throws Exception if something goes wrong
[ "Handles", "a", "request", "for", "a", "PDF", "thumbnail", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/pdftools/CmsPdfResourceHandler.java#L247-L284
buschmais/jqa-core-framework
rule/src/main/java/com/buschmais/jqassistant/core/rule/impl/reader/AsciidocRuleParserPlugin.java
AsciidocRuleParserPlugin.getSeverity
private Severity getSeverity(Attributes attributes, Severity defaultSeverity) throws RuleException { """ Extract the optional severity of a rule. @param attributes The attributes of the rule. @param defaultSeverity The default severity to use if no severity is specified. @return The severity. """ String severity = attributes.getString(SEVERITY); if (severity == null) { return defaultSeverity; } Severity value = Severity.fromValue(severity.toLowerCase()); return value != null ? value : defaultSeverity; }
java
private Severity getSeverity(Attributes attributes, Severity defaultSeverity) throws RuleException { String severity = attributes.getString(SEVERITY); if (severity == null) { return defaultSeverity; } Severity value = Severity.fromValue(severity.toLowerCase()); return value != null ? value : defaultSeverity; }
[ "private", "Severity", "getSeverity", "(", "Attributes", "attributes", ",", "Severity", "defaultSeverity", ")", "throws", "RuleException", "{", "String", "severity", "=", "attributes", ".", "getString", "(", "SEVERITY", ")", ";", "if", "(", "severity", "==", "null", ")", "{", "return", "defaultSeverity", ";", "}", "Severity", "value", "=", "Severity", ".", "fromValue", "(", "severity", ".", "toLowerCase", "(", ")", ")", ";", "return", "value", "!=", "null", "?", "value", ":", "defaultSeverity", ";", "}" ]
Extract the optional severity of a rule. @param attributes The attributes of the rule. @param defaultSeverity The default severity to use if no severity is specified. @return The severity.
[ "Extract", "the", "optional", "severity", "of", "a", "rule", "." ]
train
https://github.com/buschmais/jqa-core-framework/blob/0e63ff509cfe52f9063539a23d5f9f183b2ea4a5/rule/src/main/java/com/buschmais/jqassistant/core/rule/impl/reader/AsciidocRuleParserPlugin.java#L323-L330
alkacon/opencms-core
src/org/opencms/db/generic/CmsSqlManager.java
CmsSqlManager.setBytes
public void setBytes(PreparedStatement statement, int pos, byte[] content) throws SQLException { """ Sets the designated parameter to the given Java array of bytes.<p> The driver converts this to an SQL VARBINARY or LONGVARBINARY (depending on the argument's size relative to the driver's limits on VARBINARY values) when it sends it to the database. @param statement the PreparedStatement where the content is set @param pos the first parameter is 1, the second is 2, ... @param content the parameter value @throws SQLException if a database access error occurs """ if (content.length < 2000) { statement.setBytes(pos, content); } else { statement.setBinaryStream(pos, new ByteArrayInputStream(content), content.length); } }
java
public void setBytes(PreparedStatement statement, int pos, byte[] content) throws SQLException { if (content.length < 2000) { statement.setBytes(pos, content); } else { statement.setBinaryStream(pos, new ByteArrayInputStream(content), content.length); } }
[ "public", "void", "setBytes", "(", "PreparedStatement", "statement", ",", "int", "pos", ",", "byte", "[", "]", "content", ")", "throws", "SQLException", "{", "if", "(", "content", ".", "length", "<", "2000", ")", "{", "statement", ".", "setBytes", "(", "pos", ",", "content", ")", ";", "}", "else", "{", "statement", ".", "setBinaryStream", "(", "pos", ",", "new", "ByteArrayInputStream", "(", "content", ")", ",", "content", ".", "length", ")", ";", "}", "}" ]
Sets the designated parameter to the given Java array of bytes.<p> The driver converts this to an SQL VARBINARY or LONGVARBINARY (depending on the argument's size relative to the driver's limits on VARBINARY values) when it sends it to the database. @param statement the PreparedStatement where the content is set @param pos the first parameter is 1, the second is 2, ... @param content the parameter value @throws SQLException if a database access error occurs
[ "Sets", "the", "designated", "parameter", "to", "the", "given", "Java", "array", "of", "bytes", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsSqlManager.java#L403-L410
google/allocation-instrumenter
src/main/java/com/google/monitoring/runtime/instrumentation/ConstructorInstrumenter.java
ConstructorInstrumenter.instrumentClass
public static void instrumentClass(Class<?> c, ConstructorCallback<?> sampler) throws UnmodifiableClassException { """ Ensures that the given sampler will be invoked every time a constructor for class c is invoked. @param c The class to be tracked @param sampler the code to be invoked when an instance of c is constructed @throws UnmodifiableClassException if c cannot be modified. """ // IMPORTANT: Don't forget that other threads may be accessing this // class while this code is running. Specifically, the class may be // executed directly after the retransformClasses is called. Thus, we need // to be careful about what happens after the retransformClasses call. synchronized (samplerPutAtomicityLock) { List<ConstructorCallback<?>> list = samplerMap.get(c); if (list == null) { CopyOnWriteArrayList<ConstructorCallback<?>> samplerList = new CopyOnWriteArrayList<ConstructorCallback<?>>(); samplerList.add(sampler); samplerMap.put(c, samplerList); Instrumentation inst = AllocationRecorder.getInstrumentation(); Class<?>[] cs = new Class<?>[1]; cs[0] = c; inst.retransformClasses(c); } else { list.add(sampler); } } }
java
public static void instrumentClass(Class<?> c, ConstructorCallback<?> sampler) throws UnmodifiableClassException { // IMPORTANT: Don't forget that other threads may be accessing this // class while this code is running. Specifically, the class may be // executed directly after the retransformClasses is called. Thus, we need // to be careful about what happens after the retransformClasses call. synchronized (samplerPutAtomicityLock) { List<ConstructorCallback<?>> list = samplerMap.get(c); if (list == null) { CopyOnWriteArrayList<ConstructorCallback<?>> samplerList = new CopyOnWriteArrayList<ConstructorCallback<?>>(); samplerList.add(sampler); samplerMap.put(c, samplerList); Instrumentation inst = AllocationRecorder.getInstrumentation(); Class<?>[] cs = new Class<?>[1]; cs[0] = c; inst.retransformClasses(c); } else { list.add(sampler); } } }
[ "public", "static", "void", "instrumentClass", "(", "Class", "<", "?", ">", "c", ",", "ConstructorCallback", "<", "?", ">", "sampler", ")", "throws", "UnmodifiableClassException", "{", "// IMPORTANT: Don't forget that other threads may be accessing this", "// class while this code is running. Specifically, the class may be", "// executed directly after the retransformClasses is called. Thus, we need", "// to be careful about what happens after the retransformClasses call.", "synchronized", "(", "samplerPutAtomicityLock", ")", "{", "List", "<", "ConstructorCallback", "<", "?", ">", ">", "list", "=", "samplerMap", ".", "get", "(", "c", ")", ";", "if", "(", "list", "==", "null", ")", "{", "CopyOnWriteArrayList", "<", "ConstructorCallback", "<", "?", ">", ">", "samplerList", "=", "new", "CopyOnWriteArrayList", "<", "ConstructorCallback", "<", "?", ">", ">", "(", ")", ";", "samplerList", ".", "add", "(", "sampler", ")", ";", "samplerMap", ".", "put", "(", "c", ",", "samplerList", ")", ";", "Instrumentation", "inst", "=", "AllocationRecorder", ".", "getInstrumentation", "(", ")", ";", "Class", "<", "?", ">", "[", "]", "cs", "=", "new", "Class", "<", "?", ">", "[", "1", "]", ";", "cs", "[", "0", "]", "=", "c", ";", "inst", ".", "retransformClasses", "(", "c", ")", ";", "}", "else", "{", "list", ".", "add", "(", "sampler", ")", ";", "}", "}", "}" ]
Ensures that the given sampler will be invoked every time a constructor for class c is invoked. @param c The class to be tracked @param sampler the code to be invoked when an instance of c is constructed @throws UnmodifiableClassException if c cannot be modified.
[ "Ensures", "that", "the", "given", "sampler", "will", "be", "invoked", "every", "time", "a", "constructor", "for", "class", "c", "is", "invoked", "." ]
train
https://github.com/google/allocation-instrumenter/blob/58d8473e8832e51f39ae7aa38328f61c4b747bff/src/main/java/com/google/monitoring/runtime/instrumentation/ConstructorInstrumenter.java#L68-L89
OpenTSDB/opentsdb
src/tsd/RpcHandler.java
RpcHandler.handleTelnetRpc
private void handleTelnetRpc(final Channel chan, final String[] command) { """ Finds the right handler for a telnet-style RPC and executes it. @param chan The channel on which the RPC was received. @param command The split telnet-style command. """ TelnetRpc rpc = rpc_manager.lookupTelnetRpc(command[0]); if (rpc == null) { rpc = unknown_cmd; } telnet_rpcs_received.incrementAndGet(); rpc.execute(tsdb, chan, command); }
java
private void handleTelnetRpc(final Channel chan, final String[] command) { TelnetRpc rpc = rpc_manager.lookupTelnetRpc(command[0]); if (rpc == null) { rpc = unknown_cmd; } telnet_rpcs_received.incrementAndGet(); rpc.execute(tsdb, chan, command); }
[ "private", "void", "handleTelnetRpc", "(", "final", "Channel", "chan", ",", "final", "String", "[", "]", "command", ")", "{", "TelnetRpc", "rpc", "=", "rpc_manager", ".", "lookupTelnetRpc", "(", "command", "[", "0", "]", ")", ";", "if", "(", "rpc", "==", "null", ")", "{", "rpc", "=", "unknown_cmd", ";", "}", "telnet_rpcs_received", ".", "incrementAndGet", "(", ")", ";", "rpc", ".", "execute", "(", "tsdb", ",", "chan", ",", "command", ")", ";", "}" ]
Finds the right handler for a telnet-style RPC and executes it. @param chan The channel on which the RPC was received. @param command The split telnet-style command.
[ "Finds", "the", "right", "handler", "for", "a", "telnet", "-", "style", "RPC", "and", "executes", "it", "." ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tsd/RpcHandler.java#L155-L162
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/metadata/ConnectionRepository.java
ConnectionRepository.addDescriptor
public JdbcConnectionDescriptor addDescriptor(String jcdAlias, String jdbcDriver, String jdbcConnectionUrl, String username, String password) { """ Creates and adds a new connection descriptor for the given JDBC connection url. This method tries to guess the platform to be used, but it should be checked afterwards nonetheless using the {@link JdbcConnectionDescriptor#getDbms()} method. For properties that are not part of the url, the following standard values are explicitly set: <ul> <li>jdbc level = 2.0</li> </ul> @param jcdAlias The connection alias for the created connection; if 'default' is used, then the new descriptor will become the default connection descriptor @param jdbcDriver The fully qualified jdbc driver name @param jdbcConnectionUrl The connection url of the form '[protocol]:[sub protocol]:{database-specific path]' where protocol is usually 'jdbc' @param username The user name (can be <code>null</code>) @param password The password (can be <code>null</code>) @return The created connection descriptor @see JdbcConnectionDescriptor#getDbms() """ JdbcConnectionDescriptor jcd = new JdbcConnectionDescriptor(); HashMap props = utils.parseConnectionUrl(jdbcConnectionUrl); jcd.setJcdAlias(jcdAlias); jcd.setProtocol((String)props.get(JdbcMetadataUtils.PROPERTY_PROTOCOL)); jcd.setSubProtocol((String)props.get(JdbcMetadataUtils.PROPERTY_SUBPROTOCOL)); jcd.setDbAlias((String)props.get(JdbcMetadataUtils.PROPERTY_DBALIAS)); String platform = utils.findPlatformFor(jcd.getSubProtocol(), jdbcDriver); jcd.setDbms(platform); jcd.setJdbcLevel(2.0); jcd.setDriver(jdbcDriver); if (username != null) { jcd.setUserName(username); jcd.setPassWord(password); } if ("default".equals(jcdAlias)) { jcd.setDefaultConnection(true); // arminw: MM will search for the default key // MetadataManager.getInstance().setDefaultPBKey(jcd.getPBKey()); } addDescriptor(jcd); return jcd; }
java
public JdbcConnectionDescriptor addDescriptor(String jcdAlias, String jdbcDriver, String jdbcConnectionUrl, String username, String password) { JdbcConnectionDescriptor jcd = new JdbcConnectionDescriptor(); HashMap props = utils.parseConnectionUrl(jdbcConnectionUrl); jcd.setJcdAlias(jcdAlias); jcd.setProtocol((String)props.get(JdbcMetadataUtils.PROPERTY_PROTOCOL)); jcd.setSubProtocol((String)props.get(JdbcMetadataUtils.PROPERTY_SUBPROTOCOL)); jcd.setDbAlias((String)props.get(JdbcMetadataUtils.PROPERTY_DBALIAS)); String platform = utils.findPlatformFor(jcd.getSubProtocol(), jdbcDriver); jcd.setDbms(platform); jcd.setJdbcLevel(2.0); jcd.setDriver(jdbcDriver); if (username != null) { jcd.setUserName(username); jcd.setPassWord(password); } if ("default".equals(jcdAlias)) { jcd.setDefaultConnection(true); // arminw: MM will search for the default key // MetadataManager.getInstance().setDefaultPBKey(jcd.getPBKey()); } addDescriptor(jcd); return jcd; }
[ "public", "JdbcConnectionDescriptor", "addDescriptor", "(", "String", "jcdAlias", ",", "String", "jdbcDriver", ",", "String", "jdbcConnectionUrl", ",", "String", "username", ",", "String", "password", ")", "{", "JdbcConnectionDescriptor", "jcd", "=", "new", "JdbcConnectionDescriptor", "(", ")", ";", "HashMap", "props", "=", "utils", ".", "parseConnectionUrl", "(", "jdbcConnectionUrl", ")", ";", "jcd", ".", "setJcdAlias", "(", "jcdAlias", ")", ";", "jcd", ".", "setProtocol", "(", "(", "String", ")", "props", ".", "get", "(", "JdbcMetadataUtils", ".", "PROPERTY_PROTOCOL", ")", ")", ";", "jcd", ".", "setSubProtocol", "(", "(", "String", ")", "props", ".", "get", "(", "JdbcMetadataUtils", ".", "PROPERTY_SUBPROTOCOL", ")", ")", ";", "jcd", ".", "setDbAlias", "(", "(", "String", ")", "props", ".", "get", "(", "JdbcMetadataUtils", ".", "PROPERTY_DBALIAS", ")", ")", ";", "String", "platform", "=", "utils", ".", "findPlatformFor", "(", "jcd", ".", "getSubProtocol", "(", ")", ",", "jdbcDriver", ")", ";", "jcd", ".", "setDbms", "(", "platform", ")", ";", "jcd", ".", "setJdbcLevel", "(", "2.0", ")", ";", "jcd", ".", "setDriver", "(", "jdbcDriver", ")", ";", "if", "(", "username", "!=", "null", ")", "{", "jcd", ".", "setUserName", "(", "username", ")", ";", "jcd", ".", "setPassWord", "(", "password", ")", ";", "}", "if", "(", "\"default\"", ".", "equals", "(", "jcdAlias", ")", ")", "{", "jcd", ".", "setDefaultConnection", "(", "true", ")", ";", "// arminw: MM will search for the default key\r", "// MetadataManager.getInstance().setDefaultPBKey(jcd.getPBKey());\r", "}", "addDescriptor", "(", "jcd", ")", ";", "return", "jcd", ";", "}" ]
Creates and adds a new connection descriptor for the given JDBC connection url. This method tries to guess the platform to be used, but it should be checked afterwards nonetheless using the {@link JdbcConnectionDescriptor#getDbms()} method. For properties that are not part of the url, the following standard values are explicitly set: <ul> <li>jdbc level = 2.0</li> </ul> @param jcdAlias The connection alias for the created connection; if 'default' is used, then the new descriptor will become the default connection descriptor @param jdbcDriver The fully qualified jdbc driver name @param jdbcConnectionUrl The connection url of the form '[protocol]:[sub protocol]:{database-specific path]' where protocol is usually 'jdbc' @param username The user name (can be <code>null</code>) @param password The password (can be <code>null</code>) @return The created connection descriptor @see JdbcConnectionDescriptor#getDbms()
[ "Creates", "and", "adds", "a", "new", "connection", "descriptor", "for", "the", "given", "JDBC", "connection", "url", ".", "This", "method", "tries", "to", "guess", "the", "platform", "to", "be", "used", "but", "it", "should", "be", "checked", "afterwards", "nonetheless", "using", "the", "{", "@link", "JdbcConnectionDescriptor#getDbms", "()", "}", "method", ".", "For", "properties", "that", "are", "not", "part", "of", "the", "url", "the", "following", "standard", "values", "are", "explicitly", "set", ":", "<ul", ">", "<li", ">", "jdbc", "level", "=", "2", ".", "0<", "/", "li", ">", "<", "/", "ul", ">" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/metadata/ConnectionRepository.java#L153-L182
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/utility/Iterate.java
Iterate.sortThisBy
public static <T, V extends Comparable<? super V>, L extends List<T>> L sortThisBy(L list, Function<? super T, ? extends V> function) { """ Sort the list by comparing an attribute defined by the function. SortThisBy is a mutating method. The List passed in is also returned. """ return Iterate.sortThis(list, Comparators.byFunction(function)); }
java
public static <T, V extends Comparable<? super V>, L extends List<T>> L sortThisBy(L list, Function<? super T, ? extends V> function) { return Iterate.sortThis(list, Comparators.byFunction(function)); }
[ "public", "static", "<", "T", ",", "V", "extends", "Comparable", "<", "?", "super", "V", ">", ",", "L", "extends", "List", "<", "T", ">", ">", "L", "sortThisBy", "(", "L", "list", ",", "Function", "<", "?", "super", "T", ",", "?", "extends", "V", ">", "function", ")", "{", "return", "Iterate", ".", "sortThis", "(", "list", ",", "Comparators", ".", "byFunction", "(", "function", ")", ")", ";", "}" ]
Sort the list by comparing an attribute defined by the function. SortThisBy is a mutating method. The List passed in is also returned.
[ "Sort", "the", "list", "by", "comparing", "an", "attribute", "defined", "by", "the", "function", ".", "SortThisBy", "is", "a", "mutating", "method", ".", "The", "List", "passed", "in", "is", "also", "returned", "." ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/Iterate.java#L919-L922
Jasig/uPortal
uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/ReferenceEntityLockService.java
ReferenceEntityLockService.convert
@Override public void convert(IEntityLock lock, int newType) throws LockingException { """ Attempts to change the lock's <code>lockType</code> to <code>newType</code>. @param lock IEntityLock @param newType int @exception org.apereo.portal.concurrency.LockingException """ convert(lock, newType, defaultLockPeriod); }
java
@Override public void convert(IEntityLock lock, int newType) throws LockingException { convert(lock, newType, defaultLockPeriod); }
[ "@", "Override", "public", "void", "convert", "(", "IEntityLock", "lock", ",", "int", "newType", ")", "throws", "LockingException", "{", "convert", "(", "lock", ",", "newType", ",", "defaultLockPeriod", ")", ";", "}" ]
Attempts to change the lock's <code>lockType</code> to <code>newType</code>. @param lock IEntityLock @param newType int @exception org.apereo.portal.concurrency.LockingException
[ "Attempts", "to", "change", "the", "lock", "s", "<code", ">", "lockType<", "/", "code", ">", "to", "<code", ">", "newType<", "/", "code", ">", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/ReferenceEntityLockService.java#L63-L66
anotheria/moskito
moskito-webui/src/main/java/net/anotheria/moskito/webui/shared/bean/AlertBean.java
AlertBean.createDismissible
public static AlertBean createDismissible(AlertType type, String message) { """ Creates default alert as in {@link #create(AlertType, String)} with dismiss functionality. """ final AlertBean result = create(type, message); result.setDismissible(true); return result; }
java
public static AlertBean createDismissible(AlertType type, String message) { final AlertBean result = create(type, message); result.setDismissible(true); return result; }
[ "public", "static", "AlertBean", "createDismissible", "(", "AlertType", "type", ",", "String", "message", ")", "{", "final", "AlertBean", "result", "=", "create", "(", "type", ",", "message", ")", ";", "result", ".", "setDismissible", "(", "true", ")", ";", "return", "result", ";", "}" ]
Creates default alert as in {@link #create(AlertType, String)} with dismiss functionality.
[ "Creates", "default", "alert", "as", "in", "{" ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-webui/src/main/java/net/anotheria/moskito/webui/shared/bean/AlertBean.java#L75-L79
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/Marshaller.java
Marshaller.initializeEmbedded
private static Object initializeEmbedded(EmbeddedMetadata embeddedMetadata, Object target) { """ Initializes the Embedded object represented by the given metadata. @param embeddedMetadata the metadata of the embedded field @param target the object in which the embedded field is declared/accessible from @return the initialized object @throws EntityManagerException if any error occurs during initialization of the embedded object """ try { // If instantiation of Entity instantiated the embeddable, we will // use the pre-initialized embedded object. Object embeddedObject = embeddedMetadata.getReadMethod().invoke(target); if (embeddedObject == null) { // Otherwise, we will instantiate the embedded object, which // could be a Builder embeddedObject = IntrospectionUtils.instantiate(embeddedMetadata); ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); if (constructorMetadata.isBuilderConstructionStrategy()) { // Build the Builder embeddedObject = constructorMetadata.getBuildMethodHandle().invoke(embeddedObject); } else { // TODO we should not be doing this?? There is no equivalent // of this for builder pattern embeddedMetadata.getWriteMethod().invoke(target, embeddedObject); } } return embeddedObject; } catch (Throwable t) { throw new EntityManagerException(t); } }
java
private static Object initializeEmbedded(EmbeddedMetadata embeddedMetadata, Object target) { try { // If instantiation of Entity instantiated the embeddable, we will // use the pre-initialized embedded object. Object embeddedObject = embeddedMetadata.getReadMethod().invoke(target); if (embeddedObject == null) { // Otherwise, we will instantiate the embedded object, which // could be a Builder embeddedObject = IntrospectionUtils.instantiate(embeddedMetadata); ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); if (constructorMetadata.isBuilderConstructionStrategy()) { // Build the Builder embeddedObject = constructorMetadata.getBuildMethodHandle().invoke(embeddedObject); } else { // TODO we should not be doing this?? There is no equivalent // of this for builder pattern embeddedMetadata.getWriteMethod().invoke(target, embeddedObject); } } return embeddedObject; } catch (Throwable t) { throw new EntityManagerException(t); } }
[ "private", "static", "Object", "initializeEmbedded", "(", "EmbeddedMetadata", "embeddedMetadata", ",", "Object", "target", ")", "{", "try", "{", "// If instantiation of Entity instantiated the embeddable, we will", "// use the pre-initialized embedded object.", "Object", "embeddedObject", "=", "embeddedMetadata", ".", "getReadMethod", "(", ")", ".", "invoke", "(", "target", ")", ";", "if", "(", "embeddedObject", "==", "null", ")", "{", "// Otherwise, we will instantiate the embedded object, which", "// could be a Builder", "embeddedObject", "=", "IntrospectionUtils", ".", "instantiate", "(", "embeddedMetadata", ")", ";", "ConstructorMetadata", "constructorMetadata", "=", "embeddedMetadata", ".", "getConstructorMetadata", "(", ")", ";", "if", "(", "constructorMetadata", ".", "isBuilderConstructionStrategy", "(", ")", ")", "{", "// Build the Builder", "embeddedObject", "=", "constructorMetadata", ".", "getBuildMethodHandle", "(", ")", ".", "invoke", "(", "embeddedObject", ")", ";", "}", "else", "{", "// TODO we should not be doing this?? There is no equivalent", "// of this for builder pattern", "embeddedMetadata", ".", "getWriteMethod", "(", ")", ".", "invoke", "(", "target", ",", "embeddedObject", ")", ";", "}", "}", "return", "embeddedObject", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "throw", "new", "EntityManagerException", "(", "t", ")", ";", "}", "}" ]
Initializes the Embedded object represented by the given metadata. @param embeddedMetadata the metadata of the embedded field @param target the object in which the embedded field is declared/accessible from @return the initialized object @throws EntityManagerException if any error occurs during initialization of the embedded object
[ "Initializes", "the", "Embedded", "object", "represented", "by", "the", "given", "metadata", "." ]
train
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/Marshaller.java#L650-L673