repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
unbescape/unbescape
src/main/java/org/unbescape/uri/UriEscape.java
UriEscape.unescapeUriQueryParam
public static void unescapeUriQueryParam(final Reader reader, final Writer writer, final String encoding) throws IOException { """ <p> Perform am URI query parameter (name or value) <strong>unescape</strong> operation on a <tt>Reader</tt> input, writing results to a <tt>Writer</tt>. </p> <p> This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input, even for those characters that do not need to be percent-encoded in this context (unreserved characters can be percent-encoded even if/when this is not required, though it is not generally considered a good practice). </p> <p> This method will use specified <tt>encoding</tt> in order to determine the characters specified in the percent-encoded byte sequences. </p> <p> This method is <strong>thread-safe</strong>. </p> @param reader the <tt>Reader</tt> reading the text to be unescaped. @param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @param encoding the encoding to be used for unescaping. @throws IOException if an input/output exception occurs @since 1.1.2 """ if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } if (encoding == null) { throw new IllegalArgumentException("Argument 'encoding' cannot be null"); } UriEscapeUtil.unescape(reader, writer, UriEscapeUtil.UriEscapeType.QUERY_PARAM, encoding); }
java
public static void unescapeUriQueryParam(final Reader reader, final Writer writer, final String encoding) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } if (encoding == null) { throw new IllegalArgumentException("Argument 'encoding' cannot be null"); } UriEscapeUtil.unescape(reader, writer, UriEscapeUtil.UriEscapeType.QUERY_PARAM, encoding); }
[ "public", "static", "void", "unescapeUriQueryParam", "(", "final", "Reader", "reader", ",", "final", "Writer", "writer", ",", "final", "String", "encoding", ")", "throws", "IOException", "{", "if", "(", "writer", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Argument 'writer' cannot be null\"", ")", ";", "}", "if", "(", "encoding", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Argument 'encoding' cannot be null\"", ")", ";", "}", "UriEscapeUtil", ".", "unescape", "(", "reader", ",", "writer", ",", "UriEscapeUtil", ".", "UriEscapeType", ".", "QUERY_PARAM", ",", "encoding", ")", ";", "}" ]
<p> Perform am URI query parameter (name or value) <strong>unescape</strong> operation on a <tt>Reader</tt> input, writing results to a <tt>Writer</tt>. </p> <p> This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input, even for those characters that do not need to be percent-encoded in this context (unreserved characters can be percent-encoded even if/when this is not required, though it is not generally considered a good practice). </p> <p> This method will use specified <tt>encoding</tt> in order to determine the characters specified in the percent-encoded byte sequences. </p> <p> This method is <strong>thread-safe</strong>. </p> @param reader the <tt>Reader</tt> reading the text to be unescaped. @param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @param encoding the encoding to be used for unescaping. @throws IOException if an input/output exception occurs @since 1.1.2
[ "<p", ">", "Perform", "am", "URI", "query", "parameter", "(", "name", "or", "value", ")", "<strong", ">", "unescape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "Reader<", "/", "tt", ">", "input", "writing", "results", "to", "a", "<tt", ">", "Writer<", "/", "tt", ">", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "will", "unescape", "every", "percent", "-", "encoded", "(", "<tt", ">", "%HH<", "/", "tt", ">", ")", "sequences", "present", "in", "input", "even", "for", "those", "characters", "that", "do", "not", "need", "to", "be", "percent", "-", "encoded", "in", "this", "context", "(", "unreserved", "characters", "can", "be", "percent", "-", "encoded", "even", "if", "/", "when", "this", "is", "not", "required", "though", "it", "is", "not", "generally", "considered", "a", "good", "practice", ")", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "will", "use", "specified", "<tt", ">", "encoding<", "/", "tt", ">", "in", "order", "to", "determine", "the", "characters", "specified", "in", "the", "percent", "-", "encoded", "byte", "sequences", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "is", "<strong", ">", "thread", "-", "safe<", "/", "strong", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L2295-L2308
matthewhorridge/binaryowl
src/main/java/org/semanticweb/binaryowl/BinaryOWLMetadata.java
BinaryOWLMetadata.setOWLObjectListAttribute
public void setOWLObjectListAttribute(String name, List<OWLObject> value) { """ Sets the {@link OWLObject} list values for an attribute. @param name The name of the attribute. Not null. @param value The value of the attribute. Not null. @throws NullPointerException if name is null or value is null. """ if(value == null) { throw new NullPointerException("value must not be null"); } List<OWLObject> valueCopy = new ArrayList<OWLObject>(value); setValue(owlObjectAttributes, name, valueCopy); }
java
public void setOWLObjectListAttribute(String name, List<OWLObject> value) { if(value == null) { throw new NullPointerException("value must not be null"); } List<OWLObject> valueCopy = new ArrayList<OWLObject>(value); setValue(owlObjectAttributes, name, valueCopy); }
[ "public", "void", "setOWLObjectListAttribute", "(", "String", "name", ",", "List", "<", "OWLObject", ">", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"value must not be null\"", ")", ";", "}", "List", "<", "OWLObject", ">", "valueCopy", "=", "new", "ArrayList", "<", "OWLObject", ">", "(", "value", ")", ";", "setValue", "(", "owlObjectAttributes", ",", "name", ",", "valueCopy", ")", ";", "}" ]
Sets the {@link OWLObject} list values for an attribute. @param name The name of the attribute. Not null. @param value The value of the attribute. Not null. @throws NullPointerException if name is null or value is null.
[ "Sets", "the", "{" ]
train
https://github.com/matthewhorridge/binaryowl/blob/7fccfe804120f86b38ca855ddbb569a81a042257/src/main/java/org/semanticweb/binaryowl/BinaryOWLMetadata.java#L471-L477
alkacon/opencms-core
src-gwt/org/opencms/ade/sitemap/client/control/CmsSitemapController.java
CmsSitemapController.loadPath
public void loadPath(final String sitePath, final AsyncCallback<CmsClientSitemapEntry> callback) { """ Loads the sitemap entry for the given site path.<p> @param sitePath the site path @param callback the callback """ loadPath(sitePath, false, callback); }
java
public void loadPath(final String sitePath, final AsyncCallback<CmsClientSitemapEntry> callback) { loadPath(sitePath, false, callback); }
[ "public", "void", "loadPath", "(", "final", "String", "sitePath", ",", "final", "AsyncCallback", "<", "CmsClientSitemapEntry", ">", "callback", ")", "{", "loadPath", "(", "sitePath", ",", "false", ",", "callback", ")", ";", "}" ]
Loads the sitemap entry for the given site path.<p> @param sitePath the site path @param callback the callback
[ "Loads", "the", "sitemap", "entry", "for", "the", "given", "site", "path", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/control/CmsSitemapController.java#L1571-L1574
alkacon/opencms-core
src/org/opencms/configuration/preferences/CmsStartViewPreference.java
CmsStartViewPreference.getViewSelectOptions
public static SelectOptions getViewSelectOptions(CmsObject cms, String value) { """ Gets the select options for the view selector.<p> @param cms the CMS context @param value the current value @return the select options """ Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); List<String> options = new ArrayList<String>(); List<String> values = new ArrayList<String>(); int selectedIndex = 0; List<I_CmsWorkplaceAppConfiguration> apps = OpenCms.getWorkplaceAppManager().getDefaultQuickLaunchConfigurations(); for (I_CmsWorkplaceAppConfiguration app : apps) { if (OpenCms.getRoleManager().hasRole( cms, cms.getRequestContext().getCurrentUser().getName(), app.getRequiredRole())) { values.add(app.getId()); options.add(app.getName(locale)); } } SelectOptions optionBean = new SelectOptions(options, values, selectedIndex); return optionBean; }
java
public static SelectOptions getViewSelectOptions(CmsObject cms, String value) { Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); List<String> options = new ArrayList<String>(); List<String> values = new ArrayList<String>(); int selectedIndex = 0; List<I_CmsWorkplaceAppConfiguration> apps = OpenCms.getWorkplaceAppManager().getDefaultQuickLaunchConfigurations(); for (I_CmsWorkplaceAppConfiguration app : apps) { if (OpenCms.getRoleManager().hasRole( cms, cms.getRequestContext().getCurrentUser().getName(), app.getRequiredRole())) { values.add(app.getId()); options.add(app.getName(locale)); } } SelectOptions optionBean = new SelectOptions(options, values, selectedIndex); return optionBean; }
[ "public", "static", "SelectOptions", "getViewSelectOptions", "(", "CmsObject", "cms", ",", "String", "value", ")", "{", "Locale", "locale", "=", "OpenCms", ".", "getWorkplaceManager", "(", ")", ".", "getWorkplaceLocale", "(", "cms", ")", ";", "List", "<", "String", ">", "options", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "List", "<", "String", ">", "values", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "int", "selectedIndex", "=", "0", ";", "List", "<", "I_CmsWorkplaceAppConfiguration", ">", "apps", "=", "OpenCms", ".", "getWorkplaceAppManager", "(", ")", ".", "getDefaultQuickLaunchConfigurations", "(", ")", ";", "for", "(", "I_CmsWorkplaceAppConfiguration", "app", ":", "apps", ")", "{", "if", "(", "OpenCms", ".", "getRoleManager", "(", ")", ".", "hasRole", "(", "cms", ",", "cms", ".", "getRequestContext", "(", ")", ".", "getCurrentUser", "(", ")", ".", "getName", "(", ")", ",", "app", ".", "getRequiredRole", "(", ")", ")", ")", "{", "values", ".", "add", "(", "app", ".", "getId", "(", ")", ")", ";", "options", ".", "add", "(", "app", ".", "getName", "(", "locale", ")", ")", ";", "}", "}", "SelectOptions", "optionBean", "=", "new", "SelectOptions", "(", "options", ",", "values", ",", "selectedIndex", ")", ";", "return", "optionBean", ";", "}" ]
Gets the select options for the view selector.<p> @param cms the CMS context @param value the current value @return the select options
[ "Gets", "the", "select", "options", "for", "the", "view", "selector", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/configuration/preferences/CmsStartViewPreference.java#L73-L95
dkmfbk/knowledgestore
ks-core/src/main/java/eu/fbk/knowledgestore/data/Record.java
Record.getUnique
@SuppressWarnings("unchecked") @Nullable public <T> T getUnique(final URI property, final Class<T> valueClass) throws IllegalStateException, IllegalArgumentException { """ Returns the unique value of the property converted to an instance of a certain class, or null if the property has no value. Note that this method fails if the property has multiple values or its unique value cannot be converted to the requested class; if this is not the desired behavior, use {@link #getUnique(URI, Class, Object)} supplying an appropriate default value to be returned in case of failure. @param property the property to read @param valueClass the class to convert the value to @param <T> the type of result @return the unique value of the property, converted to the class specified; null if the property has no value @throws IllegalStateException in case the property has multiple values @throws IllegalArgumentException in case the unique property value cannot be converted to the class specified """ final Object result; synchronized (this) { result = doGet(property, valueClass); } if (result == null) { return null; } else if (result instanceof List<?>) { final List<T> list = (List<T>) result; final StringBuilder builder = new StringBuilder("Expected one value for property ") .append(property).append(", found ").append(list.size()).append(" values: "); for (int i = 0; i < Math.min(3, list.size()); ++i) { builder.append(i > 0 ? ", " : "").append(list.get(i)); } builder.append(list.size() > 3 ? ", ..." : ""); throw new IllegalStateException(builder.toString()); } else { return (T) result; } }
java
@SuppressWarnings("unchecked") @Nullable public <T> T getUnique(final URI property, final Class<T> valueClass) throws IllegalStateException, IllegalArgumentException { final Object result; synchronized (this) { result = doGet(property, valueClass); } if (result == null) { return null; } else if (result instanceof List<?>) { final List<T> list = (List<T>) result; final StringBuilder builder = new StringBuilder("Expected one value for property ") .append(property).append(", found ").append(list.size()).append(" values: "); for (int i = 0; i < Math.min(3, list.size()); ++i) { builder.append(i > 0 ? ", " : "").append(list.get(i)); } builder.append(list.size() > 3 ? ", ..." : ""); throw new IllegalStateException(builder.toString()); } else { return (T) result; } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Nullable", "public", "<", "T", ">", "T", "getUnique", "(", "final", "URI", "property", ",", "final", "Class", "<", "T", ">", "valueClass", ")", "throws", "IllegalStateException", ",", "IllegalArgumentException", "{", "final", "Object", "result", ";", "synchronized", "(", "this", ")", "{", "result", "=", "doGet", "(", "property", ",", "valueClass", ")", ";", "}", "if", "(", "result", "==", "null", ")", "{", "return", "null", ";", "}", "else", "if", "(", "result", "instanceof", "List", "<", "?", ">", ")", "{", "final", "List", "<", "T", ">", "list", "=", "(", "List", "<", "T", ">", ")", "result", ";", "final", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", "\"Expected one value for property \"", ")", ".", "append", "(", "property", ")", ".", "append", "(", "\", found \"", ")", ".", "append", "(", "list", ".", "size", "(", ")", ")", ".", "append", "(", "\" values: \"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "Math", ".", "min", "(", "3", ",", "list", ".", "size", "(", ")", ")", ";", "++", "i", ")", "{", "builder", ".", "append", "(", "i", ">", "0", "?", "\", \"", ":", "\"\"", ")", ".", "append", "(", "list", ".", "get", "(", "i", ")", ")", ";", "}", "builder", ".", "append", "(", "list", ".", "size", "(", ")", ">", "3", "?", "\", ...\"", ":", "\"\"", ")", ";", "throw", "new", "IllegalStateException", "(", "builder", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "return", "(", "T", ")", "result", ";", "}", "}" ]
Returns the unique value of the property converted to an instance of a certain class, or null if the property has no value. Note that this method fails if the property has multiple values or its unique value cannot be converted to the requested class; if this is not the desired behavior, use {@link #getUnique(URI, Class, Object)} supplying an appropriate default value to be returned in case of failure. @param property the property to read @param valueClass the class to convert the value to @param <T> the type of result @return the unique value of the property, converted to the class specified; null if the property has no value @throws IllegalStateException in case the property has multiple values @throws IllegalArgumentException in case the unique property value cannot be converted to the class specified
[ "Returns", "the", "unique", "value", "of", "the", "property", "converted", "to", "an", "instance", "of", "a", "certain", "class", "or", "null", "if", "the", "property", "has", "no", "value", ".", "Note", "that", "this", "method", "fails", "if", "the", "property", "has", "multiple", "values", "or", "its", "unique", "value", "cannot", "be", "converted", "to", "the", "requested", "class", ";", "if", "this", "is", "not", "the", "desired", "behavior", "use", "{", "@link", "#getUnique", "(", "URI", "Class", "Object", ")", "}", "supplying", "an", "appropriate", "default", "value", "to", "be", "returned", "in", "case", "of", "failure", "." ]
train
https://github.com/dkmfbk/knowledgestore/blob/a548101b1dd67fcf72a1ec6f838ea7539bdbbe7a/ks-core/src/main/java/eu/fbk/knowledgestore/data/Record.java#L514-L536
OpenLiberty/open-liberty
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/application/NavigationHandlerImpl.java
NavigationHandlerImpl.createNavigationCase
private NavigationCase createNavigationCase(String fromViewId, String outcome, String toViewId) { """ Derive a NavigationCase from a flow node. @param flowNode @return """ return new NavigationCase(fromViewId, null, outcome, null, toViewId, null, false, false); }
java
private NavigationCase createNavigationCase(String fromViewId, String outcome, String toViewId) { return new NavigationCase(fromViewId, null, outcome, null, toViewId, null, false, false); }
[ "private", "NavigationCase", "createNavigationCase", "(", "String", "fromViewId", ",", "String", "outcome", ",", "String", "toViewId", ")", "{", "return", "new", "NavigationCase", "(", "fromViewId", ",", "null", ",", "outcome", ",", "null", ",", "toViewId", ",", "null", ",", "false", ",", "false", ")", ";", "}" ]
Derive a NavigationCase from a flow node. @param flowNode @return
[ "Derive", "a", "NavigationCase", "from", "a", "flow", "node", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/application/NavigationHandlerImpl.java#L941-L944
jronrun/benayn
benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Retryer.java
Retryer.exponentialWait
public Retryer<R> exponentialWait(final long multiplier, final long maximumWait) { """ Sets the wait strategy which sleeps for an exponential amount of time after the first failed attempt, and in exponentially incrementing amounts after each failed attempt up to the maximumTime. The wait time between the retries can be controlled by the multiplier. nextWaitTime = exponentialIncrement * {@code multiplier}. @param multiplier @param maximumTime the unit of the maximumTime is {@link TimeUnit#MILLISECONDS} @return """ checkArgument(multiplier > 0L, "multiplier must be > 0 but is %d", multiplier); checkArgument(maximumWait >= 0L, "maximumWait must be >= 0 but is %d", maximumWait); checkArgument(multiplier < maximumWait, "multiplier must be < maximumWait but is %d", multiplier); return withWaitStrategy(new WaitStrategy() { @Override public long computeSleepTime(int previousAttemptNumber, long delaySinceFirstAttemptInMillis) { double exp = Math.pow(2, previousAttemptNumber); long result = Math.round(multiplier * exp); if (result > maximumWait) { result = maximumWait; } return result >= 0L ? result : 0L; } }); }
java
public Retryer<R> exponentialWait(final long multiplier, final long maximumWait) { checkArgument(multiplier > 0L, "multiplier must be > 0 but is %d", multiplier); checkArgument(maximumWait >= 0L, "maximumWait must be >= 0 but is %d", maximumWait); checkArgument(multiplier < maximumWait, "multiplier must be < maximumWait but is %d", multiplier); return withWaitStrategy(new WaitStrategy() { @Override public long computeSleepTime(int previousAttemptNumber, long delaySinceFirstAttemptInMillis) { double exp = Math.pow(2, previousAttemptNumber); long result = Math.round(multiplier * exp); if (result > maximumWait) { result = maximumWait; } return result >= 0L ? result : 0L; } }); }
[ "public", "Retryer", "<", "R", ">", "exponentialWait", "(", "final", "long", "multiplier", ",", "final", "long", "maximumWait", ")", "{", "checkArgument", "(", "multiplier", ">", "0L", ",", "\"multiplier must be > 0 but is %d\"", ",", "multiplier", ")", ";", "checkArgument", "(", "maximumWait", ">=", "0L", ",", "\"maximumWait must be >= 0 but is %d\"", ",", "maximumWait", ")", ";", "checkArgument", "(", "multiplier", "<", "maximumWait", ",", "\"multiplier must be < maximumWait but is %d\"", ",", "multiplier", ")", ";", "return", "withWaitStrategy", "(", "new", "WaitStrategy", "(", ")", "{", "@", "Override", "public", "long", "computeSleepTime", "(", "int", "previousAttemptNumber", ",", "long", "delaySinceFirstAttemptInMillis", ")", "{", "double", "exp", "=", "Math", ".", "pow", "(", "2", ",", "previousAttemptNumber", ")", ";", "long", "result", "=", "Math", ".", "round", "(", "multiplier", "*", "exp", ")", ";", "if", "(", "result", ">", "maximumWait", ")", "{", "result", "=", "maximumWait", ";", "}", "return", "result", ">=", "0L", "?", "result", ":", "0L", ";", "}", "}", ")", ";", "}" ]
Sets the wait strategy which sleeps for an exponential amount of time after the first failed attempt, and in exponentially incrementing amounts after each failed attempt up to the maximumTime. The wait time between the retries can be controlled by the multiplier. nextWaitTime = exponentialIncrement * {@code multiplier}. @param multiplier @param maximumTime the unit of the maximumTime is {@link TimeUnit#MILLISECONDS} @return
[ "Sets", "the", "wait", "strategy", "which", "sleeps", "for", "an", "exponential", "amount", "of", "time", "after", "the", "first", "failed", "attempt", "and", "in", "exponentially", "incrementing", "amounts", "after", "each", "failed", "attempt", "up", "to", "the", "maximumTime", ".", "The", "wait", "time", "between", "the", "retries", "can", "be", "controlled", "by", "the", "multiplier", ".", "nextWaitTime", "=", "exponentialIncrement", "*", "{", "@code", "multiplier", "}", "." ]
train
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Retryer.java#L506-L522
authlete/authlete-java-common
src/main/java/com/authlete/common/dto/BackchannelAuthenticationRequest.java
BackchannelAuthenticationRequest.setParameters
public BackchannelAuthenticationRequest setParameters(Map<String, String[]> parameters) { """ Set the value of {@code parameters} which are the request parameters that the backchannel authentication endpoint of the OpenID provider implementation received from the client application. <p> This method converts the given map into a string in {@code application/x-www-form-urlencoded} and passes it to {@link #setParameters(String)} method. </p> @param parameters Request parameters. @return {@code this} object. """ return setParameters(URLCoder.formUrlEncode(parameters)); }
java
public BackchannelAuthenticationRequest setParameters(Map<String, String[]> parameters) { return setParameters(URLCoder.formUrlEncode(parameters)); }
[ "public", "BackchannelAuthenticationRequest", "setParameters", "(", "Map", "<", "String", ",", "String", "[", "]", ">", "parameters", ")", "{", "return", "setParameters", "(", "URLCoder", ".", "formUrlEncode", "(", "parameters", ")", ")", ";", "}" ]
Set the value of {@code parameters} which are the request parameters that the backchannel authentication endpoint of the OpenID provider implementation received from the client application. <p> This method converts the given map into a string in {@code application/x-www-form-urlencoded} and passes it to {@link #setParameters(String)} method. </p> @param parameters Request parameters. @return {@code this} object.
[ "Set", "the", "value", "of", "{", "@code", "parameters", "}", "which", "are", "the", "request", "parameters", "that", "the", "backchannel", "authentication", "endpoint", "of", "the", "OpenID", "provider", "implementation", "received", "from", "the", "client", "application", "." ]
train
https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/dto/BackchannelAuthenticationRequest.java#L192-L195
hawkular/hawkular-apm
server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java
ElasticsearchClient.createIndex
private boolean createIndex(String index, Map<String, Object> defaultSettings) { """ Check if index is created. if not it will created it @param index The index @return returns true if it just created the index. False if the index already existed """ IndicesExistsResponse res = client.admin().indices().prepareExists(index).execute().actionGet(); boolean created = false; if (!res.isExists()) { CreateIndexRequestBuilder req = client.admin().indices().prepareCreate(index); req.setSettings(defaultSettings); created = req.execute().actionGet().isAcknowledged(); if (!created) { throw new RuntimeException("Could not create index [" + index + "]"); } } return created; }
java
private boolean createIndex(String index, Map<String, Object> defaultSettings) { IndicesExistsResponse res = client.admin().indices().prepareExists(index).execute().actionGet(); boolean created = false; if (!res.isExists()) { CreateIndexRequestBuilder req = client.admin().indices().prepareCreate(index); req.setSettings(defaultSettings); created = req.execute().actionGet().isAcknowledged(); if (!created) { throw new RuntimeException("Could not create index [" + index + "]"); } } return created; }
[ "private", "boolean", "createIndex", "(", "String", "index", ",", "Map", "<", "String", ",", "Object", ">", "defaultSettings", ")", "{", "IndicesExistsResponse", "res", "=", "client", ".", "admin", "(", ")", ".", "indices", "(", ")", ".", "prepareExists", "(", "index", ")", ".", "execute", "(", ")", ".", "actionGet", "(", ")", ";", "boolean", "created", "=", "false", ";", "if", "(", "!", "res", ".", "isExists", "(", ")", ")", "{", "CreateIndexRequestBuilder", "req", "=", "client", ".", "admin", "(", ")", ".", "indices", "(", ")", ".", "prepareCreate", "(", "index", ")", ";", "req", ".", "setSettings", "(", "defaultSettings", ")", ";", "created", "=", "req", ".", "execute", "(", ")", ".", "actionGet", "(", ")", ".", "isAcknowledged", "(", ")", ";", "if", "(", "!", "created", ")", "{", "throw", "new", "RuntimeException", "(", "\"Could not create index [\"", "+", "index", "+", "\"]\"", ")", ";", "}", "}", "return", "created", ";", "}" ]
Check if index is created. if not it will created it @param index The index @return returns true if it just created the index. False if the index already existed
[ "Check", "if", "index", "is", "created", ".", "if", "not", "it", "will", "created", "it" ]
train
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/ElasticsearchClient.java#L315-L328
f2prateek/progressbutton
progressbutton/src/main/java/com/f2prateek/progressbutton/ProgressButton.java
ProgressButton.setProgressAndMax
public void setProgressAndMax(int progress, int max) { """ Sets the current progress and maximum progress value, both of which must be valid values. @see #setMax(int) @see #setProgress(int) """ if (progress > max || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, max)); } else if (max <= 0) { throw new IllegalArgumentException(String.format("Max (%d) must be > 0", max)); } mProgress = progress; mMax = max; invalidate(); }
java
public void setProgressAndMax(int progress, int max) { if (progress > max || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, max)); } else if (max <= 0) { throw new IllegalArgumentException(String.format("Max (%d) must be > 0", max)); } mProgress = progress; mMax = max; invalidate(); }
[ "public", "void", "setProgressAndMax", "(", "int", "progress", ",", "int", "max", ")", "{", "if", "(", "progress", ">", "max", "||", "progress", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Progress (%d) must be between %d and %d\"", ",", "progress", ",", "0", ",", "max", ")", ")", ";", "}", "else", "if", "(", "max", "<=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Max (%d) must be > 0\"", ",", "max", ")", ")", ";", "}", "mProgress", "=", "progress", ";", "mMax", "=", "max", ";", "invalidate", "(", ")", ";", "}" ]
Sets the current progress and maximum progress value, both of which must be valid values. @see #setMax(int) @see #setProgress(int)
[ "Sets", "the", "current", "progress", "and", "maximum", "progress", "value", "both", "of", "which", "must", "be", "valid", "values", "." ]
train
https://github.com/f2prateek/progressbutton/blob/ca47a9676173cdab5b2d8063a947ed2cc3c7641d/progressbutton/src/main/java/com/f2prateek/progressbutton/ProgressButton.java#L226-L237
prestodb/presto
presto-main/src/main/java/com/facebook/presto/operator/scalar/ColorFunctions.java
ColorFunctions.toAnsi
private static int toAnsi(int red, int green, int blue) { """ Convert the given color (rgb or system) to an ansi-compatible index (for use with ESC[38;5;<value>m) """ // rescale to 0-5 range red = red * 6 / 256; green = green * 6 / 256; blue = blue * 6 / 256; return 16 + red * 36 + green * 6 + blue; }
java
private static int toAnsi(int red, int green, int blue) { // rescale to 0-5 range red = red * 6 / 256; green = green * 6 / 256; blue = blue * 6 / 256; return 16 + red * 36 + green * 6 + blue; }
[ "private", "static", "int", "toAnsi", "(", "int", "red", ",", "int", "green", ",", "int", "blue", ")", "{", "// rescale to 0-5 range", "red", "=", "red", "*", "6", "/", "256", ";", "green", "=", "green", "*", "6", "/", "256", ";", "blue", "=", "blue", "*", "6", "/", "256", ";", "return", "16", "+", "red", "*", "36", "+", "green", "*", "6", "+", "blue", ";", "}" ]
Convert the given color (rgb or system) to an ansi-compatible index (for use with ESC[38;5;<value>m)
[ "Convert", "the", "given", "color", "(", "rgb", "or", "system", ")", "to", "an", "ansi", "-", "compatible", "index", "(", "for", "use", "with", "ESC", "[", "38", ";", "5", ";", "<value", ">", "m", ")" ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-main/src/main/java/com/facebook/presto/operator/scalar/ColorFunctions.java#L249-L257
dashorst/wicket-stuff-markup-validator
isorelax/src/main/java/org/iso_relax/dispatcher/impl/AbstractSchemaProviderImpl.java
AbstractSchemaProviderImpl.addSchema
public void addSchema( String uri, IslandSchema s ) { """ adds a new IslandSchema. the caller should make sure that the given uri is not defined already. """ if( schemata.containsKey(uri) ) throw new IllegalArgumentException(); schemata.put( uri, s ); }
java
public void addSchema( String uri, IslandSchema s ) { if( schemata.containsKey(uri) ) throw new IllegalArgumentException(); schemata.put( uri, s ); }
[ "public", "void", "addSchema", "(", "String", "uri", ",", "IslandSchema", "s", ")", "{", "if", "(", "schemata", ".", "containsKey", "(", "uri", ")", ")", "throw", "new", "IllegalArgumentException", "(", ")", ";", "schemata", ".", "put", "(", "uri", ",", "s", ")", ";", "}" ]
adds a new IslandSchema. the caller should make sure that the given uri is not defined already.
[ "adds", "a", "new", "IslandSchema", "." ]
train
https://github.com/dashorst/wicket-stuff-markup-validator/blob/9e529a4dc8bfdbbe4c794f3132ef400a006560a1/isorelax/src/main/java/org/iso_relax/dispatcher/impl/AbstractSchemaProviderImpl.java#L49-L53
spring-projects/spring-security-oauth
spring-security-oauth/src/main/java/org/springframework/security/oauth/provider/filter/CoreOAuthProviderSupport.java
CoreOAuthProviderSupport.normalizeUrl
protected String normalizeUrl(String url) { """ Normalize the URL for use in the signature. The OAuth spec says the URL protocol and host are to be lower-case, and the query and fragments are to be stripped. @param url The URL. @return The URL normalized for use in the signature. """ try { URL requestURL = new URL(url); StringBuilder normalized = new StringBuilder(requestURL.getProtocol().toLowerCase()).append("://").append(requestURL.getHost().toLowerCase()); if ((requestURL.getPort() >= 0) && (requestURL.getPort() != requestURL.getDefaultPort())) { normalized.append(":").append(requestURL.getPort()); } normalized.append(requestURL.getPath()); return normalized.toString(); } catch (MalformedURLException e) { throw new IllegalStateException("Illegal URL for calculating the OAuth signature.", e); } }
java
protected String normalizeUrl(String url) { try { URL requestURL = new URL(url); StringBuilder normalized = new StringBuilder(requestURL.getProtocol().toLowerCase()).append("://").append(requestURL.getHost().toLowerCase()); if ((requestURL.getPort() >= 0) && (requestURL.getPort() != requestURL.getDefaultPort())) { normalized.append(":").append(requestURL.getPort()); } normalized.append(requestURL.getPath()); return normalized.toString(); } catch (MalformedURLException e) { throw new IllegalStateException("Illegal URL for calculating the OAuth signature.", e); } }
[ "protected", "String", "normalizeUrl", "(", "String", "url", ")", "{", "try", "{", "URL", "requestURL", "=", "new", "URL", "(", "url", ")", ";", "StringBuilder", "normalized", "=", "new", "StringBuilder", "(", "requestURL", ".", "getProtocol", "(", ")", ".", "toLowerCase", "(", ")", ")", ".", "append", "(", "\"://\"", ")", ".", "append", "(", "requestURL", ".", "getHost", "(", ")", ".", "toLowerCase", "(", ")", ")", ";", "if", "(", "(", "requestURL", ".", "getPort", "(", ")", ">=", "0", ")", "&&", "(", "requestURL", ".", "getPort", "(", ")", "!=", "requestURL", ".", "getDefaultPort", "(", ")", ")", ")", "{", "normalized", ".", "append", "(", "\":\"", ")", ".", "append", "(", "requestURL", ".", "getPort", "(", ")", ")", ";", "}", "normalized", ".", "append", "(", "requestURL", ".", "getPath", "(", ")", ")", ";", "return", "normalized", ".", "toString", "(", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Illegal URL for calculating the OAuth signature.\"", ",", "e", ")", ";", "}", "}" ]
Normalize the URL for use in the signature. The OAuth spec says the URL protocol and host are to be lower-case, and the query and fragments are to be stripped. @param url The URL. @return The URL normalized for use in the signature.
[ "Normalize", "the", "URL", "for", "use", "in", "the", "signature", ".", "The", "OAuth", "spec", "says", "the", "URL", "protocol", "and", "host", "are", "to", "be", "lower", "-", "case", "and", "the", "query", "and", "fragments", "are", "to", "be", "stripped", "." ]
train
https://github.com/spring-projects/spring-security-oauth/blob/bbae0027eceb2c74a21ac26bbc86142dc732ffbe/spring-security-oauth/src/main/java/org/springframework/security/oauth/provider/filter/CoreOAuthProviderSupport.java#L154-L167
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java
CheckpointCoordinator.triggerSynchronousSavepoint
public CompletableFuture<CompletedCheckpoint> triggerSynchronousSavepoint( final long timestamp, final boolean advanceToEndOfEventTime, @Nullable final String targetLocation) { """ Triggers a synchronous savepoint with the given savepoint directory as a target. @param timestamp The timestamp for the savepoint. @param advanceToEndOfEventTime Flag indicating if the source should inject a {@code MAX_WATERMARK} in the pipeline to fire any registered event-time timers. @param targetLocation Target location for the savepoint, optional. If null, the state backend's configured default will be used. @return A future to the completed checkpoint @throws IllegalStateException If no savepoint directory has been specified and no default savepoint directory has been configured """ final CheckpointProperties properties = CheckpointProperties.forSyncSavepoint(); return triggerSavepointInternal(timestamp, properties, advanceToEndOfEventTime, targetLocation); }
java
public CompletableFuture<CompletedCheckpoint> triggerSynchronousSavepoint( final long timestamp, final boolean advanceToEndOfEventTime, @Nullable final String targetLocation) { final CheckpointProperties properties = CheckpointProperties.forSyncSavepoint(); return triggerSavepointInternal(timestamp, properties, advanceToEndOfEventTime, targetLocation); }
[ "public", "CompletableFuture", "<", "CompletedCheckpoint", ">", "triggerSynchronousSavepoint", "(", "final", "long", "timestamp", ",", "final", "boolean", "advanceToEndOfEventTime", ",", "@", "Nullable", "final", "String", "targetLocation", ")", "{", "final", "CheckpointProperties", "properties", "=", "CheckpointProperties", ".", "forSyncSavepoint", "(", ")", ";", "return", "triggerSavepointInternal", "(", "timestamp", ",", "properties", ",", "advanceToEndOfEventTime", ",", "targetLocation", ")", ";", "}" ]
Triggers a synchronous savepoint with the given savepoint directory as a target. @param timestamp The timestamp for the savepoint. @param advanceToEndOfEventTime Flag indicating if the source should inject a {@code MAX_WATERMARK} in the pipeline to fire any registered event-time timers. @param targetLocation Target location for the savepoint, optional. If null, the state backend's configured default will be used. @return A future to the completed checkpoint @throws IllegalStateException If no savepoint directory has been specified and no default savepoint directory has been configured
[ "Triggers", "a", "synchronous", "savepoint", "with", "the", "given", "savepoint", "directory", "as", "a", "target", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java#L391-L398
igniterealtime/Smack
smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoManager.java
OmemoManager.getInstanceFor
public static synchronized OmemoManager getInstanceFor(XMPPConnection connection, Integer deviceId) { """ Return an OmemoManager instance for the given connection and deviceId. If there was an OmemoManager for the connection and id before, return it. Otherwise create a new OmemoManager instance and return it. @param connection XmppConnection. @param deviceId MUST NOT be null and MUST be greater than 0. @return manager """ if (deviceId == null || deviceId < 1) { throw new IllegalArgumentException("DeviceId MUST NOT be null and MUST be greater than 0."); } TreeMap<Integer,OmemoManager> managersOfConnection = INSTANCES.get(connection); if (managersOfConnection == null) { managersOfConnection = new TreeMap<>(); INSTANCES.put(connection, managersOfConnection); } OmemoManager manager = managersOfConnection.get(deviceId); if (manager == null) { manager = new OmemoManager(connection, deviceId); managersOfConnection.put(deviceId, manager); } return manager; }
java
public static synchronized OmemoManager getInstanceFor(XMPPConnection connection, Integer deviceId) { if (deviceId == null || deviceId < 1) { throw new IllegalArgumentException("DeviceId MUST NOT be null and MUST be greater than 0."); } TreeMap<Integer,OmemoManager> managersOfConnection = INSTANCES.get(connection); if (managersOfConnection == null) { managersOfConnection = new TreeMap<>(); INSTANCES.put(connection, managersOfConnection); } OmemoManager manager = managersOfConnection.get(deviceId); if (manager == null) { manager = new OmemoManager(connection, deviceId); managersOfConnection.put(deviceId, manager); } return manager; }
[ "public", "static", "synchronized", "OmemoManager", "getInstanceFor", "(", "XMPPConnection", "connection", ",", "Integer", "deviceId", ")", "{", "if", "(", "deviceId", "==", "null", "||", "deviceId", "<", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"DeviceId MUST NOT be null and MUST be greater than 0.\"", ")", ";", "}", "TreeMap", "<", "Integer", ",", "OmemoManager", ">", "managersOfConnection", "=", "INSTANCES", ".", "get", "(", "connection", ")", ";", "if", "(", "managersOfConnection", "==", "null", ")", "{", "managersOfConnection", "=", "new", "TreeMap", "<>", "(", ")", ";", "INSTANCES", ".", "put", "(", "connection", ",", "managersOfConnection", ")", ";", "}", "OmemoManager", "manager", "=", "managersOfConnection", ".", "get", "(", "deviceId", ")", ";", "if", "(", "manager", "==", "null", ")", "{", "manager", "=", "new", "OmemoManager", "(", "connection", ",", "deviceId", ")", ";", "managersOfConnection", ".", "put", "(", "deviceId", ",", "manager", ")", ";", "}", "return", "manager", ";", "}" ]
Return an OmemoManager instance for the given connection and deviceId. If there was an OmemoManager for the connection and id before, return it. Otherwise create a new OmemoManager instance and return it. @param connection XmppConnection. @param deviceId MUST NOT be null and MUST be greater than 0. @return manager
[ "Return", "an", "OmemoManager", "instance", "for", "the", "given", "connection", "and", "deviceId", ".", "If", "there", "was", "an", "OmemoManager", "for", "the", "connection", "and", "id", "before", "return", "it", ".", "Otherwise", "create", "a", "new", "OmemoManager", "instance", "and", "return", "it", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoManager.java#L154-L172
hypfvieh/java-utils
src/main/java/com/github/hypfvieh/classloader/ComponentRegistry.java
ComponentRegistry.registerComponent
public synchronized void registerComponent(Class<?> _clazz, String _version) { """ Register a class with version. @param _clazz class @param _version version """ componentVersions.put(_clazz.getName(), _version); }
java
public synchronized void registerComponent(Class<?> _clazz, String _version) { componentVersions.put(_clazz.getName(), _version); }
[ "public", "synchronized", "void", "registerComponent", "(", "Class", "<", "?", ">", "_clazz", ",", "String", "_version", ")", "{", "componentVersions", ".", "put", "(", "_clazz", ".", "getName", "(", ")", ",", "_version", ")", ";", "}" ]
Register a class with version. @param _clazz class @param _version version
[ "Register", "a", "class", "with", "version", "." ]
train
https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/classloader/ComponentRegistry.java#L106-L108
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RouterClient.java
RouterClient.insertRouter
@BetaApi public final Operation insertRouter(ProjectRegionName region, Router routerResource) { """ Creates a Router resource in the specified project and region using the data included in the request. <p>Sample code: <pre><code> try (RouterClient routerClient = RouterClient.create()) { ProjectRegionName region = ProjectRegionName.of("[PROJECT]", "[REGION]"); Router routerResource = Router.newBuilder().build(); Operation response = routerClient.insertRouter(region, routerResource); } </code></pre> @param region Name of the region for this request. @param routerResource Router resource. @throws com.google.api.gax.rpc.ApiException if the remote call fails """ InsertRouterHttpRequest request = InsertRouterHttpRequest.newBuilder() .setRegion(region == null ? null : region.toString()) .setRouterResource(routerResource) .build(); return insertRouter(request); }
java
@BetaApi public final Operation insertRouter(ProjectRegionName region, Router routerResource) { InsertRouterHttpRequest request = InsertRouterHttpRequest.newBuilder() .setRegion(region == null ? null : region.toString()) .setRouterResource(routerResource) .build(); return insertRouter(request); }
[ "@", "BetaApi", "public", "final", "Operation", "insertRouter", "(", "ProjectRegionName", "region", ",", "Router", "routerResource", ")", "{", "InsertRouterHttpRequest", "request", "=", "InsertRouterHttpRequest", ".", "newBuilder", "(", ")", ".", "setRegion", "(", "region", "==", "null", "?", "null", ":", "region", ".", "toString", "(", ")", ")", ".", "setRouterResource", "(", "routerResource", ")", ".", "build", "(", ")", ";", "return", "insertRouter", "(", "request", ")", ";", "}" ]
Creates a Router resource in the specified project and region using the data included in the request. <p>Sample code: <pre><code> try (RouterClient routerClient = RouterClient.create()) { ProjectRegionName region = ProjectRegionName.of("[PROJECT]", "[REGION]"); Router routerResource = Router.newBuilder().build(); Operation response = routerClient.insertRouter(region, routerResource); } </code></pre> @param region Name of the region for this request. @param routerResource Router resource. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Creates", "a", "Router", "resource", "in", "the", "specified", "project", "and", "region", "using", "the", "data", "included", "in", "the", "request", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RouterClient.java#L747-L756
citrusframework/citrus
modules/citrus-core/src/main/java/com/consol/citrus/util/BooleanExpressionParser.java
BooleanExpressionParser.evaluateSubexpression
private static void evaluateSubexpression(final Deque<String> operators, final Deque<String> values) { """ Evaluates a sub expression within a pair of parentheses and pushes its result onto the stack of values @param operators Stack of operators @param values Stack of values """ String operator = operators.pop(); while (!(operator).equals(SeparatorToken.OPEN_PARENTHESIS.toString())) { values.push(getBooleanResultAsString(operator, values.pop(), values.pop())); operator = operators.pop(); } }
java
private static void evaluateSubexpression(final Deque<String> operators, final Deque<String> values) { String operator = operators.pop(); while (!(operator).equals(SeparatorToken.OPEN_PARENTHESIS.toString())) { values.push(getBooleanResultAsString(operator, values.pop(), values.pop())); operator = operators.pop(); } }
[ "private", "static", "void", "evaluateSubexpression", "(", "final", "Deque", "<", "String", ">", "operators", ",", "final", "Deque", "<", "String", ">", "values", ")", "{", "String", "operator", "=", "operators", ".", "pop", "(", ")", ";", "while", "(", "!", "(", "operator", ")", ".", "equals", "(", "SeparatorToken", ".", "OPEN_PARENTHESIS", ".", "toString", "(", ")", ")", ")", "{", "values", ".", "push", "(", "getBooleanResultAsString", "(", "operator", ",", "values", ".", "pop", "(", ")", ",", "values", ".", "pop", "(", ")", ")", ")", ";", "operator", "=", "operators", ".", "pop", "(", ")", ";", "}", "}" ]
Evaluates a sub expression within a pair of parentheses and pushes its result onto the stack of values @param operators Stack of operators @param values Stack of values
[ "Evaluates", "a", "sub", "expression", "within", "a", "pair", "of", "parentheses", "and", "pushes", "its", "result", "onto", "the", "stack", "of", "values" ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/util/BooleanExpressionParser.java#L160-L168
SonarSource/sonarqube
server/sonar-server-common/src/main/java/org/sonar/server/webhook/HttpUrlHelper.java
HttpUrlHelper.obfuscateCredentials
static String obfuscateCredentials(String originalUrl, HttpUrl parsedUrl) { """ According to inline comment in {@link okhttp3.HttpUrl.Builder#parse(HttpUrl base, String input)}: <blockquote> Username, password and port are optional. [username[:password]@]host[:port] </blockquote> <p> This function replaces the chars of the username and the password from the {@code originalUrl} by '*' chars based on username and password parsed in {@code parsedUrl}. """ String username = parsedUrl.username(); String password = parsedUrl.password(); if (username.isEmpty() && password.isEmpty()) { return originalUrl; } if (!username.isEmpty() && !password.isEmpty()) { String encodedUsername = parsedUrl.encodedUsername(); String encodedPassword = parsedUrl.encodedPassword(); return Stream.<Supplier<String>>of( () -> replaceOrDie(originalUrl, username, password), () -> replaceOrDie(originalUrl, encodedUsername, encodedPassword), () -> replaceOrDie(originalUrl, encodedUsername, password), () -> replaceOrDie(originalUrl, username, encodedPassword)) .map(Supplier::get) .filter(Objects::nonNull) .findFirst() .orElse(originalUrl); } if (!username.isEmpty()) { return Stream.<Supplier<String>>of( () -> replaceOrDie(originalUrl, username, null), () -> replaceOrDie(originalUrl, parsedUrl.encodedUsername(), null)) .map(Supplier::get) .filter(Objects::nonNull) .findFirst() .orElse(originalUrl); } checkState(password.isEmpty(), "having a password without a username should never occur"); return originalUrl; }
java
static String obfuscateCredentials(String originalUrl, HttpUrl parsedUrl) { String username = parsedUrl.username(); String password = parsedUrl.password(); if (username.isEmpty() && password.isEmpty()) { return originalUrl; } if (!username.isEmpty() && !password.isEmpty()) { String encodedUsername = parsedUrl.encodedUsername(); String encodedPassword = parsedUrl.encodedPassword(); return Stream.<Supplier<String>>of( () -> replaceOrDie(originalUrl, username, password), () -> replaceOrDie(originalUrl, encodedUsername, encodedPassword), () -> replaceOrDie(originalUrl, encodedUsername, password), () -> replaceOrDie(originalUrl, username, encodedPassword)) .map(Supplier::get) .filter(Objects::nonNull) .findFirst() .orElse(originalUrl); } if (!username.isEmpty()) { return Stream.<Supplier<String>>of( () -> replaceOrDie(originalUrl, username, null), () -> replaceOrDie(originalUrl, parsedUrl.encodedUsername(), null)) .map(Supplier::get) .filter(Objects::nonNull) .findFirst() .orElse(originalUrl); } checkState(password.isEmpty(), "having a password without a username should never occur"); return originalUrl; }
[ "static", "String", "obfuscateCredentials", "(", "String", "originalUrl", ",", "HttpUrl", "parsedUrl", ")", "{", "String", "username", "=", "parsedUrl", ".", "username", "(", ")", ";", "String", "password", "=", "parsedUrl", ".", "password", "(", ")", ";", "if", "(", "username", ".", "isEmpty", "(", ")", "&&", "password", ".", "isEmpty", "(", ")", ")", "{", "return", "originalUrl", ";", "}", "if", "(", "!", "username", ".", "isEmpty", "(", ")", "&&", "!", "password", ".", "isEmpty", "(", ")", ")", "{", "String", "encodedUsername", "=", "parsedUrl", ".", "encodedUsername", "(", ")", ";", "String", "encodedPassword", "=", "parsedUrl", ".", "encodedPassword", "(", ")", ";", "return", "Stream", ".", "<", "Supplier", "<", "String", ">", ">", "of", "(", "(", ")", "->", "replaceOrDie", "(", "originalUrl", ",", "username", ",", "password", ")", ",", "(", ")", "->", "replaceOrDie", "(", "originalUrl", ",", "encodedUsername", ",", "encodedPassword", ")", ",", "(", ")", "->", "replaceOrDie", "(", "originalUrl", ",", "encodedUsername", ",", "password", ")", ",", "(", ")", "->", "replaceOrDie", "(", "originalUrl", ",", "username", ",", "encodedPassword", ")", ")", ".", "map", "(", "Supplier", "::", "get", ")", ".", "filter", "(", "Objects", "::", "nonNull", ")", ".", "findFirst", "(", ")", ".", "orElse", "(", "originalUrl", ")", ";", "}", "if", "(", "!", "username", ".", "isEmpty", "(", ")", ")", "{", "return", "Stream", ".", "<", "Supplier", "<", "String", ">", ">", "of", "(", "(", ")", "->", "replaceOrDie", "(", "originalUrl", ",", "username", ",", "null", ")", ",", "(", ")", "->", "replaceOrDie", "(", "originalUrl", ",", "parsedUrl", ".", "encodedUsername", "(", ")", ",", "null", ")", ")", ".", "map", "(", "Supplier", "::", "get", ")", ".", "filter", "(", "Objects", "::", "nonNull", ")", ".", "findFirst", "(", ")", ".", "orElse", "(", "originalUrl", ")", ";", "}", "checkState", "(", "password", ".", "isEmpty", "(", ")", ",", "\"having a password without a username should never occur\"", ")", ";", "return", "originalUrl", ";", "}" ]
According to inline comment in {@link okhttp3.HttpUrl.Builder#parse(HttpUrl base, String input)}: <blockquote> Username, password and port are optional. [username[:password]@]host[:port] </blockquote> <p> This function replaces the chars of the username and the password from the {@code originalUrl} by '*' chars based on username and password parsed in {@code parsedUrl}.
[ "According", "to", "inline", "comment", "in", "{" ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server-common/src/main/java/org/sonar/server/webhook/HttpUrlHelper.java#L55-L86
google/error-prone-javac
src/jdk.jshell/share/classes/jdk/jshell/ExpressionToTypeInfo.java
ExpressionToTypeInfo.expressionInfo
public static ExpressionInfo expressionInfo(String code, JShell state) { """ Entry method: get expression info @param code the expression as a string @param state a JShell instance @return type information """ if (code == null || code.isEmpty()) { return null; } try { OuterWrap codeWrap = state.outerMap.wrapInTrialClass(Wrap.methodReturnWrap(code)); AnalyzeTask at = state.taskFactory.new AnalyzeTask(codeWrap); CompilationUnitTree cu = at.firstCuTree(); if (at.hasErrors() || cu == null) { return null; } return new ExpressionToTypeInfo(at, cu, state).typeOfExpression(); } catch (Exception ex) { return null; } }
java
public static ExpressionInfo expressionInfo(String code, JShell state) { if (code == null || code.isEmpty()) { return null; } try { OuterWrap codeWrap = state.outerMap.wrapInTrialClass(Wrap.methodReturnWrap(code)); AnalyzeTask at = state.taskFactory.new AnalyzeTask(codeWrap); CompilationUnitTree cu = at.firstCuTree(); if (at.hasErrors() || cu == null) { return null; } return new ExpressionToTypeInfo(at, cu, state).typeOfExpression(); } catch (Exception ex) { return null; } }
[ "public", "static", "ExpressionInfo", "expressionInfo", "(", "String", "code", ",", "JShell", "state", ")", "{", "if", "(", "code", "==", "null", "||", "code", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "try", "{", "OuterWrap", "codeWrap", "=", "state", ".", "outerMap", ".", "wrapInTrialClass", "(", "Wrap", ".", "methodReturnWrap", "(", "code", ")", ")", ";", "AnalyzeTask", "at", "=", "state", ".", "taskFactory", ".", "new", "AnalyzeTask", "(", "codeWrap", ")", ";", "CompilationUnitTree", "cu", "=", "at", ".", "firstCuTree", "(", ")", ";", "if", "(", "at", ".", "hasErrors", "(", ")", "||", "cu", "==", "null", ")", "{", "return", "null", ";", "}", "return", "new", "ExpressionToTypeInfo", "(", "at", ",", "cu", ",", "state", ")", ".", "typeOfExpression", "(", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "return", "null", ";", "}", "}" ]
Entry method: get expression info @param code the expression as a string @param state a JShell instance @return type information
[ "Entry", "method", ":", "get", "expression", "info" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jshell/share/classes/jdk/jshell/ExpressionToTypeInfo.java#L142-L157
gallandarakhneorg/afc
core/maths/mathgeom/src/main/java/org/arakhne/afc/math/geometry/d1/Transform1D.java
Transform1D.setPath
public void setPath(List<? extends S> path, Direction1D direction) { """ Set the path used by this transformation. @param path is the new path @param direction is the direction to follow on the path if the path contains only one segment. """ this.path = path == null || path.isEmpty() ? null : new ArrayList<>(path); this.firstSegmentDirection = detectFirstSegmentDirection(direction); }
java
public void setPath(List<? extends S> path, Direction1D direction) { this.path = path == null || path.isEmpty() ? null : new ArrayList<>(path); this.firstSegmentDirection = detectFirstSegmentDirection(direction); }
[ "public", "void", "setPath", "(", "List", "<", "?", "extends", "S", ">", "path", ",", "Direction1D", "direction", ")", "{", "this", ".", "path", "=", "path", "==", "null", "||", "path", ".", "isEmpty", "(", ")", "?", "null", ":", "new", "ArrayList", "<>", "(", "path", ")", ";", "this", ".", "firstSegmentDirection", "=", "detectFirstSegmentDirection", "(", "direction", ")", ";", "}" ]
Set the path used by this transformation. @param path is the new path @param direction is the direction to follow on the path if the path contains only one segment.
[ "Set", "the", "path", "used", "by", "this", "transformation", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/src/main/java/org/arakhne/afc/math/geometry/d1/Transform1D.java#L254-L257
ironjacamar/ironjacamar
codegenerator/src/main/java/org/ironjacamar/codegenerator/BaseProfile.java
BaseProfile.generateMavenXml
void generateMavenXml(Definition def, String outputDir) { """ generate ant build.xml @param def Definition @param outputDir output directory """ try { FileWriter pomfw = Utils.createFile("pom.xml", outputDir); PomXmlGen pxGen = new PomXmlGen(); pxGen.generate(def, pomfw); pomfw.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
java
void generateMavenXml(Definition def, String outputDir) { try { FileWriter pomfw = Utils.createFile("pom.xml", outputDir); PomXmlGen pxGen = new PomXmlGen(); pxGen.generate(def, pomfw); pomfw.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
[ "void", "generateMavenXml", "(", "Definition", "def", ",", "String", "outputDir", ")", "{", "try", "{", "FileWriter", "pomfw", "=", "Utils", ".", "createFile", "(", "\"pom.xml\"", ",", "outputDir", ")", ";", "PomXmlGen", "pxGen", "=", "new", "PomXmlGen", "(", ")", ";", "pxGen", ".", "generate", "(", "def", ",", "pomfw", ")", ";", "pomfw", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "ioe", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
generate ant build.xml @param def Definition @param outputDir output directory
[ "generate", "ant", "build", ".", "xml" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/BaseProfile.java#L389-L402
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbPooledConnection.java
MariaDbPooledConnection.fireStatementErrorOccured
public void fireStatementErrorOccured(Statement st, SQLException ex) { """ Fire statement error to listeners. @param st statement @param ex exception """ if (st instanceof PreparedStatement) { StatementEvent event = new StatementEvent(this, (PreparedStatement) st, ex); for (StatementEventListener listener : statementEventListeners) { listener.statementErrorOccurred(event); } } }
java
public void fireStatementErrorOccured(Statement st, SQLException ex) { if (st instanceof PreparedStatement) { StatementEvent event = new StatementEvent(this, (PreparedStatement) st, ex); for (StatementEventListener listener : statementEventListeners) { listener.statementErrorOccurred(event); } } }
[ "public", "void", "fireStatementErrorOccured", "(", "Statement", "st", ",", "SQLException", "ex", ")", "{", "if", "(", "st", "instanceof", "PreparedStatement", ")", "{", "StatementEvent", "event", "=", "new", "StatementEvent", "(", "this", ",", "(", "PreparedStatement", ")", "st", ",", "ex", ")", ";", "for", "(", "StatementEventListener", "listener", ":", "statementEventListeners", ")", "{", "listener", ".", "statementErrorOccurred", "(", "event", ")", ";", "}", "}", "}" ]
Fire statement error to listeners. @param st statement @param ex exception
[ "Fire", "statement", "error", "to", "listeners", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbPooledConnection.java#L204-L211
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/util/converters/DeployerResolverOverriderConverter.java
DeployerResolverOverriderConverter.overrideUseMavenPatterns
private void overrideUseMavenPatterns(T overrider, Class overriderClass) { """ Convert the Boolean notM2Compatible parameter to Boolean useMavenPatterns (after applying !) This convertion comes after a name change (!notM2Compatible -> useMavenPatterns) """ if (useMavenPatternsOverrideList.contains(overriderClass.getSimpleName())) { try { Field useMavenPatternsField = overriderClass.getDeclaredField("useMavenPatterns"); useMavenPatternsField.setAccessible(true); Object useMavenPatterns = useMavenPatternsField.get(overrider); if (useMavenPatterns == null) { Field notM2CompatibleField = overriderClass.getDeclaredField("notM2Compatible"); notM2CompatibleField.setAccessible(true); Object notM2Compatible = notM2CompatibleField.get(overrider); if (notM2Compatible instanceof Boolean && notM2Compatible != null) { useMavenPatternsField.set(overrider, !(Boolean)notM2Compatible); } } } catch (NoSuchFieldException | IllegalAccessException e) { converterErrors.add(getConversionErrorMessage(overrider, e)); } } }
java
private void overrideUseMavenPatterns(T overrider, Class overriderClass) { if (useMavenPatternsOverrideList.contains(overriderClass.getSimpleName())) { try { Field useMavenPatternsField = overriderClass.getDeclaredField("useMavenPatterns"); useMavenPatternsField.setAccessible(true); Object useMavenPatterns = useMavenPatternsField.get(overrider); if (useMavenPatterns == null) { Field notM2CompatibleField = overriderClass.getDeclaredField("notM2Compatible"); notM2CompatibleField.setAccessible(true); Object notM2Compatible = notM2CompatibleField.get(overrider); if (notM2Compatible instanceof Boolean && notM2Compatible != null) { useMavenPatternsField.set(overrider, !(Boolean)notM2Compatible); } } } catch (NoSuchFieldException | IllegalAccessException e) { converterErrors.add(getConversionErrorMessage(overrider, e)); } } }
[ "private", "void", "overrideUseMavenPatterns", "(", "T", "overrider", ",", "Class", "overriderClass", ")", "{", "if", "(", "useMavenPatternsOverrideList", ".", "contains", "(", "overriderClass", ".", "getSimpleName", "(", ")", ")", ")", "{", "try", "{", "Field", "useMavenPatternsField", "=", "overriderClass", ".", "getDeclaredField", "(", "\"useMavenPatterns\"", ")", ";", "useMavenPatternsField", ".", "setAccessible", "(", "true", ")", ";", "Object", "useMavenPatterns", "=", "useMavenPatternsField", ".", "get", "(", "overrider", ")", ";", "if", "(", "useMavenPatterns", "==", "null", ")", "{", "Field", "notM2CompatibleField", "=", "overriderClass", ".", "getDeclaredField", "(", "\"notM2Compatible\"", ")", ";", "notM2CompatibleField", ".", "setAccessible", "(", "true", ")", ";", "Object", "notM2Compatible", "=", "notM2CompatibleField", ".", "get", "(", "overrider", ")", ";", "if", "(", "notM2Compatible", "instanceof", "Boolean", "&&", "notM2Compatible", "!=", "null", ")", "{", "useMavenPatternsField", ".", "set", "(", "overrider", ",", "!", "(", "Boolean", ")", "notM2Compatible", ")", ";", "}", "}", "}", "catch", "(", "NoSuchFieldException", "|", "IllegalAccessException", "e", ")", "{", "converterErrors", ".", "add", "(", "getConversionErrorMessage", "(", "overrider", ",", "e", ")", ")", ";", "}", "}", "}" ]
Convert the Boolean notM2Compatible parameter to Boolean useMavenPatterns (after applying !) This convertion comes after a name change (!notM2Compatible -> useMavenPatterns)
[ "Convert", "the", "Boolean", "notM2Compatible", "parameter", "to", "Boolean", "useMavenPatterns", "(", "after", "applying", "!", ")", "This", "convertion", "comes", "after", "a", "name", "change", "(", "!notM2Compatible", "-", ">", "useMavenPatterns", ")" ]
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/util/converters/DeployerResolverOverriderConverter.java#L231-L250
roboconf/roboconf-platform
miscellaneous/roboconf-swagger/src/main/java/net/roboconf/swagger/UpdateSwaggerJson.java
UpdateSwaggerJson.convertToTypes
public static void convertToTypes( String serialization, String className, JsonObject newDef ) { """ Creates a JSon object from a serialization result. @param serialization the serialization result @param className a class or type name @param newDef the new definition object to update """ JsonParser jsonParser = new JsonParser(); JsonElement jsonTree = jsonParser.parse( serialization ); // Creating the swagger definition JsonObject innerObject = new JsonObject(); // Start adding basic properties innerObject.addProperty( "title", className ); innerObject.addProperty( "definition", "" ); innerObject.addProperty( "type", jsonTree.isJsonObject() ? "object" : jsonTree.isJsonArray() ? "array" : "string" ); // Prevent errors with classic Swagger UI innerObject.addProperty( "properties", "" ); // Inner properties innerObject.add( "example", jsonTree.getAsJsonObject()); // Update our global definition newDef.add( "json_" + className, innerObject ); }
java
public static void convertToTypes( String serialization, String className, JsonObject newDef ) { JsonParser jsonParser = new JsonParser(); JsonElement jsonTree = jsonParser.parse( serialization ); // Creating the swagger definition JsonObject innerObject = new JsonObject(); // Start adding basic properties innerObject.addProperty( "title", className ); innerObject.addProperty( "definition", "" ); innerObject.addProperty( "type", jsonTree.isJsonObject() ? "object" : jsonTree.isJsonArray() ? "array" : "string" ); // Prevent errors with classic Swagger UI innerObject.addProperty( "properties", "" ); // Inner properties innerObject.add( "example", jsonTree.getAsJsonObject()); // Update our global definition newDef.add( "json_" + className, innerObject ); }
[ "public", "static", "void", "convertToTypes", "(", "String", "serialization", ",", "String", "className", ",", "JsonObject", "newDef", ")", "{", "JsonParser", "jsonParser", "=", "new", "JsonParser", "(", ")", ";", "JsonElement", "jsonTree", "=", "jsonParser", ".", "parse", "(", "serialization", ")", ";", "// Creating the swagger definition", "JsonObject", "innerObject", "=", "new", "JsonObject", "(", ")", ";", "// Start adding basic properties", "innerObject", ".", "addProperty", "(", "\"title\"", ",", "className", ")", ";", "innerObject", ".", "addProperty", "(", "\"definition\"", ",", "\"\"", ")", ";", "innerObject", ".", "addProperty", "(", "\"type\"", ",", "jsonTree", ".", "isJsonObject", "(", ")", "?", "\"object\"", ":", "jsonTree", ".", "isJsonArray", "(", ")", "?", "\"array\"", ":", "\"string\"", ")", ";", "// Prevent errors with classic Swagger UI", "innerObject", ".", "addProperty", "(", "\"properties\"", ",", "\"\"", ")", ";", "// Inner properties", "innerObject", ".", "add", "(", "\"example\"", ",", "jsonTree", ".", "getAsJsonObject", "(", ")", ")", ";", "// Update our global definition", "newDef", ".", "add", "(", "\"json_\"", "+", "className", ",", "innerObject", ")", ";", "}" ]
Creates a JSon object from a serialization result. @param serialization the serialization result @param className a class or type name @param newDef the new definition object to update
[ "Creates", "a", "JSon", "object", "from", "a", "serialization", "result", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-swagger/src/main/java/net/roboconf/swagger/UpdateSwaggerJson.java#L307-L328
puniverse/galaxy
src/main/java/co/paralleluniverse/common/spring/SpringContainerHelper.java
SpringContainerHelper.createBeanFactory
private static DefaultListableBeanFactory createBeanFactory() { """ adds hooks to capture autowired constructor args and add them as dependencies @return """ return new DefaultListableBeanFactory() { { final InstantiationStrategy is = getInstantiationStrategy(); setInstantiationStrategy(new InstantiationStrategy() { @Override public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) throws BeansException { return is.instantiate(beanDefinition, beanName, owner); } @Override public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, Constructor<?> ctor, Object[] args) throws BeansException { final Object bean = is.instantiate(beanDefinition, beanName, owner, ctor, args); addDependencies(bean, args); return bean; } @Override public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, Object factoryBean, Method factoryMethod, Object[] args) throws BeansException { final Object bean = is.instantiate(beanDefinition, beanName, owner, factoryBean, factoryMethod, args); addDependencies(bean, args); return bean; } }); } private void addDependencies(Object bean, Object[] args) { if (bean instanceof Service) { for (Object arg : args) { if (arg instanceof Service) { ((Service) arg).addDependedBy((Service) bean); ((Service) bean).addDependsOn((Service) arg); } } } } }; }
java
private static DefaultListableBeanFactory createBeanFactory() { return new DefaultListableBeanFactory() { { final InstantiationStrategy is = getInstantiationStrategy(); setInstantiationStrategy(new InstantiationStrategy() { @Override public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) throws BeansException { return is.instantiate(beanDefinition, beanName, owner); } @Override public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, Constructor<?> ctor, Object[] args) throws BeansException { final Object bean = is.instantiate(beanDefinition, beanName, owner, ctor, args); addDependencies(bean, args); return bean; } @Override public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, Object factoryBean, Method factoryMethod, Object[] args) throws BeansException { final Object bean = is.instantiate(beanDefinition, beanName, owner, factoryBean, factoryMethod, args); addDependencies(bean, args); return bean; } }); } private void addDependencies(Object bean, Object[] args) { if (bean instanceof Service) { for (Object arg : args) { if (arg instanceof Service) { ((Service) arg).addDependedBy((Service) bean); ((Service) bean).addDependsOn((Service) arg); } } } } }; }
[ "private", "static", "DefaultListableBeanFactory", "createBeanFactory", "(", ")", "{", "return", "new", "DefaultListableBeanFactory", "(", ")", "{", "{", "final", "InstantiationStrategy", "is", "=", "getInstantiationStrategy", "(", ")", ";", "setInstantiationStrategy", "(", "new", "InstantiationStrategy", "(", ")", "{", "@", "Override", "public", "Object", "instantiate", "(", "RootBeanDefinition", "beanDefinition", ",", "String", "beanName", ",", "BeanFactory", "owner", ")", "throws", "BeansException", "{", "return", "is", ".", "instantiate", "(", "beanDefinition", ",", "beanName", ",", "owner", ")", ";", "}", "@", "Override", "public", "Object", "instantiate", "(", "RootBeanDefinition", "beanDefinition", ",", "String", "beanName", ",", "BeanFactory", "owner", ",", "Constructor", "<", "?", ">", "ctor", ",", "Object", "[", "]", "args", ")", "throws", "BeansException", "{", "final", "Object", "bean", "=", "is", ".", "instantiate", "(", "beanDefinition", ",", "beanName", ",", "owner", ",", "ctor", ",", "args", ")", ";", "addDependencies", "(", "bean", ",", "args", ")", ";", "return", "bean", ";", "}", "@", "Override", "public", "Object", "instantiate", "(", "RootBeanDefinition", "beanDefinition", ",", "String", "beanName", ",", "BeanFactory", "owner", ",", "Object", "factoryBean", ",", "Method", "factoryMethod", ",", "Object", "[", "]", "args", ")", "throws", "BeansException", "{", "final", "Object", "bean", "=", "is", ".", "instantiate", "(", "beanDefinition", ",", "beanName", ",", "owner", ",", "factoryBean", ",", "factoryMethod", ",", "args", ")", ";", "addDependencies", "(", "bean", ",", "args", ")", ";", "return", "bean", ";", "}", "}", ")", ";", "}", "private", "void", "addDependencies", "(", "Object", "bean", ",", "Object", "[", "]", "args", ")", "{", "if", "(", "bean", "instanceof", "Service", ")", "{", "for", "(", "Object", "arg", ":", "args", ")", "{", "if", "(", "arg", "instanceof", "Service", ")", "{", "(", "(", "Service", ")", "arg", ")", ".", "addDependedBy", "(", "(", "Service", ")", "bean", ")", ";", "(", "(", "Service", ")", "bean", ")", ".", "addDependsOn", "(", "(", "Service", ")", "arg", ")", ";", "}", "}", "}", "}", "}", ";", "}" ]
adds hooks to capture autowired constructor args and add them as dependencies @return
[ "adds", "hooks", "to", "capture", "autowired", "constructor", "args", "and", "add", "them", "as", "dependencies" ]
train
https://github.com/puniverse/galaxy/blob/1d077532c4a5bcd6c52ff670770c31e98420ff63/src/main/java/co/paralleluniverse/common/spring/SpringContainerHelper.java#L193-L230
apache/groovy
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
StaticTypeCheckingSupport.fullyResolve
protected static GenericsType fullyResolve(GenericsType gt, Map<GenericsTypeName, GenericsType> placeholders) { """ Given a generics type representing SomeClass&lt;T,V&gt; and a resolved placeholder map, returns a new generics type for which placeholders are resolved recursively. """ GenericsType fromMap = placeholders.get(new GenericsTypeName(gt.getName())); if (gt.isPlaceholder() && fromMap != null) { gt = fromMap; } ClassNode type = fullyResolveType(gt.getType(), placeholders); ClassNode lowerBound = gt.getLowerBound(); if (lowerBound != null) lowerBound = fullyResolveType(lowerBound, placeholders); ClassNode[] upperBounds = gt.getUpperBounds(); if (upperBounds != null) { ClassNode[] copy = new ClassNode[upperBounds.length]; for (int i = 0, upperBoundsLength = upperBounds.length; i < upperBoundsLength; i++) { final ClassNode upperBound = upperBounds[i]; copy[i] = fullyResolveType(upperBound, placeholders); } upperBounds = copy; } GenericsType genericsType = new GenericsType(type, upperBounds, lowerBound); genericsType.setWildcard(gt.isWildcard()); return genericsType; }
java
protected static GenericsType fullyResolve(GenericsType gt, Map<GenericsTypeName, GenericsType> placeholders) { GenericsType fromMap = placeholders.get(new GenericsTypeName(gt.getName())); if (gt.isPlaceholder() && fromMap != null) { gt = fromMap; } ClassNode type = fullyResolveType(gt.getType(), placeholders); ClassNode lowerBound = gt.getLowerBound(); if (lowerBound != null) lowerBound = fullyResolveType(lowerBound, placeholders); ClassNode[] upperBounds = gt.getUpperBounds(); if (upperBounds != null) { ClassNode[] copy = new ClassNode[upperBounds.length]; for (int i = 0, upperBoundsLength = upperBounds.length; i < upperBoundsLength; i++) { final ClassNode upperBound = upperBounds[i]; copy[i] = fullyResolveType(upperBound, placeholders); } upperBounds = copy; } GenericsType genericsType = new GenericsType(type, upperBounds, lowerBound); genericsType.setWildcard(gt.isWildcard()); return genericsType; }
[ "protected", "static", "GenericsType", "fullyResolve", "(", "GenericsType", "gt", ",", "Map", "<", "GenericsTypeName", ",", "GenericsType", ">", "placeholders", ")", "{", "GenericsType", "fromMap", "=", "placeholders", ".", "get", "(", "new", "GenericsTypeName", "(", "gt", ".", "getName", "(", ")", ")", ")", ";", "if", "(", "gt", ".", "isPlaceholder", "(", ")", "&&", "fromMap", "!=", "null", ")", "{", "gt", "=", "fromMap", ";", "}", "ClassNode", "type", "=", "fullyResolveType", "(", "gt", ".", "getType", "(", ")", ",", "placeholders", ")", ";", "ClassNode", "lowerBound", "=", "gt", ".", "getLowerBound", "(", ")", ";", "if", "(", "lowerBound", "!=", "null", ")", "lowerBound", "=", "fullyResolveType", "(", "lowerBound", ",", "placeholders", ")", ";", "ClassNode", "[", "]", "upperBounds", "=", "gt", ".", "getUpperBounds", "(", ")", ";", "if", "(", "upperBounds", "!=", "null", ")", "{", "ClassNode", "[", "]", "copy", "=", "new", "ClassNode", "[", "upperBounds", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ",", "upperBoundsLength", "=", "upperBounds", ".", "length", ";", "i", "<", "upperBoundsLength", ";", "i", "++", ")", "{", "final", "ClassNode", "upperBound", "=", "upperBounds", "[", "i", "]", ";", "copy", "[", "i", "]", "=", "fullyResolveType", "(", "upperBound", ",", "placeholders", ")", ";", "}", "upperBounds", "=", "copy", ";", "}", "GenericsType", "genericsType", "=", "new", "GenericsType", "(", "type", ",", "upperBounds", ",", "lowerBound", ")", ";", "genericsType", ".", "setWildcard", "(", "gt", ".", "isWildcard", "(", ")", ")", ";", "return", "genericsType", ";", "}" ]
Given a generics type representing SomeClass&lt;T,V&gt; and a resolved placeholder map, returns a new generics type for which placeholders are resolved recursively.
[ "Given", "a", "generics", "type", "representing", "SomeClass&lt", ";", "T", "V&gt", ";", "and", "a", "resolved", "placeholder", "map", "returns", "a", "new", "generics", "type", "for", "which", "placeholders", "are", "resolved", "recursively", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java#L1362-L1383
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/VerboseFormatter.java
VerboseFormatter.appendThrown
private static void appendThrown(StringBuilder message, LogRecord event) { """ Append thrown exception trace. @param message The message builder. @param event The log record. """ final Throwable thrown = event.getThrown(); if (thrown != null) { final StringWriter sw = new StringWriter(); thrown.printStackTrace(new PrintWriter(sw)); message.append(sw); } }
java
private static void appendThrown(StringBuilder message, LogRecord event) { final Throwable thrown = event.getThrown(); if (thrown != null) { final StringWriter sw = new StringWriter(); thrown.printStackTrace(new PrintWriter(sw)); message.append(sw); } }
[ "private", "static", "void", "appendThrown", "(", "StringBuilder", "message", ",", "LogRecord", "event", ")", "{", "final", "Throwable", "thrown", "=", "event", ".", "getThrown", "(", ")", ";", "if", "(", "thrown", "!=", "null", ")", "{", "final", "StringWriter", "sw", "=", "new", "StringWriter", "(", ")", ";", "thrown", ".", "printStackTrace", "(", "new", "PrintWriter", "(", "sw", ")", ")", ";", "message", ".", "append", "(", "sw", ")", ";", "}", "}" ]
Append thrown exception trace. @param message The message builder. @param event The log record.
[ "Append", "thrown", "exception", "trace", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/VerboseFormatter.java#L95-L104
codelibs/jcifs
src/main/java/jcifs/smb1/http/NtlmHttpFilter.java
NtlmHttpFilter.doFilter
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { """ This method simply calls <tt>negotiate( req, resp, false )</tt> and then <tt>chain.doFilter</tt>. You can override and call negotiate manually to achive a variety of different behavior. """ HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse resp = (HttpServletResponse)response; NtlmPasswordAuthentication ntlm; if ((ntlm = negotiate( req, resp, false )) == null) { return; } chain.doFilter( new NtlmHttpServletRequest( req, ntlm ), response ); }
java
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse resp = (HttpServletResponse)response; NtlmPasswordAuthentication ntlm; if ((ntlm = negotiate( req, resp, false )) == null) { return; } chain.doFilter( new NtlmHttpServletRequest( req, ntlm ), response ); }
[ "public", "void", "doFilter", "(", "ServletRequest", "request", ",", "ServletResponse", "response", ",", "FilterChain", "chain", ")", "throws", "IOException", ",", "ServletException", "{", "HttpServletRequest", "req", "=", "(", "HttpServletRequest", ")", "request", ";", "HttpServletResponse", "resp", "=", "(", "HttpServletResponse", ")", "response", ";", "NtlmPasswordAuthentication", "ntlm", ";", "if", "(", "(", "ntlm", "=", "negotiate", "(", "req", ",", "resp", ",", "false", ")", ")", "==", "null", ")", "{", "return", ";", "}", "chain", ".", "doFilter", "(", "new", "NtlmHttpServletRequest", "(", "req", ",", "ntlm", ")", ",", "response", ")", ";", "}" ]
This method simply calls <tt>negotiate( req, resp, false )</tt> and then <tt>chain.doFilter</tt>. You can override and call negotiate manually to achive a variety of different behavior.
[ "This", "method", "simply", "calls", "<tt", ">", "negotiate", "(", "req", "resp", "false", ")", "<", "/", "tt", ">", "and", "then", "<tt", ">", "chain", ".", "doFilter<", "/", "tt", ">", ".", "You", "can", "override", "and", "call", "negotiate", "manually", "to", "achive", "a", "variety", "of", "different", "behavior", "." ]
train
https://github.com/codelibs/jcifs/blob/ac6a8ba2925648ae003ca2508aec32316065dc34/src/main/java/jcifs/smb1/http/NtlmHttpFilter.java#L115-L127
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/InterfaceEndpointsInner.java
InterfaceEndpointsInner.beginCreateOrUpdateAsync
public Observable<InterfaceEndpointInner> beginCreateOrUpdateAsync(String resourceGroupName, String interfaceEndpointName, InterfaceEndpointInner parameters) { """ Creates or updates an interface endpoint in the specified resource group. @param resourceGroupName The name of the resource group. @param interfaceEndpointName The name of the interface endpoint. @param parameters Parameters supplied to the create or update interface endpoint operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the InterfaceEndpointInner object """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, interfaceEndpointName, parameters).map(new Func1<ServiceResponse<InterfaceEndpointInner>, InterfaceEndpointInner>() { @Override public InterfaceEndpointInner call(ServiceResponse<InterfaceEndpointInner> response) { return response.body(); } }); }
java
public Observable<InterfaceEndpointInner> beginCreateOrUpdateAsync(String resourceGroupName, String interfaceEndpointName, InterfaceEndpointInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, interfaceEndpointName, parameters).map(new Func1<ServiceResponse<InterfaceEndpointInner>, InterfaceEndpointInner>() { @Override public InterfaceEndpointInner call(ServiceResponse<InterfaceEndpointInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "InterfaceEndpointInner", ">", "beginCreateOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "interfaceEndpointName", ",", "InterfaceEndpointInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "interfaceEndpointName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "InterfaceEndpointInner", ">", ",", "InterfaceEndpointInner", ">", "(", ")", "{", "@", "Override", "public", "InterfaceEndpointInner", "call", "(", "ServiceResponse", "<", "InterfaceEndpointInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Creates or updates an interface endpoint in the specified resource group. @param resourceGroupName The name of the resource group. @param interfaceEndpointName The name of the interface endpoint. @param parameters Parameters supplied to the create or update interface endpoint operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the InterfaceEndpointInner object
[ "Creates", "or", "updates", "an", "interface", "endpoint", "in", "the", "specified", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/InterfaceEndpointsInner.java#L535-L542
ist-dresden/composum
sling/core/commons/src/main/java/com/composum/sling/core/event/AbstractChangeObserver.java
AbstractChangeObserver.getContentNode
protected Node getContentNode(Session session, String path) throws RepositoryException { """ determines the target node (the node to perform the change) of one event item """ Node node = null; try { Item item = session.getItem(path); if (item.isNode()) { node = (Node) item; } else { node = item.getParent(); } while (node != null && !isTargetNode(node) && (path = getTargetPath(node)) != null) { node = node.getParent(); } } catch (PathNotFoundException ignore) { // probably removed... ignore } return path != null ? node : null; }
java
protected Node getContentNode(Session session, String path) throws RepositoryException { Node node = null; try { Item item = session.getItem(path); if (item.isNode()) { node = (Node) item; } else { node = item.getParent(); } while (node != null && !isTargetNode(node) && (path = getTargetPath(node)) != null) { node = node.getParent(); } } catch (PathNotFoundException ignore) { // probably removed... ignore } return path != null ? node : null; }
[ "protected", "Node", "getContentNode", "(", "Session", "session", ",", "String", "path", ")", "throws", "RepositoryException", "{", "Node", "node", "=", "null", ";", "try", "{", "Item", "item", "=", "session", ".", "getItem", "(", "path", ")", ";", "if", "(", "item", ".", "isNode", "(", ")", ")", "{", "node", "=", "(", "Node", ")", "item", ";", "}", "else", "{", "node", "=", "item", ".", "getParent", "(", ")", ";", "}", "while", "(", "node", "!=", "null", "&&", "!", "isTargetNode", "(", "node", ")", "&&", "(", "path", "=", "getTargetPath", "(", "node", ")", ")", "!=", "null", ")", "{", "node", "=", "node", ".", "getParent", "(", ")", ";", "}", "}", "catch", "(", "PathNotFoundException", "ignore", ")", "{", "// probably removed... ignore", "}", "return", "path", "!=", "null", "?", "node", ":", "null", ";", "}" ]
determines the target node (the node to perform the change) of one event item
[ "determines", "the", "target", "node", "(", "the", "node", "to", "perform", "the", "change", ")", "of", "one", "event", "item" ]
train
https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/core/event/AbstractChangeObserver.java#L255-L274
spring-projects/spring-hateoas
src/main/java/org/springframework/hateoas/mediatype/hal/HalLinkRelation.java
HalLinkRelation.of
@JsonCreator private static HalLinkRelation of(String relation) { """ Creates a new {@link HalLinkRelation} from the given link relation {@link String}. @param relation must not be {@literal null}. @return """ String[] split = relation.split(":"); String curie = split.length == 1 ? null : split[0]; String localPart = split.length == 1 ? split[0] : split[1]; return new HalLinkRelation(curie, localPart); }
java
@JsonCreator private static HalLinkRelation of(String relation) { String[] split = relation.split(":"); String curie = split.length == 1 ? null : split[0]; String localPart = split.length == 1 ? split[0] : split[1]; return new HalLinkRelation(curie, localPart); }
[ "@", "JsonCreator", "private", "static", "HalLinkRelation", "of", "(", "String", "relation", ")", "{", "String", "[", "]", "split", "=", "relation", ".", "split", "(", "\":\"", ")", ";", "String", "curie", "=", "split", ".", "length", "==", "1", "?", "null", ":", "split", "[", "0", "]", ";", "String", "localPart", "=", "split", ".", "length", "==", "1", "?", "split", "[", "0", "]", ":", "split", "[", "1", "]", ";", "return", "new", "HalLinkRelation", "(", "curie", ",", "localPart", ")", ";", "}" ]
Creates a new {@link HalLinkRelation} from the given link relation {@link String}. @param relation must not be {@literal null}. @return
[ "Creates", "a", "new", "{", "@link", "HalLinkRelation", "}", "from", "the", "given", "link", "relation", "{", "@link", "String", "}", "." ]
train
https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/mediatype/hal/HalLinkRelation.java#L74-L83
aws/aws-sdk-java
aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/CreateSimulationJobRequest.java
CreateSimulationJobRequest.withTags
public CreateSimulationJobRequest withTags(java.util.Map<String, String> tags) { """ <p> A map that contains tag keys and tag values that are attached to the simulation job. </p> @param tags A map that contains tag keys and tag values that are attached to the simulation job. @return Returns a reference to this object so that method calls can be chained together. """ setTags(tags); return this; }
java
public CreateSimulationJobRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "CreateSimulationJobRequest", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
<p> A map that contains tag keys and tag values that are attached to the simulation job. </p> @param tags A map that contains tag keys and tag values that are attached to the simulation job. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "map", "that", "contains", "tag", "keys", "and", "tag", "values", "that", "are", "attached", "to", "the", "simulation", "job", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/CreateSimulationJobRequest.java#L622-L625
carrotsearch/hppc
hppc/src/main/templates/com/carrotsearch/hppc/KTypeVTypeHashMap.java
KTypeVTypeHashMap.equalElements
protected boolean equalElements(KTypeVTypeHashMap<?, ?> other) { """ Return true if all keys of some other container exist in this container. #if ($TemplateOptions.KTypeGeneric) Equality comparison is performed with this object's {@link #equals(Object, Object)} method. #end #if ($TemplateOptions.VTypeGeneric) Values are compared using {@link Objects#equals(Object)} method. #end """ if (other.size() != size()) { return false; } for (KTypeVTypeCursor<?, ?> c : other) { KType key = Intrinsics.<KType> cast(c.key); if (!containsKey(key) || !Intrinsics.<VType> equals(c.value, get(key))) { return false; } } return true; }
java
protected boolean equalElements(KTypeVTypeHashMap<?, ?> other) { if (other.size() != size()) { return false; } for (KTypeVTypeCursor<?, ?> c : other) { KType key = Intrinsics.<KType> cast(c.key); if (!containsKey(key) || !Intrinsics.<VType> equals(c.value, get(key))) { return false; } } return true; }
[ "protected", "boolean", "equalElements", "(", "KTypeVTypeHashMap", "<", "?", ",", "?", ">", "other", ")", "{", "if", "(", "other", ".", "size", "(", ")", "!=", "size", "(", ")", ")", "{", "return", "false", ";", "}", "for", "(", "KTypeVTypeCursor", "<", "?", ",", "?", ">", "c", ":", "other", ")", "{", "KType", "key", "=", "Intrinsics", ".", "<", "KType", ">", "cast", "(", "c", ".", "key", ")", ";", "if", "(", "!", "containsKey", "(", "key", ")", "||", "!", "Intrinsics", ".", "<", "VType", ">", "equals", "(", "c", ".", "value", ",", "get", "(", "key", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Return true if all keys of some other container exist in this container. #if ($TemplateOptions.KTypeGeneric) Equality comparison is performed with this object's {@link #equals(Object, Object)} method. #end #if ($TemplateOptions.VTypeGeneric) Values are compared using {@link Objects#equals(Object)} method. #end
[ "Return", "true", "if", "all", "keys", "of", "some", "other", "container", "exist", "in", "this", "container", ".", "#if", "(", "$TemplateOptions", ".", "KTypeGeneric", ")", "Equality", "comparison", "is", "performed", "with", "this", "object", "s", "{" ]
train
https://github.com/carrotsearch/hppc/blob/e359e9da358e846fcbffc64a765611df954ba3f6/hppc/src/main/templates/com/carrotsearch/hppc/KTypeVTypeHashMap.java#L647-L661
phax/ph-javacc-maven-plugin
src/main/java/org/codehaus/mojo/javacc/JTB.java
JTB.getEffectiveNodeDirectory
private File getEffectiveNodeDirectory () { """ Gets the absolute path to the output directory for the syntax tree files. @return The absolute path to the output directory for the syntax tree files, only <code>null</code> if neither {@link #outputDirectory} nor {@link #nodeDirectory} have been set. """ if (this.nodeDirectory != null) return this.nodeDirectory; if (this.outputDirectory != null) return new File (this.outputDirectory, getLastPackageName (getEffectiveNodePackageName ())); return null; }
java
private File getEffectiveNodeDirectory () { if (this.nodeDirectory != null) return this.nodeDirectory; if (this.outputDirectory != null) return new File (this.outputDirectory, getLastPackageName (getEffectiveNodePackageName ())); return null; }
[ "private", "File", "getEffectiveNodeDirectory", "(", ")", "{", "if", "(", "this", ".", "nodeDirectory", "!=", "null", ")", "return", "this", ".", "nodeDirectory", ";", "if", "(", "this", ".", "outputDirectory", "!=", "null", ")", "return", "new", "File", "(", "this", ".", "outputDirectory", ",", "getLastPackageName", "(", "getEffectiveNodePackageName", "(", ")", ")", ")", ";", "return", "null", ";", "}" ]
Gets the absolute path to the output directory for the syntax tree files. @return The absolute path to the output directory for the syntax tree files, only <code>null</code> if neither {@link #outputDirectory} nor {@link #nodeDirectory} have been set.
[ "Gets", "the", "absolute", "path", "to", "the", "output", "directory", "for", "the", "syntax", "tree", "files", "." ]
train
https://github.com/phax/ph-javacc-maven-plugin/blob/99497a971fe59ab2289258ca7ddcfa40e651f19f/src/main/java/org/codehaus/mojo/javacc/JTB.java#L212-L219
overturetool/overture
ide/core/src/main/java/org/overture/ide/internal/core/resources/VdmProject.java
VdmProject.createBaseProject
private static IProject createBaseProject(String projectName, URI location) { """ Just do the basics: create a basic project. @param location @param projectName """ // it is acceptable to use the ResourcesPlugin class IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); if (!newProject.exists()) { URI projectLocation = location; IProjectDescription desc = newProject.getWorkspace().newProjectDescription(newProject.getName()); if (location != null || ResourcesPlugin.getWorkspace().getRoot().getLocationURI().equals(location)) { projectLocation = null; } desc.setLocationURI(projectLocation); try { newProject.create(desc, null); if (!newProject.isOpen()) { newProject.open(null); } } catch (CoreException e) { VdmCore.log("VdmModelManager createBaseProject", e); } } return newProject; }
java
private static IProject createBaseProject(String projectName, URI location) { // it is acceptable to use the ResourcesPlugin class IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); if (!newProject.exists()) { URI projectLocation = location; IProjectDescription desc = newProject.getWorkspace().newProjectDescription(newProject.getName()); if (location != null || ResourcesPlugin.getWorkspace().getRoot().getLocationURI().equals(location)) { projectLocation = null; } desc.setLocationURI(projectLocation); try { newProject.create(desc, null); if (!newProject.isOpen()) { newProject.open(null); } } catch (CoreException e) { VdmCore.log("VdmModelManager createBaseProject", e); } } return newProject; }
[ "private", "static", "IProject", "createBaseProject", "(", "String", "projectName", ",", "URI", "location", ")", "{", "// it is acceptable to use the ResourcesPlugin class", "IProject", "newProject", "=", "ResourcesPlugin", ".", "getWorkspace", "(", ")", ".", "getRoot", "(", ")", ".", "getProject", "(", "projectName", ")", ";", "if", "(", "!", "newProject", ".", "exists", "(", ")", ")", "{", "URI", "projectLocation", "=", "location", ";", "IProjectDescription", "desc", "=", "newProject", ".", "getWorkspace", "(", ")", ".", "newProjectDescription", "(", "newProject", ".", "getName", "(", ")", ")", ";", "if", "(", "location", "!=", "null", "||", "ResourcesPlugin", ".", "getWorkspace", "(", ")", ".", "getRoot", "(", ")", ".", "getLocationURI", "(", ")", ".", "equals", "(", "location", ")", ")", "{", "projectLocation", "=", "null", ";", "}", "desc", ".", "setLocationURI", "(", "projectLocation", ")", ";", "try", "{", "newProject", ".", "create", "(", "desc", ",", "null", ")", ";", "if", "(", "!", "newProject", ".", "isOpen", "(", ")", ")", "{", "newProject", ".", "open", "(", "null", ")", ";", "}", "}", "catch", "(", "CoreException", "e", ")", "{", "VdmCore", ".", "log", "(", "\"VdmModelManager createBaseProject\"", ",", "e", ")", ";", "}", "}", "return", "newProject", ";", "}" ]
Just do the basics: create a basic project. @param location @param projectName
[ "Just", "do", "the", "basics", ":", "create", "a", "basic", "project", "." ]
train
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/core/src/main/java/org/overture/ide/internal/core/resources/VdmProject.java#L462-L493
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/CertificatesInner.java
CertificatesInner.createOrUpdate
public IntegrationAccountCertificateInner createOrUpdate(String resourceGroupName, String integrationAccountName, String certificateName, IntegrationAccountCertificateInner certificate) { """ Creates or updates an integration account certificate. @param resourceGroupName The resource group name. @param integrationAccountName The integration account name. @param certificateName The integration account certificate name. @param certificate The integration account certificate. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the IntegrationAccountCertificateInner object if successful. """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, certificateName, certificate).toBlocking().single().body(); }
java
public IntegrationAccountCertificateInner createOrUpdate(String resourceGroupName, String integrationAccountName, String certificateName, IntegrationAccountCertificateInner certificate) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, certificateName, certificate).toBlocking().single().body(); }
[ "public", "IntegrationAccountCertificateInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "integrationAccountName", ",", "String", "certificateName", ",", "IntegrationAccountCertificateInner", "certificate", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "integrationAccountName", ",", "certificateName", ",", "certificate", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates an integration account certificate. @param resourceGroupName The resource group name. @param integrationAccountName The integration account name. @param certificateName The integration account certificate name. @param certificate The integration account certificate. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the IntegrationAccountCertificateInner object if successful.
[ "Creates", "or", "updates", "an", "integration", "account", "certificate", "." ]
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/CertificatesInner.java#L436-L438
samskivert/pythagoras
src/main/java/pythagoras/f/Path.java
Path.checkBuf
protected void checkBuf (int pointCount, boolean checkMove) { """ Checks points and types buffer size to add pointCount points. If necessary realloc buffers to enlarge size. @param pointCount the point count to be added in buffer """ if (checkMove && typeSize == 0) { throw new IllegalPathStateException("First segment must be a SEG_MOVETO"); } if (typeSize == types.length) { byte[] tmp = new byte[typeSize + BUFFER_CAPACITY]; System.arraycopy(types, 0, tmp, 0, typeSize); types = tmp; } if (pointSize + pointCount > points.length) { float[] tmp = new float[pointSize + Math.max(BUFFER_CAPACITY * 2, pointCount)]; System.arraycopy(points, 0, tmp, 0, pointSize); points = tmp; } }
java
protected void checkBuf (int pointCount, boolean checkMove) { if (checkMove && typeSize == 0) { throw new IllegalPathStateException("First segment must be a SEG_MOVETO"); } if (typeSize == types.length) { byte[] tmp = new byte[typeSize + BUFFER_CAPACITY]; System.arraycopy(types, 0, tmp, 0, typeSize); types = tmp; } if (pointSize + pointCount > points.length) { float[] tmp = new float[pointSize + Math.max(BUFFER_CAPACITY * 2, pointCount)]; System.arraycopy(points, 0, tmp, 0, pointSize); points = tmp; } }
[ "protected", "void", "checkBuf", "(", "int", "pointCount", ",", "boolean", "checkMove", ")", "{", "if", "(", "checkMove", "&&", "typeSize", "==", "0", ")", "{", "throw", "new", "IllegalPathStateException", "(", "\"First segment must be a SEG_MOVETO\"", ")", ";", "}", "if", "(", "typeSize", "==", "types", ".", "length", ")", "{", "byte", "[", "]", "tmp", "=", "new", "byte", "[", "typeSize", "+", "BUFFER_CAPACITY", "]", ";", "System", ".", "arraycopy", "(", "types", ",", "0", ",", "tmp", ",", "0", ",", "typeSize", ")", ";", "types", "=", "tmp", ";", "}", "if", "(", "pointSize", "+", "pointCount", ">", "points", ".", "length", ")", "{", "float", "[", "]", "tmp", "=", "new", "float", "[", "pointSize", "+", "Math", ".", "max", "(", "BUFFER_CAPACITY", "*", "2", ",", "pointCount", ")", "]", ";", "System", ".", "arraycopy", "(", "points", ",", "0", ",", "tmp", ",", "0", ",", "pointSize", ")", ";", "points", "=", "tmp", ";", "}", "}" ]
Checks points and types buffer size to add pointCount points. If necessary realloc buffers to enlarge size. @param pointCount the point count to be added in buffer
[ "Checks", "points", "and", "types", "buffer", "size", "to", "add", "pointCount", "points", ".", "If", "necessary", "realloc", "buffers", "to", "enlarge", "size", "." ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Path.java#L264-L278
elki-project/elki
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/projection/SNE.java
SNE.computeQij
protected double computeQij(double[][] qij, double[][] solution) { """ Compute the qij of the solution, and the sum. @param qij Qij matrix (output) @param solution Solution matrix (input) @return qij sum """ double qij_sum = 0; for(int i = 1; i < qij.length; i++) { final double[] qij_i = qij[i], vi = solution[i]; for(int j = 0; j < i; j++) { qij_sum += qij_i[j] = qij[j][i] = MathUtil.exp(-sqDist(vi, solution[j])); } } return qij_sum * 2; // Symmetry }
java
protected double computeQij(double[][] qij, double[][] solution) { double qij_sum = 0; for(int i = 1; i < qij.length; i++) { final double[] qij_i = qij[i], vi = solution[i]; for(int j = 0; j < i; j++) { qij_sum += qij_i[j] = qij[j][i] = MathUtil.exp(-sqDist(vi, solution[j])); } } return qij_sum * 2; // Symmetry }
[ "protected", "double", "computeQij", "(", "double", "[", "]", "[", "]", "qij", ",", "double", "[", "]", "[", "]", "solution", ")", "{", "double", "qij_sum", "=", "0", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "qij", ".", "length", ";", "i", "++", ")", "{", "final", "double", "[", "]", "qij_i", "=", "qij", "[", "i", "]", ",", "vi", "=", "solution", "[", "i", "]", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "i", ";", "j", "++", ")", "{", "qij_sum", "+=", "qij_i", "[", "j", "]", "=", "qij", "[", "j", "]", "[", "i", "]", "=", "MathUtil", ".", "exp", "(", "-", "sqDist", "(", "vi", ",", "solution", "[", "j", "]", ")", ")", ";", "}", "}", "return", "qij_sum", "*", "2", ";", "// Symmetry", "}" ]
Compute the qij of the solution, and the sum. @param qij Qij matrix (output) @param solution Solution matrix (input) @return qij sum
[ "Compute", "the", "qij", "of", "the", "solution", "and", "the", "sum", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/projection/SNE.java#L257-L266
op4j/op4j
src/main/java/org/op4j/functions/FnString.java
FnString.toDate
public static final Function<String,Date> toDate(final String pattern, final Locale locale) { """ <p> Converts the target String to a <tt>java.util.Date</tt> by applying the specified pattern and locale. The locale is needed for correctly parsing month names. </p> <p> Pattern format is that of <tt>java.text.SimpleDateFormat</tt>. </p> @param pattern the pattern to be used. @param locale the locale which will be used for parsing month names @return the resulting Date """ return new ToDate(pattern, locale); }
java
public static final Function<String,Date> toDate(final String pattern, final Locale locale) { return new ToDate(pattern, locale); }
[ "public", "static", "final", "Function", "<", "String", ",", "Date", ">", "toDate", "(", "final", "String", "pattern", ",", "final", "Locale", "locale", ")", "{", "return", "new", "ToDate", "(", "pattern", ",", "locale", ")", ";", "}" ]
<p> Converts the target String to a <tt>java.util.Date</tt> by applying the specified pattern and locale. The locale is needed for correctly parsing month names. </p> <p> Pattern format is that of <tt>java.text.SimpleDateFormat</tt>. </p> @param pattern the pattern to be used. @param locale the locale which will be used for parsing month names @return the resulting Date
[ "<p", ">", "Converts", "the", "target", "String", "to", "a", "<tt", ">", "java", ".", "util", ".", "Date<", "/", "tt", ">", "by", "applying", "the", "specified", "pattern", "and", "locale", ".", "The", "locale", "is", "needed", "for", "correctly", "parsing", "month", "names", ".", "<", "/", "p", ">", "<p", ">", "Pattern", "format", "is", "that", "of", "<tt", ">", "java", ".", "text", ".", "SimpleDateFormat<", "/", "tt", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/functions/FnString.java#L1736-L1738
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java
ArrayFunctions.arrayPrepend
public static Expression arrayPrepend(String expression, Expression value) { """ Returned expression results in the new array with value pre-pended. """ return arrayPrepend(x(expression), value); }
java
public static Expression arrayPrepend(String expression, Expression value) { return arrayPrepend(x(expression), value); }
[ "public", "static", "Expression", "arrayPrepend", "(", "String", "expression", ",", "Expression", "value", ")", "{", "return", "arrayPrepend", "(", "x", "(", "expression", ")", ",", "value", ")", ";", "}" ]
Returned expression results in the new array with value pre-pended.
[ "Returned", "expression", "results", "in", "the", "new", "array", "with", "value", "pre", "-", "pended", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java#L289-L291
super-csv/super-csv
super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrMinMax.java
StrMinMax.execute
public Object execute(final Object value, final CsvContext context) { """ {@inheritDoc} @throws SuperCsvCellProcessorException if value is null @throws SuperCsvConstraintViolationException if {@code length < min} or {@code length > max} """ validateInputNotNull(value, context); final String stringValue = value.toString(); final int length = stringValue.length(); if( length < min || length > max ) { throw new SuperCsvConstraintViolationException(String.format( "the length (%d) of value '%s' does not lie between the min (%d) and max (%d) values (inclusive)", length, stringValue, min, max), context, this); } return next.execute(stringValue, context); }
java
public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); final String stringValue = value.toString(); final int length = stringValue.length(); if( length < min || length > max ) { throw new SuperCsvConstraintViolationException(String.format( "the length (%d) of value '%s' does not lie between the min (%d) and max (%d) values (inclusive)", length, stringValue, min, max), context, this); } return next.execute(stringValue, context); }
[ "public", "Object", "execute", "(", "final", "Object", "value", ",", "final", "CsvContext", "context", ")", "{", "validateInputNotNull", "(", "value", ",", "context", ")", ";", "final", "String", "stringValue", "=", "value", ".", "toString", "(", ")", ";", "final", "int", "length", "=", "stringValue", ".", "length", "(", ")", ";", "if", "(", "length", "<", "min", "||", "length", ">", "max", ")", "{", "throw", "new", "SuperCsvConstraintViolationException", "(", "String", ".", "format", "(", "\"the length (%d) of value '%s' does not lie between the min (%d) and max (%d) values (inclusive)\"", ",", "length", ",", "stringValue", ",", "min", ",", "max", ")", ",", "context", ",", "this", ")", ";", "}", "return", "next", ".", "execute", "(", "stringValue", ",", "context", ")", ";", "}" ]
{@inheritDoc} @throws SuperCsvCellProcessorException if value is null @throws SuperCsvConstraintViolationException if {@code length < min} or {@code length > max}
[ "{", "@inheritDoc", "}" ]
train
https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrMinMax.java#L105-L117
gallandarakhneorg/afc
core/maths/mathgeom/tobeincluded/src/d3/continuous/Quaternion.java
Quaternion.setEulerAngles
public void setEulerAngles(double attitude, double bank, double heading, CoordinateSystem3D system) { """ Set the quaternion with the Euler angles. @param attitude is the rotation around left vector. @param bank is the rotation around front vector. @param heading is the rotation around top vector. @param system the coordinate system to use for applying the Euler angles. @see <a href="http://en.wikipedia.org/wiki/Euler_angles">Euler Angles</a> @see <a href="http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm">Euler to Quaternion</a> """ CoordinateSystem3D cs = (system == null) ? CoordinateSystem3D.getDefaultCoordinateSystem() : system; double c1 = Math.cos(heading / 2.); double s1 = Math.sin(heading / 2.); double c2 = Math.cos(attitude / 2.); double s2 = Math.sin(attitude / 2.); double c3 = Math.cos(bank / 2.); double s3 = Math.sin(bank / 2.); double x1, y1, z1, w1; // Source: http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm // Standard used: XZY_RIGHT_HAND double c1c2 = c1 * c2; double s1s2 = s1 * s2; w1 = c1c2 * c3 - s1s2 * s3; x1 = c1c2 * s3 + s1s2 * c3; y1 = s1 * c2 * c3 + c1 * s2 * s3; z1 = c1 * s2 * c3 - s1 * c2 * s3; set(x1, y1, z1, w1); CoordinateSystem3D.XZY_RIGHT_HAND.toSystem(this, cs); }
java
public void setEulerAngles(double attitude, double bank, double heading, CoordinateSystem3D system) { CoordinateSystem3D cs = (system == null) ? CoordinateSystem3D.getDefaultCoordinateSystem() : system; double c1 = Math.cos(heading / 2.); double s1 = Math.sin(heading / 2.); double c2 = Math.cos(attitude / 2.); double s2 = Math.sin(attitude / 2.); double c3 = Math.cos(bank / 2.); double s3 = Math.sin(bank / 2.); double x1, y1, z1, w1; // Source: http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm // Standard used: XZY_RIGHT_HAND double c1c2 = c1 * c2; double s1s2 = s1 * s2; w1 = c1c2 * c3 - s1s2 * s3; x1 = c1c2 * s3 + s1s2 * c3; y1 = s1 * c2 * c3 + c1 * s2 * s3; z1 = c1 * s2 * c3 - s1 * c2 * s3; set(x1, y1, z1, w1); CoordinateSystem3D.XZY_RIGHT_HAND.toSystem(this, cs); }
[ "public", "void", "setEulerAngles", "(", "double", "attitude", ",", "double", "bank", ",", "double", "heading", ",", "CoordinateSystem3D", "system", ")", "{", "CoordinateSystem3D", "cs", "=", "(", "system", "==", "null", ")", "?", "CoordinateSystem3D", ".", "getDefaultCoordinateSystem", "(", ")", ":", "system", ";", "double", "c1", "=", "Math", ".", "cos", "(", "heading", "/", "2.", ")", ";", "double", "s1", "=", "Math", ".", "sin", "(", "heading", "/", "2.", ")", ";", "double", "c2", "=", "Math", ".", "cos", "(", "attitude", "/", "2.", ")", ";", "double", "s2", "=", "Math", ".", "sin", "(", "attitude", "/", "2.", ")", ";", "double", "c3", "=", "Math", ".", "cos", "(", "bank", "/", "2.", ")", ";", "double", "s3", "=", "Math", ".", "sin", "(", "bank", "/", "2.", ")", ";", "double", "x1", ",", "y1", ",", "z1", ",", "w1", ";", "// Source: http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm", "// Standard used: XZY_RIGHT_HAND", "double", "c1c2", "=", "c1", "*", "c2", ";", "double", "s1s2", "=", "s1", "*", "s2", ";", "w1", "=", "c1c2", "*", "c3", "-", "s1s2", "*", "s3", ";", "x1", "=", "c1c2", "*", "s3", "+", "s1s2", "*", "c3", ";", "y1", "=", "s1", "*", "c2", "*", "c3", "+", "c1", "*", "s2", "*", "s3", ";", "z1", "=", "c1", "*", "s2", "*", "c3", "-", "s1", "*", "c2", "*", "s3", ";", "set", "(", "x1", ",", "y1", ",", "z1", ",", "w1", ")", ";", "CoordinateSystem3D", ".", "XZY_RIGHT_HAND", ".", "toSystem", "(", "this", ",", "cs", ")", ";", "}" ]
Set the quaternion with the Euler angles. @param attitude is the rotation around left vector. @param bank is the rotation around front vector. @param heading is the rotation around top vector. @param system the coordinate system to use for applying the Euler angles. @see <a href="http://en.wikipedia.org/wiki/Euler_angles">Euler Angles</a> @see <a href="http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm">Euler to Quaternion</a>
[ "Set", "the", "quaternion", "with", "the", "Euler", "angles", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/tobeincluded/src/d3/continuous/Quaternion.java#L853-L876
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/ResultUtil.java
ResultUtil.listSearchCaseInsensitive
public static int listSearchCaseInsensitive(List<String> source, String target) { """ Given a list of String, do a case insensitive search for target string Used by resultsetMetadata to search for target column name @param source source string list @param target target string to match @return index in the source string list that matches the target string index starts from zero """ for (int i = 0; i < source.size(); i++) { if (target.equalsIgnoreCase(source.get(i))) { return i; } } return -1; }
java
public static int listSearchCaseInsensitive(List<String> source, String target) { for (int i = 0; i < source.size(); i++) { if (target.equalsIgnoreCase(source.get(i))) { return i; } } return -1; }
[ "public", "static", "int", "listSearchCaseInsensitive", "(", "List", "<", "String", ">", "source", ",", "String", "target", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "source", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "target", ".", "equalsIgnoreCase", "(", "source", ".", "get", "(", "i", ")", ")", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}" ]
Given a list of String, do a case insensitive search for target string Used by resultsetMetadata to search for target column name @param source source string list @param target target string to match @return index in the source string list that matches the target string index starts from zero
[ "Given", "a", "list", "of", "String", "do", "a", "case", "insensitive", "search", "for", "target", "string", "Used", "by", "resultsetMetadata", "to", "search", "for", "target", "column", "name" ]
train
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/ResultUtil.java#L1001-L1011
mgormley/pacaya
src/main/java/edu/jhu/pacaya/util/cli/ArgParser.java
ArgParser.getName
private static String getName(Opt option, Field field) { """ Gets the name specified in @Opt(name=...) if present, or the name of the field otherwise. """ if (option.name().equals(Opt.DEFAULT_STRING)) { return field.getName(); } else { return option.name(); } }
java
private static String getName(Opt option, Field field) { if (option.name().equals(Opt.DEFAULT_STRING)) { return field.getName(); } else { return option.name(); } }
[ "private", "static", "String", "getName", "(", "Opt", "option", ",", "Field", "field", ")", "{", "if", "(", "option", ".", "name", "(", ")", ".", "equals", "(", "Opt", ".", "DEFAULT_STRING", ")", ")", "{", "return", "field", ".", "getName", "(", ")", ";", "}", "else", "{", "return", "option", ".", "name", "(", ")", ";", "}", "}" ]
Gets the name specified in @Opt(name=...) if present, or the name of the field otherwise.
[ "Gets", "the", "name", "specified", "in" ]
train
https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/util/cli/ArgParser.java#L157-L163
rzwitserloot/lombok
src/core/lombok/javac/handlers/JavacHandlerUtil.java
JavacHandlerUtil.chainDots
public static JCExpression chainDots(JavacNode node, int pos, String elem1, String elem2, String... elems) { """ In javac, dotted access of any kind, from {@code java.lang.String} to {@code var.methodName} is represented by a fold-left of {@code Select} nodes with the leftmost string represented by a {@code Ident} node. This method generates such an expression. <p> The position of the generated node(s) will be equal to the {@code pos} parameter. For example, maker.Select(maker.Select(maker.Ident(NAME[java]), NAME[lang]), NAME[String]). @see com.sun.tools.javac.tree.JCTree.JCIdent @see com.sun.tools.javac.tree.JCTree.JCFieldAccess """ assert elems != null; JavacTreeMaker maker = node.getTreeMaker(); if (pos != -1) maker = maker.at(pos); JCExpression e = null; if (elem1 != null) e = maker.Ident(node.toName(elem1)); if (elem2 != null) e = e == null ? maker.Ident(node.toName(elem2)) : maker.Select(e, node.toName(elem2)); for (int i = 0 ; i < elems.length ; i++) { e = e == null ? maker.Ident(node.toName(elems[i])) : maker.Select(e, node.toName(elems[i])); } assert e != null; return e; }
java
public static JCExpression chainDots(JavacNode node, int pos, String elem1, String elem2, String... elems) { assert elems != null; JavacTreeMaker maker = node.getTreeMaker(); if (pos != -1) maker = maker.at(pos); JCExpression e = null; if (elem1 != null) e = maker.Ident(node.toName(elem1)); if (elem2 != null) e = e == null ? maker.Ident(node.toName(elem2)) : maker.Select(e, node.toName(elem2)); for (int i = 0 ; i < elems.length ; i++) { e = e == null ? maker.Ident(node.toName(elems[i])) : maker.Select(e, node.toName(elems[i])); } assert e != null; return e; }
[ "public", "static", "JCExpression", "chainDots", "(", "JavacNode", "node", ",", "int", "pos", ",", "String", "elem1", ",", "String", "elem2", ",", "String", "...", "elems", ")", "{", "assert", "elems", "!=", "null", ";", "JavacTreeMaker", "maker", "=", "node", ".", "getTreeMaker", "(", ")", ";", "if", "(", "pos", "!=", "-", "1", ")", "maker", "=", "maker", ".", "at", "(", "pos", ")", ";", "JCExpression", "e", "=", "null", ";", "if", "(", "elem1", "!=", "null", ")", "e", "=", "maker", ".", "Ident", "(", "node", ".", "toName", "(", "elem1", ")", ")", ";", "if", "(", "elem2", "!=", "null", ")", "e", "=", "e", "==", "null", "?", "maker", ".", "Ident", "(", "node", ".", "toName", "(", "elem2", ")", ")", ":", "maker", ".", "Select", "(", "e", ",", "node", ".", "toName", "(", "elem2", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "elems", ".", "length", ";", "i", "++", ")", "{", "e", "=", "e", "==", "null", "?", "maker", ".", "Ident", "(", "node", ".", "toName", "(", "elems", "[", "i", "]", ")", ")", ":", "maker", ".", "Select", "(", "e", ",", "node", ".", "toName", "(", "elems", "[", "i", "]", ")", ")", ";", "}", "assert", "e", "!=", "null", ";", "return", "e", ";", "}" ]
In javac, dotted access of any kind, from {@code java.lang.String} to {@code var.methodName} is represented by a fold-left of {@code Select} nodes with the leftmost string represented by a {@code Ident} node. This method generates such an expression. <p> The position of the generated node(s) will be equal to the {@code pos} parameter. For example, maker.Select(maker.Select(maker.Ident(NAME[java]), NAME[lang]), NAME[String]). @see com.sun.tools.javac.tree.JCTree.JCIdent @see com.sun.tools.javac.tree.JCTree.JCFieldAccess
[ "In", "javac", "dotted", "access", "of", "any", "kind", "from", "{", "@code", "java", ".", "lang", ".", "String", "}", "to", "{", "@code", "var", ".", "methodName", "}", "is", "represented", "by", "a", "fold", "-", "left", "of", "{", "@code", "Select", "}", "nodes", "with", "the", "leftmost", "string", "represented", "by", "a", "{", "@code", "Ident", "}", "node", ".", "This", "method", "generates", "such", "an", "expression", ".", "<p", ">", "The", "position", "of", "the", "generated", "node", "(", "s", ")", "will", "be", "equal", "to", "the", "{", "@code", "pos", "}", "parameter", "." ]
train
https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/javac/handlers/JavacHandlerUtil.java#L1358-L1373
soi-toolkit/soi-toolkit-mule
tools/soitoolkit-generator/soitoolkit-generator/src/main/java/org/soitoolkit/tools/generator/model/ModelFactory.java
ModelFactory.doCreateNewModel
private static IModel doCreateNewModel(String groupId, String artifactId, String version, String service, MuleVersionEnum muleVersion, DeploymentModelEnum deploymentModel, List<TransportEnum> transports, TransportEnum inboundTransport, TransportEnum outboundTransport, TransformerEnum transformerType, String serviceDescriptor, List<String> operations) { """ Constructor-method to use when service descriptors are required (e.g. schema and wsdl for services) @param groupId @param artifactId @param version @param service @param deploymentModel @param serviceDescriptor @param operations @return the new model instance """ try { DefaultModelImpl m = (DefaultModelImpl)modelClass.newInstance(); m.initModel(groupId, artifactId, version, service, muleVersion, deploymentModel, transports, inboundTransport, outboundTransport, transformerType, serviceDescriptor, operations); return m; } catch (Exception e) { throw new RuntimeException(e); } }
java
private static IModel doCreateNewModel(String groupId, String artifactId, String version, String service, MuleVersionEnum muleVersion, DeploymentModelEnum deploymentModel, List<TransportEnum> transports, TransportEnum inboundTransport, TransportEnum outboundTransport, TransformerEnum transformerType, String serviceDescriptor, List<String> operations) { try { DefaultModelImpl m = (DefaultModelImpl)modelClass.newInstance(); m.initModel(groupId, artifactId, version, service, muleVersion, deploymentModel, transports, inboundTransport, outboundTransport, transformerType, serviceDescriptor, operations); return m; } catch (Exception e) { throw new RuntimeException(e); } }
[ "private", "static", "IModel", "doCreateNewModel", "(", "String", "groupId", ",", "String", "artifactId", ",", "String", "version", ",", "String", "service", ",", "MuleVersionEnum", "muleVersion", ",", "DeploymentModelEnum", "deploymentModel", ",", "List", "<", "TransportEnum", ">", "transports", ",", "TransportEnum", "inboundTransport", ",", "TransportEnum", "outboundTransport", ",", "TransformerEnum", "transformerType", ",", "String", "serviceDescriptor", ",", "List", "<", "String", ">", "operations", ")", "{", "try", "{", "DefaultModelImpl", "m", "=", "(", "DefaultModelImpl", ")", "modelClass", ".", "newInstance", "(", ")", ";", "m", ".", "initModel", "(", "groupId", ",", "artifactId", ",", "version", ",", "service", ",", "muleVersion", ",", "deploymentModel", ",", "transports", ",", "inboundTransport", ",", "outboundTransport", ",", "transformerType", ",", "serviceDescriptor", ",", "operations", ")", ";", "return", "m", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Constructor-method to use when service descriptors are required (e.g. schema and wsdl for services) @param groupId @param artifactId @param version @param service @param deploymentModel @param serviceDescriptor @param operations @return the new model instance
[ "Constructor", "-", "method", "to", "use", "when", "service", "descriptors", "are", "required", "(", "e", ".", "g", ".", "schema", "and", "wsdl", "for", "services", ")" ]
train
https://github.com/soi-toolkit/soi-toolkit-mule/blob/e891350dbf55e6307be94d193d056bdb785b37d3/tools/soitoolkit-generator/soitoolkit-generator/src/main/java/org/soitoolkit/tools/generator/model/ModelFactory.java#L140-L148
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ZipUtil.java
ZipUtil.addDir
private static void addDir(String path, ZipOutputStream out) throws UtilException { """ 在压缩包中新建目录 @param path 压缩的路径 @param out 压缩文件存储对象 @throws UtilException IO异常 """ path = StrUtil.addSuffixIfNot(path, StrUtil.SLASH); try { out.putNextEntry(new ZipEntry(path)); } catch (IOException e) { throw new UtilException(e); } finally { closeEntry(out); } }
java
private static void addDir(String path, ZipOutputStream out) throws UtilException { path = StrUtil.addSuffixIfNot(path, StrUtil.SLASH); try { out.putNextEntry(new ZipEntry(path)); } catch (IOException e) { throw new UtilException(e); } finally { closeEntry(out); } }
[ "private", "static", "void", "addDir", "(", "String", "path", ",", "ZipOutputStream", "out", ")", "throws", "UtilException", "{", "path", "=", "StrUtil", ".", "addSuffixIfNot", "(", "path", ",", "StrUtil", ".", "SLASH", ")", ";", "try", "{", "out", ".", "putNextEntry", "(", "new", "ZipEntry", "(", "path", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "UtilException", "(", "e", ")", ";", "}", "finally", "{", "closeEntry", "(", "out", ")", ";", "}", "}" ]
在压缩包中新建目录 @param path 压缩的路径 @param out 压缩文件存储对象 @throws UtilException IO异常
[ "在压缩包中新建目录" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ZipUtil.java#L841-L850
hankcs/HanLP
src/main/java/com/hankcs/hanlp/mining/word/TfIdf.java
TfIdf.tfs
public static <TERM> Iterable<Map<TERM, Double>> tfs(Iterable<Collection<TERM>> documents) { """ 多文档词频 @param documents 多个文档,每个文档都是一个词袋 @param <TERM> 词语类型 @return 一个包含词频的Map的列表 """ return tfs(documents, TfType.NATURAL); }
java
public static <TERM> Iterable<Map<TERM, Double>> tfs(Iterable<Collection<TERM>> documents) { return tfs(documents, TfType.NATURAL); }
[ "public", "static", "<", "TERM", ">", "Iterable", "<", "Map", "<", "TERM", ",", "Double", ">", ">", "tfs", "(", "Iterable", "<", "Collection", "<", "TERM", ">", ">", "documents", ")", "{", "return", "tfs", "(", "documents", ",", "TfType", ".", "NATURAL", ")", ";", "}" ]
多文档词频 @param documents 多个文档,每个文档都是一个词袋 @param <TERM> 词语类型 @return 一个包含词频的Map的列表
[ "多文档词频" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/mining/word/TfIdf.java#L118-L121
googleapis/google-cloud-java
google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/v1/FirestoreAdminClient.java
FirestoreAdminClient.createIndex
public final Operation createIndex(String parent, Index index) { """ Creates a composite index. This returns a [google.longrunning.Operation][google.longrunning.Operation] which may be used to track the status of the creation. The metadata for the operation will be the type [IndexOperationMetadata][google.firestore.admin.v1.IndexOperationMetadata]. <p>Sample code: <pre><code> try (FirestoreAdminClient firestoreAdminClient = FirestoreAdminClient.create()) { ParentName parent = ParentName.of("[PROJECT]", "[DATABASE]", "[COLLECTION_ID]"); Index index = Index.newBuilder().build(); Operation response = firestoreAdminClient.createIndex(parent.toString(), index); } </code></pre> @param parent A parent name of the form `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` @param index The composite index to create. @throws com.google.api.gax.rpc.ApiException if the remote call fails """ CreateIndexRequest request = CreateIndexRequest.newBuilder().setParent(parent).setIndex(index).build(); return createIndex(request); }
java
public final Operation createIndex(String parent, Index index) { CreateIndexRequest request = CreateIndexRequest.newBuilder().setParent(parent).setIndex(index).build(); return createIndex(request); }
[ "public", "final", "Operation", "createIndex", "(", "String", "parent", ",", "Index", "index", ")", "{", "CreateIndexRequest", "request", "=", "CreateIndexRequest", ".", "newBuilder", "(", ")", ".", "setParent", "(", "parent", ")", ".", "setIndex", "(", "index", ")", ".", "build", "(", ")", ";", "return", "createIndex", "(", "request", ")", ";", "}" ]
Creates a composite index. This returns a [google.longrunning.Operation][google.longrunning.Operation] which may be used to track the status of the creation. The metadata for the operation will be the type [IndexOperationMetadata][google.firestore.admin.v1.IndexOperationMetadata]. <p>Sample code: <pre><code> try (FirestoreAdminClient firestoreAdminClient = FirestoreAdminClient.create()) { ParentName parent = ParentName.of("[PROJECT]", "[DATABASE]", "[COLLECTION_ID]"); Index index = Index.newBuilder().build(); Operation response = firestoreAdminClient.createIndex(parent.toString(), index); } </code></pre> @param parent A parent name of the form `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` @param index The composite index to create. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Creates", "a", "composite", "index", ".", "This", "returns", "a", "[", "google", ".", "longrunning", ".", "Operation", "]", "[", "google", ".", "longrunning", ".", "Operation", "]", "which", "may", "be", "used", "to", "track", "the", "status", "of", "the", "creation", ".", "The", "metadata", "for", "the", "operation", "will", "be", "the", "type", "[", "IndexOperationMetadata", "]", "[", "google", ".", "firestore", ".", "admin", ".", "v1", ".", "IndexOperationMetadata", "]", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/v1/FirestoreAdminClient.java#L231-L236
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java
FileUtil.readLines
public static <T extends Collection<String>> T readLines(File file, String charset, T collection) throws IORuntimeException { """ 从文件中读取每一行数据 @param <T> 集合类型 @param file 文件路径 @param charset 字符集 @param collection 集合 @return 文件中的每行内容的集合 @throws IORuntimeException IO异常 """ return FileReader.create(file, CharsetUtil.charset(charset)).readLines(collection); }
java
public static <T extends Collection<String>> T readLines(File file, String charset, T collection) throws IORuntimeException { return FileReader.create(file, CharsetUtil.charset(charset)).readLines(collection); }
[ "public", "static", "<", "T", "extends", "Collection", "<", "String", ">", ">", "T", "readLines", "(", "File", "file", ",", "String", "charset", ",", "T", "collection", ")", "throws", "IORuntimeException", "{", "return", "FileReader", ".", "create", "(", "file", ",", "CharsetUtil", ".", "charset", "(", "charset", ")", ")", ".", "readLines", "(", "collection", ")", ";", "}" ]
从文件中读取每一行数据 @param <T> 集合类型 @param file 文件路径 @param charset 字符集 @param collection 集合 @return 文件中的每行内容的集合 @throws IORuntimeException IO异常
[ "从文件中读取每一行数据" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L2220-L2222
googleapis/google-cloud-java
google-cloud-clients/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystem.java
CloudStorageFileSystem.forBucket
@CheckReturnValue public static CloudStorageFileSystem forBucket(String bucket, CloudStorageConfiguration config) { """ Creates new file system instance for {@code bucket}, with customizable settings. @see #forBucket(String) """ checkArgument( !bucket.startsWith(URI_SCHEME + ":"), "Bucket name must not have schema: %s", bucket); checkNotNull(config); return new CloudStorageFileSystem( new CloudStorageFileSystemProvider(config.userProject()), bucket, config); }
java
@CheckReturnValue public static CloudStorageFileSystem forBucket(String bucket, CloudStorageConfiguration config) { checkArgument( !bucket.startsWith(URI_SCHEME + ":"), "Bucket name must not have schema: %s", bucket); checkNotNull(config); return new CloudStorageFileSystem( new CloudStorageFileSystemProvider(config.userProject()), bucket, config); }
[ "@", "CheckReturnValue", "public", "static", "CloudStorageFileSystem", "forBucket", "(", "String", "bucket", ",", "CloudStorageConfiguration", "config", ")", "{", "checkArgument", "(", "!", "bucket", ".", "startsWith", "(", "URI_SCHEME", "+", "\":\"", ")", ",", "\"Bucket name must not have schema: %s\"", ",", "bucket", ")", ";", "checkNotNull", "(", "config", ")", ";", "return", "new", "CloudStorageFileSystem", "(", "new", "CloudStorageFileSystemProvider", "(", "config", ".", "userProject", "(", ")", ")", ",", "bucket", ",", "config", ")", ";", "}" ]
Creates new file system instance for {@code bucket}, with customizable settings. @see #forBucket(String)
[ "Creates", "new", "file", "system", "instance", "for", "{", "@code", "bucket", "}", "with", "customizable", "settings", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystem.java#L142-L149
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/github/lgooddatepicker/durationpicker_underconstruction/DurationDemo.java
DurationDemo.initializeComponents
private void initializeComponents() { """ initializeComponents, This creates the user interface for the basic demo. """ // Set up the form which holds the date picker components. setTitle("LGoodDatePicker Basic Demo " + InternalUtilities.getProjectVersionString()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); setSize(new Dimension(640, 480)); setLocationRelativeTo(null); // Create a duration picker, and add it to the form. DurationPicker durationPicker1 = new DurationPicker(); add(durationPicker1); /** * The code below shows: 1) How to create a DateTimePicker (with default settings), 2) How * to create a DatePicker with some custom settings, and 3) How to create a TimePicker with * some custom settings. To keep the Basic Demo interface simpler, the lines for adding * these components to the form have been commented out. */ // Create a DateTimePicker. (But don't add it to the form). DateTimePicker dateTimePicker1 = new DateTimePicker(); // To display this picker, uncomment this line. // add(dateTimePicker1); // Create a date picker with some custom settings. DatePickerSettings dateSettings = new DatePickerSettings(); dateSettings.setFirstDayOfWeek(DayOfWeek.MONDAY); DatePicker datePicker2 = new DatePicker(dateSettings); // To display this picker, uncomment this line. // add(datePicker2); // Create a time picker with some custom settings. TimePickerSettings timeSettings = new TimePickerSettings(); timeSettings.setColor(TimeArea.TimePickerTextValidTime, Color.blue); timeSettings.initialTime = LocalTime.now(); TimePicker timePicker2 = new TimePicker(timeSettings); // To display this picker, uncomment this line. // add(timePicker2); }
java
private void initializeComponents() { // Set up the form which holds the date picker components. setTitle("LGoodDatePicker Basic Demo " + InternalUtilities.getProjectVersionString()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); setSize(new Dimension(640, 480)); setLocationRelativeTo(null); // Create a duration picker, and add it to the form. DurationPicker durationPicker1 = new DurationPicker(); add(durationPicker1); /** * The code below shows: 1) How to create a DateTimePicker (with default settings), 2) How * to create a DatePicker with some custom settings, and 3) How to create a TimePicker with * some custom settings. To keep the Basic Demo interface simpler, the lines for adding * these components to the form have been commented out. */ // Create a DateTimePicker. (But don't add it to the form). DateTimePicker dateTimePicker1 = new DateTimePicker(); // To display this picker, uncomment this line. // add(dateTimePicker1); // Create a date picker with some custom settings. DatePickerSettings dateSettings = new DatePickerSettings(); dateSettings.setFirstDayOfWeek(DayOfWeek.MONDAY); DatePicker datePicker2 = new DatePicker(dateSettings); // To display this picker, uncomment this line. // add(datePicker2); // Create a time picker with some custom settings. TimePickerSettings timeSettings = new TimePickerSettings(); timeSettings.setColor(TimeArea.TimePickerTextValidTime, Color.blue); timeSettings.initialTime = LocalTime.now(); TimePicker timePicker2 = new TimePicker(timeSettings); // To display this picker, uncomment this line. // add(timePicker2); }
[ "private", "void", "initializeComponents", "(", ")", "{", "// Set up the form which holds the date picker components. ", "setTitle", "(", "\"LGoodDatePicker Basic Demo \"", "+", "InternalUtilities", ".", "getProjectVersionString", "(", ")", ")", ";", "setDefaultCloseOperation", "(", "JFrame", ".", "EXIT_ON_CLOSE", ")", ";", "setLayout", "(", "new", "FlowLayout", "(", ")", ")", ";", "setSize", "(", "new", "Dimension", "(", "640", ",", "480", ")", ")", ";", "setLocationRelativeTo", "(", "null", ")", ";", "// Create a duration picker, and add it to the form.", "DurationPicker", "durationPicker1", "=", "new", "DurationPicker", "(", ")", ";", "add", "(", "durationPicker1", ")", ";", "/**\n * The code below shows: 1) How to create a DateTimePicker (with default settings), 2) How\n * to create a DatePicker with some custom settings, and 3) How to create a TimePicker with\n * some custom settings. To keep the Basic Demo interface simpler, the lines for adding\n * these components to the form have been commented out.\n */", "// Create a DateTimePicker. (But don't add it to the form).", "DateTimePicker", "dateTimePicker1", "=", "new", "DateTimePicker", "(", ")", ";", "// To display this picker, uncomment this line.", "// add(dateTimePicker1);", "// Create a date picker with some custom settings. ", "DatePickerSettings", "dateSettings", "=", "new", "DatePickerSettings", "(", ")", ";", "dateSettings", ".", "setFirstDayOfWeek", "(", "DayOfWeek", ".", "MONDAY", ")", ";", "DatePicker", "datePicker2", "=", "new", "DatePicker", "(", "dateSettings", ")", ";", "// To display this picker, uncomment this line.", "// add(datePicker2);", "// Create a time picker with some custom settings.", "TimePickerSettings", "timeSettings", "=", "new", "TimePickerSettings", "(", ")", ";", "timeSettings", ".", "setColor", "(", "TimeArea", ".", "TimePickerTextValidTime", ",", "Color", ".", "blue", ")", ";", "timeSettings", ".", "initialTime", "=", "LocalTime", ".", "now", "(", ")", ";", "TimePicker", "timePicker2", "=", "new", "TimePicker", "(", "timeSettings", ")", ";", "// To display this picker, uncomment this line.", "// add(timePicker2);", "}" ]
initializeComponents, This creates the user interface for the basic demo.
[ "initializeComponents", "This", "creates", "the", "user", "interface", "for", "the", "basic", "demo", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/github/lgooddatepicker/durationpicker_underconstruction/DurationDemo.java#L49-L86
lucee/Lucee
core/src/main/java/lucee/commons/io/res/util/ResourceSnippet.java
ResourceSnippet.createResourceSnippet
public static ResourceSnippet createResourceSnippet(Resource res, int startChar, int endChar, String charset) { """ extract a ResourceSnippet from a Resource at the given char positions @param res - Resource from which to extract the snippet @param startChar - start position of the snippet @param endChar - end position of the snippet @param charset - use server's charset, default should be UTF-8 @return """ try { return createResourceSnippet(res.getInputStream(), startChar, endChar, charset); } catch (IOException ex) { return ResourceSnippet.Empty; } }
java
public static ResourceSnippet createResourceSnippet(Resource res, int startChar, int endChar, String charset) { try { return createResourceSnippet(res.getInputStream(), startChar, endChar, charset); } catch (IOException ex) { return ResourceSnippet.Empty; } }
[ "public", "static", "ResourceSnippet", "createResourceSnippet", "(", "Resource", "res", ",", "int", "startChar", ",", "int", "endChar", ",", "String", "charset", ")", "{", "try", "{", "return", "createResourceSnippet", "(", "res", ".", "getInputStream", "(", ")", ",", "startChar", ",", "endChar", ",", "charset", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "return", "ResourceSnippet", ".", "Empty", ";", "}", "}" ]
extract a ResourceSnippet from a Resource at the given char positions @param res - Resource from which to extract the snippet @param startChar - start position of the snippet @param endChar - end position of the snippet @param charset - use server's charset, default should be UTF-8 @return
[ "extract", "a", "ResourceSnippet", "from", "a", "Resource", "at", "the", "given", "char", "positions" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/io/res/util/ResourceSnippet.java#L120-L130
apache/incubator-gobblin
gobblin-api/src/main/java/org/apache/gobblin/password/PasswordManager.java
PasswordManager.getInstance
public static PasswordManager getInstance(Path masterPwdLoc) { """ Get an instance. The master password file is given by masterPwdLoc. """ State state = new State(); state.setProp(ConfigurationKeys.ENCRYPT_KEY_LOC, masterPwdLoc.toString()); state.setProp(ConfigurationKeys.ENCRYPT_KEY_FS_URI, masterPwdLoc.toUri()); try { return CACHED_INSTANCES .get(new CachedInstanceKey(state)); } catch (ExecutionException e) { throw new RuntimeException("Unable to get an instance of PasswordManager", e); } }
java
public static PasswordManager getInstance(Path masterPwdLoc) { State state = new State(); state.setProp(ConfigurationKeys.ENCRYPT_KEY_LOC, masterPwdLoc.toString()); state.setProp(ConfigurationKeys.ENCRYPT_KEY_FS_URI, masterPwdLoc.toUri()); try { return CACHED_INSTANCES .get(new CachedInstanceKey(state)); } catch (ExecutionException e) { throw new RuntimeException("Unable to get an instance of PasswordManager", e); } }
[ "public", "static", "PasswordManager", "getInstance", "(", "Path", "masterPwdLoc", ")", "{", "State", "state", "=", "new", "State", "(", ")", ";", "state", ".", "setProp", "(", "ConfigurationKeys", ".", "ENCRYPT_KEY_LOC", ",", "masterPwdLoc", ".", "toString", "(", ")", ")", ";", "state", ".", "setProp", "(", "ConfigurationKeys", ".", "ENCRYPT_KEY_FS_URI", ",", "masterPwdLoc", ".", "toUri", "(", ")", ")", ";", "try", "{", "return", "CACHED_INSTANCES", ".", "get", "(", "new", "CachedInstanceKey", "(", "state", ")", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Unable to get an instance of PasswordManager\"", ",", "e", ")", ";", "}", "}" ]
Get an instance. The master password file is given by masterPwdLoc.
[ "Get", "an", "instance", ".", "The", "master", "password", "file", "is", "given", "by", "masterPwdLoc", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/password/PasswordManager.java#L178-L188
eFaps/eFaps-Kernel
src/main/java/org/efaps/db/store/JDBCStoreResource.java
JDBCStoreResource.read
@Override public InputStream read() throws EFapsException { """ Returns for the file the input stream. @return input stream of the file with the content @throws EFapsException on error """ StoreResourceInputStream in = null; ConnectionResource res = null; try { res = Context.getThreadContext().getConnectionResource(); final Statement stmt = res.createStatement(); final StringBuffer cmd = new StringBuffer() .append("select ").append(JDBCStoreResource.COLNAME_FILECONTENT).append(" ") .append("from ").append(JDBCStoreResource.TABLENAME_STORE).append(" ") .append("where ID =").append(getGeneralID()); final ResultSet resultSet = stmt.executeQuery(cmd.toString()); if (resultSet.next()) { if (Context.getDbType().supportsBinaryInputStream()) { in = new JDBCStoreResourceInputStream(this, res, resultSet.getBinaryStream(1)); } else { in = new JDBCStoreResourceInputStream(this, res, resultSet.getBlob(1)); } } resultSet.close(); stmt.close(); } catch (final IOException e) { JDBCStoreResource.LOG.error("read of content failed", e); throw new EFapsException(JDBCStoreResource.class, "read.SQLException", e); } catch (final SQLException e) { JDBCStoreResource.LOG.error("read of content failed", e); throw new EFapsException(JDBCStoreResource.class, "read.SQLException", e); } return in; }
java
@Override public InputStream read() throws EFapsException { StoreResourceInputStream in = null; ConnectionResource res = null; try { res = Context.getThreadContext().getConnectionResource(); final Statement stmt = res.createStatement(); final StringBuffer cmd = new StringBuffer() .append("select ").append(JDBCStoreResource.COLNAME_FILECONTENT).append(" ") .append("from ").append(JDBCStoreResource.TABLENAME_STORE).append(" ") .append("where ID =").append(getGeneralID()); final ResultSet resultSet = stmt.executeQuery(cmd.toString()); if (resultSet.next()) { if (Context.getDbType().supportsBinaryInputStream()) { in = new JDBCStoreResourceInputStream(this, res, resultSet.getBinaryStream(1)); } else { in = new JDBCStoreResourceInputStream(this, res, resultSet.getBlob(1)); } } resultSet.close(); stmt.close(); } catch (final IOException e) { JDBCStoreResource.LOG.error("read of content failed", e); throw new EFapsException(JDBCStoreResource.class, "read.SQLException", e); } catch (final SQLException e) { JDBCStoreResource.LOG.error("read of content failed", e); throw new EFapsException(JDBCStoreResource.class, "read.SQLException", e); } return in; }
[ "@", "Override", "public", "InputStream", "read", "(", ")", "throws", "EFapsException", "{", "StoreResourceInputStream", "in", "=", "null", ";", "ConnectionResource", "res", "=", "null", ";", "try", "{", "res", "=", "Context", ".", "getThreadContext", "(", ")", ".", "getConnectionResource", "(", ")", ";", "final", "Statement", "stmt", "=", "res", ".", "createStatement", "(", ")", ";", "final", "StringBuffer", "cmd", "=", "new", "StringBuffer", "(", ")", ".", "append", "(", "\"select \"", ")", ".", "append", "(", "JDBCStoreResource", ".", "COLNAME_FILECONTENT", ")", ".", "append", "(", "\" \"", ")", ".", "append", "(", "\"from \"", ")", ".", "append", "(", "JDBCStoreResource", ".", "TABLENAME_STORE", ")", ".", "append", "(", "\" \"", ")", ".", "append", "(", "\"where ID =\"", ")", ".", "append", "(", "getGeneralID", "(", ")", ")", ";", "final", "ResultSet", "resultSet", "=", "stmt", ".", "executeQuery", "(", "cmd", ".", "toString", "(", ")", ")", ";", "if", "(", "resultSet", ".", "next", "(", ")", ")", "{", "if", "(", "Context", ".", "getDbType", "(", ")", ".", "supportsBinaryInputStream", "(", ")", ")", "{", "in", "=", "new", "JDBCStoreResourceInputStream", "(", "this", ",", "res", ",", "resultSet", ".", "getBinaryStream", "(", "1", ")", ")", ";", "}", "else", "{", "in", "=", "new", "JDBCStoreResourceInputStream", "(", "this", ",", "res", ",", "resultSet", ".", "getBlob", "(", "1", ")", ")", ";", "}", "}", "resultSet", ".", "close", "(", ")", ";", "stmt", ".", "close", "(", ")", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "JDBCStoreResource", ".", "LOG", ".", "error", "(", "\"read of content failed\"", ",", "e", ")", ";", "throw", "new", "EFapsException", "(", "JDBCStoreResource", ".", "class", ",", "\"read.SQLException\"", ",", "e", ")", ";", "}", "catch", "(", "final", "SQLException", "e", ")", "{", "JDBCStoreResource", ".", "LOG", ".", "error", "(", "\"read of content failed\"", ",", "e", ")", ";", "throw", "new", "EFapsException", "(", "JDBCStoreResource", ".", "class", ",", "\"read.SQLException\"", ",", "e", ")", ";", "}", "return", "in", ";", "}" ]
Returns for the file the input stream. @return input stream of the file with the content @throws EFapsException on error
[ "Returns", "for", "the", "file", "the", "input", "stream", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/db/store/JDBCStoreResource.java#L179-L215
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/util/GosuStringUtil.java
GosuStringUtil.countRegexpMatches
public static int countRegexpMatches(String str, String regexp) { """ <p>Counts how many times the regexp appears in the larger String.</p> <p>A <code>null</code> or empty ("") String input returns <code>0</code>.</p> <pre> GosuStringUtil.countMatches(null, *) = 0 GosuStringUtil.countMatches("", *) = 0 GosuStringUtil.countMatches("abba", null) = 0 GosuStringUtil.countMatches("abba", "") = 0 GosuStringUtil.countMatches("abba", "a") = 2 GosuStringUtil.countMatches("abba", "ab") = 1 GosuStringUtil.countMatches("abba", ".b") = 2 GosuStringUtil.countMatches("abba", "xxx") = 0 </pre> @param str the String to check, may be null @param regexp the regexp to count, may be null @return the number of occurrences, 0 if either String is <code>null</code> """ if (isEmpty(str) || isEmpty(regexp)) { return 0; } Pattern pattern = Pattern.compile(regexp); Matcher matcher = pattern.matcher(str); int i = 0; while (matcher.find()) { i++; } return i; }
java
public static int countRegexpMatches(String str, String regexp) { if (isEmpty(str) || isEmpty(regexp)) { return 0; } Pattern pattern = Pattern.compile(regexp); Matcher matcher = pattern.matcher(str); int i = 0; while (matcher.find()) { i++; } return i; }
[ "public", "static", "int", "countRegexpMatches", "(", "String", "str", ",", "String", "regexp", ")", "{", "if", "(", "isEmpty", "(", "str", ")", "||", "isEmpty", "(", "regexp", ")", ")", "{", "return", "0", ";", "}", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "regexp", ")", ";", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", "str", ")", ";", "int", "i", "=", "0", ";", "while", "(", "matcher", ".", "find", "(", ")", ")", "{", "i", "++", ";", "}", "return", "i", ";", "}" ]
<p>Counts how many times the regexp appears in the larger String.</p> <p>A <code>null</code> or empty ("") String input returns <code>0</code>.</p> <pre> GosuStringUtil.countMatches(null, *) = 0 GosuStringUtil.countMatches("", *) = 0 GosuStringUtil.countMatches("abba", null) = 0 GosuStringUtil.countMatches("abba", "") = 0 GosuStringUtil.countMatches("abba", "a") = 2 GosuStringUtil.countMatches("abba", "ab") = 1 GosuStringUtil.countMatches("abba", ".b") = 2 GosuStringUtil.countMatches("abba", "xxx") = 0 </pre> @param str the String to check, may be null @param regexp the regexp to count, may be null @return the number of occurrences, 0 if either String is <code>null</code>
[ "<p", ">", "Counts", "how", "many", "times", "the", "regexp", "appears", "in", "the", "larger", "String", ".", "<", "/", "p", ">" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/util/GosuStringUtil.java#L4892-L4903
Stratio/stratio-cassandra
src/java/org/apache/cassandra/tools/SSTableExport.java
SSTableExport.enumeratekeys
public static void enumeratekeys(Descriptor desc, PrintStream outs, CFMetaData metadata) throws IOException { """ Enumerate row keys from an SSTableReader and write the result to a PrintStream. @param desc the descriptor of the file to export the rows from @param outs PrintStream to write the output to @param metadata Metadata to print keys in a proper format @throws IOException on failure to read/write input/output """ KeyIterator iter = new KeyIterator(desc); try { DecoratedKey lastKey = null; while (iter.hasNext()) { DecoratedKey key = iter.next(); // validate order of the keys in the sstable if (lastKey != null && lastKey.compareTo(key) > 0) throw new IOException("Key out of order! " + lastKey + " > " + key); lastKey = key; outs.println(metadata.getKeyValidator().getString(key.getKey())); checkStream(outs); // flushes } } finally { iter.close(); } }
java
public static void enumeratekeys(Descriptor desc, PrintStream outs, CFMetaData metadata) throws IOException { KeyIterator iter = new KeyIterator(desc); try { DecoratedKey lastKey = null; while (iter.hasNext()) { DecoratedKey key = iter.next(); // validate order of the keys in the sstable if (lastKey != null && lastKey.compareTo(key) > 0) throw new IOException("Key out of order! " + lastKey + " > " + key); lastKey = key; outs.println(metadata.getKeyValidator().getString(key.getKey())); checkStream(outs); // flushes } } finally { iter.close(); } }
[ "public", "static", "void", "enumeratekeys", "(", "Descriptor", "desc", ",", "PrintStream", "outs", ",", "CFMetaData", "metadata", ")", "throws", "IOException", "{", "KeyIterator", "iter", "=", "new", "KeyIterator", "(", "desc", ")", ";", "try", "{", "DecoratedKey", "lastKey", "=", "null", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "DecoratedKey", "key", "=", "iter", ".", "next", "(", ")", ";", "// validate order of the keys in the sstable", "if", "(", "lastKey", "!=", "null", "&&", "lastKey", ".", "compareTo", "(", "key", ")", ">", "0", ")", "throw", "new", "IOException", "(", "\"Key out of order! \"", "+", "lastKey", "+", "\" > \"", "+", "key", ")", ";", "lastKey", "=", "key", ";", "outs", ".", "println", "(", "metadata", ".", "getKeyValidator", "(", ")", ".", "getString", "(", "key", ".", "getKey", "(", ")", ")", ")", ";", "checkStream", "(", "outs", ")", ";", "// flushes", "}", "}", "finally", "{", "iter", ".", "close", "(", ")", ";", "}", "}" ]
Enumerate row keys from an SSTableReader and write the result to a PrintStream. @param desc the descriptor of the file to export the rows from @param outs PrintStream to write the output to @param metadata Metadata to print keys in a proper format @throws IOException on failure to read/write input/output
[ "Enumerate", "row", "keys", "from", "an", "SSTableReader", "and", "write", "the", "result", "to", "a", "PrintStream", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/tools/SSTableExport.java#L225-L249
guardtime/ksi-java-sdk
ksi-common/src/main/java/com/guardtime/ksi/tlv/TLVInputStream.java
TLVInputStream.readElement
public TLVElement readElement() throws IOException, TLVParserException { """ Reads the next TLV element from the stream. @return Instance of {@link TLVElement}. @throws IOException when reading from underlying stream fails. @throws TLVParserException when input stream is null. """ TlvHeader header = readHeader(); TLVElement element = new TLVElement(header.tlv16, header.nonCritical, header.forwarded, header.type); int count = countNestedTlvElements(header); if (count > 0) { readNestedElements(element, count); } else { element.setContent(readTlvContent(header)); } return element; }
java
public TLVElement readElement() throws IOException, TLVParserException { TlvHeader header = readHeader(); TLVElement element = new TLVElement(header.tlv16, header.nonCritical, header.forwarded, header.type); int count = countNestedTlvElements(header); if (count > 0) { readNestedElements(element, count); } else { element.setContent(readTlvContent(header)); } return element; }
[ "public", "TLVElement", "readElement", "(", ")", "throws", "IOException", ",", "TLVParserException", "{", "TlvHeader", "header", "=", "readHeader", "(", ")", ";", "TLVElement", "element", "=", "new", "TLVElement", "(", "header", ".", "tlv16", ",", "header", ".", "nonCritical", ",", "header", ".", "forwarded", ",", "header", ".", "type", ")", ";", "int", "count", "=", "countNestedTlvElements", "(", "header", ")", ";", "if", "(", "count", ">", "0", ")", "{", "readNestedElements", "(", "element", ",", "count", ")", ";", "}", "else", "{", "element", ".", "setContent", "(", "readTlvContent", "(", "header", ")", ")", ";", "}", "return", "element", ";", "}" ]
Reads the next TLV element from the stream. @return Instance of {@link TLVElement}. @throws IOException when reading from underlying stream fails. @throws TLVParserException when input stream is null.
[ "Reads", "the", "next", "TLV", "element", "from", "the", "stream", "." ]
train
https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-common/src/main/java/com/guardtime/ksi/tlv/TLVInputStream.java#L81-L91
JadiraOrg/jadira
cloning/src/main/java/org/jadira/reflection/access/unsafe/UnsafeOperations.java
UnsafeOperations.putBoolean
public final void putBoolean(Object parent, long offset, boolean value) { """ Puts the value at the given offset of the supplied parent object @param parent The Object's parent @param offset The offset @param value boolean to be put """ THE_UNSAFE.putBoolean(parent, offset, value); }
java
public final void putBoolean(Object parent, long offset, boolean value) { THE_UNSAFE.putBoolean(parent, offset, value); }
[ "public", "final", "void", "putBoolean", "(", "Object", "parent", ",", "long", "offset", ",", "boolean", "value", ")", "{", "THE_UNSAFE", ".", "putBoolean", "(", "parent", ",", "offset", ",", "value", ")", ";", "}" ]
Puts the value at the given offset of the supplied parent object @param parent The Object's parent @param offset The offset @param value boolean to be put
[ "Puts", "the", "value", "at", "the", "given", "offset", "of", "the", "supplied", "parent", "object" ]
train
https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/cloning/src/main/java/org/jadira/reflection/access/unsafe/UnsafeOperations.java#L953-L955
codelibs/fess
src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java
FessMessages.addConstraintsEanMessage
public FessMessages addConstraintsEanMessage(String property, String type) { """ Add the created action message for the key 'constraints.EAN.message' with parameters. <pre> message: {item} is invalid {type} barcode. </pre> @param property The property name for the message. (NotNull) @param type The parameter type for message. (NotNull) @return this. (NotNull) """ assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_EAN_MESSAGE, type)); return this; }
java
public FessMessages addConstraintsEanMessage(String property, String type) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_EAN_MESSAGE, type)); return this; }
[ "public", "FessMessages", "addConstraintsEanMessage", "(", "String", "property", ",", "String", "type", ")", "{", "assertPropertyNotNull", "(", "property", ")", ";", "add", "(", "property", ",", "new", "UserMessage", "(", "CONSTRAINTS_EAN_MESSAGE", ",", "type", ")", ")", ";", "return", "this", ";", "}" ]
Add the created action message for the key 'constraints.EAN.message' with parameters. <pre> message: {item} is invalid {type} barcode. </pre> @param property The property name for the message. (NotNull) @param type The parameter type for message. (NotNull) @return this. (NotNull)
[ "Add", "the", "created", "action", "message", "for", "the", "key", "constraints", ".", "EAN", ".", "message", "with", "parameters", ".", "<pre", ">", "message", ":", "{", "item", "}", "is", "invalid", "{", "type", "}", "barcode", ".", "<", "/", "pre", ">" ]
train
https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L814-L818
Azure/azure-sdk-for-java
kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/EventHubConnectionsInner.java
EventHubConnectionsInner.beginCreateOrUpdate
public EventHubConnectionInner beginCreateOrUpdate(String resourceGroupName, String clusterName, String databaseName, String eventHubConnectionName, EventHubConnectionInner parameters) { """ Creates or updates a Event Hub connection. @param resourceGroupName The name of the resource group containing the Kusto cluster. @param clusterName The name of the Kusto cluster. @param databaseName The name of the database in the Kusto cluster. @param eventHubConnectionName The name of the event hub connection. @param parameters The Event Hub connection parameters supplied to the CreateOrUpdate operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the EventHubConnectionInner object if successful. """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, clusterName, databaseName, eventHubConnectionName, parameters).toBlocking().single().body(); }
java
public EventHubConnectionInner beginCreateOrUpdate(String resourceGroupName, String clusterName, String databaseName, String eventHubConnectionName, EventHubConnectionInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, clusterName, databaseName, eventHubConnectionName, parameters).toBlocking().single().body(); }
[ "public", "EventHubConnectionInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "clusterName", ",", "String", "databaseName", ",", "String", "eventHubConnectionName", ",", "EventHubConnectionInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "clusterName", ",", "databaseName", ",", "eventHubConnectionName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates a Event Hub connection. @param resourceGroupName The name of the resource group containing the Kusto cluster. @param clusterName The name of the Kusto cluster. @param databaseName The name of the database in the Kusto cluster. @param eventHubConnectionName The name of the event hub connection. @param parameters The Event Hub connection parameters supplied to the CreateOrUpdate operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the EventHubConnectionInner object if successful.
[ "Creates", "or", "updates", "a", "Event", "Hub", "connection", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/EventHubConnectionsInner.java#L504-L506
BlueBrain/bluima
modules/bluima_abbreviations/src/main/java/com/wcohen/ss/SourcedTFIDF.java
SourcedTFIDF.explainScore
public String explainScore(StringWrapper s, StringWrapper t) { """ Explain how the distance was computed. In the output, the tokens in S and T are listed, and the common tokens are marked with an asterisk. """ BagOfSourcedTokens sBag = (BagOfSourcedTokens)s; BagOfSourcedTokens tBag = (BagOfSourcedTokens)t; StringBuffer buf = new StringBuffer(""); PrintfFormat fmt = new PrintfFormat("%.3f"); buf.append("Common tokens: "); for (Iterator i = sBag.tokenIterator(); i.hasNext(); ) { SourcedToken sTok = (SourcedToken)i.next(); SourcedToken tTok = null; if ((tTok = tBag.getEquivalentToken(sTok))!=null) { buf.append(" "+sTok.getValue()+": "); buf.append(fmt.sprintf(sBag.getWeight(sTok))); buf.append("*"); buf.append(fmt.sprintf(tBag.getWeight(tTok))); } } buf.append("\nscore = "+score(s,t)); return buf.toString(); }
java
public String explainScore(StringWrapper s, StringWrapper t) { BagOfSourcedTokens sBag = (BagOfSourcedTokens)s; BagOfSourcedTokens tBag = (BagOfSourcedTokens)t; StringBuffer buf = new StringBuffer(""); PrintfFormat fmt = new PrintfFormat("%.3f"); buf.append("Common tokens: "); for (Iterator i = sBag.tokenIterator(); i.hasNext(); ) { SourcedToken sTok = (SourcedToken)i.next(); SourcedToken tTok = null; if ((tTok = tBag.getEquivalentToken(sTok))!=null) { buf.append(" "+sTok.getValue()+": "); buf.append(fmt.sprintf(sBag.getWeight(sTok))); buf.append("*"); buf.append(fmt.sprintf(tBag.getWeight(tTok))); } } buf.append("\nscore = "+score(s,t)); return buf.toString(); }
[ "public", "String", "explainScore", "(", "StringWrapper", "s", ",", "StringWrapper", "t", ")", "{", "BagOfSourcedTokens", "sBag", "=", "(", "BagOfSourcedTokens", ")", "s", ";", "BagOfSourcedTokens", "tBag", "=", "(", "BagOfSourcedTokens", ")", "t", ";", "StringBuffer", "buf", "=", "new", "StringBuffer", "(", "\"\"", ")", ";", "PrintfFormat", "fmt", "=", "new", "PrintfFormat", "(", "\"%.3f\"", ")", ";", "buf", ".", "append", "(", "\"Common tokens: \"", ")", ";", "for", "(", "Iterator", "i", "=", "sBag", ".", "tokenIterator", "(", ")", ";", "i", ".", "hasNext", "(", ")", ";", ")", "{", "SourcedToken", "sTok", "=", "(", "SourcedToken", ")", "i", ".", "next", "(", ")", ";", "SourcedToken", "tTok", "=", "null", ";", "if", "(", "(", "tTok", "=", "tBag", ".", "getEquivalentToken", "(", "sTok", ")", ")", "!=", "null", ")", "{", "buf", ".", "append", "(", "\" \"", "+", "sTok", ".", "getValue", "(", ")", "+", "\": \"", ")", ";", "buf", ".", "append", "(", "fmt", ".", "sprintf", "(", "sBag", ".", "getWeight", "(", "sTok", ")", ")", ")", ";", "buf", ".", "append", "(", "\"*\"", ")", ";", "buf", ".", "append", "(", "fmt", ".", "sprintf", "(", "tBag", ".", "getWeight", "(", "tTok", ")", ")", ")", ";", "}", "}", "buf", ".", "append", "(", "\"\\nscore = \"", "+", "score", "(", "s", ",", "t", ")", ")", ";", "return", "buf", ".", "toString", "(", ")", ";", "}" ]
Explain how the distance was computed. In the output, the tokens in S and T are listed, and the common tokens are marked with an asterisk.
[ "Explain", "how", "the", "distance", "was", "computed", ".", "In", "the", "output", "the", "tokens", "in", "S", "and", "T", "are", "listed", "and", "the", "common", "tokens", "are", "marked", "with", "an", "asterisk", "." ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_abbreviations/src/main/java/com/wcohen/ss/SourcedTFIDF.java#L137-L156
netty/netty
handler/src/main/java/io/netty/handler/ssl/SslContext.java
SslContext.newHandler
public final SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort) { """ Creates a new {@link SslHandler} @see #newHandler(ByteBufAllocator, String, int, Executor) """ return newHandler(alloc, peerHost, peerPort, startTls); }
java
public final SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort) { return newHandler(alloc, peerHost, peerPort, startTls); }
[ "public", "final", "SslHandler", "newHandler", "(", "ByteBufAllocator", "alloc", ",", "String", "peerHost", ",", "int", "peerPort", ")", "{", "return", "newHandler", "(", "alloc", ",", "peerHost", ",", "peerPort", ",", "startTls", ")", ";", "}" ]
Creates a new {@link SslHandler} @see #newHandler(ByteBufAllocator, String, int, Executor)
[ "Creates", "a", "new", "{", "@link", "SslHandler", "}" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/SslContext.java#L941-L943
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/util/Maps.java
Maps.putIntoValueArrayList
public static <K, V> void putIntoValueArrayList(Map<K, List<V>> map, K key, V value) { """ Adds the value to the ArrayList given by map.get(key), creating a new ArrayList if needed. """ CollectionFactory<V> factory = CollectionFactory.arrayListFactory(); putIntoValueCollection(map, key, value, factory); }
java
public static <K, V> void putIntoValueArrayList(Map<K, List<V>> map, K key, V value) { CollectionFactory<V> factory = CollectionFactory.arrayListFactory(); putIntoValueCollection(map, key, value, factory); }
[ "public", "static", "<", "K", ",", "V", ">", "void", "putIntoValueArrayList", "(", "Map", "<", "K", ",", "List", "<", "V", ">", ">", "map", ",", "K", "key", ",", "V", "value", ")", "{", "CollectionFactory", "<", "V", ">", "factory", "=", "CollectionFactory", ".", "arrayListFactory", "(", ")", ";", "putIntoValueCollection", "(", "map", ",", "key", ",", "value", ",", "factory", ")", ";", "}" ]
Adds the value to the ArrayList given by map.get(key), creating a new ArrayList if needed.
[ "Adds", "the", "value", "to", "the", "ArrayList", "given", "by", "map", ".", "get", "(", "key", ")", "creating", "a", "new", "ArrayList", "if", "needed", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/Maps.java#L34-L37
dita-ot/dita-ot
src/main/java/org/dita/dost/util/XMLUtils.java
XMLUtils.removeAttribute
public static void removeAttribute(final AttributesImpl atts, final String qName) { """ Remove an attribute from the list. Do nothing if attribute does not exist. @param atts attributes @param qName QName of the attribute to remove """ final int i = atts.getIndex(qName); if (i != -1) { atts.removeAttribute(i); } }
java
public static void removeAttribute(final AttributesImpl atts, final String qName) { final int i = atts.getIndex(qName); if (i != -1) { atts.removeAttribute(i); } }
[ "public", "static", "void", "removeAttribute", "(", "final", "AttributesImpl", "atts", ",", "final", "String", "qName", ")", "{", "final", "int", "i", "=", "atts", ".", "getIndex", "(", "qName", ")", ";", "if", "(", "i", "!=", "-", "1", ")", "{", "atts", ".", "removeAttribute", "(", "i", ")", ";", "}", "}" ]
Remove an attribute from the list. Do nothing if attribute does not exist. @param atts attributes @param qName QName of the attribute to remove
[ "Remove", "an", "attribute", "from", "the", "list", ".", "Do", "nothing", "if", "attribute", "does", "not", "exist", "." ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/XMLUtils.java#L417-L422
alkacon/opencms-core
src/org/opencms/jsp/CmsJspTagBundle.java
CmsJspTagBundle.findMatch
private static ResourceBundle findMatch(String basename, Locale pref) { """ Gets the resource bundle with the given base name and preferred locale. @param basename the resource bundle base name @param pref the preferred locale """ ResourceBundle match = null; try { ResourceBundle bundle = CmsResourceBundleLoader.getBundle(basename, pref); match = bundle; } catch (MissingResourceException mre) { // ignored } return match; }
java
private static ResourceBundle findMatch(String basename, Locale pref) { ResourceBundle match = null; try { ResourceBundle bundle = CmsResourceBundleLoader.getBundle(basename, pref); match = bundle; } catch (MissingResourceException mre) { // ignored } return match; }
[ "private", "static", "ResourceBundle", "findMatch", "(", "String", "basename", ",", "Locale", "pref", ")", "{", "ResourceBundle", "match", "=", "null", ";", "try", "{", "ResourceBundle", "bundle", "=", "CmsResourceBundleLoader", ".", "getBundle", "(", "basename", ",", "pref", ")", ";", "match", "=", "bundle", ";", "}", "catch", "(", "MissingResourceException", "mre", ")", "{", "// ignored\r", "}", "return", "match", ";", "}" ]
Gets the resource bundle with the given base name and preferred locale. @param basename the resource bundle base name @param pref the preferred locale
[ "Gets", "the", "resource", "bundle", "with", "the", "given", "base", "name", "and", "preferred", "locale", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagBundle.java#L190-L200
zk1931/jzab
src/main/java/com/github/zk1931/jzab/FileUtils.java
FileUtils.writePropertiesToFile
public static void writePropertiesToFile(Properties prop, File file) throws IOException { """ Atomically writes properties to a file. This method writes properties to a file by first writing it to a temporary file and then atomically moving it to the destination, overwriting the destination file if it already exists. @param prop a Properties object to write. @param file file to write the value to. @throws IOException if an I/O error occurs. """ // Create a temp file in the same directory as the file parameter. File temp = File.createTempFile(file.getName(), null, file.getAbsoluteFile().getParentFile()); try (FileOutputStream fos = new FileOutputStream(temp)) { prop.store(fos, ""); fos.getChannel().force(true); } atomicMove(temp, file); LOG.debug("Atomically moved {} to {}", temp, file); }
java
public static void writePropertiesToFile(Properties prop, File file) throws IOException { // Create a temp file in the same directory as the file parameter. File temp = File.createTempFile(file.getName(), null, file.getAbsoluteFile().getParentFile()); try (FileOutputStream fos = new FileOutputStream(temp)) { prop.store(fos, ""); fos.getChannel().force(true); } atomicMove(temp, file); LOG.debug("Atomically moved {} to {}", temp, file); }
[ "public", "static", "void", "writePropertiesToFile", "(", "Properties", "prop", ",", "File", "file", ")", "throws", "IOException", "{", "// Create a temp file in the same directory as the file parameter.", "File", "temp", "=", "File", ".", "createTempFile", "(", "file", ".", "getName", "(", ")", ",", "null", ",", "file", ".", "getAbsoluteFile", "(", ")", ".", "getParentFile", "(", ")", ")", ";", "try", "(", "FileOutputStream", "fos", "=", "new", "FileOutputStream", "(", "temp", ")", ")", "{", "prop", ".", "store", "(", "fos", ",", "\"\"", ")", ";", "fos", ".", "getChannel", "(", ")", ".", "force", "(", "true", ")", ";", "}", "atomicMove", "(", "temp", ",", "file", ")", ";", "LOG", ".", "debug", "(", "\"Atomically moved {} to {}\"", ",", "temp", ",", "file", ")", ";", "}" ]
Atomically writes properties to a file. This method writes properties to a file by first writing it to a temporary file and then atomically moving it to the destination, overwriting the destination file if it already exists. @param prop a Properties object to write. @param file file to write the value to. @throws IOException if an I/O error occurs.
[ "Atomically", "writes", "properties", "to", "a", "file", "." ]
train
https://github.com/zk1931/jzab/blob/2a8893bcc1a125f3aebdaddee80ad49c9761bba1/src/main/java/com/github/zk1931/jzab/FileUtils.java#L103-L114
threerings/nenya
core/src/main/java/com/threerings/openal/ResourceStream.java
ResourceStream.queueResource
public void queueResource (String bundle, String resource, boolean loop) { """ Adds a resource to the queue of files to play. @param loop if true, play this file in a loop if there's nothing else on the queue """ try { queueURL(new URL("resource://" + bundle + "/" + resource), loop); } catch (MalformedURLException e) { log.warning("Invalid resource url.", "resource", resource, e); } }
java
public void queueResource (String bundle, String resource, boolean loop) { try { queueURL(new URL("resource://" + bundle + "/" + resource), loop); } catch (MalformedURLException e) { log.warning("Invalid resource url.", "resource", resource, e); } }
[ "public", "void", "queueResource", "(", "String", "bundle", ",", "String", "resource", ",", "boolean", "loop", ")", "{", "try", "{", "queueURL", "(", "new", "URL", "(", "\"resource://\"", "+", "bundle", "+", "\"/\"", "+", "resource", ")", ",", "loop", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "log", ".", "warning", "(", "\"Invalid resource url.\"", ",", "\"resource\"", ",", "resource", ",", "e", ")", ";", "}", "}" ]
Adds a resource to the queue of files to play. @param loop if true, play this file in a loop if there's nothing else on the queue
[ "Adds", "a", "resource", "to", "the", "queue", "of", "files", "to", "play", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/openal/ResourceStream.java#L76-L83
Steveice10/OpenNBT
src/main/java/com/github/steveice10/opennbt/NBTIO.java
NBTIO.writeTag
public static void writeTag(OutputStream out, Tag tag) throws IOException { """ Writes an NBT tag in big endian. @param out Output stream to write to. @param tag Tag to write. @throws java.io.IOException If an I/O error occurs. """ writeTag(out, tag, false); }
java
public static void writeTag(OutputStream out, Tag tag) throws IOException { writeTag(out, tag, false); }
[ "public", "static", "void", "writeTag", "(", "OutputStream", "out", ",", "Tag", "tag", ")", "throws", "IOException", "{", "writeTag", "(", "out", ",", "tag", ",", "false", ")", ";", "}" ]
Writes an NBT tag in big endian. @param out Output stream to write to. @param tag Tag to write. @throws java.io.IOException If an I/O error occurs.
[ "Writes", "an", "NBT", "tag", "in", "big", "endian", "." ]
train
https://github.com/Steveice10/OpenNBT/blob/9bf4adb2afd206a21bc4309c85d642494d1fb536/src/main/java/com/github/steveice10/opennbt/NBTIO.java#L204-L206
apache/flink
flink-connectors/flink-connector-kafka-0.8/src/main/java/org/apache/flink/streaming/connectors/kafka/internals/SimpleConsumerThread.java
SimpleConsumerThread.requestAndSetSpecificTimeOffsetsFromKafka
private static void requestAndSetSpecificTimeOffsetsFromKafka( SimpleConsumer consumer, List<KafkaTopicPartitionState<TopicAndPartition>> partitions, long whichTime) throws IOException { """ Request offsets before a specific time for a set of partitions, via a Kafka consumer. @param consumer The consumer connected to lead broker @param partitions The list of partitions we need offsets for @param whichTime The type of time we are requesting. -1 and -2 are special constants (See OffsetRequest) """ Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<>(); for (KafkaTopicPartitionState<TopicAndPartition> part : partitions) { requestInfo.put(part.getKafkaPartitionHandle(), new PartitionOffsetRequestInfo(whichTime, 1)); } requestAndSetOffsetsFromKafka(consumer, partitions, requestInfo); }
java
private static void requestAndSetSpecificTimeOffsetsFromKafka( SimpleConsumer consumer, List<KafkaTopicPartitionState<TopicAndPartition>> partitions, long whichTime) throws IOException { Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<>(); for (KafkaTopicPartitionState<TopicAndPartition> part : partitions) { requestInfo.put(part.getKafkaPartitionHandle(), new PartitionOffsetRequestInfo(whichTime, 1)); } requestAndSetOffsetsFromKafka(consumer, partitions, requestInfo); }
[ "private", "static", "void", "requestAndSetSpecificTimeOffsetsFromKafka", "(", "SimpleConsumer", "consumer", ",", "List", "<", "KafkaTopicPartitionState", "<", "TopicAndPartition", ">", ">", "partitions", ",", "long", "whichTime", ")", "throws", "IOException", "{", "Map", "<", "TopicAndPartition", ",", "PartitionOffsetRequestInfo", ">", "requestInfo", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "KafkaTopicPartitionState", "<", "TopicAndPartition", ">", "part", ":", "partitions", ")", "{", "requestInfo", ".", "put", "(", "part", ".", "getKafkaPartitionHandle", "(", ")", ",", "new", "PartitionOffsetRequestInfo", "(", "whichTime", ",", "1", ")", ")", ";", "}", "requestAndSetOffsetsFromKafka", "(", "consumer", ",", "partitions", ",", "requestInfo", ")", ";", "}" ]
Request offsets before a specific time for a set of partitions, via a Kafka consumer. @param consumer The consumer connected to lead broker @param partitions The list of partitions we need offsets for @param whichTime The type of time we are requesting. -1 and -2 are special constants (See OffsetRequest)
[ "Request", "offsets", "before", "a", "specific", "time", "for", "a", "set", "of", "partitions", "via", "a", "Kafka", "consumer", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-connector-kafka-0.8/src/main/java/org/apache/flink/streaming/connectors/kafka/internals/SimpleConsumerThread.java#L442-L452
baratine/baratine
web/src/main/java/com/caucho/v5/log/impl/RolloverLogBase.java
RolloverLogBase.getFormatName
protected String getFormatName(String format, long time) { """ Returns the name of the archived file @param time the archive date """ if (time <= 0) { time = CurrentTime.currentTime(); } if (true) throw new UnsupportedOperationException(); /* if (format != null) return QDate.formatLocal(time, format); else if (_rolloverCron != null) return _rolloverPrefix + "." + QDate.formatLocal(time, "%Y%m%d.%H"); else if (getRolloverPeriod() % (24 * 3600 * 1000L) == 0) return _rolloverPrefix + "." + QDate.formatLocal(time, "%Y%m%d"); else return _rolloverPrefix + "." + QDate.formatLocal(time, "%Y%m%d.%H"); */ return _rolloverPrefix + ".date"; }
java
protected String getFormatName(String format, long time) { if (time <= 0) { time = CurrentTime.currentTime(); } if (true) throw new UnsupportedOperationException(); /* if (format != null) return QDate.formatLocal(time, format); else if (_rolloverCron != null) return _rolloverPrefix + "." + QDate.formatLocal(time, "%Y%m%d.%H"); else if (getRolloverPeriod() % (24 * 3600 * 1000L) == 0) return _rolloverPrefix + "." + QDate.formatLocal(time, "%Y%m%d"); else return _rolloverPrefix + "." + QDate.formatLocal(time, "%Y%m%d.%H"); */ return _rolloverPrefix + ".date"; }
[ "protected", "String", "getFormatName", "(", "String", "format", ",", "long", "time", ")", "{", "if", "(", "time", "<=", "0", ")", "{", "time", "=", "CurrentTime", ".", "currentTime", "(", ")", ";", "}", "if", "(", "true", ")", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "/*\n if (format != null)\n return QDate.formatLocal(time, format);\n else if (_rolloverCron != null)\n return _rolloverPrefix + \".\" + QDate.formatLocal(time, \"%Y%m%d.%H\");\n else if (getRolloverPeriod() % (24 * 3600 * 1000L) == 0)\n return _rolloverPrefix + \".\" + QDate.formatLocal(time, \"%Y%m%d\");\n else\n return _rolloverPrefix + \".\" + QDate.formatLocal(time, \"%Y%m%d.%H\");\n */", "return", "_rolloverPrefix", "+", "\".date\"", ";", "}" ]
Returns the name of the archived file @param time the archive date
[ "Returns", "the", "name", "of", "the", "archived", "file" ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/web/src/main/java/com/caucho/v5/log/impl/RolloverLogBase.java#L827-L847
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/misc/FloatingDecimal.java
FloatingDecimal.getBinaryToASCIIConverter
static BinaryToASCIIConverter getBinaryToASCIIConverter(double d, boolean isCompatibleFormat) { """ Returns a <code>BinaryToASCIIConverter</code> for a <code>double</code>. The returned object is a <code>ThreadLocal</code> variable of this class. @param d The double precision value to convert. @param isCompatibleFormat @return The converter. """ long dBits = Double.doubleToRawLongBits(d); boolean isNegative = (dBits&DoubleConsts.SIGN_BIT_MASK) != 0; // discover sign long fractBits = dBits & DoubleConsts.SIGNIF_BIT_MASK; int binExp = (int)( (dBits&DoubleConsts.EXP_BIT_MASK) >> EXP_SHIFT ); // Discover obvious special cases of NaN and Infinity. if ( binExp == (int)(DoubleConsts.EXP_BIT_MASK>>EXP_SHIFT) ) { if ( fractBits == 0L ){ return isNegative ? B2AC_NEGATIVE_INFINITY : B2AC_POSITIVE_INFINITY; } else { return B2AC_NOT_A_NUMBER; } } // Finish unpacking // Normalize denormalized numbers. // Insert assumed high-order bit for normalized numbers. // Subtract exponent bias. int nSignificantBits; if ( binExp == 0 ){ if ( fractBits == 0L ){ // not a denorm, just a 0! return isNegative ? B2AC_NEGATIVE_ZERO : B2AC_POSITIVE_ZERO; } int leadingZeros = Long.numberOfLeadingZeros(fractBits); int shift = leadingZeros-(63-EXP_SHIFT); fractBits <<= shift; binExp = 1 - shift; nSignificantBits = 64-leadingZeros; // recall binExp is - shift count. } else { fractBits |= FRACT_HOB; nSignificantBits = EXP_SHIFT+1; } binExp -= DoubleConsts.EXP_BIAS; BinaryToASCIIBuffer buf = getBinaryToASCIIBuffer(); buf.setSign(isNegative); // call the routine that actually does all the hard work. buf.dtoa(binExp, fractBits, nSignificantBits, isCompatibleFormat); return buf; }
java
static BinaryToASCIIConverter getBinaryToASCIIConverter(double d, boolean isCompatibleFormat) { long dBits = Double.doubleToRawLongBits(d); boolean isNegative = (dBits&DoubleConsts.SIGN_BIT_MASK) != 0; // discover sign long fractBits = dBits & DoubleConsts.SIGNIF_BIT_MASK; int binExp = (int)( (dBits&DoubleConsts.EXP_BIT_MASK) >> EXP_SHIFT ); // Discover obvious special cases of NaN and Infinity. if ( binExp == (int)(DoubleConsts.EXP_BIT_MASK>>EXP_SHIFT) ) { if ( fractBits == 0L ){ return isNegative ? B2AC_NEGATIVE_INFINITY : B2AC_POSITIVE_INFINITY; } else { return B2AC_NOT_A_NUMBER; } } // Finish unpacking // Normalize denormalized numbers. // Insert assumed high-order bit for normalized numbers. // Subtract exponent bias. int nSignificantBits; if ( binExp == 0 ){ if ( fractBits == 0L ){ // not a denorm, just a 0! return isNegative ? B2AC_NEGATIVE_ZERO : B2AC_POSITIVE_ZERO; } int leadingZeros = Long.numberOfLeadingZeros(fractBits); int shift = leadingZeros-(63-EXP_SHIFT); fractBits <<= shift; binExp = 1 - shift; nSignificantBits = 64-leadingZeros; // recall binExp is - shift count. } else { fractBits |= FRACT_HOB; nSignificantBits = EXP_SHIFT+1; } binExp -= DoubleConsts.EXP_BIAS; BinaryToASCIIBuffer buf = getBinaryToASCIIBuffer(); buf.setSign(isNegative); // call the routine that actually does all the hard work. buf.dtoa(binExp, fractBits, nSignificantBits, isCompatibleFormat); return buf; }
[ "static", "BinaryToASCIIConverter", "getBinaryToASCIIConverter", "(", "double", "d", ",", "boolean", "isCompatibleFormat", ")", "{", "long", "dBits", "=", "Double", ".", "doubleToRawLongBits", "(", "d", ")", ";", "boolean", "isNegative", "=", "(", "dBits", "&", "DoubleConsts", ".", "SIGN_BIT_MASK", ")", "!=", "0", ";", "// discover sign", "long", "fractBits", "=", "dBits", "&", "DoubleConsts", ".", "SIGNIF_BIT_MASK", ";", "int", "binExp", "=", "(", "int", ")", "(", "(", "dBits", "&", "DoubleConsts", ".", "EXP_BIT_MASK", ")", ">>", "EXP_SHIFT", ")", ";", "// Discover obvious special cases of NaN and Infinity.", "if", "(", "binExp", "==", "(", "int", ")", "(", "DoubleConsts", ".", "EXP_BIT_MASK", ">>", "EXP_SHIFT", ")", ")", "{", "if", "(", "fractBits", "==", "0L", ")", "{", "return", "isNegative", "?", "B2AC_NEGATIVE_INFINITY", ":", "B2AC_POSITIVE_INFINITY", ";", "}", "else", "{", "return", "B2AC_NOT_A_NUMBER", ";", "}", "}", "// Finish unpacking", "// Normalize denormalized numbers.", "// Insert assumed high-order bit for normalized numbers.", "// Subtract exponent bias.", "int", "nSignificantBits", ";", "if", "(", "binExp", "==", "0", ")", "{", "if", "(", "fractBits", "==", "0L", ")", "{", "// not a denorm, just a 0!", "return", "isNegative", "?", "B2AC_NEGATIVE_ZERO", ":", "B2AC_POSITIVE_ZERO", ";", "}", "int", "leadingZeros", "=", "Long", ".", "numberOfLeadingZeros", "(", "fractBits", ")", ";", "int", "shift", "=", "leadingZeros", "-", "(", "63", "-", "EXP_SHIFT", ")", ";", "fractBits", "<<=", "shift", ";", "binExp", "=", "1", "-", "shift", ";", "nSignificantBits", "=", "64", "-", "leadingZeros", ";", "// recall binExp is - shift count.", "}", "else", "{", "fractBits", "|=", "FRACT_HOB", ";", "nSignificantBits", "=", "EXP_SHIFT", "+", "1", ";", "}", "binExp", "-=", "DoubleConsts", ".", "EXP_BIAS", ";", "BinaryToASCIIBuffer", "buf", "=", "getBinaryToASCIIBuffer", "(", ")", ";", "buf", ".", "setSign", "(", "isNegative", ")", ";", "// call the routine that actually does all the hard work.", "buf", ".", "dtoa", "(", "binExp", ",", "fractBits", ",", "nSignificantBits", ",", "isCompatibleFormat", ")", ";", "return", "buf", ";", "}" ]
Returns a <code>BinaryToASCIIConverter</code> for a <code>double</code>. The returned object is a <code>ThreadLocal</code> variable of this class. @param d The double precision value to convert. @param isCompatibleFormat @return The converter.
[ "Returns", "a", "<code", ">", "BinaryToASCIIConverter<", "/", "code", ">", "for", "a", "<code", ">", "double<", "/", "code", ">", ".", "The", "returned", "object", "is", "a", "<code", ">", "ThreadLocal<", "/", "code", ">", "variable", "of", "this", "class", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/misc/FloatingDecimal.java#L1742-L1780
Stratio/deep-spark
deep-core/src/main/java/com/stratio/deep/core/context/DeepSparkContext.java
DeepSparkContext.createS3RDD
public RDD<Cells> createS3RDD(ExtractorConfig<Cells> config) { """ Returns a Cells RDD from S3 fileSystem. @param config Amazon S3 ExtractorConfig. @return RDD of Cells. """ Serializable bucket = config.getValues().get(ExtractorConstants.S3_BUCKET); Serializable path = config.getValues().get(ExtractorConstants.FS_FILE_PATH); final TextFileDataTable textFileDataTable = UtilFS.createTextFileMetaDataFromConfig(config, this); String filePath = path.toString(); if (config.getExtractorImplClassName().equals(ExtractorConstants.S3)) { filePath = ExtractorConstants.S3_PREFIX + bucket.toString() + path.toString(); } Configuration hadoopConf = this.sc().hadoopConfiguration(); hadoopConf.set("fs.s3n.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem"); hadoopConf.set("fs.s3n.awsAccessKeyId", config.getString(ExtractorConstants.S3_ACCESS_KEY_ID)); hadoopConf.set("fs.s3n.awsSecretAccessKey", config.getString(ExtractorConstants.S3_SECRET_ACCESS_KEY)); return createRDDFromFilePath(filePath, textFileDataTable); }
java
public RDD<Cells> createS3RDD(ExtractorConfig<Cells> config) { Serializable bucket = config.getValues().get(ExtractorConstants.S3_BUCKET); Serializable path = config.getValues().get(ExtractorConstants.FS_FILE_PATH); final TextFileDataTable textFileDataTable = UtilFS.createTextFileMetaDataFromConfig(config, this); String filePath = path.toString(); if (config.getExtractorImplClassName().equals(ExtractorConstants.S3)) { filePath = ExtractorConstants.S3_PREFIX + bucket.toString() + path.toString(); } Configuration hadoopConf = this.sc().hadoopConfiguration(); hadoopConf.set("fs.s3n.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem"); hadoopConf.set("fs.s3n.awsAccessKeyId", config.getString(ExtractorConstants.S3_ACCESS_KEY_ID)); hadoopConf.set("fs.s3n.awsSecretAccessKey", config.getString(ExtractorConstants.S3_SECRET_ACCESS_KEY)); return createRDDFromFilePath(filePath, textFileDataTable); }
[ "public", "RDD", "<", "Cells", ">", "createS3RDD", "(", "ExtractorConfig", "<", "Cells", ">", "config", ")", "{", "Serializable", "bucket", "=", "config", ".", "getValues", "(", ")", ".", "get", "(", "ExtractorConstants", ".", "S3_BUCKET", ")", ";", "Serializable", "path", "=", "config", ".", "getValues", "(", ")", ".", "get", "(", "ExtractorConstants", ".", "FS_FILE_PATH", ")", ";", "final", "TextFileDataTable", "textFileDataTable", "=", "UtilFS", ".", "createTextFileMetaDataFromConfig", "(", "config", ",", "this", ")", ";", "String", "filePath", "=", "path", ".", "toString", "(", ")", ";", "if", "(", "config", ".", "getExtractorImplClassName", "(", ")", ".", "equals", "(", "ExtractorConstants", ".", "S3", ")", ")", "{", "filePath", "=", "ExtractorConstants", ".", "S3_PREFIX", "+", "bucket", ".", "toString", "(", ")", "+", "path", ".", "toString", "(", ")", ";", "}", "Configuration", "hadoopConf", "=", "this", ".", "sc", "(", ")", ".", "hadoopConfiguration", "(", ")", ";", "hadoopConf", ".", "set", "(", "\"fs.s3n.impl\"", ",", "\"org.apache.hadoop.fs.s3native.NativeS3FileSystem\"", ")", ";", "hadoopConf", ".", "set", "(", "\"fs.s3n.awsAccessKeyId\"", ",", "config", ".", "getString", "(", "ExtractorConstants", ".", "S3_ACCESS_KEY_ID", ")", ")", ";", "hadoopConf", ".", "set", "(", "\"fs.s3n.awsSecretAccessKey\"", ",", "config", ".", "getString", "(", "ExtractorConstants", ".", "S3_SECRET_ACCESS_KEY", ")", ")", ";", "return", "createRDDFromFilePath", "(", "filePath", ",", "textFileDataTable", ")", ";", "}" ]
Returns a Cells RDD from S3 fileSystem. @param config Amazon S3 ExtractorConfig. @return RDD of Cells.
[ "Returns", "a", "Cells", "RDD", "from", "S3", "fileSystem", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-core/src/main/java/com/stratio/deep/core/context/DeepSparkContext.java#L298-L314
forge/core
dependencies/api/src/main/java/org/jboss/forge/addon/dependencies/collection/DependencyNodeUtil.java
DependencyNodeUtil.selectFirst
public static <T> T selectFirst(Iterator<T> nodeIterator, Predicate<T> filter) { """ Returns the first {@link DependencyNode} object found that satisfy the filter. @param nodeIterator A tree iterator @param filter the {@link DependencyNodeFilter} being used @return the first element that matches the filter. null if nothing is found @see #breadthFirstIterator(DependencyNode) @see #depthFirstIterator(DependencyNode) @see #preorderIterator(DependencyNode) """ while (nodeIterator.hasNext()) { T element = nodeIterator.next(); if (filter.accept(element)) { return element; } } return null; }
java
public static <T> T selectFirst(Iterator<T> nodeIterator, Predicate<T> filter) { while (nodeIterator.hasNext()) { T element = nodeIterator.next(); if (filter.accept(element)) { return element; } } return null; }
[ "public", "static", "<", "T", ">", "T", "selectFirst", "(", "Iterator", "<", "T", ">", "nodeIterator", ",", "Predicate", "<", "T", ">", "filter", ")", "{", "while", "(", "nodeIterator", ".", "hasNext", "(", ")", ")", "{", "T", "element", "=", "nodeIterator", ".", "next", "(", ")", ";", "if", "(", "filter", ".", "accept", "(", "element", ")", ")", "{", "return", "element", ";", "}", "}", "return", "null", ";", "}" ]
Returns the first {@link DependencyNode} object found that satisfy the filter. @param nodeIterator A tree iterator @param filter the {@link DependencyNodeFilter} being used @return the first element that matches the filter. null if nothing is found @see #breadthFirstIterator(DependencyNode) @see #depthFirstIterator(DependencyNode) @see #preorderIterator(DependencyNode)
[ "Returns", "the", "first", "{", "@link", "DependencyNode", "}", "object", "found", "that", "satisfy", "the", "filter", "." ]
train
https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/dependencies/api/src/main/java/org/jboss/forge/addon/dependencies/collection/DependencyNodeUtil.java#L50-L61
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/UserResources.java
UserResources.getUserByUsername
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/username/ { """ Returns the user having the given username. @param req The HTTP request. @param userName The username to retrieve. @return The user DTO. @throws WebApplicationException If an error occurs. """username}") @Description("Returns the user having the given username.") public PrincipalUserDto getUserByUsername(@Context HttpServletRequest req, @PathParam("username") final String userName) { Enumeration<String> headerNames = req.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); String headerValue = req.getHeader(headerName); System.out.println(headerName + ": " + headerValue); } if (userName == null || userName.isEmpty()) { throw new WebApplicationException("Username cannot be null or empty.", Status.BAD_REQUEST); } PrincipalUser remoteUser = validateAndGetOwner(req, null); PrincipalUser user = _uService.findUserByUsername(userName); if (user != null) { super.validateResourceAuthorization(req, user, remoteUser); return PrincipalUserDto.transformToDto(user); } else if (!remoteUser.isPrivileged()) { throw new WebApplicationException(Response.Status.FORBIDDEN.getReasonPhrase(), Response.Status.FORBIDDEN); } else { throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND); } }
java
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/username/{username}") @Description("Returns the user having the given username.") public PrincipalUserDto getUserByUsername(@Context HttpServletRequest req, @PathParam("username") final String userName) { Enumeration<String> headerNames = req.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); String headerValue = req.getHeader(headerName); System.out.println(headerName + ": " + headerValue); } if (userName == null || userName.isEmpty()) { throw new WebApplicationException("Username cannot be null or empty.", Status.BAD_REQUEST); } PrincipalUser remoteUser = validateAndGetOwner(req, null); PrincipalUser user = _uService.findUserByUsername(userName); if (user != null) { super.validateResourceAuthorization(req, user, remoteUser); return PrincipalUserDto.transformToDto(user); } else if (!remoteUser.isPrivileged()) { throw new WebApplicationException(Response.Status.FORBIDDEN.getReasonPhrase(), Response.Status.FORBIDDEN); } else { throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND); } }
[ "@", "GET", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Path", "(", "\"/username/{username}\"", ")", "@", "Description", "(", "\"Returns the user having the given username.\"", ")", "public", "PrincipalUserDto", "getUserByUsername", "(", "@", "Context", "HttpServletRequest", "req", ",", "@", "PathParam", "(", "\"username\"", ")", "final", "String", "userName", ")", "{", "Enumeration", "<", "String", ">", "headerNames", "=", "req", ".", "getHeaderNames", "(", ")", ";", "while", "(", "headerNames", ".", "hasMoreElements", "(", ")", ")", "{", "String", "headerName", "=", "headerNames", ".", "nextElement", "(", ")", ";", "String", "headerValue", "=", "req", ".", "getHeader", "(", "headerName", ")", ";", "System", ".", "out", ".", "println", "(", "headerName", "+", "\": \"", "+", "headerValue", ")", ";", "}", "if", "(", "userName", "==", "null", "||", "userName", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "WebApplicationException", "(", "\"Username cannot be null or empty.\"", ",", "Status", ".", "BAD_REQUEST", ")", ";", "}", "PrincipalUser", "remoteUser", "=", "validateAndGetOwner", "(", "req", ",", "null", ")", ";", "PrincipalUser", "user", "=", "_uService", ".", "findUserByUsername", "(", "userName", ")", ";", "if", "(", "user", "!=", "null", ")", "{", "super", ".", "validateResourceAuthorization", "(", "req", ",", "user", ",", "remoteUser", ")", ";", "return", "PrincipalUserDto", ".", "transformToDto", "(", "user", ")", ";", "}", "else", "if", "(", "!", "remoteUser", ".", "isPrivileged", "(", ")", ")", "{", "throw", "new", "WebApplicationException", "(", "Response", ".", "Status", ".", "FORBIDDEN", ".", "getReasonPhrase", "(", ")", ",", "Response", ".", "Status", ".", "FORBIDDEN", ")", ";", "}", "else", "{", "throw", "new", "WebApplicationException", "(", "Response", ".", "Status", ".", "NOT_FOUND", ".", "getReasonPhrase", "(", ")", ",", "Response", ".", "Status", ".", "NOT_FOUND", ")", ";", "}", "}" ]
Returns the user having the given username. @param req The HTTP request. @param userName The username to retrieve. @return The user DTO. @throws WebApplicationException If an error occurs.
[ "Returns", "the", "user", "having", "the", "given", "username", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/UserResources.java#L137-L166
alkacon/opencms-core
src-gwt/org/opencms/ade/galleries/client/ui/CmsResultListItem.java
CmsResultListItem.createButton
private static CmsPushButton createButton(String imageClass, String title) { """ Creates a button for the list item.<p> @param imageClass the icon image class @param title the button title @return the button """ CmsPushButton result = new CmsPushButton(); result.setImageClass(imageClass); result.setButtonStyle(ButtonStyle.FONT_ICON, null); result.setTitle(title); return result; }
java
private static CmsPushButton createButton(String imageClass, String title) { CmsPushButton result = new CmsPushButton(); result.setImageClass(imageClass); result.setButtonStyle(ButtonStyle.FONT_ICON, null); result.setTitle(title); return result; }
[ "private", "static", "CmsPushButton", "createButton", "(", "String", "imageClass", ",", "String", "title", ")", "{", "CmsPushButton", "result", "=", "new", "CmsPushButton", "(", ")", ";", "result", ".", "setImageClass", "(", "imageClass", ")", ";", "result", ".", "setButtonStyle", "(", "ButtonStyle", ".", "FONT_ICON", ",", "null", ")", ";", "result", ".", "setTitle", "(", "title", ")", ";", "return", "result", ";", "}" ]
Creates a button for the list item.<p> @param imageClass the icon image class @param title the button title @return the button
[ "Creates", "a", "button", "for", "the", "list", "item", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/ui/CmsResultListItem.java#L140-L147
ironjacamar/ironjacamar
common/src/main/java/org/ironjacamar/common/annotations/Annotations.java
Annotations.hasAnnotation
private boolean hasAnnotation(Class c, Class targetClass, AnnotationRepository annotationRepository) { """ hasAnnotation, if class c contains annotation targetClass @param c @param targetClass @param annotationRepository @return """ Collection<Annotation> values = annotationRepository.getAnnotation(targetClass); if (values == null) return false; for (Annotation annotation : values) { if (annotation.getClassName() != null && annotation.getClassName().equals(c.getName())) return true; } return false; }
java
private boolean hasAnnotation(Class c, Class targetClass, AnnotationRepository annotationRepository) { Collection<Annotation> values = annotationRepository.getAnnotation(targetClass); if (values == null) return false; for (Annotation annotation : values) { if (annotation.getClassName() != null && annotation.getClassName().equals(c.getName())) return true; } return false; }
[ "private", "boolean", "hasAnnotation", "(", "Class", "c", ",", "Class", "targetClass", ",", "AnnotationRepository", "annotationRepository", ")", "{", "Collection", "<", "Annotation", ">", "values", "=", "annotationRepository", ".", "getAnnotation", "(", "targetClass", ")", ";", "if", "(", "values", "==", "null", ")", "return", "false", ";", "for", "(", "Annotation", "annotation", ":", "values", ")", "{", "if", "(", "annotation", ".", "getClassName", "(", ")", "!=", "null", "&&", "annotation", ".", "getClassName", "(", ")", ".", "equals", "(", "c", ".", "getName", "(", ")", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
hasAnnotation, if class c contains annotation targetClass @param c @param targetClass @param annotationRepository @return
[ "hasAnnotation", "if", "class", "c", "contains", "annotation", "targetClass" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/common/src/main/java/org/ironjacamar/common/annotations/Annotations.java#L915-L927
SimiaCryptus/utilities
java-util/src/main/java/com/simiacryptus/text/CharTrie.java
CharTrie.reduceSimple
public CharTrie reduceSimple(CharTrie z, BiFunction<Long, Long, Long> fn) { """ Reduce simple char trie. @param z the z @param fn the fn @return the char trie """ return reduce(z, (left, right) -> { TreeMap<Character, ? extends TrieNode> leftChildren = null == left ? new TreeMap<>() : left.getChildrenMap(); TreeMap<Character, ? extends TrieNode> rightChildren = null == right ? new TreeMap<>() : right.getChildrenMap(); Map<Character, Long> map = Stream.of(rightChildren.keySet(), leftChildren.keySet()).flatMap(x -> x.stream()).distinct().collect(Collectors.toMap(c -> c, (Character c) -> { assert (null != leftChildren); assert (null != rightChildren); assert (null != c); TrieNode leftChild = leftChildren.get(c); Long l = null == leftChild ? null : leftChild.getCursorCount(); TrieNode rightChild = rightChildren.get(c); Long r = null == rightChild ? null : rightChild.getCursorCount(); return fn.apply(l, r); })); return new TreeMap<>(map); }); }
java
public CharTrie reduceSimple(CharTrie z, BiFunction<Long, Long, Long> fn) { return reduce(z, (left, right) -> { TreeMap<Character, ? extends TrieNode> leftChildren = null == left ? new TreeMap<>() : left.getChildrenMap(); TreeMap<Character, ? extends TrieNode> rightChildren = null == right ? new TreeMap<>() : right.getChildrenMap(); Map<Character, Long> map = Stream.of(rightChildren.keySet(), leftChildren.keySet()).flatMap(x -> x.stream()).distinct().collect(Collectors.toMap(c -> c, (Character c) -> { assert (null != leftChildren); assert (null != rightChildren); assert (null != c); TrieNode leftChild = leftChildren.get(c); Long l = null == leftChild ? null : leftChild.getCursorCount(); TrieNode rightChild = rightChildren.get(c); Long r = null == rightChild ? null : rightChild.getCursorCount(); return fn.apply(l, r); })); return new TreeMap<>(map); }); }
[ "public", "CharTrie", "reduceSimple", "(", "CharTrie", "z", ",", "BiFunction", "<", "Long", ",", "Long", ",", "Long", ">", "fn", ")", "{", "return", "reduce", "(", "z", ",", "(", "left", ",", "right", ")", "->", "{", "TreeMap", "<", "Character", ",", "?", "extends", "TrieNode", ">", "leftChildren", "=", "null", "==", "left", "?", "new", "TreeMap", "<>", "(", ")", ":", "left", ".", "getChildrenMap", "(", ")", ";", "TreeMap", "<", "Character", ",", "?", "extends", "TrieNode", ">", "rightChildren", "=", "null", "==", "right", "?", "new", "TreeMap", "<>", "(", ")", ":", "right", ".", "getChildrenMap", "(", ")", ";", "Map", "<", "Character", ",", "Long", ">", "map", "=", "Stream", ".", "of", "(", "rightChildren", ".", "keySet", "(", ")", ",", "leftChildren", ".", "keySet", "(", ")", ")", ".", "flatMap", "(", "x", "->", "x", ".", "stream", "(", ")", ")", ".", "distinct", "(", ")", ".", "collect", "(", "Collectors", ".", "toMap", "(", "c", "->", "c", ",", "(", "Character", "c", ")", "->", "{", "assert", "(", "null", "!=", "leftChildren", ")", ";", "assert", "(", "null", "!=", "rightChildren", ")", ";", "assert", "(", "null", "!=", "c", ")", ";", "TrieNode", "leftChild", "=", "leftChildren", ".", "get", "(", "c", ")", ";", "Long", "l", "=", "null", "==", "leftChild", "?", "null", ":", "leftChild", ".", "getCursorCount", "(", ")", ";", "TrieNode", "rightChild", "=", "rightChildren", ".", "get", "(", "c", ")", ";", "Long", "r", "=", "null", "==", "rightChild", "?", "null", ":", "rightChild", ".", "getCursorCount", "(", ")", ";", "return", "fn", ".", "apply", "(", "l", ",", "r", ")", ";", "}", ")", ")", ";", "return", "new", "TreeMap", "<>", "(", "map", ")", ";", "}", ")", ";", "}" ]
Reduce simple char trie. @param z the z @param fn the fn @return the char trie
[ "Reduce", "simple", "char", "trie", "." ]
train
https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/text/CharTrie.java#L237-L253
jenkinsci/jenkins
core/src/main/java/hudson/Util.java
Util.getDigestOf
@Nonnull public static String getDigestOf(@Nonnull InputStream source) throws IOException { """ Computes MD5 digest of the given input stream. @param source The stream will be closed by this method at the end of this method. @return 32-char wide string @see DigestUtils#md5Hex(InputStream) """ try { MessageDigest md5 = MessageDigest.getInstance("MD5"); DigestInputStream in = new DigestInputStream(source, md5); // Note: IOUtils.copy() buffers the input internally, so there is no // need to use a BufferedInputStream. IOUtils.copy(in, NullOutputStream.NULL_OUTPUT_STREAM); return toHexString(md5.digest()); } catch (NoSuchAlgorithmException e) { throw new IOException("MD5 not installed",e); // impossible } finally { source.close(); } /* JENKINS-18178: confuses Maven 2 runner try { return DigestUtils.md5Hex(source); } finally { source.close(); } */ }
java
@Nonnull public static String getDigestOf(@Nonnull InputStream source) throws IOException { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); DigestInputStream in = new DigestInputStream(source, md5); // Note: IOUtils.copy() buffers the input internally, so there is no // need to use a BufferedInputStream. IOUtils.copy(in, NullOutputStream.NULL_OUTPUT_STREAM); return toHexString(md5.digest()); } catch (NoSuchAlgorithmException e) { throw new IOException("MD5 not installed",e); // impossible } finally { source.close(); } /* JENKINS-18178: confuses Maven 2 runner try { return DigestUtils.md5Hex(source); } finally { source.close(); } */ }
[ "@", "Nonnull", "public", "static", "String", "getDigestOf", "(", "@", "Nonnull", "InputStream", "source", ")", "throws", "IOException", "{", "try", "{", "MessageDigest", "md5", "=", "MessageDigest", ".", "getInstance", "(", "\"MD5\"", ")", ";", "DigestInputStream", "in", "=", "new", "DigestInputStream", "(", "source", ",", "md5", ")", ";", "// Note: IOUtils.copy() buffers the input internally, so there is no", "// need to use a BufferedInputStream.", "IOUtils", ".", "copy", "(", "in", ",", "NullOutputStream", ".", "NULL_OUTPUT_STREAM", ")", ";", "return", "toHexString", "(", "md5", ".", "digest", "(", ")", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "throw", "new", "IOException", "(", "\"MD5 not installed\"", ",", "e", ")", ";", "// impossible", "}", "finally", "{", "source", ".", "close", "(", ")", ";", "}", "/* JENKINS-18178: confuses Maven 2 runner\n try {\n return DigestUtils.md5Hex(source);\n } finally {\n source.close();\n }\n */", "}" ]
Computes MD5 digest of the given input stream. @param source The stream will be closed by this method at the end of this method. @return 32-char wide string @see DigestUtils#md5Hex(InputStream)
[ "Computes", "MD5", "digest", "of", "the", "given", "input", "stream", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/Util.java#L597-L618
CenturyLinkCloud/mdw
mdw-common/src/com/centurylink/mdw/xml/XmlPath.java
XmlPath.evaluate
public static String evaluate(XmlObject xmlbean, String path) { """ Using XPath or XQuery. NOTE!!!! To use this code, need to include xbean_xpath.jar, saxon9.jar, saxon9-dom.jar in CLASSPATH in startWebLogic.cmd @param xmlbean @param path @return """ XmlCursor cursor = xmlbean.newCursor(); String value; // 1.2.3. use XQuery or selectPath // // cursor.toFirstChild(); // String defaultNamespace = cursor.namespaceForPrefix(""); // String namespaceDecl = "declare default element namespace '" + defaultNamespace + "';"; // Map<String,String> namespaces = new HashMap<String,String>(); // cursor.getAllNamespaces(namespaces); // for (String prefix : namespaces.keySet()) // { // namespaceDecl += "declare namespace " + prefix + "='" + namespaces.get(prefix) + "';"; // } // 1. use XQuery // XmlCursor results = cursor.execQuery(namespaceDecl + path); // value = (results==null)?null:results.getTextValue(); // 2. use selectPath on XmlObject // XmlObject[] result = xmlbean.selectPath(namespaceDecl + path); // 3. use selectPath on XmlCursor // cursor.toParent(); // XmlOptions options = new XmlOptions(); // options.put(Path.PATH_DELEGATE_INTERFACE,"org.apache.xmlbeans.impl.xpath.saxon.XBeansXPath"); // cursor.selectPath(namespaceDecl + path, options); // if (cursor.getSelectionCount()>0) { // cursor.toNextSelection(); // value = cursor.getTextValue(); // } else value = null; // 4. use our own implementation try { XmlPath matcher = new XmlPath(path); value = matcher.evaluate_segment(cursor, matcher.path_seg); } catch (XmlException e) { value = null; // xpath syntax error - treated as no match } cursor.dispose(); return value; }
java
public static String evaluate(XmlObject xmlbean, String path) { XmlCursor cursor = xmlbean.newCursor(); String value; // 1.2.3. use XQuery or selectPath // // cursor.toFirstChild(); // String defaultNamespace = cursor.namespaceForPrefix(""); // String namespaceDecl = "declare default element namespace '" + defaultNamespace + "';"; // Map<String,String> namespaces = new HashMap<String,String>(); // cursor.getAllNamespaces(namespaces); // for (String prefix : namespaces.keySet()) // { // namespaceDecl += "declare namespace " + prefix + "='" + namespaces.get(prefix) + "';"; // } // 1. use XQuery // XmlCursor results = cursor.execQuery(namespaceDecl + path); // value = (results==null)?null:results.getTextValue(); // 2. use selectPath on XmlObject // XmlObject[] result = xmlbean.selectPath(namespaceDecl + path); // 3. use selectPath on XmlCursor // cursor.toParent(); // XmlOptions options = new XmlOptions(); // options.put(Path.PATH_DELEGATE_INTERFACE,"org.apache.xmlbeans.impl.xpath.saxon.XBeansXPath"); // cursor.selectPath(namespaceDecl + path, options); // if (cursor.getSelectionCount()>0) { // cursor.toNextSelection(); // value = cursor.getTextValue(); // } else value = null; // 4. use our own implementation try { XmlPath matcher = new XmlPath(path); value = matcher.evaluate_segment(cursor, matcher.path_seg); } catch (XmlException e) { value = null; // xpath syntax error - treated as no match } cursor.dispose(); return value; }
[ "public", "static", "String", "evaluate", "(", "XmlObject", "xmlbean", ",", "String", "path", ")", "{", "XmlCursor", "cursor", "=", "xmlbean", ".", "newCursor", "(", ")", ";", "String", "value", ";", "// 1.2.3. use XQuery or selectPath", "//", "// cursor.toFirstChild();", "// String defaultNamespace = cursor.namespaceForPrefix(\"\");", "// String namespaceDecl = \"declare default element namespace '\" + defaultNamespace + \"';\";", "// Map<String,String> namespaces = new HashMap<String,String>();", "// cursor.getAllNamespaces(namespaces);", "// for (String prefix : namespaces.keySet())", "// {", "// namespaceDecl += \"declare namespace \" + prefix + \"='\" + namespaces.get(prefix) + \"';\";", "// }", "// 1. use XQuery", "// XmlCursor results = cursor.execQuery(namespaceDecl + path);", "// value = (results==null)?null:results.getTextValue();", "// 2. use selectPath on XmlObject", "// XmlObject[] result = xmlbean.selectPath(namespaceDecl + path);", "// 3. use selectPath on XmlCursor ", "// cursor.toParent();", "// XmlOptions options = new XmlOptions();", "// options.put(Path.PATH_DELEGATE_INTERFACE,\"org.apache.xmlbeans.impl.xpath.saxon.XBeansXPath\");", "// cursor.selectPath(namespaceDecl + path, options);", "// if (cursor.getSelectionCount()>0) {", "// cursor.toNextSelection();", "// value = cursor.getTextValue();", "// } else value = null;", "// 4. use our own implementation", "try", "{", "XmlPath", "matcher", "=", "new", "XmlPath", "(", "path", ")", ";", "value", "=", "matcher", ".", "evaluate_segment", "(", "cursor", ",", "matcher", ".", "path_seg", ")", ";", "}", "catch", "(", "XmlException", "e", ")", "{", "value", "=", "null", ";", "// xpath syntax error - treated as no match", "}", "cursor", ".", "dispose", "(", ")", ";", "return", "value", ";", "}" ]
Using XPath or XQuery. NOTE!!!! To use this code, need to include xbean_xpath.jar, saxon9.jar, saxon9-dom.jar in CLASSPATH in startWebLogic.cmd @param xmlbean @param path @return
[ "Using", "XPath", "or", "XQuery", ".", "NOTE!!!!", "To", "use", "this", "code", "need", "to", "include", "xbean_xpath", ".", "jar", "saxon9", ".", "jar", "saxon9", "-", "dom", ".", "jar", "in", "CLASSPATH", "in", "startWebLogic", ".", "cmd" ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/xml/XmlPath.java#L62-L104
TGIO/RNCryptorNative
jncryptor/src/main/java/org/cryptonode/jncryptor/Validate.java
Validate.isCorrectLength
static void isCorrectLength(byte[] object, int length, String name) { """ Tests object is not null and is of correct length. @param object @param length @param name """ Validate.notNull(object, "%s cannot be null.", name); Validate.isTrue(object.length == length, "%s should be %d bytes, found %d bytes.", name, length, object.length); }
java
static void isCorrectLength(byte[] object, int length, String name) { Validate.notNull(object, "%s cannot be null.", name); Validate.isTrue(object.length == length, "%s should be %d bytes, found %d bytes.", name, length, object.length); }
[ "static", "void", "isCorrectLength", "(", "byte", "[", "]", "object", ",", "int", "length", ",", "String", "name", ")", "{", "Validate", ".", "notNull", "(", "object", ",", "\"%s cannot be null.\"", ",", "name", ")", ";", "Validate", ".", "isTrue", "(", "object", ".", "length", "==", "length", ",", "\"%s should be %d bytes, found %d bytes.\"", ",", "name", ",", "length", ",", "object", ".", "length", ")", ";", "}" ]
Tests object is not null and is of correct length. @param object @param length @param name
[ "Tests", "object", "is", "not", "null", "and", "is", "of", "correct", "length", "." ]
train
https://github.com/TGIO/RNCryptorNative/blob/5209f10b988e4033c0b769a40b0d6cc99ea16af7/jncryptor/src/main/java/org/cryptonode/jncryptor/Validate.java#L44-L49
avaje-common/avaje-jetty-runner
src/main/java/org/avaje/jettyrunner/RunWar.java
RunWar.setupForWar
protected void setupForWar() { """ Setup the webapp pointing to the war file that contains this class. """ // Identify the war file that contains this class ProtectionDomain protectionDomain = RunWar.class.getProtectionDomain(); URL location = protectionDomain.getCodeSource().getLocation(); String warFilePath = trimToFile(location.toExternalForm()); File warFile = new File(warFilePath); if (!warFile.exists()) { throw new IllegalStateException("war file not found: " + warFilePath); } webapp.setWar(warFilePath); webapp.setClassLoader(Thread.currentThread().getContextClassLoader()); if (!Boolean.getBoolean("webapp.extractWar")) { try { webapp.setExtractWAR(false); webapp.setBaseResource(JarResource.newJarResource(Resource.newResource(warFile))); } catch (IOException e) { throw new RuntimeException("Error setting base resource to:" + warFilePath, e); } } if (log().isDebugEnabled()) { ClassLoader classLoader = webapp.getClassLoader(); log().debug("webapp classLoader: " + classLoader); if (classLoader instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) classLoader).getURLs(); log().debug("webapp classLoader URLs: " + Arrays.toString(urls)); } } }
java
protected void setupForWar() { // Identify the war file that contains this class ProtectionDomain protectionDomain = RunWar.class.getProtectionDomain(); URL location = protectionDomain.getCodeSource().getLocation(); String warFilePath = trimToFile(location.toExternalForm()); File warFile = new File(warFilePath); if (!warFile.exists()) { throw new IllegalStateException("war file not found: " + warFilePath); } webapp.setWar(warFilePath); webapp.setClassLoader(Thread.currentThread().getContextClassLoader()); if (!Boolean.getBoolean("webapp.extractWar")) { try { webapp.setExtractWAR(false); webapp.setBaseResource(JarResource.newJarResource(Resource.newResource(warFile))); } catch (IOException e) { throw new RuntimeException("Error setting base resource to:" + warFilePath, e); } } if (log().isDebugEnabled()) { ClassLoader classLoader = webapp.getClassLoader(); log().debug("webapp classLoader: " + classLoader); if (classLoader instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) classLoader).getURLs(); log().debug("webapp classLoader URLs: " + Arrays.toString(urls)); } } }
[ "protected", "void", "setupForWar", "(", ")", "{", "// Identify the war file that contains this class", "ProtectionDomain", "protectionDomain", "=", "RunWar", ".", "class", ".", "getProtectionDomain", "(", ")", ";", "URL", "location", "=", "protectionDomain", ".", "getCodeSource", "(", ")", ".", "getLocation", "(", ")", ";", "String", "warFilePath", "=", "trimToFile", "(", "location", ".", "toExternalForm", "(", ")", ")", ";", "File", "warFile", "=", "new", "File", "(", "warFilePath", ")", ";", "if", "(", "!", "warFile", ".", "exists", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"war file not found: \"", "+", "warFilePath", ")", ";", "}", "webapp", ".", "setWar", "(", "warFilePath", ")", ";", "webapp", ".", "setClassLoader", "(", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ")", ";", "if", "(", "!", "Boolean", ".", "getBoolean", "(", "\"webapp.extractWar\"", ")", ")", "{", "try", "{", "webapp", ".", "setExtractWAR", "(", "false", ")", ";", "webapp", ".", "setBaseResource", "(", "JarResource", ".", "newJarResource", "(", "Resource", ".", "newResource", "(", "warFile", ")", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error setting base resource to:\"", "+", "warFilePath", ",", "e", ")", ";", "}", "}", "if", "(", "log", "(", ")", ".", "isDebugEnabled", "(", ")", ")", "{", "ClassLoader", "classLoader", "=", "webapp", ".", "getClassLoader", "(", ")", ";", "log", "(", ")", ".", "debug", "(", "\"webapp classLoader: \"", "+", "classLoader", ")", ";", "if", "(", "classLoader", "instanceof", "URLClassLoader", ")", "{", "URL", "[", "]", "urls", "=", "(", "(", "URLClassLoader", ")", "classLoader", ")", ".", "getURLs", "(", ")", ";", "log", "(", ")", ".", "debug", "(", "\"webapp classLoader URLs: \"", "+", "Arrays", ".", "toString", "(", "urls", ")", ")", ";", "}", "}", "}" ]
Setup the webapp pointing to the war file that contains this class.
[ "Setup", "the", "webapp", "pointing", "to", "the", "war", "file", "that", "contains", "this", "class", "." ]
train
https://github.com/avaje-common/avaje-jetty-runner/blob/acddc23754facc339233fa0b9736e94abc8ae842/src/main/java/org/avaje/jettyrunner/RunWar.java#L47-L78
looly/hutool
hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelWriter.java
ExcelWriter.writeCellValue
public ExcelWriter writeCellValue(int x, int y, Object value) { """ 给指定单元格赋值,使用默认单元格样式 @param x X坐标,从0计数,既列号 @param y Y坐标,从0计数,既行号 @param value 值 @return this @since 4.0.2 """ final Cell cell = getOrCreateCell(x, y); CellUtil.setCellValue(cell, value, this.styleSet, false); return this; }
java
public ExcelWriter writeCellValue(int x, int y, Object value) { final Cell cell = getOrCreateCell(x, y); CellUtil.setCellValue(cell, value, this.styleSet, false); return this; }
[ "public", "ExcelWriter", "writeCellValue", "(", "int", "x", ",", "int", "y", ",", "Object", "value", ")", "{", "final", "Cell", "cell", "=", "getOrCreateCell", "(", "x", ",", "y", ")", ";", "CellUtil", ".", "setCellValue", "(", "cell", ",", "value", ",", "this", ".", "styleSet", ",", "false", ")", ";", "return", "this", ";", "}" ]
给指定单元格赋值,使用默认单元格样式 @param x X坐标,从0计数,既列号 @param y Y坐标,从0计数,既行号 @param value 值 @return this @since 4.0.2
[ "给指定单元格赋值,使用默认单元格样式" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelWriter.java#L751-L755
cache2k/cache2k
cache2k-api/src/main/java/org/cache2k/configuration/Cache2kConfiguration.java
Cache2kConfiguration.setListeners
public void setListeners(Collection<CustomizationSupplier<CacheEntryOperationListener<K,V>>> c) { """ Adds the collection of customizations to the existing list. This method is intended to improve integration with bean configuration mechanisms that use the set method and construct a set or list, like Springs' bean XML configuration. """ getListeners().addAll(c); }
java
public void setListeners(Collection<CustomizationSupplier<CacheEntryOperationListener<K,V>>> c) { getListeners().addAll(c); }
[ "public", "void", "setListeners", "(", "Collection", "<", "CustomizationSupplier", "<", "CacheEntryOperationListener", "<", "K", ",", "V", ">", ">", ">", "c", ")", "{", "getListeners", "(", ")", ".", "addAll", "(", "c", ")", ";", "}" ]
Adds the collection of customizations to the existing list. This method is intended to improve integration with bean configuration mechanisms that use the set method and construct a set or list, like Springs' bean XML configuration.
[ "Adds", "the", "collection", "of", "customizations", "to", "the", "existing", "list", ".", "This", "method", "is", "intended", "to", "improve", "integration", "with", "bean", "configuration", "mechanisms", "that", "use", "the", "set", "method", "and", "construct", "a", "set", "or", "list", "like", "Springs", "bean", "XML", "configuration", "." ]
train
https://github.com/cache2k/cache2k/blob/3c9ccff12608c598c387ec50957089784cc4b618/cache2k-api/src/main/java/org/cache2k/configuration/Cache2kConfiguration.java#L533-L535
knowm/XChart
xchart/src/main/java/org/knowm/xchart/OHLCChart.java
OHLCChart.addSeries
public OHLCSeries addSeries( String seriesName, float[] openData, float[] highData, float[] lowData, float[] closeData) { """ Add a series for a OHLC type chart using using float arrays @param seriesName @param openData the open data @param highData the high data @param lowData the low data @param closeData the close data @return A Series object that you can set properties on """ return addSeries(seriesName, null, openData, highData, lowData, closeData); }
java
public OHLCSeries addSeries( String seriesName, float[] openData, float[] highData, float[] lowData, float[] closeData) { return addSeries(seriesName, null, openData, highData, lowData, closeData); }
[ "public", "OHLCSeries", "addSeries", "(", "String", "seriesName", ",", "float", "[", "]", "openData", ",", "float", "[", "]", "highData", ",", "float", "[", "]", "lowData", ",", "float", "[", "]", "closeData", ")", "{", "return", "addSeries", "(", "seriesName", ",", "null", ",", "openData", ",", "highData", ",", "lowData", ",", "closeData", ")", ";", "}" ]
Add a series for a OHLC type chart using using float arrays @param seriesName @param openData the open data @param highData the high data @param lowData the low data @param closeData the close data @return A Series object that you can set properties on
[ "Add", "a", "series", "for", "a", "OHLC", "type", "chart", "using", "using", "float", "arrays" ]
train
https://github.com/knowm/XChart/blob/677a105753a855edf24782fab1bf1f5aec3e642b/xchart/src/main/java/org/knowm/xchart/OHLCChart.java#L86-L90
aspectran/aspectran
core/src/main/java/com/aspectran/core/util/StringUtils.java
StringUtils.trimLeadingCharacter
public static String trimLeadingCharacter(String str, char leadingCharacter) { """ Trim all occurrences of the supplied leading character from the given {@code String}. @param str the {@code String} to check @param leadingCharacter the leading character to be trimmed @return the trimmed {@code String} """ if (!hasLength(str)) { return str; } StringBuilder buf = new StringBuilder(str); while (buf.length() > 0 && buf.charAt(0) == leadingCharacter) { buf.deleteCharAt(0); } return buf.toString(); }
java
public static String trimLeadingCharacter(String str, char leadingCharacter) { if (!hasLength(str)) { return str; } StringBuilder buf = new StringBuilder(str); while (buf.length() > 0 && buf.charAt(0) == leadingCharacter) { buf.deleteCharAt(0); } return buf.toString(); }
[ "public", "static", "String", "trimLeadingCharacter", "(", "String", "str", ",", "char", "leadingCharacter", ")", "{", "if", "(", "!", "hasLength", "(", "str", ")", ")", "{", "return", "str", ";", "}", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", "str", ")", ";", "while", "(", "buf", ".", "length", "(", ")", ">", "0", "&&", "buf", ".", "charAt", "(", "0", ")", "==", "leadingCharacter", ")", "{", "buf", ".", "deleteCharAt", "(", "0", ")", ";", "}", "return", "buf", ".", "toString", "(", ")", ";", "}" ]
Trim all occurrences of the supplied leading character from the given {@code String}. @param str the {@code String} to check @param leadingCharacter the leading character to be trimmed @return the trimmed {@code String}
[ "Trim", "all", "occurrences", "of", "the", "supplied", "leading", "character", "from", "the", "given", "{", "@code", "String", "}", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/StringUtils.java#L234-L243
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/methods/TmdbTV.java
TmdbTV.getTVKeywords
public ResultList<Keyword> getTVKeywords(int tvID) throws MovieDbException { """ Get the plot keywords for a specific TV show id. @param tvID @return @throws com.omertron.themoviedbapi.MovieDbException """ TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); URL url = new ApiUrl(apiKey, MethodBase.TV).subMethod(MethodSub.KEYWORDS).buildUrl(parameters); WrapperGenericList<Keyword> wrapper = processWrapper(getTypeReference(Keyword.class), url, "keywords"); return wrapper.getResultsList(); }
java
public ResultList<Keyword> getTVKeywords(int tvID) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); URL url = new ApiUrl(apiKey, MethodBase.TV).subMethod(MethodSub.KEYWORDS).buildUrl(parameters); WrapperGenericList<Keyword> wrapper = processWrapper(getTypeReference(Keyword.class), url, "keywords"); return wrapper.getResultsList(); }
[ "public", "ResultList", "<", "Keyword", ">", "getTVKeywords", "(", "int", "tvID", ")", "throws", "MovieDbException", "{", "TmdbParameters", "parameters", "=", "new", "TmdbParameters", "(", ")", ";", "parameters", ".", "add", "(", "Param", ".", "ID", ",", "tvID", ")", ";", "URL", "url", "=", "new", "ApiUrl", "(", "apiKey", ",", "MethodBase", ".", "TV", ")", ".", "subMethod", "(", "MethodSub", ".", "KEYWORDS", ")", ".", "buildUrl", "(", "parameters", ")", ";", "WrapperGenericList", "<", "Keyword", ">", "wrapper", "=", "processWrapper", "(", "getTypeReference", "(", "Keyword", ".", "class", ")", ",", "url", ",", "\"keywords\"", ")", ";", "return", "wrapper", ".", "getResultsList", "(", ")", ";", "}" ]
Get the plot keywords for a specific TV show id. @param tvID @return @throws com.omertron.themoviedbapi.MovieDbException
[ "Get", "the", "plot", "keywords", "for", "a", "specific", "TV", "show", "id", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbTV.java#L248-L255
unbescape/unbescape
src/main/java/org/unbescape/xml/XmlEscape.java
XmlEscape.escapeXml11Attribute
public static void escapeXml11Attribute(final String text, final Writer writer) throws IOException { """ <p> Perform an XML 1.1 level 2 (markup-significant and all non-ASCII chars) <strong>escape</strong> operation on a <tt>String</tt> input meant to be an XML attribute value, writing results to a <tt>Writer</tt>. </p> <p> <em>Level 2</em> means this method will escape: </p> <ul> <li>The five markup-significant characters: <tt>&lt;</tt>, <tt>&gt;</tt>, <tt>&amp;</tt>, <tt>&quot;</tt> and <tt>&#39;</tt></li> <li>All non ASCII characters.</li> </ul> <p> This escape will be performed by replacing those chars by the corresponding XML Character Entity References (e.g. <tt>'&amp;lt;'</tt>) when such CER exists for the replaced character, and replacing by a hexadecimal character reference (e.g. <tt>'&amp;#x2430;'</tt>) when there there is no CER for the replaced character. </p> <p> Besides, being an attribute value also <tt>&#92;t</tt>, <tt>&#92;n</tt> and <tt>&#92;r</tt> will be escaped to avoid white-space normalization from removing line feeds (turning them into white spaces) during future parsing operations. </p> <p> This method calls {@link #escapeXml11(String, Writer, XmlEscapeType, XmlEscapeLevel)} with the following preconfigured values: </p> <ul> <li><tt>type</tt>: {@link org.unbescape.xml.XmlEscapeType#CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA}</li> <li><tt>level</tt>: {@link org.unbescape.xml.XmlEscapeLevel#LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT}</li> </ul> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>String</tt> to be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs @since 1.1.5 """ escapeXml(text, writer, XmlEscapeSymbols.XML11_ATTRIBUTE_SYMBOLS, XmlEscapeType.CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA, XmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT); }
java
public static void escapeXml11Attribute(final String text, final Writer writer) throws IOException { escapeXml(text, writer, XmlEscapeSymbols.XML11_ATTRIBUTE_SYMBOLS, XmlEscapeType.CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA, XmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT); }
[ "public", "static", "void", "escapeXml11Attribute", "(", "final", "String", "text", ",", "final", "Writer", "writer", ")", "throws", "IOException", "{", "escapeXml", "(", "text", ",", "writer", ",", "XmlEscapeSymbols", ".", "XML11_ATTRIBUTE_SYMBOLS", ",", "XmlEscapeType", ".", "CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA", ",", "XmlEscapeLevel", ".", "LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT", ")", ";", "}" ]
<p> Perform an XML 1.1 level 2 (markup-significant and all non-ASCII chars) <strong>escape</strong> operation on a <tt>String</tt> input meant to be an XML attribute value, writing results to a <tt>Writer</tt>. </p> <p> <em>Level 2</em> means this method will escape: </p> <ul> <li>The five markup-significant characters: <tt>&lt;</tt>, <tt>&gt;</tt>, <tt>&amp;</tt>, <tt>&quot;</tt> and <tt>&#39;</tt></li> <li>All non ASCII characters.</li> </ul> <p> This escape will be performed by replacing those chars by the corresponding XML Character Entity References (e.g. <tt>'&amp;lt;'</tt>) when such CER exists for the replaced character, and replacing by a hexadecimal character reference (e.g. <tt>'&amp;#x2430;'</tt>) when there there is no CER for the replaced character. </p> <p> Besides, being an attribute value also <tt>&#92;t</tt>, <tt>&#92;n</tt> and <tt>&#92;r</tt> will be escaped to avoid white-space normalization from removing line feeds (turning them into white spaces) during future parsing operations. </p> <p> This method calls {@link #escapeXml11(String, Writer, XmlEscapeType, XmlEscapeLevel)} with the following preconfigured values: </p> <ul> <li><tt>type</tt>: {@link org.unbescape.xml.XmlEscapeType#CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA}</li> <li><tt>level</tt>: {@link org.unbescape.xml.XmlEscapeLevel#LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT}</li> </ul> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>String</tt> to be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs @since 1.1.5
[ "<p", ">", "Perform", "an", "XML", "1", ".", "1", "level", "2", "(", "markup", "-", "significant", "and", "all", "non", "-", "ASCII", "chars", ")", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "String<", "/", "tt", ">", "input", "meant", "to", "be", "an", "XML", "attribute", "value", "writing", "results", "to", "a", "<tt", ">", "Writer<", "/", "tt", ">", ".", "<", "/", "p", ">", "<p", ">", "<em", ">", "Level", "2<", "/", "em", ">", "means", "this", "method", "will", "escape", ":", "<", "/", "p", ">", "<ul", ">", "<li", ">", "The", "five", "markup", "-", "significant", "characters", ":", "<tt", ">", "&lt", ";", "<", "/", "tt", ">", "<tt", ">", "&gt", ";", "<", "/", "tt", ">", "<tt", ">", "&amp", ";", "<", "/", "tt", ">", "<tt", ">", "&quot", ";", "<", "/", "tt", ">", "and", "<tt", ">", "&#39", ";", "<", "/", "tt", ">", "<", "/", "li", ">", "<li", ">", "All", "non", "ASCII", "characters", ".", "<", "/", "li", ">", "<", "/", "ul", ">", "<p", ">", "This", "escape", "will", "be", "performed", "by", "replacing", "those", "chars", "by", "the", "corresponding", "XML", "Character", "Entity", "References", "(", "e", ".", "g", ".", "<tt", ">", "&amp", ";", "lt", ";", "<", "/", "tt", ">", ")", "when", "such", "CER", "exists", "for", "the", "replaced", "character", "and", "replacing", "by", "a", "hexadecimal", "character", "reference", "(", "e", ".", "g", ".", "<tt", ">", "&amp", ";", "#x2430", ";", "<", "/", "tt", ">", ")", "when", "there", "there", "is", "no", "CER", "for", "the", "replaced", "character", ".", "<", "/", "p", ">", "<p", ">", "Besides", "being", "an", "attribute", "value", "also", "<tt", ">", "&#92", ";", "t<", "/", "tt", ">", "<tt", ">", "&#92", ";", "n<", "/", "tt", ">", "and", "<tt", ">", "&#92", ";", "r<", "/", "tt", ">", "will", "be", "escaped", "to", "avoid", "white", "-", "space", "normalization", "from", "removing", "line", "feeds", "(", "turning", "them", "into", "white", "spaces", ")", "during", "future", "parsing", "operations", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "calls", "{", "@link", "#escapeXml11", "(", "String", "Writer", "XmlEscapeType", "XmlEscapeLevel", ")", "}", "with", "the", "following", "preconfigured", "values", ":", "<", "/", "p", ">", "<ul", ">", "<li", ">", "<tt", ">", "type<", "/", "tt", ">", ":", "{", "@link", "org", ".", "unbescape", ".", "xml", ".", "XmlEscapeType#CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA", "}", "<", "/", "li", ">", "<li", ">", "<tt", ">", "level<", "/", "tt", ">", ":", "{", "@link", "org", ".", "unbescape", ".", "xml", ".", "XmlEscapeLevel#LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT", "}", "<", "/", "li", ">", "<", "/", "ul", ">", "<p", ">", "This", "method", "is", "<strong", ">", "thread", "-", "safe<", "/", "strong", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/xml/XmlEscape.java#L1020-L1025
igniterealtime/Smack
smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoRatchet.java
OmemoRatchet.decryptMessageElement
static String decryptMessageElement(OmemoElement element, CipherAndAuthTag cipherAndAuthTag) throws CryptoFailedException { """ Use the symmetric key in cipherAndAuthTag to decrypt the payload of the omemoMessage. The decrypted payload will be the body of the returned Message. @param element omemoElement containing a payload. @param cipherAndAuthTag cipher and authentication tag. @return decrypted plain text. @throws CryptoFailedException if decryption using AES key fails. """ if (!element.isMessageElement()) { throw new IllegalArgumentException("decryptMessageElement cannot decrypt OmemoElement which is no MessageElement!"); } if (cipherAndAuthTag.getAuthTag() == null || cipherAndAuthTag.getAuthTag().length != 16) { throw new CryptoFailedException("AuthenticationTag is null or has wrong length: " + (cipherAndAuthTag.getAuthTag() == null ? "null" : cipherAndAuthTag.getAuthTag().length)); } byte[] encryptedBody = payloadAndAuthTag(element, cipherAndAuthTag.getAuthTag()); try { String plaintext = new String(cipherAndAuthTag.getCipher().doFinal(encryptedBody), StringUtils.UTF8); return plaintext; } catch (UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException e) { throw new CryptoFailedException("decryptMessageElement could not decipher message body: " + e.getMessage()); } }
java
static String decryptMessageElement(OmemoElement element, CipherAndAuthTag cipherAndAuthTag) throws CryptoFailedException { if (!element.isMessageElement()) { throw new IllegalArgumentException("decryptMessageElement cannot decrypt OmemoElement which is no MessageElement!"); } if (cipherAndAuthTag.getAuthTag() == null || cipherAndAuthTag.getAuthTag().length != 16) { throw new CryptoFailedException("AuthenticationTag is null or has wrong length: " + (cipherAndAuthTag.getAuthTag() == null ? "null" : cipherAndAuthTag.getAuthTag().length)); } byte[] encryptedBody = payloadAndAuthTag(element, cipherAndAuthTag.getAuthTag()); try { String plaintext = new String(cipherAndAuthTag.getCipher().doFinal(encryptedBody), StringUtils.UTF8); return plaintext; } catch (UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException e) { throw new CryptoFailedException("decryptMessageElement could not decipher message body: " + e.getMessage()); } }
[ "static", "String", "decryptMessageElement", "(", "OmemoElement", "element", ",", "CipherAndAuthTag", "cipherAndAuthTag", ")", "throws", "CryptoFailedException", "{", "if", "(", "!", "element", ".", "isMessageElement", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"decryptMessageElement cannot decrypt OmemoElement which is no MessageElement!\"", ")", ";", "}", "if", "(", "cipherAndAuthTag", ".", "getAuthTag", "(", ")", "==", "null", "||", "cipherAndAuthTag", ".", "getAuthTag", "(", ")", ".", "length", "!=", "16", ")", "{", "throw", "new", "CryptoFailedException", "(", "\"AuthenticationTag is null or has wrong length: \"", "+", "(", "cipherAndAuthTag", ".", "getAuthTag", "(", ")", "==", "null", "?", "\"null\"", ":", "cipherAndAuthTag", ".", "getAuthTag", "(", ")", ".", "length", ")", ")", ";", "}", "byte", "[", "]", "encryptedBody", "=", "payloadAndAuthTag", "(", "element", ",", "cipherAndAuthTag", ".", "getAuthTag", "(", ")", ")", ";", "try", "{", "String", "plaintext", "=", "new", "String", "(", "cipherAndAuthTag", ".", "getCipher", "(", ")", ".", "doFinal", "(", "encryptedBody", ")", ",", "StringUtils", ".", "UTF8", ")", ";", "return", "plaintext", ";", "}", "catch", "(", "UnsupportedEncodingException", "|", "IllegalBlockSizeException", "|", "BadPaddingException", "e", ")", "{", "throw", "new", "CryptoFailedException", "(", "\"decryptMessageElement could not decipher message body: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Use the symmetric key in cipherAndAuthTag to decrypt the payload of the omemoMessage. The decrypted payload will be the body of the returned Message. @param element omemoElement containing a payload. @param cipherAndAuthTag cipher and authentication tag. @return decrypted plain text. @throws CryptoFailedException if decryption using AES key fails.
[ "Use", "the", "symmetric", "key", "in", "cipherAndAuthTag", "to", "decrypt", "the", "payload", "of", "the", "omemoMessage", ".", "The", "decrypted", "payload", "will", "be", "the", "body", "of", "the", "returned", "Message", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoRatchet.java#L156-L177
hibernate/hibernate-ogm
core/src/main/java/org/hibernate/ogm/datastore/document/impl/EmbeddableStateFinder.java
EmbeddableStateFinder.maybeCacheOnNonNullEmbeddable
private void maybeCacheOnNonNullEmbeddable(String[] path, int index, Set<String> columnsOfEmbeddable) { """ The embeddable is not null. Only cache the values if we are in the most specific embeddable containing {@code column} otherwise a more specific embeddable might be null and we would miss it Only set the values for the columns sharing this specific embeddable columns from deeper embeddables might be null """ if ( index == path.length - 2 ) { //right level (i.e. the most specific embeddable for the column at bay for ( String columnInvolved : columnsOfEmbeddable ) { if ( columnInvolved.split( "\\." ).length == path.length ) { // Only cache for columns from the same embeddable columnToOuterMostNullEmbeddableCache.put( columnInvolved, null ); } } } }
java
private void maybeCacheOnNonNullEmbeddable(String[] path, int index, Set<String> columnsOfEmbeddable) { if ( index == path.length - 2 ) { //right level (i.e. the most specific embeddable for the column at bay for ( String columnInvolved : columnsOfEmbeddable ) { if ( columnInvolved.split( "\\." ).length == path.length ) { // Only cache for columns from the same embeddable columnToOuterMostNullEmbeddableCache.put( columnInvolved, null ); } } } }
[ "private", "void", "maybeCacheOnNonNullEmbeddable", "(", "String", "[", "]", "path", ",", "int", "index", ",", "Set", "<", "String", ">", "columnsOfEmbeddable", ")", "{", "if", "(", "index", "==", "path", ".", "length", "-", "2", ")", "{", "//right level (i.e. the most specific embeddable for the column at bay", "for", "(", "String", "columnInvolved", ":", "columnsOfEmbeddable", ")", "{", "if", "(", "columnInvolved", ".", "split", "(", "\"\\\\.\"", ")", ".", "length", "==", "path", ".", "length", ")", "{", "// Only cache for columns from the same embeddable", "columnToOuterMostNullEmbeddableCache", ".", "put", "(", "columnInvolved", ",", "null", ")", ";", "}", "}", "}", "}" ]
The embeddable is not null. Only cache the values if we are in the most specific embeddable containing {@code column} otherwise a more specific embeddable might be null and we would miss it Only set the values for the columns sharing this specific embeddable columns from deeper embeddables might be null
[ "The", "embeddable", "is", "not", "null", ".", "Only", "cache", "the", "values", "if", "we", "are", "in", "the", "most", "specific", "embeddable", "containing", "{", "@code", "column", "}", "otherwise", "a", "more", "specific", "embeddable", "might", "be", "null", "and", "we", "would", "miss", "it" ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/datastore/document/impl/EmbeddableStateFinder.java#L97-L107
jboss/jboss-jsf-api_spec
src/main/java/javax/faces/context/ExternalContext.java
ExternalContext.responseSendError
public void responseSendError(int statusCode, String message) throws IOException { """ <p class="changed_added_2_0">Sends an HTTP status code with message.</p> <p><em>Servlet:</em> This must be performed by calling the <code>javax.servlet.http.HttpServletResponse</code> <code>sendError</code> method.</p> <p>The default implementation throws <code>UnsupportedOperationException</code> and is provided for the sole purpose of not breaking existing applications that extend this class.</p> @param statusCode an HTTP status code @param message an option message to detail the cause of the code @since 2.0 """ if (defaultExternalContext != null) { defaultExternalContext.responseSendError(statusCode, message); } else { throw new UnsupportedOperationException(); } }
java
public void responseSendError(int statusCode, String message) throws IOException { if (defaultExternalContext != null) { defaultExternalContext.responseSendError(statusCode, message); } else { throw new UnsupportedOperationException(); } }
[ "public", "void", "responseSendError", "(", "int", "statusCode", ",", "String", "message", ")", "throws", "IOException", "{", "if", "(", "defaultExternalContext", "!=", "null", ")", "{", "defaultExternalContext", ".", "responseSendError", "(", "statusCode", ",", "message", ")", ";", "}", "else", "{", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "}" ]
<p class="changed_added_2_0">Sends an HTTP status code with message.</p> <p><em>Servlet:</em> This must be performed by calling the <code>javax.servlet.http.HttpServletResponse</code> <code>sendError</code> method.</p> <p>The default implementation throws <code>UnsupportedOperationException</code> and is provided for the sole purpose of not breaking existing applications that extend this class.</p> @param statusCode an HTTP status code @param message an option message to detail the cause of the code @since 2.0
[ "<p", "class", "=", "changed_added_2_0", ">", "Sends", "an", "HTTP", "status", "code", "with", "message", ".", "<", "/", "p", ">" ]
train
https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/context/ExternalContext.java#L1819-L1827
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/internal/util/VelocityParser.java
VelocityParser.getMethodParameters
public int getMethodParameters(char[] array, int currentIndex, StringBuffer velocityBlock, VelocityParserContext context) { """ Get the Velocity method parameters (including <code>(</code> and <code>)</code>). @param array the source to parse @param currentIndex the current index in the <code>array</code> @param velocityBlock the buffer where to append matched velocity block @param context the parser context to put some informations @return the index in the <code>array</code> after the matched block """ return getParameters(array, currentIndex, velocityBlock, ')', context); }
java
public int getMethodParameters(char[] array, int currentIndex, StringBuffer velocityBlock, VelocityParserContext context) { return getParameters(array, currentIndex, velocityBlock, ')', context); }
[ "public", "int", "getMethodParameters", "(", "char", "[", "]", "array", ",", "int", "currentIndex", ",", "StringBuffer", "velocityBlock", ",", "VelocityParserContext", "context", ")", "{", "return", "getParameters", "(", "array", ",", "currentIndex", ",", "velocityBlock", ",", "'", "'", ",", "context", ")", ";", "}" ]
Get the Velocity method parameters (including <code>(</code> and <code>)</code>). @param array the source to parse @param currentIndex the current index in the <code>array</code> @param velocityBlock the buffer where to append matched velocity block @param context the parser context to put some informations @return the index in the <code>array</code> after the matched block
[ "Get", "the", "Velocity", "method", "parameters", "(", "including", "<code", ">", "(", "<", "/", "code", ">", "and", "<code", ">", ")", "<", "/", "code", ">", ")", "." ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/internal/util/VelocityParser.java#L532-L536
rometools/rome-certiorem
src/main/java/com/rometools/certiorem/hub/notify/standard/AbstractNotifier.java
AbstractNotifier.postNotification
protected SubscriptionSummary postNotification(final Subscriber subscriber, final String mimeType, final byte[] payload) { """ POSTs the payload to the subscriber's callback and returns a SubscriptionSummary with subscriber counts (where possible) and the success state of the notification. @param subscriber subscriber data. @param mimeType MIME type for the request @param payload payload of the feed to send @return SubscriptionSummary with the returned data. """ final SubscriptionSummary result = new SubscriptionSummary(); try { final URL target = new URL(subscriber.getCallback()); LOG.info("Posting notification to subscriber {}", subscriber.getCallback()); result.setHost(target.getHost()); final HttpURLConnection connection = (HttpURLConnection) target.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", mimeType); connection.setDoOutput(true); connection.connect(); final OutputStream os = connection.getOutputStream(); os.write(payload); os.close(); final int responseCode = connection.getResponseCode(); final String subscribers = connection.getHeaderField("X-Hub-On-Behalf-Of"); connection.disconnect(); if (responseCode != 200) { LOG.warn("Got code {} from {}", responseCode, target); result.setLastPublishSuccessful(false); return result; } if (subscribers != null) { try { result.setSubscribers(Integer.parseInt(subscribers)); } catch (final NumberFormatException nfe) { LOG.warn("Invalid subscriber value " + subscribers + " " + target, nfe); result.setSubscribers(-1); } } else { result.setSubscribers(-1); } } catch (final MalformedURLException ex) { LOG.warn(null, ex); result.setLastPublishSuccessful(false); } catch (final IOException ex) { LOG.error(null, ex); result.setLastPublishSuccessful(false); } return result; }
java
protected SubscriptionSummary postNotification(final Subscriber subscriber, final String mimeType, final byte[] payload) { final SubscriptionSummary result = new SubscriptionSummary(); try { final URL target = new URL(subscriber.getCallback()); LOG.info("Posting notification to subscriber {}", subscriber.getCallback()); result.setHost(target.getHost()); final HttpURLConnection connection = (HttpURLConnection) target.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", mimeType); connection.setDoOutput(true); connection.connect(); final OutputStream os = connection.getOutputStream(); os.write(payload); os.close(); final int responseCode = connection.getResponseCode(); final String subscribers = connection.getHeaderField("X-Hub-On-Behalf-Of"); connection.disconnect(); if (responseCode != 200) { LOG.warn("Got code {} from {}", responseCode, target); result.setLastPublishSuccessful(false); return result; } if (subscribers != null) { try { result.setSubscribers(Integer.parseInt(subscribers)); } catch (final NumberFormatException nfe) { LOG.warn("Invalid subscriber value " + subscribers + " " + target, nfe); result.setSubscribers(-1); } } else { result.setSubscribers(-1); } } catch (final MalformedURLException ex) { LOG.warn(null, ex); result.setLastPublishSuccessful(false); } catch (final IOException ex) { LOG.error(null, ex); result.setLastPublishSuccessful(false); } return result; }
[ "protected", "SubscriptionSummary", "postNotification", "(", "final", "Subscriber", "subscriber", ",", "final", "String", "mimeType", ",", "final", "byte", "[", "]", "payload", ")", "{", "final", "SubscriptionSummary", "result", "=", "new", "SubscriptionSummary", "(", ")", ";", "try", "{", "final", "URL", "target", "=", "new", "URL", "(", "subscriber", ".", "getCallback", "(", ")", ")", ";", "LOG", ".", "info", "(", "\"Posting notification to subscriber {}\"", ",", "subscriber", ".", "getCallback", "(", ")", ")", ";", "result", ".", "setHost", "(", "target", ".", "getHost", "(", ")", ")", ";", "final", "HttpURLConnection", "connection", "=", "(", "HttpURLConnection", ")", "target", ".", "openConnection", "(", ")", ";", "connection", ".", "setRequestMethod", "(", "\"POST\"", ")", ";", "connection", ".", "setRequestProperty", "(", "\"Content-Type\"", ",", "mimeType", ")", ";", "connection", ".", "setDoOutput", "(", "true", ")", ";", "connection", ".", "connect", "(", ")", ";", "final", "OutputStream", "os", "=", "connection", ".", "getOutputStream", "(", ")", ";", "os", ".", "write", "(", "payload", ")", ";", "os", ".", "close", "(", ")", ";", "final", "int", "responseCode", "=", "connection", ".", "getResponseCode", "(", ")", ";", "final", "String", "subscribers", "=", "connection", ".", "getHeaderField", "(", "\"X-Hub-On-Behalf-Of\"", ")", ";", "connection", ".", "disconnect", "(", ")", ";", "if", "(", "responseCode", "!=", "200", ")", "{", "LOG", ".", "warn", "(", "\"Got code {} from {}\"", ",", "responseCode", ",", "target", ")", ";", "result", ".", "setLastPublishSuccessful", "(", "false", ")", ";", "return", "result", ";", "}", "if", "(", "subscribers", "!=", "null", ")", "{", "try", "{", "result", ".", "setSubscribers", "(", "Integer", ".", "parseInt", "(", "subscribers", ")", ")", ";", "}", "catch", "(", "final", "NumberFormatException", "nfe", ")", "{", "LOG", ".", "warn", "(", "\"Invalid subscriber value \"", "+", "subscribers", "+", "\" \"", "+", "target", ",", "nfe", ")", ";", "result", ".", "setSubscribers", "(", "-", "1", ")", ";", "}", "}", "else", "{", "result", ".", "setSubscribers", "(", "-", "1", ")", ";", "}", "}", "catch", "(", "final", "MalformedURLException", "ex", ")", "{", "LOG", ".", "warn", "(", "null", ",", "ex", ")", ";", "result", ".", "setLastPublishSuccessful", "(", "false", ")", ";", "}", "catch", "(", "final", "IOException", "ex", ")", "{", "LOG", ".", "error", "(", "null", ",", "ex", ")", ";", "result", ".", "setLastPublishSuccessful", "(", "false", ")", ";", "}", "return", "result", ";", "}" ]
POSTs the payload to the subscriber's callback and returns a SubscriptionSummary with subscriber counts (where possible) and the success state of the notification. @param subscriber subscriber data. @param mimeType MIME type for the request @param payload payload of the feed to send @return SubscriptionSummary with the returned data.
[ "POSTs", "the", "payload", "to", "the", "subscriber", "s", "callback", "and", "returns", "a", "SubscriptionSummary", "with", "subscriber", "counts", "(", "where", "possible", ")", "and", "the", "success", "state", "of", "the", "notification", "." ]
train
https://github.com/rometools/rome-certiorem/blob/e5a003193dd2abd748e77961c0f216a7f5690712/src/main/java/com/rometools/certiorem/hub/notify/standard/AbstractNotifier.java#L114-L161
flex-oss/flex-fruit
fruit-core/src/main/java/org/cdlflex/fruit/Range.java
Range.includes
public boolean includes(T value, boolean inclusive) { """ Checks whether the given value is included in this range. If inclusive is set to true, checking for 1 in the range of 1,10 will return true. @param value the value to check @param inclusive whether or not the range is open (the value is included) @return true if the value is inside this range, false otherwise """ if (inclusive) { return value.compareTo(getStart()) >= 0 && value.compareTo(getEnd()) <= 0; } else { return value.compareTo(getStart()) > 0 && value.compareTo(getEnd()) < 0; } }
java
public boolean includes(T value, boolean inclusive) { if (inclusive) { return value.compareTo(getStart()) >= 0 && value.compareTo(getEnd()) <= 0; } else { return value.compareTo(getStart()) > 0 && value.compareTo(getEnd()) < 0; } }
[ "public", "boolean", "includes", "(", "T", "value", ",", "boolean", "inclusive", ")", "{", "if", "(", "inclusive", ")", "{", "return", "value", ".", "compareTo", "(", "getStart", "(", ")", ")", ">=", "0", "&&", "value", ".", "compareTo", "(", "getEnd", "(", ")", ")", "<=", "0", ";", "}", "else", "{", "return", "value", ".", "compareTo", "(", "getStart", "(", ")", ")", ">", "0", "&&", "value", ".", "compareTo", "(", "getEnd", "(", ")", ")", "<", "0", ";", "}", "}" ]
Checks whether the given value is included in this range. If inclusive is set to true, checking for 1 in the range of 1,10 will return true. @param value the value to check @param inclusive whether or not the range is open (the value is included) @return true if the value is inside this range, false otherwise
[ "Checks", "whether", "the", "given", "value", "is", "included", "in", "this", "range", ".", "If", "inclusive", "is", "set", "to", "true", "checking", "for", "1", "in", "the", "range", "of", "1", "10", "will", "return", "true", "." ]
train
https://github.com/flex-oss/flex-fruit/blob/30d7eca5ee796b829f96c9932a95b259ca9738d9/fruit-core/src/main/java/org/cdlflex/fruit/Range.java#L73-L80
Impetus/Kundera
src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/index/Neo4JIndexManager.java
Neo4JIndexManager.updateRelationshipIndex
public void updateRelationshipIndex(EntityMetadata entityMetadata, GraphDatabaseService graphDb, Relationship relationship, MetamodelImpl metaModel) { """ If relationship auto-indexing is disabled, Update index for this relationship manually @param entityMetadata @param graphDb @param autoIndexing @param node """ if (!isRelationshipAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable()) { Index<Relationship> relationshipIndex = graphDb.index().forRelationships(entityMetadata.getIndexName()); // Remove all existing relationship entries from Index relationshipIndex.remove(relationship); // Recreate fresh index on this relationship addRelationshipIndex(entityMetadata, relationship, relationshipIndex, metaModel); } }
java
public void updateRelationshipIndex(EntityMetadata entityMetadata, GraphDatabaseService graphDb, Relationship relationship, MetamodelImpl metaModel) { if (!isRelationshipAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable()) { Index<Relationship> relationshipIndex = graphDb.index().forRelationships(entityMetadata.getIndexName()); // Remove all existing relationship entries from Index relationshipIndex.remove(relationship); // Recreate fresh index on this relationship addRelationshipIndex(entityMetadata, relationship, relationshipIndex, metaModel); } }
[ "public", "void", "updateRelationshipIndex", "(", "EntityMetadata", "entityMetadata", ",", "GraphDatabaseService", "graphDb", ",", "Relationship", "relationship", ",", "MetamodelImpl", "metaModel", ")", "{", "if", "(", "!", "isRelationshipAutoIndexingEnabled", "(", "graphDb", ")", "&&", "entityMetadata", ".", "isIndexable", "(", ")", ")", "{", "Index", "<", "Relationship", ">", "relationshipIndex", "=", "graphDb", ".", "index", "(", ")", ".", "forRelationships", "(", "entityMetadata", ".", "getIndexName", "(", ")", ")", ";", "// Remove all existing relationship entries from Index", "relationshipIndex", ".", "remove", "(", "relationship", ")", ";", "// Recreate fresh index on this relationship", "addRelationshipIndex", "(", "entityMetadata", ",", "relationship", ",", "relationshipIndex", ",", "metaModel", ")", ";", "}", "}" ]
If relationship auto-indexing is disabled, Update index for this relationship manually @param entityMetadata @param graphDb @param autoIndexing @param node
[ "If", "relationship", "auto", "-", "indexing", "is", "disabled", "Update", "index", "for", "this", "relationship", "manually" ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/index/Neo4JIndexManager.java#L185-L198
onepf/OpenIAB
library/src/main/java/org/onepf/oms/util/Utils.java
Utils.hasRequestedPermission
public static boolean hasRequestedPermission(@NotNull Context context, @NotNull final String permission) { """ Checks if the AndroidManifest contains a permission. @param permission The permission to test. @return true if the permission is requested by the application. """ boolean hasRequestedPermission = false; if (TextUtils.isEmpty(permission)) { throw new IllegalArgumentException("Permission can't be null or empty."); } try { PackageInfo info = context.getPackageManager() .getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS); if (!CollectionUtils.isEmpty(info.requestedPermissions)) { for (String requestedPermission : info.requestedPermissions) { if (permission.equals(requestedPermission)) { hasRequestedPermission = true; break; } } } } catch (PackageManager.NameNotFoundException e) { Logger.e(e, "Error during checking permission ", permission); } Logger.d("hasRequestedPermission() is ", hasRequestedPermission, " for ", permission); return hasRequestedPermission; }
java
public static boolean hasRequestedPermission(@NotNull Context context, @NotNull final String permission) { boolean hasRequestedPermission = false; if (TextUtils.isEmpty(permission)) { throw new IllegalArgumentException("Permission can't be null or empty."); } try { PackageInfo info = context.getPackageManager() .getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS); if (!CollectionUtils.isEmpty(info.requestedPermissions)) { for (String requestedPermission : info.requestedPermissions) { if (permission.equals(requestedPermission)) { hasRequestedPermission = true; break; } } } } catch (PackageManager.NameNotFoundException e) { Logger.e(e, "Error during checking permission ", permission); } Logger.d("hasRequestedPermission() is ", hasRequestedPermission, " for ", permission); return hasRequestedPermission; }
[ "public", "static", "boolean", "hasRequestedPermission", "(", "@", "NotNull", "Context", "context", ",", "@", "NotNull", "final", "String", "permission", ")", "{", "boolean", "hasRequestedPermission", "=", "false", ";", "if", "(", "TextUtils", ".", "isEmpty", "(", "permission", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Permission can't be null or empty.\"", ")", ";", "}", "try", "{", "PackageInfo", "info", "=", "context", ".", "getPackageManager", "(", ")", ".", "getPackageInfo", "(", "context", ".", "getPackageName", "(", ")", ",", "PackageManager", ".", "GET_PERMISSIONS", ")", ";", "if", "(", "!", "CollectionUtils", ".", "isEmpty", "(", "info", ".", "requestedPermissions", ")", ")", "{", "for", "(", "String", "requestedPermission", ":", "info", ".", "requestedPermissions", ")", "{", "if", "(", "permission", ".", "equals", "(", "requestedPermission", ")", ")", "{", "hasRequestedPermission", "=", "true", ";", "break", ";", "}", "}", "}", "}", "catch", "(", "PackageManager", ".", "NameNotFoundException", "e", ")", "{", "Logger", ".", "e", "(", "e", ",", "\"Error during checking permission \"", ",", "permission", ")", ";", "}", "Logger", ".", "d", "(", "\"hasRequestedPermission() is \"", ",", "hasRequestedPermission", ",", "\" for \"", ",", "permission", ")", ";", "return", "hasRequestedPermission", ";", "}" ]
Checks if the AndroidManifest contains a permission. @param permission The permission to test. @return true if the permission is requested by the application.
[ "Checks", "if", "the", "AndroidManifest", "contains", "a", "permission", "." ]
train
https://github.com/onepf/OpenIAB/blob/90552d53c5303b322940d96a0c4b7cb797d78760/library/src/main/java/org/onepf/oms/util/Utils.java#L24-L46
albfernandez/itext2
src/main/java/com/lowagie/text/Phrase.java
Phrase.getInstance
public static final Phrase getInstance(int leading, String string, Font font) { """ Gets a special kind of Phrase that changes some characters into corresponding symbols. @param leading @param string @param font @return a newly constructed Phrase """ Phrase p = new Phrase(true); p.setLeading(leading); p.font = font; if (font.getFamily() != Font.SYMBOL && font.getFamily() != Font.ZAPFDINGBATS && font.getBaseFont() == null) { int index; while((index = SpecialSymbol.index(string)) > -1) { if (index > 0) { String firstPart = string.substring(0, index); ((ArrayList)p).add(new Chunk(firstPart, font)); string = string.substring(index); } Font symbol = new Font(Font.SYMBOL, font.getSize(), font.getStyle(), font.getColor()); StringBuffer buf = new StringBuffer(); buf.append(SpecialSymbol.getCorrespondingSymbol(string.charAt(0))); string = string.substring(1); while (SpecialSymbol.index(string) == 0) { buf.append(SpecialSymbol.getCorrespondingSymbol(string.charAt(0))); string = string.substring(1); } ((ArrayList)p).add(new Chunk(buf.toString(), symbol)); } } if (string != null && string.length() != 0) { ((ArrayList)p).add(new Chunk(string, font)); } return p; }
java
public static final Phrase getInstance(int leading, String string, Font font) { Phrase p = new Phrase(true); p.setLeading(leading); p.font = font; if (font.getFamily() != Font.SYMBOL && font.getFamily() != Font.ZAPFDINGBATS && font.getBaseFont() == null) { int index; while((index = SpecialSymbol.index(string)) > -1) { if (index > 0) { String firstPart = string.substring(0, index); ((ArrayList)p).add(new Chunk(firstPart, font)); string = string.substring(index); } Font symbol = new Font(Font.SYMBOL, font.getSize(), font.getStyle(), font.getColor()); StringBuffer buf = new StringBuffer(); buf.append(SpecialSymbol.getCorrespondingSymbol(string.charAt(0))); string = string.substring(1); while (SpecialSymbol.index(string) == 0) { buf.append(SpecialSymbol.getCorrespondingSymbol(string.charAt(0))); string = string.substring(1); } ((ArrayList)p).add(new Chunk(buf.toString(), symbol)); } } if (string != null && string.length() != 0) { ((ArrayList)p).add(new Chunk(string, font)); } return p; }
[ "public", "static", "final", "Phrase", "getInstance", "(", "int", "leading", ",", "String", "string", ",", "Font", "font", ")", "{", "Phrase", "p", "=", "new", "Phrase", "(", "true", ")", ";", "p", ".", "setLeading", "(", "leading", ")", ";", "p", ".", "font", "=", "font", ";", "if", "(", "font", ".", "getFamily", "(", ")", "!=", "Font", ".", "SYMBOL", "&&", "font", ".", "getFamily", "(", ")", "!=", "Font", ".", "ZAPFDINGBATS", "&&", "font", ".", "getBaseFont", "(", ")", "==", "null", ")", "{", "int", "index", ";", "while", "(", "(", "index", "=", "SpecialSymbol", ".", "index", "(", "string", ")", ")", ">", "-", "1", ")", "{", "if", "(", "index", ">", "0", ")", "{", "String", "firstPart", "=", "string", ".", "substring", "(", "0", ",", "index", ")", ";", "(", "(", "ArrayList", ")", "p", ")", ".", "add", "(", "new", "Chunk", "(", "firstPart", ",", "font", ")", ")", ";", "string", "=", "string", ".", "substring", "(", "index", ")", ";", "}", "Font", "symbol", "=", "new", "Font", "(", "Font", ".", "SYMBOL", ",", "font", ".", "getSize", "(", ")", ",", "font", ".", "getStyle", "(", ")", ",", "font", ".", "getColor", "(", ")", ")", ";", "StringBuffer", "buf", "=", "new", "StringBuffer", "(", ")", ";", "buf", ".", "append", "(", "SpecialSymbol", ".", "getCorrespondingSymbol", "(", "string", ".", "charAt", "(", "0", ")", ")", ")", ";", "string", "=", "string", ".", "substring", "(", "1", ")", ";", "while", "(", "SpecialSymbol", ".", "index", "(", "string", ")", "==", "0", ")", "{", "buf", ".", "append", "(", "SpecialSymbol", ".", "getCorrespondingSymbol", "(", "string", ".", "charAt", "(", "0", ")", ")", ")", ";", "string", "=", "string", ".", "substring", "(", "1", ")", ";", "}", "(", "(", "ArrayList", ")", "p", ")", ".", "add", "(", "new", "Chunk", "(", "buf", ".", "toString", "(", ")", ",", "symbol", ")", ")", ";", "}", "}", "if", "(", "string", "!=", "null", "&&", "string", ".", "length", "(", ")", "!=", "0", ")", "{", "(", "(", "ArrayList", ")", "p", ")", ".", "add", "(", "new", "Chunk", "(", "string", ",", "font", ")", ")", ";", "}", "return", "p", ";", "}" ]
Gets a special kind of Phrase that changes some characters into corresponding symbols. @param leading @param string @param font @return a newly constructed Phrase
[ "Gets", "a", "special", "kind", "of", "Phrase", "that", "changes", "some", "characters", "into", "corresponding", "symbols", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/Phrase.java#L560-L587
foundation-runtime/service-directory
2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/async/WatcherManager.java
WatcherManager.deleteWatcher
public boolean deleteWatcher(String name, Watcher watcher) { """ Delete a watcher from the Service. @param name the Service Name. @param watcher the Watcher object. @return true if success. """ if(LOGGER.isTraceEnabled()){ LOGGER.trace("Delete a watcher, name={}", name); } synchronized(watchers){ if (watchers.containsKey(name)) { return watchers.get(name).remove(watcher); } } return false; }
java
public boolean deleteWatcher(String name, Watcher watcher){ if(LOGGER.isTraceEnabled()){ LOGGER.trace("Delete a watcher, name={}", name); } synchronized(watchers){ if (watchers.containsKey(name)) { return watchers.get(name).remove(watcher); } } return false; }
[ "public", "boolean", "deleteWatcher", "(", "String", "name", ",", "Watcher", "watcher", ")", "{", "if", "(", "LOGGER", ".", "isTraceEnabled", "(", ")", ")", "{", "LOGGER", ".", "trace", "(", "\"Delete a watcher, name={}\"", ",", "name", ")", ";", "}", "synchronized", "(", "watchers", ")", "{", "if", "(", "watchers", ".", "containsKey", "(", "name", ")", ")", "{", "return", "watchers", ".", "get", "(", "name", ")", ".", "remove", "(", "watcher", ")", ";", "}", "}", "return", "false", ";", "}" ]
Delete a watcher from the Service. @param name the Service Name. @param watcher the Watcher object. @return true if success.
[ "Delete", "a", "watcher", "from", "the", "Service", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/async/WatcherManager.java#L112-L123
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/bos/BosClient.java
BosClient.putObject
public PutObjectResponse putObject(String bucketName, String key, File file, ObjectMetadata metadata) { """ Uploads the specified file and object metadata to Bos under the specified bucket and key name. @param bucketName The name of an existing bucket, to which you have Write permission. @param key The key under which to store the specified file. @param file The file containing the data to be uploaded to Bos. @param metadata Additional metadata instructing Bos how to handle the uploaded data (e.g. custom user metadata, hooks for specifying content type, etc.). @return A PutObjectResponse object containing the information returned by Bos for the newly created object. """ return this.putObject(new PutObjectRequest(bucketName, key, file, metadata)); }
java
public PutObjectResponse putObject(String bucketName, String key, File file, ObjectMetadata metadata) { return this.putObject(new PutObjectRequest(bucketName, key, file, metadata)); }
[ "public", "PutObjectResponse", "putObject", "(", "String", "bucketName", ",", "String", "key", ",", "File", "file", ",", "ObjectMetadata", "metadata", ")", "{", "return", "this", ".", "putObject", "(", "new", "PutObjectRequest", "(", "bucketName", ",", "key", ",", "file", ",", "metadata", ")", ")", ";", "}" ]
Uploads the specified file and object metadata to Bos under the specified bucket and key name. @param bucketName The name of an existing bucket, to which you have Write permission. @param key The key under which to store the specified file. @param file The file containing the data to be uploaded to Bos. @param metadata Additional metadata instructing Bos how to handle the uploaded data (e.g. custom user metadata, hooks for specifying content type, etc.). @return A PutObjectResponse object containing the information returned by Bos for the newly created object.
[ "Uploads", "the", "specified", "file", "and", "object", "metadata", "to", "Bos", "under", "the", "specified", "bucket", "and", "key", "name", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bos/BosClient.java#L802-L804