repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
jcuda/jcusparse
JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java
JCusparse.cusparseShybsv_analysis
public static int cusparseShybsv_analysis( cusparseHandle handle, int transA, cusparseMatDescr descrA, cusparseHybMat hybA, cusparseSolveAnalysisInfo info) { """ Description: Solution of triangular linear system op(A) * x = alpha * f, where A is a sparse matrix in HYB storage format, rhs f and solution x are dense vectors. """ return checkResult(cusparseShybsv_analysisNative(handle, transA, descrA, hybA, info)); }
java
public static int cusparseShybsv_analysis( cusparseHandle handle, int transA, cusparseMatDescr descrA, cusparseHybMat hybA, cusparseSolveAnalysisInfo info) { return checkResult(cusparseShybsv_analysisNative(handle, transA, descrA, hybA, info)); }
[ "public", "static", "int", "cusparseShybsv_analysis", "(", "cusparseHandle", "handle", ",", "int", "transA", ",", "cusparseMatDescr", "descrA", ",", "cusparseHybMat", "hybA", ",", "cusparseSolveAnalysisInfo", "info", ")", "{", "return", "checkResult", "(", "cusparseShybsv_analysisNative", "(", "handle", ",", "transA", ",", "descrA", ",", "hybA", ",", "info", ")", ")", ";", "}" ]
Description: Solution of triangular linear system op(A) * x = alpha * f, where A is a sparse matrix in HYB storage format, rhs f and solution x are dense vectors.
[ "Description", ":", "Solution", "of", "triangular", "linear", "system", "op", "(", "A", ")", "*", "x", "=", "alpha", "*", "f", "where", "A", "is", "a", "sparse", "matrix", "in", "HYB", "storage", "format", "rhs", "f", "and", "solution", "x", "are", "dense", "vectors", "." ]
train
https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L3480-L3488
sagiegurari/fax4j
src/main/java/org/fax4j/spi/vbs/VBSProcessOutputValidator.java
VBSProcessOutputValidator.validateProcessOutput
@Override public void validateProcessOutput(FaxClientSpi faxClientSpi,ProcessOutput processOutput,FaxActionType faxActionType) { """ This function validates the process output for errors.<br> If not valid, an exception should be thrown. @param faxClientSpi The fax client SPI @param processOutput The process output to validate @param faxActionType The fax action type """ //call exit code validation super.validateProcessOutput(faxClientSpi,processOutput,faxActionType); //get output String output=processOutput.getOutputText(); String errorPut=processOutput.getErrorText(); boolean throwError=false; if((output!=null)&&(output.length()>0)) { if(output.indexOf(VBSProcessOutputValidator.OPERATION_OUTPUT_DONE)==-1) { throwError=true; } } else { throwError=true; } if(throwError) { String message=this.getVBSFailedLineErrorMessage(errorPut); if((errorPut!=null)&&(errorPut.indexOf(VBSProcessOutputValidator.ACTIVE_X_NOT_INSTALLED)!=-1)) { throw new FaxException("Error while invoking VBS script (fax server ActiveX not installed on system),"+message+" script output:\n"+output+"\nScript error:\n"+errorPut); } throw new FaxException("Error while invoking VBS script,"+message+" script output:\n"+output+"\nScript error:\n"+errorPut); } }
java
@Override public void validateProcessOutput(FaxClientSpi faxClientSpi,ProcessOutput processOutput,FaxActionType faxActionType) { //call exit code validation super.validateProcessOutput(faxClientSpi,processOutput,faxActionType); //get output String output=processOutput.getOutputText(); String errorPut=processOutput.getErrorText(); boolean throwError=false; if((output!=null)&&(output.length()>0)) { if(output.indexOf(VBSProcessOutputValidator.OPERATION_OUTPUT_DONE)==-1) { throwError=true; } } else { throwError=true; } if(throwError) { String message=this.getVBSFailedLineErrorMessage(errorPut); if((errorPut!=null)&&(errorPut.indexOf(VBSProcessOutputValidator.ACTIVE_X_NOT_INSTALLED)!=-1)) { throw new FaxException("Error while invoking VBS script (fax server ActiveX not installed on system),"+message+" script output:\n"+output+"\nScript error:\n"+errorPut); } throw new FaxException("Error while invoking VBS script,"+message+" script output:\n"+output+"\nScript error:\n"+errorPut); } }
[ "@", "Override", "public", "void", "validateProcessOutput", "(", "FaxClientSpi", "faxClientSpi", ",", "ProcessOutput", "processOutput", ",", "FaxActionType", "faxActionType", ")", "{", "//call exit code validation", "super", ".", "validateProcessOutput", "(", "faxClientSpi", ",", "processOutput", ",", "faxActionType", ")", ";", "//get output", "String", "output", "=", "processOutput", ".", "getOutputText", "(", ")", ";", "String", "errorPut", "=", "processOutput", ".", "getErrorText", "(", ")", ";", "boolean", "throwError", "=", "false", ";", "if", "(", "(", "output", "!=", "null", ")", "&&", "(", "output", ".", "length", "(", ")", ">", "0", ")", ")", "{", "if", "(", "output", ".", "indexOf", "(", "VBSProcessOutputValidator", ".", "OPERATION_OUTPUT_DONE", ")", "==", "-", "1", ")", "{", "throwError", "=", "true", ";", "}", "}", "else", "{", "throwError", "=", "true", ";", "}", "if", "(", "throwError", ")", "{", "String", "message", "=", "this", ".", "getVBSFailedLineErrorMessage", "(", "errorPut", ")", ";", "if", "(", "(", "errorPut", "!=", "null", ")", "&&", "(", "errorPut", ".", "indexOf", "(", "VBSProcessOutputValidator", ".", "ACTIVE_X_NOT_INSTALLED", ")", "!=", "-", "1", ")", ")", "{", "throw", "new", "FaxException", "(", "\"Error while invoking VBS script (fax server ActiveX not installed on system),\"", "+", "message", "+", "\" script output:\\n\"", "+", "output", "+", "\"\\nScript error:\\n\"", "+", "errorPut", ")", ";", "}", "throw", "new", "FaxException", "(", "\"Error while invoking VBS script,\"", "+", "message", "+", "\" script output:\\n\"", "+", "output", "+", "\"\\nScript error:\\n\"", "+", "errorPut", ")", ";", "}", "}" ]
This function validates the process output for errors.<br> If not valid, an exception should be thrown. @param faxClientSpi The fax client SPI @param processOutput The process output to validate @param faxActionType The fax action type
[ "This", "function", "validates", "the", "process", "output", "for", "errors", ".", "<br", ">", "If", "not", "valid", "an", "exception", "should", "be", "thrown", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/vbs/VBSProcessOutputValidator.java#L87-L120
alipay/sofa-hessian
src/main/java/com/alipay/hessian/clhm/ConcurrentLinkedHashMap.java
ConcurrentLinkedHashMap.runTasks
@GuardedBy("evictionLock") void runTasks(Task[] tasks, int maxTaskIndex) { """ Runs the pending page replacement policy operations. @param tasks the ordered array of the pending operations @param maxTaskIndex the maximum index of the array """ for (int i = 0; i <= maxTaskIndex; i++) { runTasksInChain(tasks[i]); } }
java
@GuardedBy("evictionLock") void runTasks(Task[] tasks, int maxTaskIndex) { for (int i = 0; i <= maxTaskIndex; i++) { runTasksInChain(tasks[i]); } }
[ "@", "GuardedBy", "(", "\"evictionLock\"", ")", "void", "runTasks", "(", "Task", "[", "]", "tasks", ",", "int", "maxTaskIndex", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "maxTaskIndex", ";", "i", "++", ")", "{", "runTasksInChain", "(", "tasks", "[", "i", "]", ")", ";", "}", "}" ]
Runs the pending page replacement policy operations. @param tasks the ordered array of the pending operations @param maxTaskIndex the maximum index of the array
[ "Runs", "the", "pending", "page", "replacement", "policy", "operations", "." ]
train
https://github.com/alipay/sofa-hessian/blob/89e4f5af28602101dab7b498995018871616357b/src/main/java/com/alipay/hessian/clhm/ConcurrentLinkedHashMap.java#L527-L532
EdwardRaff/JSAT
JSAT/src/jsat/regression/RegressionDataSet.java
RegressionDataSet.addDataPoint
public void addDataPoint(Vec numerical, int[] categories, double val) { """ Creates a new data point to be added to the data set. The arguments will be used directly, modifying them after will effect the data set. @param numerical the numerical values for the data point @param categories the categorical values for the data point @param val the target value to predict @throws IllegalArgumentException if the given values are inconsistent with the data this class stores. """ if(numerical.length() != numNumerVals) throw new RuntimeException("Data point does not contain enough numerical data points"); if(categories.length != categories.length) throw new RuntimeException("Data point does not contain enough categorical data points"); for(int i = 0; i < categories.length; i++) if(!this.categories[i].isValidCategory(categories[i]) && categories[i] >= 0) // >= so that missing values (negative) are allowed throw new RuntimeException("Categoriy value given is invalid"); DataPoint dp = new DataPoint(numerical, categories, this.categories); addDataPoint(dp, val); }
java
public void addDataPoint(Vec numerical, int[] categories, double val) { if(numerical.length() != numNumerVals) throw new RuntimeException("Data point does not contain enough numerical data points"); if(categories.length != categories.length) throw new RuntimeException("Data point does not contain enough categorical data points"); for(int i = 0; i < categories.length; i++) if(!this.categories[i].isValidCategory(categories[i]) && categories[i] >= 0) // >= so that missing values (negative) are allowed throw new RuntimeException("Categoriy value given is invalid"); DataPoint dp = new DataPoint(numerical, categories, this.categories); addDataPoint(dp, val); }
[ "public", "void", "addDataPoint", "(", "Vec", "numerical", ",", "int", "[", "]", "categories", ",", "double", "val", ")", "{", "if", "(", "numerical", ".", "length", "(", ")", "!=", "numNumerVals", ")", "throw", "new", "RuntimeException", "(", "\"Data point does not contain enough numerical data points\"", ")", ";", "if", "(", "categories", ".", "length", "!=", "categories", ".", "length", ")", "throw", "new", "RuntimeException", "(", "\"Data point does not contain enough categorical data points\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "categories", ".", "length", ";", "i", "++", ")", "if", "(", "!", "this", ".", "categories", "[", "i", "]", ".", "isValidCategory", "(", "categories", "[", "i", "]", ")", "&&", "categories", "[", "i", "]", ">=", "0", ")", "// >= so that missing values (negative) are allowed\r", "throw", "new", "RuntimeException", "(", "\"Categoriy value given is invalid\"", ")", ";", "DataPoint", "dp", "=", "new", "DataPoint", "(", "numerical", ",", "categories", ",", "this", ".", "categories", ")", ";", "addDataPoint", "(", "dp", ",", "val", ")", ";", "}" ]
Creates a new data point to be added to the data set. The arguments will be used directly, modifying them after will effect the data set. @param numerical the numerical values for the data point @param categories the categorical values for the data point @param val the target value to predict @throws IllegalArgumentException if the given values are inconsistent with the data this class stores.
[ "Creates", "a", "new", "data", "point", "to", "be", "added", "to", "the", "data", "set", ".", "The", "arguments", "will", "be", "used", "directly", "modifying", "them", "after", "will", "effect", "the", "data", "set", "." ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/regression/RegressionDataSet.java#L164-L177
phax/ph-commons
ph-xml/src/main/java/com/helger/xml/XMLFactory.java
XMLFactory.newDocument
@Nonnull public static Document newDocument (@Nonnull final DocumentBuilder aDocBuilder) { """ Create a new XML document without document type using version {@link EXMLVersion#XML_10}. A custom document builder is used. @param aDocBuilder The document builder to use. May not be <code>null</code>. @return The created document. Never <code>null</code>. """ return newDocument (aDocBuilder, (EXMLVersion) null); }
java
@Nonnull public static Document newDocument (@Nonnull final DocumentBuilder aDocBuilder) { return newDocument (aDocBuilder, (EXMLVersion) null); }
[ "@", "Nonnull", "public", "static", "Document", "newDocument", "(", "@", "Nonnull", "final", "DocumentBuilder", "aDocBuilder", ")", "{", "return", "newDocument", "(", "aDocBuilder", ",", "(", "EXMLVersion", ")", "null", ")", ";", "}" ]
Create a new XML document without document type using version {@link EXMLVersion#XML_10}. A custom document builder is used. @param aDocBuilder The document builder to use. May not be <code>null</code>. @return The created document. Never <code>null</code>.
[ "Create", "a", "new", "XML", "document", "without", "document", "type", "using", "version", "{", "@link", "EXMLVersion#XML_10", "}", ".", "A", "custom", "document", "builder", "is", "used", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/XMLFactory.java#L271-L275
mbeiter/util
db/src/main/java/org/beiter/michael/db/ConnectionFactory.java
ConnectionFactory.getConnection
public static Connection getConnection(final ConnectionProperties poolSpec) throws FactoryException { """ Return a Connection instance from a pool that manages JDBC driver based connections. <p> The driver-based connection are managed in a connection pool. The pool is created using the provided properties for both the connection and the pool spec. Once the pool has been created, it is cached (based on URL and username), and can no longer be changed. Subsequent calls to this method will return a connection from the cached pool, and changes in the pool spec (e.g. changes to the size of the pool) will be ignored. @param poolSpec A connection pool spec that has the driver and url configured as non-empty strings @return a JDBC connection @throws FactoryException When the connection cannot be retrieved from the pool, or the pool cannot be created @throws NullPointerException When the {@code poolSpec}, {@code poolSpec.getDriver()}, or {@code poolSpec.getUrl()} are {@code null} @throws IllegalArgumentException When {@code poolSpec.getDriver()} or {@code poolSpec.getUrl()} are empty """ Validate.notNull(poolSpec, "The validated object 'poolSpec' is null"); Validate.notBlank(poolSpec.getDriver(), "The validated character sequence 'poolSpec.getDriver()' is null or empty"); Validate.notBlank(poolSpec.getUrl(), "The validated character sequence 'poolSpec.getUrl()' is null or empty"); // no need for defensive copies of Strings try { return DataSourceFactory.getDataSource(poolSpec).getConnection(); } catch (SQLException e) { // a connection is identified by the URL, the username, and the password final String key = String.format("%s:%s", poolSpec.getUrl(), poolSpec.getUsername()); final String error = "Error retrieving JDBC connection from pool: " + key; LOG.warn(error); throw new FactoryException(error, e); } }
java
public static Connection getConnection(final ConnectionProperties poolSpec) throws FactoryException { Validate.notNull(poolSpec, "The validated object 'poolSpec' is null"); Validate.notBlank(poolSpec.getDriver(), "The validated character sequence 'poolSpec.getDriver()' is null or empty"); Validate.notBlank(poolSpec.getUrl(), "The validated character sequence 'poolSpec.getUrl()' is null or empty"); // no need for defensive copies of Strings try { return DataSourceFactory.getDataSource(poolSpec).getConnection(); } catch (SQLException e) { // a connection is identified by the URL, the username, and the password final String key = String.format("%s:%s", poolSpec.getUrl(), poolSpec.getUsername()); final String error = "Error retrieving JDBC connection from pool: " + key; LOG.warn(error); throw new FactoryException(error, e); } }
[ "public", "static", "Connection", "getConnection", "(", "final", "ConnectionProperties", "poolSpec", ")", "throws", "FactoryException", "{", "Validate", ".", "notNull", "(", "poolSpec", ",", "\"The validated object 'poolSpec' is null\"", ")", ";", "Validate", ".", "notBlank", "(", "poolSpec", ".", "getDriver", "(", ")", ",", "\"The validated character sequence 'poolSpec.getDriver()' is null or empty\"", ")", ";", "Validate", ".", "notBlank", "(", "poolSpec", ".", "getUrl", "(", ")", ",", "\"The validated character sequence 'poolSpec.getUrl()' is null or empty\"", ")", ";", "// no need for defensive copies of Strings", "try", "{", "return", "DataSourceFactory", ".", "getDataSource", "(", "poolSpec", ")", ".", "getConnection", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "// a connection is identified by the URL, the username, and the password", "final", "String", "key", "=", "String", ".", "format", "(", "\"%s:%s\"", ",", "poolSpec", ".", "getUrl", "(", ")", ",", "poolSpec", ".", "getUsername", "(", ")", ")", ";", "final", "String", "error", "=", "\"Error retrieving JDBC connection from pool: \"", "+", "key", ";", "LOG", ".", "warn", "(", "error", ")", ";", "throw", "new", "FactoryException", "(", "error", ",", "e", ")", ";", "}", "}" ]
Return a Connection instance from a pool that manages JDBC driver based connections. <p> The driver-based connection are managed in a connection pool. The pool is created using the provided properties for both the connection and the pool spec. Once the pool has been created, it is cached (based on URL and username), and can no longer be changed. Subsequent calls to this method will return a connection from the cached pool, and changes in the pool spec (e.g. changes to the size of the pool) will be ignored. @param poolSpec A connection pool spec that has the driver and url configured as non-empty strings @return a JDBC connection @throws FactoryException When the connection cannot be retrieved from the pool, or the pool cannot be created @throws NullPointerException When the {@code poolSpec}, {@code poolSpec.getDriver()}, or {@code poolSpec.getUrl()} are {@code null} @throws IllegalArgumentException When {@code poolSpec.getDriver()} or {@code poolSpec.getUrl()} are empty
[ "Return", "a", "Connection", "instance", "from", "a", "pool", "that", "manages", "JDBC", "driver", "based", "connections", ".", "<p", ">", "The", "driver", "-", "based", "connection", "are", "managed", "in", "a", "connection", "pool", ".", "The", "pool", "is", "created", "using", "the", "provided", "properties", "for", "both", "the", "connection", "and", "the", "pool", "spec", ".", "Once", "the", "pool", "has", "been", "created", "it", "is", "cached", "(", "based", "on", "URL", "and", "username", ")", "and", "can", "no", "longer", "be", "changed", ".", "Subsequent", "calls", "to", "this", "method", "will", "return", "a", "connection", "from", "the", "cached", "pool", "and", "changes", "in", "the", "pool", "spec", "(", "e", ".", "g", ".", "changes", "to", "the", "size", "of", "the", "pool", ")", "will", "be", "ignored", "." ]
train
https://github.com/mbeiter/util/blob/490fcebecb936e00c2f2ce2096b679b2fd10865e/db/src/main/java/org/beiter/michael/db/ConnectionFactory.java#L103-L122
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/workspace/VoiceApi.java
VoiceApi.completeConference
public void completeConference(String connId, String parentConnId) throws WorkspaceApiException { """ Complete a previously initiated two-step conference identified by the provided IDs. Once completed, the two separate calls are brought together so that all three parties are participating in the same call. @param connId The connection ID of the consult call (established). @param parentConnId The connection ID of the parent call (held). """ this.completeConference(connId, parentConnId, null, null); }
java
public void completeConference(String connId, String parentConnId) throws WorkspaceApiException { this.completeConference(connId, parentConnId, null, null); }
[ "public", "void", "completeConference", "(", "String", "connId", ",", "String", "parentConnId", ")", "throws", "WorkspaceApiException", "{", "this", ".", "completeConference", "(", "connId", ",", "parentConnId", ",", "null", ",", "null", ")", ";", "}" ]
Complete a previously initiated two-step conference identified by the provided IDs. Once completed, the two separate calls are brought together so that all three parties are participating in the same call. @param connId The connection ID of the consult call (established). @param parentConnId The connection ID of the parent call (held).
[ "Complete", "a", "previously", "initiated", "two", "-", "step", "conference", "identified", "by", "the", "provided", "IDs", ".", "Once", "completed", "the", "two", "separate", "calls", "are", "brought", "together", "so", "that", "all", "three", "parties", "are", "participating", "in", "the", "same", "call", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/workspace/VoiceApi.java#L729-L731
mapbox/mapbox-navigation-android
libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/ThemeSwitcher.java
ThemeSwitcher.retrieveThemeColor
public static int retrieveThemeColor(Context context, int resId) { """ Looks are current theme and retrieves the color attribute for the given set theme. @param context to retrieve the set theme and resolved attribute and then color res Id with {@link ContextCompat} @return color resource identifier for primary theme color """ TypedValue outValue = resolveAttributeFromId(context, resId); if (outValue.type >= TypedValue.TYPE_FIRST_COLOR_INT && outValue.type <= TypedValue.TYPE_LAST_COLOR_INT) { return outValue.data; } else { return ContextCompat.getColor(context, outValue.resourceId); } }
java
public static int retrieveThemeColor(Context context, int resId) { TypedValue outValue = resolveAttributeFromId(context, resId); if (outValue.type >= TypedValue.TYPE_FIRST_COLOR_INT && outValue.type <= TypedValue.TYPE_LAST_COLOR_INT) { return outValue.data; } else { return ContextCompat.getColor(context, outValue.resourceId); } }
[ "public", "static", "int", "retrieveThemeColor", "(", "Context", "context", ",", "int", "resId", ")", "{", "TypedValue", "outValue", "=", "resolveAttributeFromId", "(", "context", ",", "resId", ")", ";", "if", "(", "outValue", ".", "type", ">=", "TypedValue", ".", "TYPE_FIRST_COLOR_INT", "&&", "outValue", ".", "type", "<=", "TypedValue", ".", "TYPE_LAST_COLOR_INT", ")", "{", "return", "outValue", ".", "data", ";", "}", "else", "{", "return", "ContextCompat", ".", "getColor", "(", "context", ",", "outValue", ".", "resourceId", ")", ";", "}", "}" ]
Looks are current theme and retrieves the color attribute for the given set theme. @param context to retrieve the set theme and resolved attribute and then color res Id with {@link ContextCompat} @return color resource identifier for primary theme color
[ "Looks", "are", "current", "theme", "and", "retrieves", "the", "color", "attribute", "for", "the", "given", "set", "theme", "." ]
train
https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/ThemeSwitcher.java#L31-L39
Jasig/uPortal
uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/ReferenceCompositeGroupService.java
ReferenceCompositeGroupService.initializeComponentServices
protected void initializeComponentServices() throws GroupsException { """ Assembles the group services composite. Once the leaf services have been retrieved, they are held in a (one-dimensional) Map. The composite identity of a service is preserved in its Map key, a javax.naming.Name. Each node of the Name is the name of a component service, starting with the service closest to the composite service and ending with the name of the leaf service. The key is built up layer by layer. @exception GroupsException """ Name leafServiceName = null; try { GroupServiceConfiguration cfg = GroupServiceConfiguration.getConfiguration(); List services = cfg.getServiceDescriptors(); for (Iterator it = services.iterator(); it.hasNext(); ) { ComponentGroupServiceDescriptor descriptor = (ComponentGroupServiceDescriptor) it.next(); String factoryName = descriptor.getServiceFactoryName(); IComponentGroupServiceFactory factory = (IComponentGroupServiceFactory) Class.forName(factoryName).newInstance(); IComponentGroupService service = factory.newGroupService(descriptor); // If it's a leaf service, add it to the Map. if (service.isLeafService()) { leafServiceName = GroupService.parseServiceName(descriptor.getName()); service.setServiceName(leafServiceName); getComponentServices().put(leafServiceName, service); } // Otherwise, get its leaf services and for each, push our node onto the service // Name // and add the service to the Map. else { Map componentMap = service.getComponentServices(); for (Iterator components = componentMap.values().iterator(); components.hasNext(); ) { IIndividualGroupService leafService = (IIndividualGroupService) components.next(); leafServiceName = leafService.getServiceName(); leafServiceName.add(0, descriptor.getName()); getComponentServices().put(leafServiceName, leafService); } } } Name defaultServiceName = GroupService.parseServiceName(cfg.getDefaultService()); defaultService = (IIndividualGroupService) getComponentService(defaultServiceName); } catch (Exception ex) { throw new GroupsException("Problem initializing component services", ex); } }
java
protected void initializeComponentServices() throws GroupsException { Name leafServiceName = null; try { GroupServiceConfiguration cfg = GroupServiceConfiguration.getConfiguration(); List services = cfg.getServiceDescriptors(); for (Iterator it = services.iterator(); it.hasNext(); ) { ComponentGroupServiceDescriptor descriptor = (ComponentGroupServiceDescriptor) it.next(); String factoryName = descriptor.getServiceFactoryName(); IComponentGroupServiceFactory factory = (IComponentGroupServiceFactory) Class.forName(factoryName).newInstance(); IComponentGroupService service = factory.newGroupService(descriptor); // If it's a leaf service, add it to the Map. if (service.isLeafService()) { leafServiceName = GroupService.parseServiceName(descriptor.getName()); service.setServiceName(leafServiceName); getComponentServices().put(leafServiceName, service); } // Otherwise, get its leaf services and for each, push our node onto the service // Name // and add the service to the Map. else { Map componentMap = service.getComponentServices(); for (Iterator components = componentMap.values().iterator(); components.hasNext(); ) { IIndividualGroupService leafService = (IIndividualGroupService) components.next(); leafServiceName = leafService.getServiceName(); leafServiceName.add(0, descriptor.getName()); getComponentServices().put(leafServiceName, leafService); } } } Name defaultServiceName = GroupService.parseServiceName(cfg.getDefaultService()); defaultService = (IIndividualGroupService) getComponentService(defaultServiceName); } catch (Exception ex) { throw new GroupsException("Problem initializing component services", ex); } }
[ "protected", "void", "initializeComponentServices", "(", ")", "throws", "GroupsException", "{", "Name", "leafServiceName", "=", "null", ";", "try", "{", "GroupServiceConfiguration", "cfg", "=", "GroupServiceConfiguration", ".", "getConfiguration", "(", ")", ";", "List", "services", "=", "cfg", ".", "getServiceDescriptors", "(", ")", ";", "for", "(", "Iterator", "it", "=", "services", ".", "iterator", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "ComponentGroupServiceDescriptor", "descriptor", "=", "(", "ComponentGroupServiceDescriptor", ")", "it", ".", "next", "(", ")", ";", "String", "factoryName", "=", "descriptor", ".", "getServiceFactoryName", "(", ")", ";", "IComponentGroupServiceFactory", "factory", "=", "(", "IComponentGroupServiceFactory", ")", "Class", ".", "forName", "(", "factoryName", ")", ".", "newInstance", "(", ")", ";", "IComponentGroupService", "service", "=", "factory", ".", "newGroupService", "(", "descriptor", ")", ";", "// If it's a leaf service, add it to the Map.", "if", "(", "service", ".", "isLeafService", "(", ")", ")", "{", "leafServiceName", "=", "GroupService", ".", "parseServiceName", "(", "descriptor", ".", "getName", "(", ")", ")", ";", "service", ".", "setServiceName", "(", "leafServiceName", ")", ";", "getComponentServices", "(", ")", ".", "put", "(", "leafServiceName", ",", "service", ")", ";", "}", "// Otherwise, get its leaf services and for each, push our node onto the service", "// Name", "// and add the service to the Map.", "else", "{", "Map", "componentMap", "=", "service", ".", "getComponentServices", "(", ")", ";", "for", "(", "Iterator", "components", "=", "componentMap", ".", "values", "(", ")", ".", "iterator", "(", ")", ";", "components", ".", "hasNext", "(", ")", ";", ")", "{", "IIndividualGroupService", "leafService", "=", "(", "IIndividualGroupService", ")", "components", ".", "next", "(", ")", ";", "leafServiceName", "=", "leafService", ".", "getServiceName", "(", ")", ";", "leafServiceName", ".", "add", "(", "0", ",", "descriptor", ".", "getName", "(", ")", ")", ";", "getComponentServices", "(", ")", ".", "put", "(", "leafServiceName", ",", "leafService", ")", ";", "}", "}", "}", "Name", "defaultServiceName", "=", "GroupService", ".", "parseServiceName", "(", "cfg", ".", "getDefaultService", "(", ")", ")", ";", "defaultService", "=", "(", "IIndividualGroupService", ")", "getComponentService", "(", "defaultServiceName", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "GroupsException", "(", "\"Problem initializing component services\"", ",", "ex", ")", ";", "}", "}" ]
Assembles the group services composite. Once the leaf services have been retrieved, they are held in a (one-dimensional) Map. The composite identity of a service is preserved in its Map key, a javax.naming.Name. Each node of the Name is the name of a component service, starting with the service closest to the composite service and ending with the name of the leaf service. The key is built up layer by layer. @exception GroupsException
[ "Assembles", "the", "group", "services", "composite", ".", "Once", "the", "leaf", "services", "have", "been", "retrieved", "they", "are", "held", "in", "a", "(", "one", "-", "dimensional", ")", "Map", ".", "The", "composite", "identity", "of", "a", "service", "is", "preserved", "in", "its", "Map", "key", "a", "javax", ".", "naming", ".", "Name", ".", "Each", "node", "of", "the", "Name", "is", "the", "name", "of", "a", "component", "service", "starting", "with", "the", "service", "closest", "to", "the", "composite", "service", "and", "ending", "with", "the", "name", "of", "the", "leaf", "service", ".", "The", "key", "is", "built", "up", "layer", "by", "layer", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/ReferenceCompositeGroupService.java#L152-L194
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java
ElementsExceptionsFactory.newComparisonException
public static ComparisonException newComparisonException(Throwable cause, String message, Object... args) { """ Constructs and initializes a new {@link ComparisonException} with the given {@link Throwable cause} and {@link String message} formatted with the given {@link Object[] arguments}. @param cause {@link Throwable} identified as the reason this {@link ComparisonException} was thrown. @param message {@link String} describing the {@link ComparisonException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link ComparisonException} with the given {@link Throwable cause} and {@link String message}. @see org.cp.elements.lang.ComparisonException """ return new ComparisonException(format(message, args), cause); }
java
public static ComparisonException newComparisonException(Throwable cause, String message, Object... args) { return new ComparisonException(format(message, args), cause); }
[ "public", "static", "ComparisonException", "newComparisonException", "(", "Throwable", "cause", ",", "String", "message", ",", "Object", "...", "args", ")", "{", "return", "new", "ComparisonException", "(", "format", "(", "message", ",", "args", ")", ",", "cause", ")", ";", "}" ]
Constructs and initializes a new {@link ComparisonException} with the given {@link Throwable cause} and {@link String message} formatted with the given {@link Object[] arguments}. @param cause {@link Throwable} identified as the reason this {@link ComparisonException} was thrown. @param message {@link String} describing the {@link ComparisonException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link ComparisonException} with the given {@link Throwable cause} and {@link String message}. @see org.cp.elements.lang.ComparisonException
[ "Constructs", "and", "initializes", "a", "new", "{", "@link", "ComparisonException", "}", "with", "the", "given", "{", "@link", "Throwable", "cause", "}", "and", "{", "@link", "String", "message", "}", "formatted", "with", "the", "given", "{", "@link", "Object", "[]", "arguments", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L313-L315
Azure/azure-sdk-for-java
network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/NetworkSecurityGroupsInner.java
NetworkSecurityGroupsInner.beginUpdateTagsAsync
public Observable<NetworkSecurityGroupInner> beginUpdateTagsAsync(String resourceGroupName, String networkSecurityGroupName, Map<String, String> tags) { """ Updates a network security group tags. @param resourceGroupName The name of the resource group. @param networkSecurityGroupName The name of the network security group. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the NetworkSecurityGroupInner object """ return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, tags).map(new Func1<ServiceResponse<NetworkSecurityGroupInner>, NetworkSecurityGroupInner>() { @Override public NetworkSecurityGroupInner call(ServiceResponse<NetworkSecurityGroupInner> response) { return response.body(); } }); }
java
public Observable<NetworkSecurityGroupInner> beginUpdateTagsAsync(String resourceGroupName, String networkSecurityGroupName, Map<String, String> tags) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, tags).map(new Func1<ServiceResponse<NetworkSecurityGroupInner>, NetworkSecurityGroupInner>() { @Override public NetworkSecurityGroupInner call(ServiceResponse<NetworkSecurityGroupInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "NetworkSecurityGroupInner", ">", "beginUpdateTagsAsync", "(", "String", "resourceGroupName", ",", "String", "networkSecurityGroupName", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "beginUpdateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "networkSecurityGroupName", ",", "tags", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "NetworkSecurityGroupInner", ">", ",", "NetworkSecurityGroupInner", ">", "(", ")", "{", "@", "Override", "public", "NetworkSecurityGroupInner", "call", "(", "ServiceResponse", "<", "NetworkSecurityGroupInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates a network security group tags. @param resourceGroupName The name of the resource group. @param networkSecurityGroupName The name of the network security group. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the NetworkSecurityGroupInner object
[ "Updates", "a", "network", "security", "group", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/NetworkSecurityGroupsInner.java#L862-L869
nohana/Amalgam
amalgam/src/main/java/com/amalgam/os/BundleUtils.java
BundleUtils.optByteArray
@Nullable public static byte[] optByteArray(@Nullable Bundle bundle, @Nullable String key) { """ Returns a optional byte array value. In other words, returns the value mapped by key if it exists and is a byte array. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null. @param bundle a bundle. If the bundle is null, this method will return a fallback value. @param key a key for the value. @return a byte array value if exists, null otherwise. @see android.os.Bundle#getByteArray(String) """ return optByteArray(bundle, key, new byte[0]); }
java
@Nullable public static byte[] optByteArray(@Nullable Bundle bundle, @Nullable String key) { return optByteArray(bundle, key, new byte[0]); }
[ "@", "Nullable", "public", "static", "byte", "[", "]", "optByteArray", "(", "@", "Nullable", "Bundle", "bundle", ",", "@", "Nullable", "String", "key", ")", "{", "return", "optByteArray", "(", "bundle", ",", "key", ",", "new", "byte", "[", "0", "]", ")", ";", "}" ]
Returns a optional byte array value. In other words, returns the value mapped by key if it exists and is a byte array. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null. @param bundle a bundle. If the bundle is null, this method will return a fallback value. @param key a key for the value. @return a byte array value if exists, null otherwise. @see android.os.Bundle#getByteArray(String)
[ "Returns", "a", "optional", "byte", "array", "value", ".", "In", "other", "words", "returns", "the", "value", "mapped", "by", "key", "if", "it", "exists", "and", "is", "a", "byte", "array", ".", "The", "bundle", "argument", "is", "allowed", "to", "be", "{" ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L241-L244
apache/incubator-gobblin
gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/InnerMetricContext.java
InnerMetricContext.getHistograms
@Override public SortedMap<String, Histogram> getHistograms(MetricFilter filter) { """ See {@link com.codahale.metrics.MetricRegistry#getHistograms(com.codahale.metrics.MetricFilter)}. <p> This method will return fully-qualified metric names if the {@link MetricContext} is configured to report fully-qualified metric names. </p> """ return getSimplyNamedMetrics(Histogram.class, Optional.of(filter)); }
java
@Override public SortedMap<String, Histogram> getHistograms(MetricFilter filter) { return getSimplyNamedMetrics(Histogram.class, Optional.of(filter)); }
[ "@", "Override", "public", "SortedMap", "<", "String", ",", "Histogram", ">", "getHistograms", "(", "MetricFilter", "filter", ")", "{", "return", "getSimplyNamedMetrics", "(", "Histogram", ".", "class", ",", "Optional", ".", "of", "(", "filter", ")", ")", ";", "}" ]
See {@link com.codahale.metrics.MetricRegistry#getHistograms(com.codahale.metrics.MetricFilter)}. <p> This method will return fully-qualified metric names if the {@link MetricContext} is configured to report fully-qualified metric names. </p>
[ "See", "{", "@link", "com", ".", "codahale", ".", "metrics", ".", "MetricRegistry#getHistograms", "(", "com", ".", "codahale", ".", "metrics", ".", "MetricFilter", ")", "}", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/InnerMetricContext.java#L216-L219
haifengl/smile
math/src/main/java/smile/math/Math.java
Math.smoothed
private static double smoothed(int x, double slope, double intercept) { """ Returns the fitted linear function value y = intercept + slope * log(x). """ return Math.exp(intercept + slope * Math.log(x)); }
java
private static double smoothed(int x, double slope, double intercept) { return Math.exp(intercept + slope * Math.log(x)); }
[ "private", "static", "double", "smoothed", "(", "int", "x", ",", "double", "slope", ",", "double", "intercept", ")", "{", "return", "Math", ".", "exp", "(", "intercept", "+", "slope", "*", "Math", ".", "log", "(", "x", ")", ")", ";", "}" ]
Returns the fitted linear function value y = intercept + slope * log(x).
[ "Returns", "the", "fitted", "linear", "function", "value", "y", "=", "intercept", "+", "slope", "*", "log", "(", "x", ")", "." ]
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/Math.java#L3248-L3250
pressgang-ccms/PressGangCCMSBuilder
src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookXMLPreProcessor.java
DocBookXMLPreProcessor.processIdList
private static List<InjectionData> processIdList(final String list) { """ Takes a comma separated list of ints, and returns an array of Integers. This is used when processing custom injection points. """ /* find the individual topic ids */ final String[] ids = list.split(","); List<InjectionData> retValue = new ArrayList<InjectionData>(ids.length); /* clean the topic ids */ for (final String id : ids) { final String topicId = id.replaceAll(OPTIONAL_MARKER, "").trim(); final boolean optional = id.contains(OPTIONAL_MARKER); try { final InjectionData topicData = new InjectionData(topicId, optional); retValue.add(topicData); } catch (final NumberFormatException ex) { /* * these lists are discovered by a regular expression so we shouldn't have any trouble here with Integer.parse */ LOG.debug("Unable to convert Injection Point ID into a Number", ex); retValue.add(new InjectionData("-1", false)); } } return retValue; }
java
private static List<InjectionData> processIdList(final String list) { /* find the individual topic ids */ final String[] ids = list.split(","); List<InjectionData> retValue = new ArrayList<InjectionData>(ids.length); /* clean the topic ids */ for (final String id : ids) { final String topicId = id.replaceAll(OPTIONAL_MARKER, "").trim(); final boolean optional = id.contains(OPTIONAL_MARKER); try { final InjectionData topicData = new InjectionData(topicId, optional); retValue.add(topicData); } catch (final NumberFormatException ex) { /* * these lists are discovered by a regular expression so we shouldn't have any trouble here with Integer.parse */ LOG.debug("Unable to convert Injection Point ID into a Number", ex); retValue.add(new InjectionData("-1", false)); } } return retValue; }
[ "private", "static", "List", "<", "InjectionData", ">", "processIdList", "(", "final", "String", "list", ")", "{", "/* find the individual topic ids */", "final", "String", "[", "]", "ids", "=", "list", ".", "split", "(", "\",\"", ")", ";", "List", "<", "InjectionData", ">", "retValue", "=", "new", "ArrayList", "<", "InjectionData", ">", "(", "ids", ".", "length", ")", ";", "/* clean the topic ids */", "for", "(", "final", "String", "id", ":", "ids", ")", "{", "final", "String", "topicId", "=", "id", ".", "replaceAll", "(", "OPTIONAL_MARKER", ",", "\"\"", ")", ".", "trim", "(", ")", ";", "final", "boolean", "optional", "=", "id", ".", "contains", "(", "OPTIONAL_MARKER", ")", ";", "try", "{", "final", "InjectionData", "topicData", "=", "new", "InjectionData", "(", "topicId", ",", "optional", ")", ";", "retValue", ".", "add", "(", "topicData", ")", ";", "}", "catch", "(", "final", "NumberFormatException", "ex", ")", "{", "/*\n * these lists are discovered by a regular expression so we shouldn't have any trouble here with Integer.parse\n */", "LOG", ".", "debug", "(", "\"Unable to convert Injection Point ID into a Number\"", ",", "ex", ")", ";", "retValue", ".", "add", "(", "new", "InjectionData", "(", "\"-1\"", ",", "false", ")", ")", ";", "}", "}", "return", "retValue", ";", "}" ]
Takes a comma separated list of ints, and returns an array of Integers. This is used when processing custom injection points.
[ "Takes", "a", "comma", "separated", "list", "of", "ints", "and", "returns", "an", "array", "of", "Integers", ".", "This", "is", "used", "when", "processing", "custom", "injection", "points", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookXMLPreProcessor.java#L468-L492
kochedykov/jlibmodbus
src/com/intelligt/modbus/jlibmodbus/msg/ModbusRequestBuilder.java
ModbusRequestBuilder.buildChangeAsciiInputDelimiter
public ModbusRequest buildChangeAsciiInputDelimiter(int serverAddress, int delimiter) throws ModbusNumberException { """ The character passed in the request data field becomes the end of message delimiter for future messages (replacing the default LF character). This function is useful in cases of a Line Feed is not required at the end of ASCII messages. @param serverAddress a slave address @param delimiter request data field @return DiagnosticsRequest instance @throws ModbusNumberException if server address is in-valid """ return buildDiagnostics(DiagnosticsSubFunctionCode.CHANGE_ASCII_INPUT_DELIMITER, serverAddress, delimiter); }
java
public ModbusRequest buildChangeAsciiInputDelimiter(int serverAddress, int delimiter) throws ModbusNumberException { return buildDiagnostics(DiagnosticsSubFunctionCode.CHANGE_ASCII_INPUT_DELIMITER, serverAddress, delimiter); }
[ "public", "ModbusRequest", "buildChangeAsciiInputDelimiter", "(", "int", "serverAddress", ",", "int", "delimiter", ")", "throws", "ModbusNumberException", "{", "return", "buildDiagnostics", "(", "DiagnosticsSubFunctionCode", ".", "CHANGE_ASCII_INPUT_DELIMITER", ",", "serverAddress", ",", "delimiter", ")", ";", "}" ]
The character passed in the request data field becomes the end of message delimiter for future messages (replacing the default LF character). This function is useful in cases of a Line Feed is not required at the end of ASCII messages. @param serverAddress a slave address @param delimiter request data field @return DiagnosticsRequest instance @throws ModbusNumberException if server address is in-valid
[ "The", "character", "passed", "in", "the", "request", "data", "field", "becomes", "the", "end", "of", "message", "delimiter", "for", "future", "messages", "(", "replacing", "the", "default", "LF", "character", ")", ".", "This", "function", "is", "useful", "in", "cases", "of", "a", "Line", "Feed", "is", "not", "required", "at", "the", "end", "of", "ASCII", "messages", "." ]
train
https://github.com/kochedykov/jlibmodbus/blob/197cb39e2649e61a6fe3cb7dc91a701d847e14be/src/com/intelligt/modbus/jlibmodbus/msg/ModbusRequestBuilder.java#L247-L249
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/store/AsyncUpdateThread.java
AsyncUpdateThread.startExecutingUpdates
private void startExecutingUpdates() throws ClosedException { """ Internal method. Should be called from within a synchronized block. """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "startExecutingUpdates"); // swap the enqueuedUnits and executingUnits. ArrayList temp = executingUnits; executingUnits = enqueuedUnits; enqueuedUnits = temp; enqueuedUnits.clear(); // enqueuedUnits is now ready to accept AsyncUpdates in enqueueWork() executing = true; try { LocalTransaction tran = tranManager.createLocalTransaction(false); ExecutionThread thread = new ExecutionThread(executingUnits, tran); mp.startNewSystemThread(thread); } catch (InterruptedException e) { // this object cannot recover from this exception since we don't know how much work the ExecutionThread // has done. should not occur! FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.store.AsyncUpdateThread.startExecutingUpdates", "1:222:1.28", this); SibTr.exception(tc, e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "startExecutingUpdates", e); closed = true; throw new ClosedException(e.getMessage()); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "startExecutingUpdates"); }
java
private void startExecutingUpdates() throws ClosedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "startExecutingUpdates"); // swap the enqueuedUnits and executingUnits. ArrayList temp = executingUnits; executingUnits = enqueuedUnits; enqueuedUnits = temp; enqueuedUnits.clear(); // enqueuedUnits is now ready to accept AsyncUpdates in enqueueWork() executing = true; try { LocalTransaction tran = tranManager.createLocalTransaction(false); ExecutionThread thread = new ExecutionThread(executingUnits, tran); mp.startNewSystemThread(thread); } catch (InterruptedException e) { // this object cannot recover from this exception since we don't know how much work the ExecutionThread // has done. should not occur! FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.store.AsyncUpdateThread.startExecutingUpdates", "1:222:1.28", this); SibTr.exception(tc, e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "startExecutingUpdates", e); closed = true; throw new ClosedException(e.getMessage()); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "startExecutingUpdates"); }
[ "private", "void", "startExecutingUpdates", "(", ")", "throws", "ClosedException", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "tc", ",", "\"startExecutingUpdates\"", ")", ";", "// swap the enqueuedUnits and executingUnits.", "ArrayList", "temp", "=", "executingUnits", ";", "executingUnits", "=", "enqueuedUnits", ";", "enqueuedUnits", "=", "temp", ";", "enqueuedUnits", ".", "clear", "(", ")", ";", "// enqueuedUnits is now ready to accept AsyncUpdates in enqueueWork()", "executing", "=", "true", ";", "try", "{", "LocalTransaction", "tran", "=", "tranManager", ".", "createLocalTransaction", "(", "false", ")", ";", "ExecutionThread", "thread", "=", "new", "ExecutionThread", "(", "executingUnits", ",", "tran", ")", ";", "mp", ".", "startNewSystemThread", "(", "thread", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "// this object cannot recover from this exception since we don't know how much work the ExecutionThread", "// has done. should not occur!", "FFDCFilter", ".", "processException", "(", "e", ",", "\"com.ibm.ws.sib.processor.impl.store.AsyncUpdateThread.startExecutingUpdates\"", ",", "\"1:222:1.28\"", ",", "this", ")", ";", "SibTr", ".", "exception", "(", "tc", ",", "e", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "exit", "(", "tc", ",", "\"startExecutingUpdates\"", ",", "e", ")", ";", "closed", "=", "true", ";", "throw", "new", "ClosedException", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "exit", "(", "tc", ",", "\"startExecutingUpdates\"", ")", ";", "}" ]
Internal method. Should be called from within a synchronized block.
[ "Internal", "method", ".", "Should", "be", "called", "from", "within", "a", "synchronized", "block", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/store/AsyncUpdateThread.java#L179-L219
beihaifeiwu/dolphin
dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/plugin/upsert/AbstractUpsertPlugin.java
AbstractUpsertPlugin.checkArrayWhere
protected XmlElement checkArrayWhere(IntrospectedTable introspectedTable) { """ 生成根据参数array判断where条件的元素 @param introspectedTable The metadata for database table @return generated where condition element """ XmlElement where = new XmlElement("where"); XmlElement include = new XmlElement("include"); include.addAttribute(new Attribute("refid", IDENTIFIERS_ARRAY_CONDITIONS)); where.addElement(include); return where; }
java
protected XmlElement checkArrayWhere(IntrospectedTable introspectedTable) { XmlElement where = new XmlElement("where"); XmlElement include = new XmlElement("include"); include.addAttribute(new Attribute("refid", IDENTIFIERS_ARRAY_CONDITIONS)); where.addElement(include); return where; }
[ "protected", "XmlElement", "checkArrayWhere", "(", "IntrospectedTable", "introspectedTable", ")", "{", "XmlElement", "where", "=", "new", "XmlElement", "(", "\"where\"", ")", ";", "XmlElement", "include", "=", "new", "XmlElement", "(", "\"include\"", ")", ";", "include", ".", "addAttribute", "(", "new", "Attribute", "(", "\"refid\"", ",", "IDENTIFIERS_ARRAY_CONDITIONS", ")", ")", ";", "where", ".", "addElement", "(", "include", ")", ";", "return", "where", ";", "}" ]
生成根据参数array判断where条件的元素 @param introspectedTable The metadata for database table @return generated where condition element
[ "生成根据参数array判断where条件的元素" ]
train
https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/plugin/upsert/AbstractUpsertPlugin.java#L127-L136
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuLaunchGridAsync
@Deprecated public static int cuLaunchGridAsync(CUfunction f, int grid_width, int grid_height, CUstream hStream) { """ Launches a CUDA function. <pre> CUresult cuLaunchGridAsync ( CUfunction f, int grid_width, int grid_height, CUstream hStream ) </pre> <div> <p>Launches a CUDA function. Deprecated Invokes the kernel <tt>f</tt> on a <tt>grid_width</tt> x <tt>grid_height</tt> grid of blocks. Each block contains the number of threads specified by a previous call to cuFuncSetBlockShape(). </p> <p>cuLaunchGridAsync() can optionally be associated to a stream by passing a non-zero <tt>hStream</tt> argument. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param f Kernel to launch @param grid_width Width of grid in blocks @param grid_height Height of grid in blocks @param hStream Stream identifier @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_LAUNCH_FAILED, CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, CUDA_ERROR_LAUNCH_TIMEOUT, CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED @see JCudaDriver#cuFuncSetBlockShape @see JCudaDriver#cuFuncSetSharedSize @see JCudaDriver#cuFuncGetAttribute @see JCudaDriver#cuParamSetSize @see JCudaDriver#cuParamSetf @see JCudaDriver#cuParamSeti @see JCudaDriver#cuParamSetv @see JCudaDriver#cuLaunch @see JCudaDriver#cuLaunchGrid @see JCudaDriver#cuLaunchKernel @deprecated Deprecated in CUDA """ return checkResult(cuLaunchGridAsyncNative(f, grid_width, grid_height, hStream)); }
java
@Deprecated public static int cuLaunchGridAsync(CUfunction f, int grid_width, int grid_height, CUstream hStream) { return checkResult(cuLaunchGridAsyncNative(f, grid_width, grid_height, hStream)); }
[ "@", "Deprecated", "public", "static", "int", "cuLaunchGridAsync", "(", "CUfunction", "f", ",", "int", "grid_width", ",", "int", "grid_height", ",", "CUstream", "hStream", ")", "{", "return", "checkResult", "(", "cuLaunchGridAsyncNative", "(", "f", ",", "grid_width", ",", "grid_height", ",", "hStream", ")", ")", ";", "}" ]
Launches a CUDA function. <pre> CUresult cuLaunchGridAsync ( CUfunction f, int grid_width, int grid_height, CUstream hStream ) </pre> <div> <p>Launches a CUDA function. Deprecated Invokes the kernel <tt>f</tt> on a <tt>grid_width</tt> x <tt>grid_height</tt> grid of blocks. Each block contains the number of threads specified by a previous call to cuFuncSetBlockShape(). </p> <p>cuLaunchGridAsync() can optionally be associated to a stream by passing a non-zero <tt>hStream</tt> argument. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param f Kernel to launch @param grid_width Width of grid in blocks @param grid_height Height of grid in blocks @param hStream Stream identifier @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_LAUNCH_FAILED, CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, CUDA_ERROR_LAUNCH_TIMEOUT, CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED @see JCudaDriver#cuFuncSetBlockShape @see JCudaDriver#cuFuncSetSharedSize @see JCudaDriver#cuFuncGetAttribute @see JCudaDriver#cuParamSetSize @see JCudaDriver#cuParamSetf @see JCudaDriver#cuParamSeti @see JCudaDriver#cuParamSetv @see JCudaDriver#cuLaunch @see JCudaDriver#cuLaunchGrid @see JCudaDriver#cuLaunchKernel @deprecated Deprecated in CUDA
[ "Launches", "a", "CUDA", "function", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L13311-L13315
steveohara/j2mod
src/main/java/com/ghgande/j2mod/modbus/facade/AbstractModbusMaster.java
AbstractModbusMaster.readInputDiscretes
public BitVector readInputDiscretes(int unitId, int ref, int count) throws ModbusException { """ Reads a given number of input discrete states from the slave. Note that the number of bits in the bit vector will be forced to the number originally requested. @param unitId the slave unit id. @param ref the offset of the input discrete to start reading from. @param count the number of input discrete states to be read. @return a <tt>BitVector</tt> instance holding the received input discrete states. @throws ModbusException if an I/O error, a slave exception or a transaction error occurs. """ checkTransaction(); if (readInputDiscretesRequest == null) { readInputDiscretesRequest = new ReadInputDiscretesRequest(); } readInputDiscretesRequest.setUnitID(unitId); readInputDiscretesRequest.setReference(ref); readInputDiscretesRequest.setBitCount(count); transaction.setRequest(readInputDiscretesRequest); transaction.execute(); BitVector bv = ((ReadInputDiscretesResponse)getAndCheckResponse()).getDiscretes(); bv.forceSize(count); return bv; }
java
public BitVector readInputDiscretes(int unitId, int ref, int count) throws ModbusException { checkTransaction(); if (readInputDiscretesRequest == null) { readInputDiscretesRequest = new ReadInputDiscretesRequest(); } readInputDiscretesRequest.setUnitID(unitId); readInputDiscretesRequest.setReference(ref); readInputDiscretesRequest.setBitCount(count); transaction.setRequest(readInputDiscretesRequest); transaction.execute(); BitVector bv = ((ReadInputDiscretesResponse)getAndCheckResponse()).getDiscretes(); bv.forceSize(count); return bv; }
[ "public", "BitVector", "readInputDiscretes", "(", "int", "unitId", ",", "int", "ref", ",", "int", "count", ")", "throws", "ModbusException", "{", "checkTransaction", "(", ")", ";", "if", "(", "readInputDiscretesRequest", "==", "null", ")", "{", "readInputDiscretesRequest", "=", "new", "ReadInputDiscretesRequest", "(", ")", ";", "}", "readInputDiscretesRequest", ".", "setUnitID", "(", "unitId", ")", ";", "readInputDiscretesRequest", ".", "setReference", "(", "ref", ")", ";", "readInputDiscretesRequest", ".", "setBitCount", "(", "count", ")", ";", "transaction", ".", "setRequest", "(", "readInputDiscretesRequest", ")", ";", "transaction", ".", "execute", "(", ")", ";", "BitVector", "bv", "=", "(", "(", "ReadInputDiscretesResponse", ")", "getAndCheckResponse", "(", ")", ")", ".", "getDiscretes", "(", ")", ";", "bv", ".", "forceSize", "(", "count", ")", ";", "return", "bv", ";", "}" ]
Reads a given number of input discrete states from the slave. Note that the number of bits in the bit vector will be forced to the number originally requested. @param unitId the slave unit id. @param ref the offset of the input discrete to start reading from. @param count the number of input discrete states to be read. @return a <tt>BitVector</tt> instance holding the received input discrete states. @throws ModbusException if an I/O error, a slave exception or a transaction error occurs.
[ "Reads", "a", "given", "number", "of", "input", "discrete", "states", "from", "the", "slave", "." ]
train
https://github.com/steveohara/j2mod/blob/67162c55d7c02564e50211a9df06b8314953b5f2/src/main/java/com/ghgande/j2mod/modbus/facade/AbstractModbusMaster.java#L170-L183
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/UNode.java
UNode.addValueNode
public UNode addValueNode(String name, String value, boolean bAttribute) { """ Create a new VALUE node with the given name, value, and attribute flag and add it as a child of this node. This node must be a MAP or ARRAY. This is convenience method that calls {@link UNode#createValueNode(String, String, boolean)} and then {@link #addChildNode(UNode)}. @param name Name of new VALUE node. @param value Value of new VALUE node. @param bAttribute True to mark the new VALUE node as an attribute (for XML). @return New VALUE node. """ return addChildNode(UNode.createValueNode(name, value, bAttribute)); }
java
public UNode addValueNode(String name, String value, boolean bAttribute) { return addChildNode(UNode.createValueNode(name, value, bAttribute)); }
[ "public", "UNode", "addValueNode", "(", "String", "name", ",", "String", "value", ",", "boolean", "bAttribute", ")", "{", "return", "addChildNode", "(", "UNode", ".", "createValueNode", "(", "name", ",", "value", ",", "bAttribute", ")", ")", ";", "}" ]
Create a new VALUE node with the given name, value, and attribute flag and add it as a child of this node. This node must be a MAP or ARRAY. This is convenience method that calls {@link UNode#createValueNode(String, String, boolean)} and then {@link #addChildNode(UNode)}. @param name Name of new VALUE node. @param value Value of new VALUE node. @param bAttribute True to mark the new VALUE node as an attribute (for XML). @return New VALUE node.
[ "Create", "a", "new", "VALUE", "node", "with", "the", "given", "name", "value", "and", "attribute", "flag", "and", "add", "it", "as", "a", "child", "of", "this", "node", ".", "This", "node", "must", "be", "a", "MAP", "or", "ARRAY", ".", "This", "is", "convenience", "method", "that", "calls", "{", "@link", "UNode#createValueNode", "(", "String", "String", "boolean", ")", "}", "and", "then", "{", "@link", "#addChildNode", "(", "UNode", ")", "}", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/UNode.java#L874-L876
eclipse/xtext-core
org.eclipse.xtext/src/org/eclipse/xtext/conversion/impl/STRINGValueConverter.java
STRINGValueConverter.convertFromString
protected String convertFromString(String literal, INode node) throws ValueConverterWithValueException { """ Converts a string literal (including leading and trailing single or double quote) to a semantic string value. Recovers from invalid escape sequences and announces the first problem with a {@link ValueConverterWithValueException}. @since 2.7 @throws ValueConverterWithValueException if the given string is syntactically invalid. @see Strings#convertFromJavaString(String, boolean) """ Implementation converter = createConverter(); String result = converter.convertFromJavaString(literal); if (converter.errorMessage != null) { throw new ValueConverterWithValueException(converter.errorMessage, node, result.toString(), converter.errorIndex, converter.errorLength, null); } return result; }
java
protected String convertFromString(String literal, INode node) throws ValueConverterWithValueException { Implementation converter = createConverter(); String result = converter.convertFromJavaString(literal); if (converter.errorMessage != null) { throw new ValueConverterWithValueException(converter.errorMessage, node, result.toString(), converter.errorIndex, converter.errorLength, null); } return result; }
[ "protected", "String", "convertFromString", "(", "String", "literal", ",", "INode", "node", ")", "throws", "ValueConverterWithValueException", "{", "Implementation", "converter", "=", "createConverter", "(", ")", ";", "String", "result", "=", "converter", ".", "convertFromJavaString", "(", "literal", ")", ";", "if", "(", "converter", ".", "errorMessage", "!=", "null", ")", "{", "throw", "new", "ValueConverterWithValueException", "(", "converter", ".", "errorMessage", ",", "node", ",", "result", ".", "toString", "(", ")", ",", "converter", ".", "errorIndex", ",", "converter", ".", "errorLength", ",", "null", ")", ";", "}", "return", "result", ";", "}" ]
Converts a string literal (including leading and trailing single or double quote) to a semantic string value. Recovers from invalid escape sequences and announces the first problem with a {@link ValueConverterWithValueException}. @since 2.7 @throws ValueConverterWithValueException if the given string is syntactically invalid. @see Strings#convertFromJavaString(String, boolean)
[ "Converts", "a", "string", "literal", "(", "including", "leading", "and", "trailing", "single", "or", "double", "quote", ")", "to", "a", "semantic", "string", "value", ".", "Recovers", "from", "invalid", "escape", "sequences", "and", "announces", "the", "first", "problem", "with", "a", "{", "@link", "ValueConverterWithValueException", "}", "." ]
train
https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext/src/org/eclipse/xtext/conversion/impl/STRINGValueConverter.java#L49-L57
looly/hutool
hutool-core/src/main/java/cn/hutool/core/text/StrSpliter.java
StrSpliter.splitToArray
public static String[] splitToArray(String str, Pattern separatorPattern, int limit, boolean isTrim, boolean ignoreEmpty) { """ 通过正则切分字符串为字符串数组 @param str 被切分的字符串 @param separatorPattern 分隔符正则{@link Pattern} @param limit 限制分片数 @param isTrim 是否去除切分字符串后每个元素两边的空格 @param ignoreEmpty 是否忽略空串 @return 切分后的集合 @since 3.0.8 """ return toArray(split(str, separatorPattern, limit, isTrim, ignoreEmpty)); }
java
public static String[] splitToArray(String str, Pattern separatorPattern, int limit, boolean isTrim, boolean ignoreEmpty){ return toArray(split(str, separatorPattern, limit, isTrim, ignoreEmpty)); }
[ "public", "static", "String", "[", "]", "splitToArray", "(", "String", "str", ",", "Pattern", "separatorPattern", ",", "int", "limit", ",", "boolean", "isTrim", ",", "boolean", "ignoreEmpty", ")", "{", "return", "toArray", "(", "split", "(", "str", ",", "separatorPattern", ",", "limit", ",", "isTrim", ",", "ignoreEmpty", ")", ")", ";", "}" ]
通过正则切分字符串为字符串数组 @param str 被切分的字符串 @param separatorPattern 分隔符正则{@link Pattern} @param limit 限制分片数 @param isTrim 是否去除切分字符串后每个元素两边的空格 @param ignoreEmpty 是否忽略空串 @return 切分后的集合 @since 3.0.8
[ "通过正则切分字符串为字符串数组" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/text/StrSpliter.java#L453-L455
ModeShape/modeshape
modeshape-common/src/main/java/org/modeshape/common/util/Reflection.java
Reflection.findMethod
public static Method findMethod(Class<?> type, String methodName) { """ Searches for a method with a given name in a class. @param type a {@link Class} instance; never null @param methodName the name of the method to search for; never null @return a {@link Method} instance if the method is found """ try { return type.getDeclaredMethod(methodName); } catch (NoSuchMethodException e) { if (type.equals(Object.class) || type.isInterface()) { throw new RuntimeException(e); } return findMethod(type.getSuperclass(), methodName); } }
java
public static Method findMethod(Class<?> type, String methodName) { try { return type.getDeclaredMethod(methodName); } catch (NoSuchMethodException e) { if (type.equals(Object.class) || type.isInterface()) { throw new RuntimeException(e); } return findMethod(type.getSuperclass(), methodName); } }
[ "public", "static", "Method", "findMethod", "(", "Class", "<", "?", ">", "type", ",", "String", "methodName", ")", "{", "try", "{", "return", "type", ".", "getDeclaredMethod", "(", "methodName", ")", ";", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "if", "(", "type", ".", "equals", "(", "Object", ".", "class", ")", "||", "type", ".", "isInterface", "(", ")", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "return", "findMethod", "(", "type", ".", "getSuperclass", "(", ")", ",", "methodName", ")", ";", "}", "}" ]
Searches for a method with a given name in a class. @param type a {@link Class} instance; never null @param methodName the name of the method to search for; never null @return a {@link Method} instance if the method is found
[ "Searches", "for", "a", "method", "with", "a", "given", "name", "in", "a", "class", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/Reflection.java#L249-L258
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlSerialMethodWriter.java
HtmlSerialMethodWriter.addMemberHeader
public void addMemberHeader(MethodDoc member, Content methodsContentTree) { """ Add the member header. @param member the method document to be listed @param methodsContentTree the content tree to which the member header will be added """ methodsContentTree.addContent(getHead(member)); methodsContentTree.addContent(getSignature(member)); }
java
public void addMemberHeader(MethodDoc member, Content methodsContentTree) { methodsContentTree.addContent(getHead(member)); methodsContentTree.addContent(getSignature(member)); }
[ "public", "void", "addMemberHeader", "(", "MethodDoc", "member", ",", "Content", "methodsContentTree", ")", "{", "methodsContentTree", ".", "addContent", "(", "getHead", "(", "member", ")", ")", ";", "methodsContentTree", ".", "addContent", "(", "getSignature", "(", "member", ")", ")", ";", "}" ]
Add the member header. @param member the method document to be listed @param methodsContentTree the content tree to which the member header will be added
[ "Add", "the", "member", "header", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlSerialMethodWriter.java#L114-L117
elki-project/elki
elki-database/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/RandomStableDistanceFunction.java
RandomStableDistanceFunction.pseudoRandom
private double pseudoRandom(final long seed, int input) { """ Pseudo random number generator, adaption of the common rand48 generator which can be found in C (man drand48), Java and attributed to Donald Knuth. @param seed Seed value @param input Input code @return Pseudo random double value """ // Default constants from "man drand48" final long mult = 0x5DEECE66DL; final long add = 0xBL; final long mask = (1L << 48) - 1; // 48 bit // Produce an initial seed each final long i1 = (input ^ seed ^ mult) & mask; final long i2 = (input ^ (seed >>> 16) ^ mult) & mask; // Compute the first random each final long l1 = (i1 * mult + add) & mask; final long l2 = (i2 * mult + add) & mask; // Use 53 bit total: final int r1 = (int) (l1 >>> 22); // 48 - 22 = 26 final int r2 = (int) (l2 >>> 21); // 48 - 21 = 27 double random = ((((long) r1) << 27) + r2) / (double) (1L << 53); return random; }
java
private double pseudoRandom(final long seed, int input) { // Default constants from "man drand48" final long mult = 0x5DEECE66DL; final long add = 0xBL; final long mask = (1L << 48) - 1; // 48 bit // Produce an initial seed each final long i1 = (input ^ seed ^ mult) & mask; final long i2 = (input ^ (seed >>> 16) ^ mult) & mask; // Compute the first random each final long l1 = (i1 * mult + add) & mask; final long l2 = (i2 * mult + add) & mask; // Use 53 bit total: final int r1 = (int) (l1 >>> 22); // 48 - 22 = 26 final int r2 = (int) (l2 >>> 21); // 48 - 21 = 27 double random = ((((long) r1) << 27) + r2) / (double) (1L << 53); return random; }
[ "private", "double", "pseudoRandom", "(", "final", "long", "seed", ",", "int", "input", ")", "{", "// Default constants from \"man drand48\"", "final", "long", "mult", "=", "0x5DEECE66D", "", "L", ";", "final", "long", "add", "=", "0xB", "L", ";", "final", "long", "mask", "=", "(", "1L", "<<", "48", ")", "-", "1", ";", "// 48 bit", "// Produce an initial seed each", "final", "long", "i1", "=", "(", "input", "^", "seed", "^", "mult", ")", "&", "mask", ";", "final", "long", "i2", "=", "(", "input", "^", "(", "seed", ">>>", "16", ")", "^", "mult", ")", "&", "mask", ";", "// Compute the first random each", "final", "long", "l1", "=", "(", "i1", "*", "mult", "+", "add", ")", "&", "mask", ";", "final", "long", "l2", "=", "(", "i2", "*", "mult", "+", "add", ")", "&", "mask", ";", "// Use 53 bit total:", "final", "int", "r1", "=", "(", "int", ")", "(", "l1", ">>>", "22", ")", ";", "// 48 - 22 = 26", "final", "int", "r2", "=", "(", "int", ")", "(", "l2", ">>>", "21", ")", ";", "// 48 - 21 = 27", "double", "random", "=", "(", "(", "(", "(", "long", ")", "r1", ")", "<<", "27", ")", "+", "r2", ")", "/", "(", "double", ")", "(", "1L", "<<", "53", ")", ";", "return", "random", ";", "}" ]
Pseudo random number generator, adaption of the common rand48 generator which can be found in C (man drand48), Java and attributed to Donald Knuth. @param seed Seed value @param input Input code @return Pseudo random double value
[ "Pseudo", "random", "number", "generator", "adaption", "of", "the", "common", "rand48", "generator", "which", "can", "be", "found", "in", "C", "(", "man", "drand48", ")", "Java", "and", "attributed", "to", "Donald", "Knuth", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-database/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/RandomStableDistanceFunction.java#L92-L108
alkacon/opencms-core
src-modules/org/opencms/workplace/administration/CmsAdminMenu.java
CmsAdminMenu.addGroup
public void addGroup(CmsAdminMenuGroup group, float position) { """ Adds a menu item at the given position.<p> @param group the group @param position the position @see CmsIdentifiableObjectContainer#addIdentifiableObject(String, Object, float) """ m_groupContainer.addIdentifiableObject(group.getName(), group, position); }
java
public void addGroup(CmsAdminMenuGroup group, float position) { m_groupContainer.addIdentifiableObject(group.getName(), group, position); }
[ "public", "void", "addGroup", "(", "CmsAdminMenuGroup", "group", ",", "float", "position", ")", "{", "m_groupContainer", ".", "addIdentifiableObject", "(", "group", ".", "getName", "(", ")", ",", "group", ",", "position", ")", ";", "}" ]
Adds a menu item at the given position.<p> @param group the group @param position the position @see CmsIdentifiableObjectContainer#addIdentifiableObject(String, Object, float)
[ "Adds", "a", "menu", "item", "at", "the", "given", "position", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/administration/CmsAdminMenu.java#L100-L103
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/RunbookDraftsInner.java
RunbookDraftsInner.beginPublish
public void beginPublish(String resourceGroupName, String automationAccountName, String runbookName) { """ Publish runbook draft. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param runbookName The parameters supplied to the publish runbook operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ beginPublishWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName).toBlocking().single().body(); }
java
public void beginPublish(String resourceGroupName, String automationAccountName, String runbookName) { beginPublishWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName).toBlocking().single().body(); }
[ "public", "void", "beginPublish", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "runbookName", ")", "{", "beginPublishWithServiceResponseAsync", "(", "resourceGroupName", ",", "automationAccountName", ",", "runbookName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Publish runbook draft. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param runbookName The parameters supplied to the publish runbook operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Publish", "runbook", "draft", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/RunbookDraftsInner.java#L536-L538
OpenLiberty/open-liberty
dev/com.ibm.ws.transport.iiop/src/com/ibm/ws/transport/iiop/yoko/ORBConfigAdapter.java
ORBConfigAdapter.createORB
private ORB createORB(String[] args, Properties props) { """ Create an ORB instance using the configured argument and property bundles. @param args The String arguments passed to ORB.init(). @param props The property bundle passed to ORB.init(). @return An ORB constructed from the provided args and properties. """ return ORB.init(args, props); }
java
private ORB createORB(String[] args, Properties props) { return ORB.init(args, props); }
[ "private", "ORB", "createORB", "(", "String", "[", "]", "args", ",", "Properties", "props", ")", "{", "return", "ORB", ".", "init", "(", "args", ",", "props", ")", ";", "}" ]
Create an ORB instance using the configured argument and property bundles. @param args The String arguments passed to ORB.init(). @param props The property bundle passed to ORB.init(). @return An ORB constructed from the provided args and properties.
[ "Create", "an", "ORB", "instance", "using", "the", "configured", "argument", "and", "property", "bundles", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.iiop/src/com/ibm/ws/transport/iiop/yoko/ORBConfigAdapter.java#L77-L79
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfCopy.java
PdfCopy.createPageStamp
public PageStamp createPageStamp(PdfImportedPage iPage) { """ Create a page stamp. New content and annotations, including new fields, are allowed. The fields added cannot have parents in another pages. This method modifies the PdfReader instance.<p> The general usage to stamp something in a page is: <p> <pre> PdfImportedPage page = copy.getImportedPage(reader, 1); PdfCopy.PageStamp ps = copy.createPageStamp(page); ps.addAnnotation(PdfAnnotation.createText(copy, new Rectangle(50, 180, 70, 200), "Hello", "No Thanks", true, "Comment")); PdfContentByte under = ps.getUnderContent(); under.addImage(img); PdfContentByte over = ps.getOverContent(); over.beginText(); over.setFontAndSize(bf, 18); over.setTextMatrix(30, 30); over.showText("total page " + totalPage); over.endText(); ps.alterContents(); copy.addPage(page); </pre> @param iPage an imported page @return the <CODE>PageStamp</CODE> """ int pageNum = iPage.getPageNumber(); PdfReader reader = iPage.getPdfReaderInstance().getReader(); PdfDictionary pageN = reader.getPageN(pageNum); return new PageStamp(reader, pageN, this); }
java
public PageStamp createPageStamp(PdfImportedPage iPage) { int pageNum = iPage.getPageNumber(); PdfReader reader = iPage.getPdfReaderInstance().getReader(); PdfDictionary pageN = reader.getPageN(pageNum); return new PageStamp(reader, pageN, this); }
[ "public", "PageStamp", "createPageStamp", "(", "PdfImportedPage", "iPage", ")", "{", "int", "pageNum", "=", "iPage", ".", "getPageNumber", "(", ")", ";", "PdfReader", "reader", "=", "iPage", ".", "getPdfReaderInstance", "(", ")", ".", "getReader", "(", ")", ";", "PdfDictionary", "pageN", "=", "reader", ".", "getPageN", "(", "pageNum", ")", ";", "return", "new", "PageStamp", "(", "reader", ",", "pageN", ",", "this", ")", ";", "}" ]
Create a page stamp. New content and annotations, including new fields, are allowed. The fields added cannot have parents in another pages. This method modifies the PdfReader instance.<p> The general usage to stamp something in a page is: <p> <pre> PdfImportedPage page = copy.getImportedPage(reader, 1); PdfCopy.PageStamp ps = copy.createPageStamp(page); ps.addAnnotation(PdfAnnotation.createText(copy, new Rectangle(50, 180, 70, 200), "Hello", "No Thanks", true, "Comment")); PdfContentByte under = ps.getUnderContent(); under.addImage(img); PdfContentByte over = ps.getOverContent(); over.beginText(); over.setFontAndSize(bf, 18); over.setTextMatrix(30, 30); over.showText("total page " + totalPage); over.endText(); ps.alterContents(); copy.addPage(page); </pre> @param iPage an imported page @return the <CODE>PageStamp</CODE>
[ "Create", "a", "page", "stamp", ".", "New", "content", "and", "annotations", "including", "new", "fields", "are", "allowed", ".", "The", "fields", "added", "cannot", "have", "parents", "in", "another", "pages", ".", "This", "method", "modifies", "the", "PdfReader", "instance", ".", "<p", ">", "The", "general", "usage", "to", "stamp", "something", "in", "a", "page", "is", ":", "<p", ">", "<pre", ">", "PdfImportedPage", "page", "=", "copy", ".", "getImportedPage", "(", "reader", "1", ")", ";", "PdfCopy", ".", "PageStamp", "ps", "=", "copy", ".", "createPageStamp", "(", "page", ")", ";", "ps", ".", "addAnnotation", "(", "PdfAnnotation", ".", "createText", "(", "copy", "new", "Rectangle", "(", "50", "180", "70", "200", ")", "Hello", "No", "Thanks", "true", "Comment", "))", ";", "PdfContentByte", "under", "=", "ps", ".", "getUnderContent", "()", ";", "under", ".", "addImage", "(", "img", ")", ";", "PdfContentByte", "over", "=", "ps", ".", "getOverContent", "()", ";", "over", ".", "beginText", "()", ";", "over", ".", "setFontAndSize", "(", "bf", "18", ")", ";", "over", ".", "setTextMatrix", "(", "30", "30", ")", ";", "over", ".", "showText", "(", "total", "page", "+", "totalPage", ")", ";", "over", ".", "endText", "()", ";", "ps", ".", "alterContents", "()", ";", "copy", ".", "addPage", "(", "page", ")", ";", "<", "/", "pre", ">" ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfCopy.java#L540-L545
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/replace/CmsReplaceContentWidget.java
CmsReplaceContentWidget.displayDialogInfo
public void displayDialogInfo(String msg, boolean warning) { """ Sets the dialog info message.<p> @param msg the message to display @param warning signals whether the message should be a warning or nor """ StringBuffer buffer = new StringBuffer(64); if (!warning) { buffer.append("<p class=\""); buffer.append(I_CmsLayoutBundle.INSTANCE.uploadButton().dialogMessage()); buffer.append("\">"); buffer.append(msg); buffer.append("</p>"); } else { buffer.append(FontOpenCms.WARNING.getHtml(32, I_CmsConstantsBundle.INSTANCE.css().colorWarning())); buffer.append("<p class=\""); buffer.append(I_CmsLayoutBundle.INSTANCE.uploadButton().warningMessage()); buffer.append("\">"); buffer.append(msg); buffer.append("</p>"); } m_dialogInfo.setHTML(buffer.toString()); }
java
public void displayDialogInfo(String msg, boolean warning) { StringBuffer buffer = new StringBuffer(64); if (!warning) { buffer.append("<p class=\""); buffer.append(I_CmsLayoutBundle.INSTANCE.uploadButton().dialogMessage()); buffer.append("\">"); buffer.append(msg); buffer.append("</p>"); } else { buffer.append(FontOpenCms.WARNING.getHtml(32, I_CmsConstantsBundle.INSTANCE.css().colorWarning())); buffer.append("<p class=\""); buffer.append(I_CmsLayoutBundle.INSTANCE.uploadButton().warningMessage()); buffer.append("\">"); buffer.append(msg); buffer.append("</p>"); } m_dialogInfo.setHTML(buffer.toString()); }
[ "public", "void", "displayDialogInfo", "(", "String", "msg", ",", "boolean", "warning", ")", "{", "StringBuffer", "buffer", "=", "new", "StringBuffer", "(", "64", ")", ";", "if", "(", "!", "warning", ")", "{", "buffer", ".", "append", "(", "\"<p class=\\\"\"", ")", ";", "buffer", ".", "append", "(", "I_CmsLayoutBundle", ".", "INSTANCE", ".", "uploadButton", "(", ")", ".", "dialogMessage", "(", ")", ")", ";", "buffer", ".", "append", "(", "\"\\\">\"", ")", ";", "buffer", ".", "append", "(", "msg", ")", ";", "buffer", ".", "append", "(", "\"</p>\"", ")", ";", "}", "else", "{", "buffer", ".", "append", "(", "FontOpenCms", ".", "WARNING", ".", "getHtml", "(", "32", ",", "I_CmsConstantsBundle", ".", "INSTANCE", ".", "css", "(", ")", ".", "colorWarning", "(", ")", ")", ")", ";", "buffer", ".", "append", "(", "\"<p class=\\\"\"", ")", ";", "buffer", ".", "append", "(", "I_CmsLayoutBundle", ".", "INSTANCE", ".", "uploadButton", "(", ")", ".", "warningMessage", "(", ")", ")", ";", "buffer", ".", "append", "(", "\"\\\">\"", ")", ";", "buffer", ".", "append", "(", "msg", ")", ";", "buffer", ".", "append", "(", "\"</p>\"", ")", ";", "}", "m_dialogInfo", ".", "setHTML", "(", "buffer", ".", "toString", "(", ")", ")", ";", "}" ]
Sets the dialog info message.<p> @param msg the message to display @param warning signals whether the message should be a warning or nor
[ "Sets", "the", "dialog", "info", "message", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/replace/CmsReplaceContentWidget.java#L88-L106
Ordinastie/MalisisCore
src/main/java/net/malisis/core/util/syncer/Syncer.java
Syncer.doSync
private <T, S extends ISyncableData> void doSync(T caller, String... syncNames) { """ Synchronizes the specified fields names and sends the corresponding packet. @param <T> the type of the caller @param caller the caller @param syncNames the sync names """ @SuppressWarnings("unchecked") ISyncHandler<T, S> handler = (ISyncHandler<T, S>) getHandler(caller); if (handler == null) return; S data = handler.getSyncData(caller); int indexes = getFieldIndexes(handler, syncNames); Map<String, Object> values = getFieldValues(caller, handler, syncNames); SyncerMessage.Packet<T, S> packet = new Packet<>(getHandlerId(caller.getClass()), data, indexes, values); handler.send(caller, packet); }
java
private <T, S extends ISyncableData> void doSync(T caller, String... syncNames) { @SuppressWarnings("unchecked") ISyncHandler<T, S> handler = (ISyncHandler<T, S>) getHandler(caller); if (handler == null) return; S data = handler.getSyncData(caller); int indexes = getFieldIndexes(handler, syncNames); Map<String, Object> values = getFieldValues(caller, handler, syncNames); SyncerMessage.Packet<T, S> packet = new Packet<>(getHandlerId(caller.getClass()), data, indexes, values); handler.send(caller, packet); }
[ "private", "<", "T", ",", "S", "extends", "ISyncableData", ">", "void", "doSync", "(", "T", "caller", ",", "String", "...", "syncNames", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "ISyncHandler", "<", "T", ",", "S", ">", "handler", "=", "(", "ISyncHandler", "<", "T", ",", "S", ">", ")", "getHandler", "(", "caller", ")", ";", "if", "(", "handler", "==", "null", ")", "return", ";", "S", "data", "=", "handler", ".", "getSyncData", "(", "caller", ")", ";", "int", "indexes", "=", "getFieldIndexes", "(", "handler", ",", "syncNames", ")", ";", "Map", "<", "String", ",", "Object", ">", "values", "=", "getFieldValues", "(", "caller", ",", "handler", ",", "syncNames", ")", ";", "SyncerMessage", ".", "Packet", "<", "T", ",", "S", ">", "packet", "=", "new", "Packet", "<>", "(", "getHandlerId", "(", "caller", ".", "getClass", "(", ")", ")", ",", "data", ",", "indexes", ",", "values", ")", ";", "handler", ".", "send", "(", "caller", ",", "packet", ")", ";", "}" ]
Synchronizes the specified fields names and sends the corresponding packet. @param <T> the type of the caller @param caller the caller @param syncNames the sync names
[ "Synchronizes", "the", "specified", "fields", "names", "and", "sends", "the", "corresponding", "packet", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/syncer/Syncer.java#L293-L307
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/MetadataUtils.java
MetadataUtils.indexSearchEnabled
public static boolean indexSearchEnabled(final String persistenceUnit, final KunderaMetadata kunderaMetadata) { """ Index based search has to be optional, ideally need to register a callback in case index persistence/search etc is optional. @param persistenceUnit persistence unit @return true, if index based search is enabled. """ PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata, persistenceUnit); String clientFactoryName = puMetadata != null ? puMetadata .getProperty(PersistenceProperties.KUNDERA_CLIENT_FACTORY) : null; return !(Constants.REDIS_CLIENT_FACTORY.equalsIgnoreCase(clientFactoryName)); }
java
public static boolean indexSearchEnabled(final String persistenceUnit, final KunderaMetadata kunderaMetadata) { PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata, persistenceUnit); String clientFactoryName = puMetadata != null ? puMetadata .getProperty(PersistenceProperties.KUNDERA_CLIENT_FACTORY) : null; return !(Constants.REDIS_CLIENT_FACTORY.equalsIgnoreCase(clientFactoryName)); }
[ "public", "static", "boolean", "indexSearchEnabled", "(", "final", "String", "persistenceUnit", ",", "final", "KunderaMetadata", "kunderaMetadata", ")", "{", "PersistenceUnitMetadata", "puMetadata", "=", "KunderaMetadataManager", ".", "getPersistenceUnitMetadata", "(", "kunderaMetadata", ",", "persistenceUnit", ")", ";", "String", "clientFactoryName", "=", "puMetadata", "!=", "null", "?", "puMetadata", ".", "getProperty", "(", "PersistenceProperties", ".", "KUNDERA_CLIENT_FACTORY", ")", ":", "null", ";", "return", "!", "(", "Constants", ".", "REDIS_CLIENT_FACTORY", ".", "equalsIgnoreCase", "(", "clientFactoryName", ")", ")", ";", "}" ]
Index based search has to be optional, ideally need to register a callback in case index persistence/search etc is optional. @param persistenceUnit persistence unit @return true, if index based search is enabled.
[ "Index", "based", "search", "has", "to", "be", "optional", "ideally", "need", "to", "register", "a", "callback", "in", "case", "index", "persistence", "/", "search", "etc", "is", "optional", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/MetadataUtils.java#L603-L611
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/ntp_sync.java
ntp_sync.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ ntp_sync_responses result = (ntp_sync_responses) service.get_payload_formatter().string_to_resource(ntp_sync_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ntp_sync_response_array); } ntp_sync[] result_ntp_sync = new ntp_sync[result.ntp_sync_response_array.length]; for(int i = 0; i < result.ntp_sync_response_array.length; i++) { result_ntp_sync[i] = result.ntp_sync_response_array[i].ntp_sync[0]; } return result_ntp_sync; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { ntp_sync_responses result = (ntp_sync_responses) service.get_payload_formatter().string_to_resource(ntp_sync_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ntp_sync_response_array); } ntp_sync[] result_ntp_sync = new ntp_sync[result.ntp_sync_response_array.length]; for(int i = 0; i < result.ntp_sync_response_array.length; i++) { result_ntp_sync[i] = result.ntp_sync_response_array[i].ntp_sync[0]; } return result_ntp_sync; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "ntp_sync_responses", "result", "=", "(", "ntp_sync_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "ntp_sync_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "ntp_sync_response_array", ")", ";", "}", "ntp_sync", "[", "]", "result_ntp_sync", "=", "new", "ntp_sync", "[", "result", ".", "ntp_sync_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "ntp_sync_response_array", ".", "length", ";", "i", "++", ")", "{", "result_ntp_sync", "[", "i", "]", "=", "result", ".", "ntp_sync_response_array", "[", "i", "]", ".", "ntp_sync", "[", "0", "]", ";", "}", "return", "result_ntp_sync", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/ntp_sync.java#L226-L243
kirgor/enklib
ejb/src/main/java/com/kirgor/enklib/ejb/Bean.java
Bean.handleAPIException
protected Response handleAPIException(APIException ex, Method method, Object[] params) throws Exception { """ Called by interceptor in case of API invocation exception. <p/> Default implementation simply returns {@link Response} with HTTP code taken from ex param. @param ex Caught exception instance. @param method Invoked method. @param params Invoked method params. @return Method must return {@link Response} on behalf of invoked API method. @throws Exception """ return buildResponse(Response.status(ex.getHttpStatus())); }
java
protected Response handleAPIException(APIException ex, Method method, Object[] params) throws Exception { return buildResponse(Response.status(ex.getHttpStatus())); }
[ "protected", "Response", "handleAPIException", "(", "APIException", "ex", ",", "Method", "method", ",", "Object", "[", "]", "params", ")", "throws", "Exception", "{", "return", "buildResponse", "(", "Response", ".", "status", "(", "ex", ".", "getHttpStatus", "(", ")", ")", ")", ";", "}" ]
Called by interceptor in case of API invocation exception. <p/> Default implementation simply returns {@link Response} with HTTP code taken from ex param. @param ex Caught exception instance. @param method Invoked method. @param params Invoked method params. @return Method must return {@link Response} on behalf of invoked API method. @throws Exception
[ "Called", "by", "interceptor", "in", "case", "of", "API", "invocation", "exception", ".", "<p", "/", ">", "Default", "implementation", "simply", "returns", "{", "@link", "Response", "}", "with", "HTTP", "code", "taken", "from", "ex", "param", "." ]
train
https://github.com/kirgor/enklib/blob/8a24db296dc43db5d8fe509cf64ace0a0c7be8f2/ejb/src/main/java/com/kirgor/enklib/ejb/Bean.java#L269-L271
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java
CalendarPagerAdapter.selectRange
public void selectRange(final CalendarDay first, final CalendarDay last) { """ Clear the previous selection, select the range of days from first to last, and finally invalidate. First day should be before last day, otherwise the selection won't happen. @param first The first day of the range. @param last The last day in the range. @see CalendarPagerAdapter#setDateSelected(CalendarDay, boolean) """ selectedDates.clear(); // Copy to start from the first day and increment LocalDate temp = LocalDate.of(first.getYear(), first.getMonth(), first.getDay()); // for comparison final LocalDate end = last.getDate(); while( temp.isBefore(end) || temp.equals(end) ) { selectedDates.add(CalendarDay.from(temp)); temp = temp.plusDays(1); } invalidateSelectedDates(); }
java
public void selectRange(final CalendarDay first, final CalendarDay last) { selectedDates.clear(); // Copy to start from the first day and increment LocalDate temp = LocalDate.of(first.getYear(), first.getMonth(), first.getDay()); // for comparison final LocalDate end = last.getDate(); while( temp.isBefore(end) || temp.equals(end) ) { selectedDates.add(CalendarDay.from(temp)); temp = temp.plusDays(1); } invalidateSelectedDates(); }
[ "public", "void", "selectRange", "(", "final", "CalendarDay", "first", ",", "final", "CalendarDay", "last", ")", "{", "selectedDates", ".", "clear", "(", ")", ";", "// Copy to start from the first day and increment", "LocalDate", "temp", "=", "LocalDate", ".", "of", "(", "first", ".", "getYear", "(", ")", ",", "first", ".", "getMonth", "(", ")", ",", "first", ".", "getDay", "(", ")", ")", ";", "// for comparison", "final", "LocalDate", "end", "=", "last", ".", "getDate", "(", ")", ";", "while", "(", "temp", ".", "isBefore", "(", "end", ")", "||", "temp", ".", "equals", "(", "end", ")", ")", "{", "selectedDates", ".", "add", "(", "CalendarDay", ".", "from", "(", "temp", ")", ")", ";", "temp", "=", "temp", ".", "plusDays", "(", "1", ")", ";", "}", "invalidateSelectedDates", "(", ")", ";", "}" ]
Clear the previous selection, select the range of days from first to last, and finally invalidate. First day should be before last day, otherwise the selection won't happen. @param first The first day of the range. @param last The last day in the range. @see CalendarPagerAdapter#setDateSelected(CalendarDay, boolean)
[ "Clear", "the", "previous", "selection", "select", "the", "range", "of", "days", "from", "first", "to", "last", "and", "finally", "invalidate", ".", "First", "day", "should", "be", "before", "last", "day", "otherwise", "the", "selection", "won", "t", "happen", "." ]
train
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java#L325-L340
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_ddi_serviceName_changeDestination_POST
public OvhTask billingAccount_ddi_serviceName_changeDestination_POST(String billingAccount, String serviceName, String destination) throws IOException { """ Change the destination of the DDI REST: POST /telephony/{billingAccount}/ddi/{serviceName}/changeDestination @param destination [required] The destination @param billingAccount [required] The name of your billingAccount @param serviceName [required] """ String qPath = "/telephony/{billingAccount}/ddi/{serviceName}/changeDestination"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "destination", destination); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask billingAccount_ddi_serviceName_changeDestination_POST(String billingAccount, String serviceName, String destination) throws IOException { String qPath = "/telephony/{billingAccount}/ddi/{serviceName}/changeDestination"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "destination", destination); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "billingAccount_ddi_serviceName_changeDestination_POST", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "String", "destination", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/ddi/{serviceName}/changeDestination\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "billingAccount", ",", "serviceName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"destination\"", ",", "destination", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhTask", ".", "class", ")", ";", "}" ]
Change the destination of the DDI REST: POST /telephony/{billingAccount}/ddi/{serviceName}/changeDestination @param destination [required] The destination @param billingAccount [required] The name of your billingAccount @param serviceName [required]
[ "Change", "the", "destination", "of", "the", "DDI" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L8470-L8477
alkacon/opencms-core
src/org/opencms/module/CmsModuleUpdater.java
CmsModuleUpdater.compareProperties
private List<CmsProperty> compareProperties( CmsObject cms, CmsResourceImportData resData, CmsResource existingResource) throws CmsException { """ Compares properties of an existing resource with those to be imported, and returns a list of properties that need to be updated.<p> @param cms the current CMS context @param resData the resource import data @param existingResource the existing resource @return the list of properties that need to be updated @throws CmsException if something goes wrong """ if (existingResource == null) { return Collections.emptyList(); } Map<String, CmsProperty> importProps = resData.getProperties(); Map<String, CmsProperty> existingProps = CmsProperty.getPropertyMap( cms.readPropertyObjects(existingResource, false)); Map<String, CmsProperty> propsToWrite = new HashMap<>(); Set<String> keys = new HashSet<>(); keys.addAll(existingProps.keySet()); keys.addAll(importProps.keySet()); for (String key : keys) { CmsProperty existingProp = existingProps.get(key); CmsProperty importProp = importProps.get(key); if (existingProp == null) { propsToWrite.put(key, importProp); } else if (importProp == null) { propsToWrite.put(key, new CmsProperty(key, "", "")); } else if (!existingProp.isIdentical(importProp)) { propsToWrite.put(key, importProp); } } return new ArrayList<>(propsToWrite.values()); }
java
private List<CmsProperty> compareProperties( CmsObject cms, CmsResourceImportData resData, CmsResource existingResource) throws CmsException { if (existingResource == null) { return Collections.emptyList(); } Map<String, CmsProperty> importProps = resData.getProperties(); Map<String, CmsProperty> existingProps = CmsProperty.getPropertyMap( cms.readPropertyObjects(existingResource, false)); Map<String, CmsProperty> propsToWrite = new HashMap<>(); Set<String> keys = new HashSet<>(); keys.addAll(existingProps.keySet()); keys.addAll(importProps.keySet()); for (String key : keys) { CmsProperty existingProp = existingProps.get(key); CmsProperty importProp = importProps.get(key); if (existingProp == null) { propsToWrite.put(key, importProp); } else if (importProp == null) { propsToWrite.put(key, new CmsProperty(key, "", "")); } else if (!existingProp.isIdentical(importProp)) { propsToWrite.put(key, importProp); } } return new ArrayList<>(propsToWrite.values()); }
[ "private", "List", "<", "CmsProperty", ">", "compareProperties", "(", "CmsObject", "cms", ",", "CmsResourceImportData", "resData", ",", "CmsResource", "existingResource", ")", "throws", "CmsException", "{", "if", "(", "existingResource", "==", "null", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "Map", "<", "String", ",", "CmsProperty", ">", "importProps", "=", "resData", ".", "getProperties", "(", ")", ";", "Map", "<", "String", ",", "CmsProperty", ">", "existingProps", "=", "CmsProperty", ".", "getPropertyMap", "(", "cms", ".", "readPropertyObjects", "(", "existingResource", ",", "false", ")", ")", ";", "Map", "<", "String", ",", "CmsProperty", ">", "propsToWrite", "=", "new", "HashMap", "<>", "(", ")", ";", "Set", "<", "String", ">", "keys", "=", "new", "HashSet", "<>", "(", ")", ";", "keys", ".", "addAll", "(", "existingProps", ".", "keySet", "(", ")", ")", ";", "keys", ".", "addAll", "(", "importProps", ".", "keySet", "(", ")", ")", ";", "for", "(", "String", "key", ":", "keys", ")", "{", "CmsProperty", "existingProp", "=", "existingProps", ".", "get", "(", "key", ")", ";", "CmsProperty", "importProp", "=", "importProps", ".", "get", "(", "key", ")", ";", "if", "(", "existingProp", "==", "null", ")", "{", "propsToWrite", ".", "put", "(", "key", ",", "importProp", ")", ";", "}", "else", "if", "(", "importProp", "==", "null", ")", "{", "propsToWrite", ".", "put", "(", "key", ",", "new", "CmsProperty", "(", "key", ",", "\"\"", ",", "\"\"", ")", ")", ";", "}", "else", "if", "(", "!", "existingProp", ".", "isIdentical", "(", "importProp", ")", ")", "{", "propsToWrite", ".", "put", "(", "key", ",", "importProp", ")", ";", "}", "}", "return", "new", "ArrayList", "<>", "(", "propsToWrite", ".", "values", "(", ")", ")", ";", "}" ]
Compares properties of an existing resource with those to be imported, and returns a list of properties that need to be updated.<p> @param cms the current CMS context @param resData the resource import data @param existingResource the existing resource @return the list of properties that need to be updated @throws CmsException if something goes wrong
[ "Compares", "properties", "of", "an", "existing", "resource", "with", "those", "to", "be", "imported", "and", "returns", "a", "list", "of", "properties", "that", "need", "to", "be", "updated", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModuleUpdater.java#L664-L695
apache/flink
flink-optimizer/src/main/java/org/apache/flink/optimizer/dataproperties/RequestedGlobalProperties.java
RequestedGlobalProperties.setCustomPartitioned
public void setCustomPartitioned(FieldSet partitionedFields, Partitioner<?> partitioner) { """ Sets these properties to request a custom partitioning with the given {@link Partitioner} instance. If the fields are provided as {@link FieldSet}, then any permutation of the fields is a valid partitioning, including subsets. If the fields are given as a {@link FieldList}, then only an exact partitioning on the fields matches this requested partitioning. @param partitionedFields The key fields for the partitioning. """ if (partitionedFields == null || partitioner == null) { throw new NullPointerException(); } this.partitioning = PartitioningProperty.CUSTOM_PARTITIONING; this.partitioningFields = partitionedFields; this.ordering = null; this.customPartitioner = partitioner; }
java
public void setCustomPartitioned(FieldSet partitionedFields, Partitioner<?> partitioner) { if (partitionedFields == null || partitioner == null) { throw new NullPointerException(); } this.partitioning = PartitioningProperty.CUSTOM_PARTITIONING; this.partitioningFields = partitionedFields; this.ordering = null; this.customPartitioner = partitioner; }
[ "public", "void", "setCustomPartitioned", "(", "FieldSet", "partitionedFields", ",", "Partitioner", "<", "?", ">", "partitioner", ")", "{", "if", "(", "partitionedFields", "==", "null", "||", "partitioner", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "this", ".", "partitioning", "=", "PartitioningProperty", ".", "CUSTOM_PARTITIONING", ";", "this", ".", "partitioningFields", "=", "partitionedFields", ";", "this", ".", "ordering", "=", "null", ";", "this", ".", "customPartitioner", "=", "partitioner", ";", "}" ]
Sets these properties to request a custom partitioning with the given {@link Partitioner} instance. If the fields are provided as {@link FieldSet}, then any permutation of the fields is a valid partitioning, including subsets. If the fields are given as a {@link FieldList}, then only an exact partitioning on the fields matches this requested partitioning. @param partitionedFields The key fields for the partitioning.
[ "Sets", "these", "properties", "to", "request", "a", "custom", "partitioning", "with", "the", "given", "{", "@link", "Partitioner", "}", "instance", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-optimizer/src/main/java/org/apache/flink/optimizer/dataproperties/RequestedGlobalProperties.java#L154-L163
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/validation/CmsValidationController.java
CmsValidationController.startAsyncValidation
private void startAsyncValidation(final String formValidationHandler, final String config) { """ Starts the asynchronous validation.<p> @param formValidationHandler the form validator class to use @param config the form validator configuration string """ CmsRpcAction<Map<String, CmsValidationResult>> action = new CmsRpcAction<Map<String, CmsValidationResult>>() { /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute() */ @Override public void execute() { final Map<String, String> values = new HashMap<String, String>(); for (I_CmsFormField field : m_fields) { values.put(field.getId(), field.getModelValue()); } start(0, false); CmsCoreProvider.getService().validate(formValidationHandler, m_validationQueries, values, config, this); } /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object) */ @Override protected void onResponse(Map<String, CmsValidationResult> result) { stop(false); onReceiveValidationResults(result); } }; action.execute(); }
java
private void startAsyncValidation(final String formValidationHandler, final String config) { CmsRpcAction<Map<String, CmsValidationResult>> action = new CmsRpcAction<Map<String, CmsValidationResult>>() { /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute() */ @Override public void execute() { final Map<String, String> values = new HashMap<String, String>(); for (I_CmsFormField field : m_fields) { values.put(field.getId(), field.getModelValue()); } start(0, false); CmsCoreProvider.getService().validate(formValidationHandler, m_validationQueries, values, config, this); } /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object) */ @Override protected void onResponse(Map<String, CmsValidationResult> result) { stop(false); onReceiveValidationResults(result); } }; action.execute(); }
[ "private", "void", "startAsyncValidation", "(", "final", "String", "formValidationHandler", ",", "final", "String", "config", ")", "{", "CmsRpcAction", "<", "Map", "<", "String", ",", "CmsValidationResult", ">", ">", "action", "=", "new", "CmsRpcAction", "<", "Map", "<", "String", ",", "CmsValidationResult", ">", ">", "(", ")", "{", "/**\n * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()\n */", "@", "Override", "public", "void", "execute", "(", ")", "{", "final", "Map", "<", "String", ",", "String", ">", "values", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "for", "(", "I_CmsFormField", "field", ":", "m_fields", ")", "{", "values", ".", "put", "(", "field", ".", "getId", "(", ")", ",", "field", ".", "getModelValue", "(", ")", ")", ";", "}", "start", "(", "0", ",", "false", ")", ";", "CmsCoreProvider", ".", "getService", "(", ")", ".", "validate", "(", "formValidationHandler", ",", "m_validationQueries", ",", "values", ",", "config", ",", "this", ")", ";", "}", "/**\n * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)\n */", "@", "Override", "protected", "void", "onResponse", "(", "Map", "<", "String", ",", "CmsValidationResult", ">", "result", ")", "{", "stop", "(", "false", ")", ";", "onReceiveValidationResults", "(", "result", ")", ";", "}", "}", ";", "action", ".", "execute", "(", ")", ";", "}" ]
Starts the asynchronous validation.<p> @param formValidationHandler the form validator class to use @param config the form validator configuration string
[ "Starts", "the", "asynchronous", "validation", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/validation/CmsValidationController.java#L275-L305
kiegroup/droolsjbpm-integration
kie-server-parent/kie-server-common/src/main/java/org/kie/server/common/rest/variant/AcceptHeaders.java
AcceptHeaders.evaluateAcceptParameters
private static QualityValue evaluateAcceptParameters(Map<String, String> parameters) { """ Evaluates and removes the accept parameters. <pre> accept-params = ";" "q" "=" qvalue *( accept-extension ) accept-extension = ";" token [ "=" ( token | quoted-string ) ] </pre> @param parameters all parameters in order of appearance. @return the qvalue. @see "accept-params """ Iterator<String> i = parameters.keySet().iterator(); while (i.hasNext()) { String name = i.next(); if ("q".equals(name)) { if (i.hasNext()) { logger.debug("Accept extensions not supported."); i.remove(); do { i.next(); i.remove(); } while (i.hasNext()); return QualityValue.NOT_ACCEPTABLE; } else { String value = parameters.get(name); i.remove(); return QualityValue.valueOf(value); } } } return QualityValue.DEFAULT; }
java
private static QualityValue evaluateAcceptParameters(Map<String, String> parameters) { Iterator<String> i = parameters.keySet().iterator(); while (i.hasNext()) { String name = i.next(); if ("q".equals(name)) { if (i.hasNext()) { logger.debug("Accept extensions not supported."); i.remove(); do { i.next(); i.remove(); } while (i.hasNext()); return QualityValue.NOT_ACCEPTABLE; } else { String value = parameters.get(name); i.remove(); return QualityValue.valueOf(value); } } } return QualityValue.DEFAULT; }
[ "private", "static", "QualityValue", "evaluateAcceptParameters", "(", "Map", "<", "String", ",", "String", ">", "parameters", ")", "{", "Iterator", "<", "String", ">", "i", "=", "parameters", ".", "keySet", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "i", ".", "hasNext", "(", ")", ")", "{", "String", "name", "=", "i", ".", "next", "(", ")", ";", "if", "(", "\"q\"", ".", "equals", "(", "name", ")", ")", "{", "if", "(", "i", ".", "hasNext", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Accept extensions not supported.\"", ")", ";", "i", ".", "remove", "(", ")", ";", "do", "{", "i", ".", "next", "(", ")", ";", "i", ".", "remove", "(", ")", ";", "}", "while", "(", "i", ".", "hasNext", "(", ")", ")", ";", "return", "QualityValue", ".", "NOT_ACCEPTABLE", ";", "}", "else", "{", "String", "value", "=", "parameters", ".", "get", "(", "name", ")", ";", "i", ".", "remove", "(", ")", ";", "return", "QualityValue", ".", "valueOf", "(", "value", ")", ";", "}", "}", "}", "return", "QualityValue", ".", "DEFAULT", ";", "}" ]
Evaluates and removes the accept parameters. <pre> accept-params = ";" "q" "=" qvalue *( accept-extension ) accept-extension = ";" token [ "=" ( token | quoted-string ) ] </pre> @param parameters all parameters in order of appearance. @return the qvalue. @see "accept-params
[ "Evaluates", "and", "removes", "the", "accept", "parameters", ".", "<pre", ">", "accept", "-", "params", "=", ";", "q", "=", "qvalue", "*", "(", "accept", "-", "extension", ")", "accept", "-", "extension", "=", ";", "token", "[", "=", "(", "token", "|", "quoted", "-", "string", ")", "]", "<", "/", "pre", ">" ]
train
https://github.com/kiegroup/droolsjbpm-integration/blob/6c26200ab03855dbb92b56ca0c6363cdec0eaf2c/kie-server-parent/kie-server-common/src/main/java/org/kie/server/common/rest/variant/AcceptHeaders.java#L293-L321
OpenLiberty/open-liberty
dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/config/SSLConfigManager.java
SSLConfigManager.addSSLConfigToMap
public synchronized void addSSLConfigToMap(String alias, SSLConfig sslConfig) throws Exception { """ * This method adds an SSL config from the SSLConfigManager map and list. @param alias @param sslConfig @throws Exception * """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "addSSLConfigToMap: alias=" + alias); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, sslConfig.toString()); } if (sslConfigMap.containsKey(alias)) { sslConfigMap.remove(alias); outboundSSL.removeDynamicSelectionsWithSSLConfig(alias); } if (validationEnabled()) sslConfig.validateSSLConfig(); sslConfigMap.put(alias, sslConfig); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "addSSLConfigToMap"); }
java
public synchronized void addSSLConfigToMap(String alias, SSLConfig sslConfig) throws Exception { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "addSSLConfigToMap: alias=" + alias); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, sslConfig.toString()); } if (sslConfigMap.containsKey(alias)) { sslConfigMap.remove(alias); outboundSSL.removeDynamicSelectionsWithSSLConfig(alias); } if (validationEnabled()) sslConfig.validateSSLConfig(); sslConfigMap.put(alias, sslConfig); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "addSSLConfigToMap"); }
[ "public", "synchronized", "void", "addSSLConfigToMap", "(", "String", "alias", ",", "SSLConfig", "sslConfig", ")", "throws", "Exception", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "entry", "(", "tc", ",", "\"addSSLConfigToMap: alias=\"", "+", "alias", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "sslConfig", ".", "toString", "(", ")", ")", ";", "}", "if", "(", "sslConfigMap", ".", "containsKey", "(", "alias", ")", ")", "{", "sslConfigMap", ".", "remove", "(", "alias", ")", ";", "outboundSSL", ".", "removeDynamicSelectionsWithSSLConfig", "(", "alias", ")", ";", "}", "if", "(", "validationEnabled", "(", ")", ")", "sslConfig", ".", "validateSSLConfig", "(", ")", ";", "sslConfigMap", ".", "put", "(", "alias", ",", "sslConfig", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "exit", "(", "tc", ",", "\"addSSLConfigToMap\"", ")", ";", "}" ]
* This method adds an SSL config from the SSLConfigManager map and list. @param alias @param sslConfig @throws Exception *
[ "*", "This", "method", "adds", "an", "SSL", "config", "from", "the", "SSLConfigManager", "map", "and", "list", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/config/SSLConfigManager.java#L1341-L1362
anotheria/moskito
moskito-core/src/main/java/net/anotheria/moskito/core/predefined/PageInBrowserStats.java
PageInBrowserStats.getDomMinLoadTime
public long getDomMinLoadTime(final String intervalName, final TimeUnit unit) { """ Returns DOM minimum load time for given interval and time unit. @param intervalName name of the interval @param unit {@link TimeUnit} @return DOM minimum load time """ final long min = domMinLoadTime.getValueAsLong(intervalName); return min == Constants.MIN_TIME_DEFAULT ? min : unit.transformMillis(min); }
java
public long getDomMinLoadTime(final String intervalName, final TimeUnit unit) { final long min = domMinLoadTime.getValueAsLong(intervalName); return min == Constants.MIN_TIME_DEFAULT ? min : unit.transformMillis(min); }
[ "public", "long", "getDomMinLoadTime", "(", "final", "String", "intervalName", ",", "final", "TimeUnit", "unit", ")", "{", "final", "long", "min", "=", "domMinLoadTime", ".", "getValueAsLong", "(", "intervalName", ")", ";", "return", "min", "==", "Constants", ".", "MIN_TIME_DEFAULT", "?", "min", ":", "unit", ".", "transformMillis", "(", "min", ")", ";", "}" ]
Returns DOM minimum load time for given interval and time unit. @param intervalName name of the interval @param unit {@link TimeUnit} @return DOM minimum load time
[ "Returns", "DOM", "minimum", "load", "time", "for", "given", "interval", "and", "time", "unit", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/predefined/PageInBrowserStats.java#L129-L132
cdk/cdk
tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomPlacer3D.java
AtomPlacer3D.getPlacedHeavyAtom
public IAtom getPlacedHeavyAtom(IAtomContainer molecule, IAtom atom) { """ Returns a placed atom connected to a given atom. @param molecule @param atom The Atom whose placed bonding partners are to be returned @return a placed heavy atom connected to a given atom author: steinbeck """ List<IBond> bonds = molecule.getConnectedBondsList(atom); for (IBond bond : bonds) { IAtom connectedAtom = bond.getOther(atom); if (isPlacedHeavyAtom(connectedAtom)) { return connectedAtom; } } return null; }
java
public IAtom getPlacedHeavyAtom(IAtomContainer molecule, IAtom atom) { List<IBond> bonds = molecule.getConnectedBondsList(atom); for (IBond bond : bonds) { IAtom connectedAtom = bond.getOther(atom); if (isPlacedHeavyAtom(connectedAtom)) { return connectedAtom; } } return null; }
[ "public", "IAtom", "getPlacedHeavyAtom", "(", "IAtomContainer", "molecule", ",", "IAtom", "atom", ")", "{", "List", "<", "IBond", ">", "bonds", "=", "molecule", ".", "getConnectedBondsList", "(", "atom", ")", ";", "for", "(", "IBond", "bond", ":", "bonds", ")", "{", "IAtom", "connectedAtom", "=", "bond", ".", "getOther", "(", "atom", ")", ";", "if", "(", "isPlacedHeavyAtom", "(", "connectedAtom", ")", ")", "{", "return", "connectedAtom", ";", "}", "}", "return", "null", ";", "}" ]
Returns a placed atom connected to a given atom. @param molecule @param atom The Atom whose placed bonding partners are to be returned @return a placed heavy atom connected to a given atom author: steinbeck
[ "Returns", "a", "placed", "atom", "connected", "to", "a", "given", "atom", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomPlacer3D.java#L521-L530
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/util/FirstNonNullHelper.java
FirstNonNullHelper.firstNonNull
@SafeVarargs public static <T> T firstNonNull(Supplier<T>... suppliers) { """ Gets first supplier's result which is not null. Suppliers are called sequentially. Once a non-null result is obtained the remaining suppliers are not called. @param <T> type of result returned by suppliers. @param suppliers all possible suppliers that might be able to supply a value. @return first result obtained which was not null, OR <code>null</code> if all suppliers returned <code>null</code>. """ return firstNonNull(Supplier::get, suppliers); }
java
@SafeVarargs public static <T> T firstNonNull(Supplier<T>... suppliers) { return firstNonNull(Supplier::get, suppliers); }
[ "@", "SafeVarargs", "public", "static", "<", "T", ">", "T", "firstNonNull", "(", "Supplier", "<", "T", ">", "...", "suppliers", ")", "{", "return", "firstNonNull", "(", "Supplier", "::", "get", ",", "suppliers", ")", ";", "}" ]
Gets first supplier's result which is not null. Suppliers are called sequentially. Once a non-null result is obtained the remaining suppliers are not called. @param <T> type of result returned by suppliers. @param suppliers all possible suppliers that might be able to supply a value. @return first result obtained which was not null, OR <code>null</code> if all suppliers returned <code>null</code>.
[ "Gets", "first", "supplier", "s", "result", "which", "is", "not", "null", ".", "Suppliers", "are", "called", "sequentially", ".", "Once", "a", "non", "-", "null", "result", "is", "obtained", "the", "remaining", "suppliers", "are", "not", "called", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/FirstNonNullHelper.java#L21-L24
languagetool-org/languagetool
languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/GermanSpellerRule.java
GermanSpellerRule.getPastTenseVerbSuggestion
@Nullable private String getPastTenseVerbSuggestion(String word) { """ non-native speakers and cannot be found by just looking for similar words. """ if (word.endsWith("e")) { // strip trailing "e" String wordStem = word.substring(0, word.length()-1); try { String lemma = baseForThirdPersonSingularVerb(wordStem); if (lemma != null) { AnalyzedToken token = new AnalyzedToken(lemma, null, lemma); String[] forms = synthesizer.synthesize(token, "VER:3:SIN:PRT:.*", true); if (forms.length > 0) { return forms[0]; } } } catch (IOException e) { throw new RuntimeException(e); } } return null; }
java
@Nullable private String getPastTenseVerbSuggestion(String word) { if (word.endsWith("e")) { // strip trailing "e" String wordStem = word.substring(0, word.length()-1); try { String lemma = baseForThirdPersonSingularVerb(wordStem); if (lemma != null) { AnalyzedToken token = new AnalyzedToken(lemma, null, lemma); String[] forms = synthesizer.synthesize(token, "VER:3:SIN:PRT:.*", true); if (forms.length > 0) { return forms[0]; } } } catch (IOException e) { throw new RuntimeException(e); } } return null; }
[ "@", "Nullable", "private", "String", "getPastTenseVerbSuggestion", "(", "String", "word", ")", "{", "if", "(", "word", ".", "endsWith", "(", "\"e\"", ")", ")", "{", "// strip trailing \"e\"", "String", "wordStem", "=", "word", ".", "substring", "(", "0", ",", "word", ".", "length", "(", ")", "-", "1", ")", ";", "try", "{", "String", "lemma", "=", "baseForThirdPersonSingularVerb", "(", "wordStem", ")", ";", "if", "(", "lemma", "!=", "null", ")", "{", "AnalyzedToken", "token", "=", "new", "AnalyzedToken", "(", "lemma", ",", "null", ",", "lemma", ")", ";", "String", "[", "]", "forms", "=", "synthesizer", ".", "synthesize", "(", "token", ",", "\"VER:3:SIN:PRT:.*\"", ",", "true", ")", ";", "if", "(", "forms", ".", "length", ">", "0", ")", "{", "return", "forms", "[", "0", "]", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", "return", "null", ";", "}" ]
non-native speakers and cannot be found by just looking for similar words.
[ "non", "-", "native", "speakers", "and", "cannot", "be", "found", "by", "just", "looking", "for", "similar", "words", "." ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/GermanSpellerRule.java#L1147-L1166
joniles/mpxj
src/main/java/net/sf/mpxj/synchro/DatatypeConverter.java
DatatypeConverter.getShort
public static final int getShort(InputStream is) throws IOException { """ Read a short int from an input stream. @param is input stream @return int value """ byte[] data = new byte[2]; is.read(data); return getShort(data, 0); }
java
public static final int getShort(InputStream is) throws IOException { byte[] data = new byte[2]; is.read(data); return getShort(data, 0); }
[ "public", "static", "final", "int", "getShort", "(", "InputStream", "is", ")", "throws", "IOException", "{", "byte", "[", "]", "data", "=", "new", "byte", "[", "2", "]", ";", "is", ".", "read", "(", "data", ")", ";", "return", "getShort", "(", "data", ",", "0", ")", ";", "}" ]
Read a short int from an input stream. @param is input stream @return int value
[ "Read", "a", "short", "int", "from", "an", "input", "stream", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/synchro/DatatypeConverter.java#L156-L161
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java
ByteExtensions.sequenceEqualConstantTime
public static boolean sequenceEqualConstantTime(byte[] self, byte[] other) { """ Compares two byte arrays in constant time. @param self The first byte array to compare @param other The second byte array to compare @return True if the two byte arrays are equal. """ if (self == null) { throw new IllegalArgumentException("self"); } if (other == null) { throw new IllegalArgumentException("other"); } // Constant time comparison of two byte arrays long difference = (self.length & 0xffffffffL) ^ (other.length & 0xffffffffL); for (int i = 0; i < self.length && i < other.length; i++) { difference |= (self[i] ^ other[i]) & 0xffffffffL; } return difference == 0; }
java
public static boolean sequenceEqualConstantTime(byte[] self, byte[] other) { if (self == null) { throw new IllegalArgumentException("self"); } if (other == null) { throw new IllegalArgumentException("other"); } // Constant time comparison of two byte arrays long difference = (self.length & 0xffffffffL) ^ (other.length & 0xffffffffL); for (int i = 0; i < self.length && i < other.length; i++) { difference |= (self[i] ^ other[i]) & 0xffffffffL; } return difference == 0; }
[ "public", "static", "boolean", "sequenceEqualConstantTime", "(", "byte", "[", "]", "self", ",", "byte", "[", "]", "other", ")", "{", "if", "(", "self", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"self\"", ")", ";", "}", "if", "(", "other", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"other\"", ")", ";", "}", "// Constant time comparison of two byte arrays", "long", "difference", "=", "(", "self", ".", "length", "&", "0xffffffff", "L", ")", "^", "(", "other", ".", "length", "&", "0xffffffff", "L", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "self", ".", "length", "&&", "i", "<", "other", ".", "length", ";", "i", "++", ")", "{", "difference", "|=", "(", "self", "[", "i", "]", "^", "other", "[", "i", "]", ")", "&", "0xffffffff", "", "L", ";", "}", "return", "difference", "==", "0", ";", "}" ]
Compares two byte arrays in constant time. @param self The first byte array to compare @param other The second byte array to compare @return True if the two byte arrays are equal.
[ "Compares", "two", "byte", "arrays", "in", "constant", "time", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java#L78-L95
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/ocr/OcrClient.java
OcrClient.idcardRecognition
public IdcardRecognitionResponse idcardRecognition(IdcardRecognitionRequest request) { """ Gets the idcard recognition properties of specific image resource. <p> The caller <i>must</i> authenticate with a valid BCE Access Key / Private Key pair. @param request The request wrapper object containing all options. @return The idcard recognition properties of the image resource """ checkNotNull(request, "request should not be null."); checkStringNotEmpty(request.getImage(), "Image should not be null or empty!"); InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, PARA_ID); return invokeHttpClient(internalRequest, IdcardRecognitionResponse.class); }
java
public IdcardRecognitionResponse idcardRecognition(IdcardRecognitionRequest request) { checkNotNull(request, "request should not be null."); checkStringNotEmpty(request.getImage(), "Image should not be null or empty!"); InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, PARA_ID); return invokeHttpClient(internalRequest, IdcardRecognitionResponse.class); }
[ "public", "IdcardRecognitionResponse", "idcardRecognition", "(", "IdcardRecognitionRequest", "request", ")", "{", "checkNotNull", "(", "request", ",", "\"request should not be null.\"", ")", ";", "checkStringNotEmpty", "(", "request", ".", "getImage", "(", ")", ",", "\"Image should not be null or empty!\"", ")", ";", "InternalRequest", "internalRequest", "=", "createRequest", "(", "HttpMethodName", ".", "POST", ",", "request", ",", "PARA_ID", ")", ";", "return", "invokeHttpClient", "(", "internalRequest", ",", "IdcardRecognitionResponse", ".", "class", ")", ";", "}" ]
Gets the idcard recognition properties of specific image resource. <p> The caller <i>must</i> authenticate with a valid BCE Access Key / Private Key pair. @param request The request wrapper object containing all options. @return The idcard recognition properties of the image resource
[ "Gets", "the", "idcard", "recognition", "properties", "of", "specific", "image", "resource", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/ocr/OcrClient.java#L154-L162
hageldave/ImagingKit
ImagingKit_Filter/src/main/java/hageldave/imagingkit/filter/util/GenericsHelper.java
GenericsHelper.isAssignableFrom
public static boolean isAssignableFrom(Class<?> assignedCls, Class<?> assigningCls) { """ same as class.isAssignableFrom(class) but with implicit cast check for native numbers """ if(isNativeNumberType(assigningCls) && isNativeNumberType(assignedCls)){ return isNumberImplicitlyCastableFrom(assignedCls, assigningCls); } return assignedCls.isAssignableFrom(assigningCls); }
java
public static boolean isAssignableFrom(Class<?> assignedCls, Class<?> assigningCls){ if(isNativeNumberType(assigningCls) && isNativeNumberType(assignedCls)){ return isNumberImplicitlyCastableFrom(assignedCls, assigningCls); } return assignedCls.isAssignableFrom(assigningCls); }
[ "public", "static", "boolean", "isAssignableFrom", "(", "Class", "<", "?", ">", "assignedCls", ",", "Class", "<", "?", ">", "assigningCls", ")", "{", "if", "(", "isNativeNumberType", "(", "assigningCls", ")", "&&", "isNativeNumberType", "(", "assignedCls", ")", ")", "{", "return", "isNumberImplicitlyCastableFrom", "(", "assignedCls", ",", "assigningCls", ")", ";", "}", "return", "assignedCls", ".", "isAssignableFrom", "(", "assigningCls", ")", ";", "}" ]
same as class.isAssignableFrom(class) but with implicit cast check for native numbers
[ "same", "as", "class", ".", "isAssignableFrom", "(", "class", ")", "but", "with", "implicit", "cast", "check", "for", "native", "numbers" ]
train
https://github.com/hageldave/ImagingKit/blob/3837c7d550a12cf4dc5718b644ced94b97f52668/ImagingKit_Filter/src/main/java/hageldave/imagingkit/filter/util/GenericsHelper.java#L7-L12
amzn/ion-java
src/com/amazon/ion/impl/IonUTF8.java
IonUTF8.packBytesAfter1
public final static int packBytesAfter1(int unicodeScalar, int utf8Len) { """ converts a unicode code point to a 0-3 bytes of UTF8 encoded data and a length - note this doesn't pack a 1 byte character and it returns the start character. this is the unpacking routine while (_utf8_pretch_byte_count > 0 && offset < limit) { _utf8_pretch_byte_count--; buffer[offset++] = (byte)((_utf8_pretch_bytes >> (_utf8_pretch_byte_count*8)) & 0xff); } """ int packed_chars; switch (utf8Len) { default: throw new IllegalArgumentException("pack requires len > 1"); case 2: packed_chars = getByte2Of2(unicodeScalar); break; case 3: packed_chars = getByte2Of3(unicodeScalar); packed_chars |= getByte3Of3(unicodeScalar) << 8; break; case 4: packed_chars = getByte2Of4(unicodeScalar); packed_chars |= getByte3Of4(unicodeScalar) << 8; packed_chars |= getByte4Of4(unicodeScalar) << 16; break; } return packed_chars; }
java
public final static int packBytesAfter1(int unicodeScalar, int utf8Len) { int packed_chars; switch (utf8Len) { default: throw new IllegalArgumentException("pack requires len > 1"); case 2: packed_chars = getByte2Of2(unicodeScalar); break; case 3: packed_chars = getByte2Of3(unicodeScalar); packed_chars |= getByte3Of3(unicodeScalar) << 8; break; case 4: packed_chars = getByte2Of4(unicodeScalar); packed_chars |= getByte3Of4(unicodeScalar) << 8; packed_chars |= getByte4Of4(unicodeScalar) << 16; break; } return packed_chars; }
[ "public", "final", "static", "int", "packBytesAfter1", "(", "int", "unicodeScalar", ",", "int", "utf8Len", ")", "{", "int", "packed_chars", ";", "switch", "(", "utf8Len", ")", "{", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"pack requires len > 1\"", ")", ";", "case", "2", ":", "packed_chars", "=", "getByte2Of2", "(", "unicodeScalar", ")", ";", "break", ";", "case", "3", ":", "packed_chars", "=", "getByte2Of3", "(", "unicodeScalar", ")", ";", "packed_chars", "|=", "getByte3Of3", "(", "unicodeScalar", ")", "<<", "8", ";", "break", ";", "case", "4", ":", "packed_chars", "=", "getByte2Of4", "(", "unicodeScalar", ")", ";", "packed_chars", "|=", "getByte3Of4", "(", "unicodeScalar", ")", "<<", "8", ";", "packed_chars", "|=", "getByte4Of4", "(", "unicodeScalar", ")", "<<", "16", ";", "break", ";", "}", "return", "packed_chars", ";", "}" ]
converts a unicode code point to a 0-3 bytes of UTF8 encoded data and a length - note this doesn't pack a 1 byte character and it returns the start character. this is the unpacking routine while (_utf8_pretch_byte_count > 0 && offset < limit) { _utf8_pretch_byte_count--; buffer[offset++] = (byte)((_utf8_pretch_bytes >> (_utf8_pretch_byte_count*8)) & 0xff); }
[ "converts", "a", "unicode", "code", "point", "to", "a", "0", "-", "3", "bytes", "of", "UTF8", "encoded", "data", "and", "a", "length", "-", "note", "this", "doesn", "t", "pack", "a", "1", "byte", "character", "and", "it", "returns", "the", "start", "character", ".", "this", "is", "the", "unpacking", "routine", "while", "(", "_utf8_pretch_byte_count", ">", "0", "&&", "offset", "<", "limit", ")", "{", "_utf8_pretch_byte_count", "--", ";", "buffer", "[", "offset", "++", "]", "=", "(", "byte", ")", "((", "_utf8_pretch_bytes", ">>", "(", "_utf8_pretch_byte_count", "*", "8", "))", "&", "0xff", ")", ";", "}" ]
train
https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/IonUTF8.java#L250-L272
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/swapper/HdfsFailedFetchLock.java
HdfsFailedFetchLock.handleIOException
private void handleIOException(IOException e, String action, int attempt) throws VoldemortException, InterruptedException { """ This function is intended to detect the subset of IOException which are not considered recoverable, in which case we want to bubble up the exception, instead of retrying. @throws VoldemortException """ if ( // any of the following happens, we need to bubble up // FileSystem instance got closed, somehow e.getMessage().contains("Filesystem closed") || // HDFS permission issues ExceptionUtils.recursiveClassEquals(e, AccessControlException.class)) { throw new VoldemortException("Got an IOException we cannot recover from while trying to " + action + ". Attempt # " + attempt + "/" + maxAttempts + ". Will not try again.", e); } else { logFailureAndWait(action, IO_EXCEPTION, attempt, e); } }
java
private void handleIOException(IOException e, String action, int attempt) throws VoldemortException, InterruptedException { if ( // any of the following happens, we need to bubble up // FileSystem instance got closed, somehow e.getMessage().contains("Filesystem closed") || // HDFS permission issues ExceptionUtils.recursiveClassEquals(e, AccessControlException.class)) { throw new VoldemortException("Got an IOException we cannot recover from while trying to " + action + ". Attempt # " + attempt + "/" + maxAttempts + ". Will not try again.", e); } else { logFailureAndWait(action, IO_EXCEPTION, attempt, e); } }
[ "private", "void", "handleIOException", "(", "IOException", "e", ",", "String", "action", ",", "int", "attempt", ")", "throws", "VoldemortException", ",", "InterruptedException", "{", "if", "(", "// any of the following happens, we need to bubble up", "// FileSystem instance got closed, somehow", "e", ".", "getMessage", "(", ")", ".", "contains", "(", "\"Filesystem closed\"", ")", "||", "// HDFS permission issues", "ExceptionUtils", ".", "recursiveClassEquals", "(", "e", ",", "AccessControlException", ".", "class", ")", ")", "{", "throw", "new", "VoldemortException", "(", "\"Got an IOException we cannot recover from while trying to \"", "+", "action", "+", "\". Attempt # \"", "+", "attempt", "+", "\"/\"", "+", "maxAttempts", "+", "\". Will not try again.\"", ",", "e", ")", ";", "}", "else", "{", "logFailureAndWait", "(", "action", ",", "IO_EXCEPTION", ",", "attempt", ",", "e", ")", ";", "}", "}" ]
This function is intended to detect the subset of IOException which are not considered recoverable, in which case we want to bubble up the exception, instead of retrying. @throws VoldemortException
[ "This", "function", "is", "intended", "to", "detect", "the", "subset", "of", "IOException", "which", "are", "not", "considered", "recoverable", "in", "which", "case", "we", "want", "to", "bubble", "up", "the", "exception", "instead", "of", "retrying", "." ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/swapper/HdfsFailedFetchLock.java#L186-L198
Abnaxos/markdown-doclet
doclet/jdk8/src/main/java/ch/raffael/mddoclet/MarkdownDoclet.java
MarkdownDoclet.defaultProcess
protected void defaultProcess(Doc doc, boolean fixLeadingSpaces) { """ Default processing of any documentation node. @param doc The documentation. @param fixLeadingSpaces `true` if leading spaces should be fixed. @see Options#toHtml(String, boolean) """ try { StringBuilder buf = new StringBuilder(); buf.append(getOptions().toHtml(doc.commentText(), fixLeadingSpaces)); buf.append('\n'); for ( Tag tag : doc.tags() ) { processTag(tag, buf); buf.append('\n'); } doc.setRawCommentText(buf.toString()); } catch ( final ParserRuntimeException e ) { if ( doc instanceof RootDoc ) { printError(new SourcePosition() { @Override public File file() { return options.getOverviewFile(); } @Override public int line() { return 0; } @Override public int column() { return 0; } }, e.getMessage()); } else { printError(doc.position(), e.getMessage()); } } }
java
protected void defaultProcess(Doc doc, boolean fixLeadingSpaces) { try { StringBuilder buf = new StringBuilder(); buf.append(getOptions().toHtml(doc.commentText(), fixLeadingSpaces)); buf.append('\n'); for ( Tag tag : doc.tags() ) { processTag(tag, buf); buf.append('\n'); } doc.setRawCommentText(buf.toString()); } catch ( final ParserRuntimeException e ) { if ( doc instanceof RootDoc ) { printError(new SourcePosition() { @Override public File file() { return options.getOverviewFile(); } @Override public int line() { return 0; } @Override public int column() { return 0; } }, e.getMessage()); } else { printError(doc.position(), e.getMessage()); } } }
[ "protected", "void", "defaultProcess", "(", "Doc", "doc", ",", "boolean", "fixLeadingSpaces", ")", "{", "try", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", ")", ";", "buf", ".", "append", "(", "getOptions", "(", ")", ".", "toHtml", "(", "doc", ".", "commentText", "(", ")", ",", "fixLeadingSpaces", ")", ")", ";", "buf", ".", "append", "(", "'", "'", ")", ";", "for", "(", "Tag", "tag", ":", "doc", ".", "tags", "(", ")", ")", "{", "processTag", "(", "tag", ",", "buf", ")", ";", "buf", ".", "append", "(", "'", "'", ")", ";", "}", "doc", ".", "setRawCommentText", "(", "buf", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "final", "ParserRuntimeException", "e", ")", "{", "if", "(", "doc", "instanceof", "RootDoc", ")", "{", "printError", "(", "new", "SourcePosition", "(", ")", "{", "@", "Override", "public", "File", "file", "(", ")", "{", "return", "options", ".", "getOverviewFile", "(", ")", ";", "}", "@", "Override", "public", "int", "line", "(", ")", "{", "return", "0", ";", "}", "@", "Override", "public", "int", "column", "(", ")", "{", "return", "0", ";", "}", "}", ",", "e", ".", "getMessage", "(", ")", ")", ";", "}", "else", "{", "printError", "(", "doc", ".", "position", "(", ")", ",", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "}" ]
Default processing of any documentation node. @param doc The documentation. @param fixLeadingSpaces `true` if leading spaces should be fixed. @see Options#toHtml(String, boolean)
[ "Default", "processing", "of", "any", "documentation", "node", "." ]
train
https://github.com/Abnaxos/markdown-doclet/blob/e98a9630206fc9c8d813cf2349ff594be8630054/doclet/jdk8/src/main/java/ch/raffael/mddoclet/MarkdownDoclet.java#L367-L399
zeroturnaround/maven-jrebel-plugin
src/main/java/org/zeroturnaround/javarebel/maven/GenerateRebelMojo.java
GenerateRebelMojo.fixFilePath
protected String fixFilePath(File file) throws MojoExecutionException { """ Returns path expressed through rootPath and relativePath. @param file to be fixed @return fixed path @throws MojoExecutionException if something goes wrong """ File baseDir = getProject().getFile().getParentFile(); if (file.isAbsolute() && !isRelativeToPath(new File(baseDir, getRelativePath()), file)) { return StringUtils.replace(getCanonicalPath(file), '\\', '/'); } if (!file.isAbsolute()) { file = new File(baseDir, file.getPath()); } String relative = getRelativePath(new File(baseDir, getRelativePath()), file); if (!(new File(relative)).isAbsolute()) { return StringUtils.replace(getRootPath(), '\\', '/') + "/" + relative; } //relative path was outside baseDir //if root path is absolute then try to get a path relative to root if ((new File(getRootPath())).isAbsolute()) { String s = getRelativePath(new File(getRootPath()), file); if (!(new File(s)).isAbsolute()) { return StringUtils.replace(getRootPath(), '\\', '/') + "/" + s; } else { // root path and the calculated path are absolute, so // just return calculated path return s; } } //return absolute path to file return StringUtils.replace(file.getAbsolutePath(), '\\', '/'); }
java
protected String fixFilePath(File file) throws MojoExecutionException { File baseDir = getProject().getFile().getParentFile(); if (file.isAbsolute() && !isRelativeToPath(new File(baseDir, getRelativePath()), file)) { return StringUtils.replace(getCanonicalPath(file), '\\', '/'); } if (!file.isAbsolute()) { file = new File(baseDir, file.getPath()); } String relative = getRelativePath(new File(baseDir, getRelativePath()), file); if (!(new File(relative)).isAbsolute()) { return StringUtils.replace(getRootPath(), '\\', '/') + "/" + relative; } //relative path was outside baseDir //if root path is absolute then try to get a path relative to root if ((new File(getRootPath())).isAbsolute()) { String s = getRelativePath(new File(getRootPath()), file); if (!(new File(s)).isAbsolute()) { return StringUtils.replace(getRootPath(), '\\', '/') + "/" + s; } else { // root path and the calculated path are absolute, so // just return calculated path return s; } } //return absolute path to file return StringUtils.replace(file.getAbsolutePath(), '\\', '/'); }
[ "protected", "String", "fixFilePath", "(", "File", "file", ")", "throws", "MojoExecutionException", "{", "File", "baseDir", "=", "getProject", "(", ")", ".", "getFile", "(", ")", ".", "getParentFile", "(", ")", ";", "if", "(", "file", ".", "isAbsolute", "(", ")", "&&", "!", "isRelativeToPath", "(", "new", "File", "(", "baseDir", ",", "getRelativePath", "(", ")", ")", ",", "file", ")", ")", "{", "return", "StringUtils", ".", "replace", "(", "getCanonicalPath", "(", "file", ")", ",", "'", "'", ",", "'", "'", ")", ";", "}", "if", "(", "!", "file", ".", "isAbsolute", "(", ")", ")", "{", "file", "=", "new", "File", "(", "baseDir", ",", "file", ".", "getPath", "(", ")", ")", ";", "}", "String", "relative", "=", "getRelativePath", "(", "new", "File", "(", "baseDir", ",", "getRelativePath", "(", ")", ")", ",", "file", ")", ";", "if", "(", "!", "(", "new", "File", "(", "relative", ")", ")", ".", "isAbsolute", "(", ")", ")", "{", "return", "StringUtils", ".", "replace", "(", "getRootPath", "(", ")", ",", "'", "'", ",", "'", "'", ")", "+", "\"/\"", "+", "relative", ";", "}", "//relative path was outside baseDir", "//if root path is absolute then try to get a path relative to root", "if", "(", "(", "new", "File", "(", "getRootPath", "(", ")", ")", ")", ".", "isAbsolute", "(", ")", ")", "{", "String", "s", "=", "getRelativePath", "(", "new", "File", "(", "getRootPath", "(", ")", ")", ",", "file", ")", ";", "if", "(", "!", "(", "new", "File", "(", "s", ")", ")", ".", "isAbsolute", "(", ")", ")", "{", "return", "StringUtils", ".", "replace", "(", "getRootPath", "(", ")", ",", "'", "'", ",", "'", "'", ")", "+", "\"/\"", "+", "s", ";", "}", "else", "{", "// root path and the calculated path are absolute, so ", "// just return calculated path", "return", "s", ";", "}", "}", "//return absolute path to file", "return", "StringUtils", ".", "replace", "(", "file", ".", "getAbsolutePath", "(", ")", ",", "'", "'", ",", "'", "'", ")", ";", "}" ]
Returns path expressed through rootPath and relativePath. @param file to be fixed @return fixed path @throws MojoExecutionException if something goes wrong
[ "Returns", "path", "expressed", "through", "rootPath", "and", "relativePath", "." ]
train
https://github.com/zeroturnaround/maven-jrebel-plugin/blob/6a0d12529a13ae6b2b772658a714398147c091ca/src/main/java/org/zeroturnaround/javarebel/maven/GenerateRebelMojo.java#L814-L847
jMotif/SAX
src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java
EuclideanDistance.distance2
public double distance2(double[] point1, double[] point2) throws Exception { """ Calculates the square of the Euclidean distance between two multidimensional points represented by the rational vectors. @param point1 The first point. @param point2 The second point. @return The Euclidean distance. @throws Exception In the case of error. """ if (point1.length == point2.length) { Double sum = 0D; for (int i = 0; i < point1.length; i++) { double tmp = point2[i] - point1[i]; sum = sum + tmp * tmp; } return sum; } else { throw new Exception("Exception in Euclidean distance: array lengths are not equal"); } }
java
public double distance2(double[] point1, double[] point2) throws Exception { if (point1.length == point2.length) { Double sum = 0D; for (int i = 0; i < point1.length; i++) { double tmp = point2[i] - point1[i]; sum = sum + tmp * tmp; } return sum; } else { throw new Exception("Exception in Euclidean distance: array lengths are not equal"); } }
[ "public", "double", "distance2", "(", "double", "[", "]", "point1", ",", "double", "[", "]", "point2", ")", "throws", "Exception", "{", "if", "(", "point1", ".", "length", "==", "point2", ".", "length", ")", "{", "Double", "sum", "=", "0D", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "point1", ".", "length", ";", "i", "++", ")", "{", "double", "tmp", "=", "point2", "[", "i", "]", "-", "point1", "[", "i", "]", ";", "sum", "=", "sum", "+", "tmp", "*", "tmp", ";", "}", "return", "sum", ";", "}", "else", "{", "throw", "new", "Exception", "(", "\"Exception in Euclidean distance: array lengths are not equal\"", ")", ";", "}", "}" ]
Calculates the square of the Euclidean distance between two multidimensional points represented by the rational vectors. @param point1 The first point. @param point2 The second point. @return The Euclidean distance. @throws Exception In the case of error.
[ "Calculates", "the", "square", "of", "the", "Euclidean", "distance", "between", "two", "multidimensional", "points", "represented", "by", "the", "rational", "vectors", "." ]
train
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java#L75-L87
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/config/CommandLine.java
CommandLine.addSwitch
public void addSwitch(String option, String description) { """ Add a command line switch. This method is for adding options that do not require an argument. @param option the option, must start with "-" @param description single line description of the option """ optionList.add(option); optionDescriptionMap.put(option, description); if (option.length() > maxWidth) { maxWidth = option.length(); } }
java
public void addSwitch(String option, String description) { optionList.add(option); optionDescriptionMap.put(option, description); if (option.length() > maxWidth) { maxWidth = option.length(); } }
[ "public", "void", "addSwitch", "(", "String", "option", ",", "String", "description", ")", "{", "optionList", ".", "add", "(", "option", ")", ";", "optionDescriptionMap", ".", "put", "(", "option", ",", "description", ")", ";", "if", "(", "option", ".", "length", "(", ")", ">", "maxWidth", ")", "{", "maxWidth", "=", "option", ".", "length", "(", ")", ";", "}", "}" ]
Add a command line switch. This method is for adding options that do not require an argument. @param option the option, must start with "-" @param description single line description of the option
[ "Add", "a", "command", "line", "switch", ".", "This", "method", "is", "for", "adding", "options", "that", "do", "not", "require", "an", "argument", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/config/CommandLine.java#L94-L101
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java
CommonOps_DDF2.extractColumn
public static DMatrix2 extractColumn( DMatrix2x2 a , int column , DMatrix2 out ) { """ Extracts the column from the matrix a. @param a Input matrix @param column Which column is to be extracted @param out output. Storage for the extracted column. If null then a new vector will be returned. @return The extracted column. """ if( out == null) out = new DMatrix2(); switch( column ) { case 0: out.a1 = a.a11; out.a2 = a.a21; break; case 1: out.a1 = a.a12; out.a2 = a.a22; break; default: throw new IllegalArgumentException("Out of bounds column. column = "+column); } return out; }
java
public static DMatrix2 extractColumn( DMatrix2x2 a , int column , DMatrix2 out ) { if( out == null) out = new DMatrix2(); switch( column ) { case 0: out.a1 = a.a11; out.a2 = a.a21; break; case 1: out.a1 = a.a12; out.a2 = a.a22; break; default: throw new IllegalArgumentException("Out of bounds column. column = "+column); } return out; }
[ "public", "static", "DMatrix2", "extractColumn", "(", "DMatrix2x2", "a", ",", "int", "column", ",", "DMatrix2", "out", ")", "{", "if", "(", "out", "==", "null", ")", "out", "=", "new", "DMatrix2", "(", ")", ";", "switch", "(", "column", ")", "{", "case", "0", ":", "out", ".", "a1", "=", "a", ".", "a11", ";", "out", ".", "a2", "=", "a", ".", "a21", ";", "break", ";", "case", "1", ":", "out", ".", "a1", "=", "a", ".", "a12", ";", "out", ".", "a2", "=", "a", ".", "a22", ";", "break", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Out of bounds column. column = \"", "+", "column", ")", ";", "}", "return", "out", ";", "}" ]
Extracts the column from the matrix a. @param a Input matrix @param column Which column is to be extracted @param out output. Storage for the extracted column. If null then a new vector will be returned. @return The extracted column.
[ "Extracts", "the", "column", "from", "the", "matrix", "a", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java#L1181-L1196
alkacon/opencms-core
src/org/opencms/cmis/CmsCmisRelationHelper.java
CmsCmisRelationHelper.createKey
protected static String createKey(CmsUUID source, CmsUUID target, String relType) { """ Creates a relation id string from the source and target ids and a relation type.<p> @param source the source id @param target the target id @param relType the relation type @return the relation id """ return RELATION_ID_PREFIX + source + "_" + target + "_" + relType; }
java
protected static String createKey(CmsUUID source, CmsUUID target, String relType) { return RELATION_ID_PREFIX + source + "_" + target + "_" + relType; }
[ "protected", "static", "String", "createKey", "(", "CmsUUID", "source", ",", "CmsUUID", "target", ",", "String", "relType", ")", "{", "return", "RELATION_ID_PREFIX", "+", "source", "+", "\"_\"", "+", "target", "+", "\"_\"", "+", "relType", ";", "}" ]
Creates a relation id string from the source and target ids and a relation type.<p> @param source the source id @param target the target id @param relType the relation type @return the relation id
[ "Creates", "a", "relation", "id", "string", "from", "the", "source", "and", "target", "ids", "and", "a", "relation", "type", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/cmis/CmsCmisRelationHelper.java#L259-L262
flow/commons
src/main/java/com/flowpowered/commons/hashing/Int21TripleHashed.java
Int21TripleHashed.key
public static long key(int x, int y, int z) { """ Packs the most significant and the twenty least significant of each int into a <code>long</code> @param x an <code>int</code> value @param y an <code>int</code> value @param z an <code>int</code> value @return the most significant and the twenty least significant of each int packed into a <code>long</code> """ return ((long) ((x >> 11) & 0x100000 | x & 0xFFFFF)) << 42 | ((long) ((y >> 11) & 0x100000 | y & 0xFFFFF)) << 21 | ((z >> 11) & 0x100000 | z & 0xFFFFF); }
java
public static long key(int x, int y, int z) { return ((long) ((x >> 11) & 0x100000 | x & 0xFFFFF)) << 42 | ((long) ((y >> 11) & 0x100000 | y & 0xFFFFF)) << 21 | ((z >> 11) & 0x100000 | z & 0xFFFFF); }
[ "public", "static", "long", "key", "(", "int", "x", ",", "int", "y", ",", "int", "z", ")", "{", "return", "(", "(", "long", ")", "(", "(", "x", ">>", "11", ")", "&", "0x100000", "|", "x", "&", "0xFFFFF", ")", ")", "<<", "42", "|", "(", "(", "long", ")", "(", "(", "y", ">>", "11", ")", "&", "0x100000", "|", "y", "&", "0xFFFFF", ")", ")", "<<", "21", "|", "(", "(", "z", ">>", "11", ")", "&", "0x100000", "|", "z", "&", "0xFFFFF", ")", ";", "}" ]
Packs the most significant and the twenty least significant of each int into a <code>long</code> @param x an <code>int</code> value @param y an <code>int</code> value @param z an <code>int</code> value @return the most significant and the twenty least significant of each int packed into a <code>long</code>
[ "Packs", "the", "most", "significant", "and", "the", "twenty", "least", "significant", "of", "each", "int", "into", "a", "<code", ">", "long<", "/", "code", ">" ]
train
https://github.com/flow/commons/blob/0690efdac06fd728fcd7e9cf10f2b1319379c45b/src/main/java/com/flowpowered/commons/hashing/Int21TripleHashed.java#L38-L40
exoplatform/jcr
exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/MembershipTypeHandlerImpl.java
MembershipTypeHandlerImpl.getOrCreateMembershipTypeNode
private Node getOrCreateMembershipTypeNode(Session session, MembershipTypeImpl mType) throws Exception { """ Creates and returns membership type node. If node already exists it will be returned otherwise the new one will be created. """ try { return mType.getInternalId() != null ? session.getNodeByUUID(mType.getInternalId()) : utils .getMembershipTypeNode(session, mType.getName()); } catch (ItemNotFoundException e) { return createNewMembershipTypeNode(session, mType); } catch (PathNotFoundException e) { return createNewMembershipTypeNode(session, mType); } }
java
private Node getOrCreateMembershipTypeNode(Session session, MembershipTypeImpl mType) throws Exception { try { return mType.getInternalId() != null ? session.getNodeByUUID(mType.getInternalId()) : utils .getMembershipTypeNode(session, mType.getName()); } catch (ItemNotFoundException e) { return createNewMembershipTypeNode(session, mType); } catch (PathNotFoundException e) { return createNewMembershipTypeNode(session, mType); } }
[ "private", "Node", "getOrCreateMembershipTypeNode", "(", "Session", "session", ",", "MembershipTypeImpl", "mType", ")", "throws", "Exception", "{", "try", "{", "return", "mType", ".", "getInternalId", "(", ")", "!=", "null", "?", "session", ".", "getNodeByUUID", "(", "mType", ".", "getInternalId", "(", ")", ")", ":", "utils", ".", "getMembershipTypeNode", "(", "session", ",", "mType", ".", "getName", "(", ")", ")", ";", "}", "catch", "(", "ItemNotFoundException", "e", ")", "{", "return", "createNewMembershipTypeNode", "(", "session", ",", "mType", ")", ";", "}", "catch", "(", "PathNotFoundException", "e", ")", "{", "return", "createNewMembershipTypeNode", "(", "session", ",", "mType", ")", ";", "}", "}" ]
Creates and returns membership type node. If node already exists it will be returned otherwise the new one will be created.
[ "Creates", "and", "returns", "membership", "type", "node", ".", "If", "node", "already", "exists", "it", "will", "be", "returned", "otherwise", "the", "new", "one", "will", "be", "created", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/MembershipTypeHandlerImpl.java#L352-L367
Stratio/deep-spark
deep-cassandra/src/main/java/com/stratio/deep/cassandra/cql/RangeUtils.java
RangeUtils.getSplits
public static List<DeepTokenRange> getSplits(CassandraDeepJobConfig config) { """ Returns the token ranges that will be mapped to Spark partitions. @param config the Deep configuration object. @return the list of computed token ranges. """ Map<String, Iterable<Comparable>> tokens = new HashMap<>(); IPartitioner p = getPartitioner(config); Pair<Session, String> sessionWithHost = CassandraClientProvider.getSession( config.getHost(), config, false); String queryLocal = "select tokens from system.local"; tokens.putAll(fetchTokens(queryLocal, sessionWithHost, p)); String queryPeers = "select peer, tokens from system.peers"; tokens.putAll(fetchTokens(queryPeers, sessionWithHost, p)); List<DeepTokenRange> merged = mergeTokenRanges(tokens, sessionWithHost.left, p); return splitRanges(merged, p, config.getBisectFactor()); }
java
public static List<DeepTokenRange> getSplits(CassandraDeepJobConfig config) { Map<String, Iterable<Comparable>> tokens = new HashMap<>(); IPartitioner p = getPartitioner(config); Pair<Session, String> sessionWithHost = CassandraClientProvider.getSession( config.getHost(), config, false); String queryLocal = "select tokens from system.local"; tokens.putAll(fetchTokens(queryLocal, sessionWithHost, p)); String queryPeers = "select peer, tokens from system.peers"; tokens.putAll(fetchTokens(queryPeers, sessionWithHost, p)); List<DeepTokenRange> merged = mergeTokenRanges(tokens, sessionWithHost.left, p); return splitRanges(merged, p, config.getBisectFactor()); }
[ "public", "static", "List", "<", "DeepTokenRange", ">", "getSplits", "(", "CassandraDeepJobConfig", "config", ")", "{", "Map", "<", "String", ",", "Iterable", "<", "Comparable", ">", ">", "tokens", "=", "new", "HashMap", "<>", "(", ")", ";", "IPartitioner", "p", "=", "getPartitioner", "(", "config", ")", ";", "Pair", "<", "Session", ",", "String", ">", "sessionWithHost", "=", "CassandraClientProvider", ".", "getSession", "(", "config", ".", "getHost", "(", ")", ",", "config", ",", "false", ")", ";", "String", "queryLocal", "=", "\"select tokens from system.local\"", ";", "tokens", ".", "putAll", "(", "fetchTokens", "(", "queryLocal", ",", "sessionWithHost", ",", "p", ")", ")", ";", "String", "queryPeers", "=", "\"select peer, tokens from system.peers\"", ";", "tokens", ".", "putAll", "(", "fetchTokens", "(", "queryPeers", ",", "sessionWithHost", ",", "p", ")", ")", ";", "List", "<", "DeepTokenRange", ">", "merged", "=", "mergeTokenRanges", "(", "tokens", ",", "sessionWithHost", ".", "left", ",", "p", ")", ";", "return", "splitRanges", "(", "merged", ",", "p", ",", "config", ".", "getBisectFactor", "(", ")", ")", ";", "}" ]
Returns the token ranges that will be mapped to Spark partitions. @param config the Deep configuration object. @return the list of computed token ranges.
[ "Returns", "the", "token", "ranges", "that", "will", "be", "mapped", "to", "Spark", "partitions", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-cassandra/src/main/java/com/stratio/deep/cassandra/cql/RangeUtils.java#L159-L175
anotheria/moskito
moskito-core/src/main/java/net/anotheria/moskito/core/predefined/PageInBrowserStats.java
PageInBrowserStats.getWindowMaxLoadTime
public long getWindowMaxLoadTime(final String intervalName, final TimeUnit unit) { """ Returns web page maximum load time for given interval and {@link TimeUnit}. @param intervalName name of the interval @param unit {@link TimeUnit} @return web page maximum load time """ final long max = windowMaxLoadTime.getValueAsLong(intervalName); return max == Constants.MAX_TIME_DEFAULT ? max : unit.transformMillis(max); }
java
public long getWindowMaxLoadTime(final String intervalName, final TimeUnit unit) { final long max = windowMaxLoadTime.getValueAsLong(intervalName); return max == Constants.MAX_TIME_DEFAULT ? max : unit.transformMillis(max); }
[ "public", "long", "getWindowMaxLoadTime", "(", "final", "String", "intervalName", ",", "final", "TimeUnit", "unit", ")", "{", "final", "long", "max", "=", "windowMaxLoadTime", ".", "getValueAsLong", "(", "intervalName", ")", ";", "return", "max", "==", "Constants", ".", "MAX_TIME_DEFAULT", "?", "max", ":", "unit", ".", "transformMillis", "(", "max", ")", ";", "}" ]
Returns web page maximum load time for given interval and {@link TimeUnit}. @param intervalName name of the interval @param unit {@link TimeUnit} @return web page maximum load time
[ "Returns", "web", "page", "maximum", "load", "time", "for", "given", "interval", "and", "{", "@link", "TimeUnit", "}", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/predefined/PageInBrowserStats.java#L187-L190
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/scheduler/QuartzScheduler.java
QuartzScheduler.pauseJobIfPresent
public synchronized boolean pauseJobIfPresent(final String jobName, final String groupName) throws SchedulerException { """ Pause a job if it's present. @param jobName @param groupName @return true if job has been paused, no if job doesn't exist. @throws SchedulerException """ if (ifJobExist(jobName, groupName)) { this.scheduler.pauseJob(new JobKey(jobName, groupName)); return true; } else { return false; } }
java
public synchronized boolean pauseJobIfPresent(final String jobName, final String groupName) throws SchedulerException { if (ifJobExist(jobName, groupName)) { this.scheduler.pauseJob(new JobKey(jobName, groupName)); return true; } else { return false; } }
[ "public", "synchronized", "boolean", "pauseJobIfPresent", "(", "final", "String", "jobName", ",", "final", "String", "groupName", ")", "throws", "SchedulerException", "{", "if", "(", "ifJobExist", "(", "jobName", ",", "groupName", ")", ")", "{", "this", ".", "scheduler", ".", "pauseJob", "(", "new", "JobKey", "(", "jobName", ",", "groupName", ")", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Pause a job if it's present. @param jobName @param groupName @return true if job has been paused, no if job doesn't exist. @throws SchedulerException
[ "Pause", "a", "job", "if", "it", "s", "present", "." ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-web-server/src/main/java/azkaban/scheduler/QuartzScheduler.java#L95-L103
alkacon/opencms-core
src/org/opencms/ade/configuration/CmsConfigurationCache.java
CmsConfigurationCache.loadElementViews
protected Map<CmsUUID, CmsElementView> loadElementViews() { """ Loads the available element views.<p> @return the element views """ List<CmsElementView> views = new ArrayList<CmsElementView>(); if (m_cms.existsResource("/")) { views.add(CmsElementView.DEFAULT_ELEMENT_VIEW); try { @SuppressWarnings("deprecation") CmsResourceFilter filter = CmsResourceFilter.ONLY_VISIBLE_NO_DELETED.addRequireType( m_elementViewType.getTypeId()); List<CmsResource> groups = m_cms.readResources("/", filter); for (CmsResource res : groups) { try { views.add(new CmsElementView(m_cms, res)); } catch (Exception e) { LOG.error(e.getMessage(), e); } } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } Collections.sort(views, new CmsElementView.ElementViewComparator()); Map<CmsUUID, CmsElementView> elementViews = new LinkedHashMap<CmsUUID, CmsElementView>(); for (CmsElementView view : views) { elementViews.put(view.getId(), view); } return elementViews; } return null; }
java
protected Map<CmsUUID, CmsElementView> loadElementViews() { List<CmsElementView> views = new ArrayList<CmsElementView>(); if (m_cms.existsResource("/")) { views.add(CmsElementView.DEFAULT_ELEMENT_VIEW); try { @SuppressWarnings("deprecation") CmsResourceFilter filter = CmsResourceFilter.ONLY_VISIBLE_NO_DELETED.addRequireType( m_elementViewType.getTypeId()); List<CmsResource> groups = m_cms.readResources("/", filter); for (CmsResource res : groups) { try { views.add(new CmsElementView(m_cms, res)); } catch (Exception e) { LOG.error(e.getMessage(), e); } } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } Collections.sort(views, new CmsElementView.ElementViewComparator()); Map<CmsUUID, CmsElementView> elementViews = new LinkedHashMap<CmsUUID, CmsElementView>(); for (CmsElementView view : views) { elementViews.put(view.getId(), view); } return elementViews; } return null; }
[ "protected", "Map", "<", "CmsUUID", ",", "CmsElementView", ">", "loadElementViews", "(", ")", "{", "List", "<", "CmsElementView", ">", "views", "=", "new", "ArrayList", "<", "CmsElementView", ">", "(", ")", ";", "if", "(", "m_cms", ".", "existsResource", "(", "\"/\"", ")", ")", "{", "views", ".", "add", "(", "CmsElementView", ".", "DEFAULT_ELEMENT_VIEW", ")", ";", "try", "{", "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "CmsResourceFilter", "filter", "=", "CmsResourceFilter", ".", "ONLY_VISIBLE_NO_DELETED", ".", "addRequireType", "(", "m_elementViewType", ".", "getTypeId", "(", ")", ")", ";", "List", "<", "CmsResource", ">", "groups", "=", "m_cms", ".", "readResources", "(", "\"/\"", ",", "filter", ")", ";", "for", "(", "CmsResource", "res", ":", "groups", ")", "{", "try", "{", "views", ".", "add", "(", "new", "CmsElementView", "(", "m_cms", ",", "res", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "}", "catch", "(", "CmsException", "e", ")", "{", "LOG", ".", "error", "(", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "}", "Collections", ".", "sort", "(", "views", ",", "new", "CmsElementView", ".", "ElementViewComparator", "(", ")", ")", ";", "Map", "<", "CmsUUID", ",", "CmsElementView", ">", "elementViews", "=", "new", "LinkedHashMap", "<", "CmsUUID", ",", "CmsElementView", ">", "(", ")", ";", "for", "(", "CmsElementView", "view", ":", "views", ")", "{", "elementViews", ".", "put", "(", "view", ".", "getId", "(", ")", ",", "view", ")", ";", "}", "return", "elementViews", ";", "}", "return", "null", ";", "}" ]
Loads the available element views.<p> @return the element views
[ "Loads", "the", "available", "element", "views", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsConfigurationCache.java#L477-L505
osmdroid/osmdroid
osmdroid-android/src/main/java/org/osmdroid/util/SegmentClipper.java
SegmentClipper.getClosestCorner
private int getClosestCorner(final long pX0, final long pY0, final long pX1, final long pY1) { """ Gets the clip area corner which is the closest to the given segment @since 6.0.0 We have a clip area and we have a segment with no intersection with this clip area. The question is: how do we clip this segment? If we only clip both segment ends, we may end up with a (min,min) x (max,max) clip approximation that displays a backslash on the screen. The idea is to compute the clip area corner which is the closest to the segment, and to use it as a clip step. Which will do something like: (min,min)[first segment point] x (min,max)[closest corner] x (max,max)[second segment point] or (min,min)[first segment point] x (max,min)[closest corner] x (max,max)[second segment point] """ double min = Double.MAX_VALUE; int corner = 0; for (int i = 0 ; i < cornerX.length ; i ++) { final double distance = Distance.getSquaredDistanceToSegment( cornerX[i], cornerY[i], pX0, pY0, pX1, pY1); if (min > distance) { min = distance; corner = i; } } return corner; }
java
private int getClosestCorner(final long pX0, final long pY0, final long pX1, final long pY1) { double min = Double.MAX_VALUE; int corner = 0; for (int i = 0 ; i < cornerX.length ; i ++) { final double distance = Distance.getSquaredDistanceToSegment( cornerX[i], cornerY[i], pX0, pY0, pX1, pY1); if (min > distance) { min = distance; corner = i; } } return corner; }
[ "private", "int", "getClosestCorner", "(", "final", "long", "pX0", ",", "final", "long", "pY0", ",", "final", "long", "pX1", ",", "final", "long", "pY1", ")", "{", "double", "min", "=", "Double", ".", "MAX_VALUE", ";", "int", "corner", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "cornerX", ".", "length", ";", "i", "++", ")", "{", "final", "double", "distance", "=", "Distance", ".", "getSquaredDistanceToSegment", "(", "cornerX", "[", "i", "]", ",", "cornerY", "[", "i", "]", ",", "pX0", ",", "pY0", ",", "pX1", ",", "pY1", ")", ";", "if", "(", "min", ">", "distance", ")", "{", "min", "=", "distance", ";", "corner", "=", "i", ";", "}", "}", "return", "corner", ";", "}" ]
Gets the clip area corner which is the closest to the given segment @since 6.0.0 We have a clip area and we have a segment with no intersection with this clip area. The question is: how do we clip this segment? If we only clip both segment ends, we may end up with a (min,min) x (max,max) clip approximation that displays a backslash on the screen. The idea is to compute the clip area corner which is the closest to the segment, and to use it as a clip step. Which will do something like: (min,min)[first segment point] x (min,max)[closest corner] x (max,max)[second segment point] or (min,min)[first segment point] x (max,min)[closest corner] x (max,max)[second segment point]
[ "Gets", "the", "clip", "area", "corner", "which", "is", "the", "closest", "to", "the", "given", "segment" ]
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/util/SegmentClipper.java#L220-L233
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WColumnRenderer.java
WColumnRenderer.doRender
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { """ Paints the given WButton. @param component the WColumn to paint. @param renderContext the RenderContext to paint to. """ WColumn col = (WColumn) component; XmlStringBuilder xml = renderContext.getWriter(); xml.appendTagOpen("ui:column"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", component.getHtmlClass()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); int width = col.getWidth(); xml.appendOptionalAttribute("width", width > 0, width); switch (col.getAlignment()) { case LEFT: // left is assumed if omitted break; case RIGHT: xml.appendAttribute("align", "right"); break; case CENTER: xml.appendAttribute("align", "center"); break; default: throw new IllegalArgumentException("Invalid alignment: " + col.getAlignment()); } xml.appendClose(); // Paint column contents paintChildren(col, renderContext); xml.appendEndTag("ui:column"); }
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WColumn col = (WColumn) component; XmlStringBuilder xml = renderContext.getWriter(); xml.appendTagOpen("ui:column"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", component.getHtmlClass()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); int width = col.getWidth(); xml.appendOptionalAttribute("width", width > 0, width); switch (col.getAlignment()) { case LEFT: // left is assumed if omitted break; case RIGHT: xml.appendAttribute("align", "right"); break; case CENTER: xml.appendAttribute("align", "center"); break; default: throw new IllegalArgumentException("Invalid alignment: " + col.getAlignment()); } xml.appendClose(); // Paint column contents paintChildren(col, renderContext); xml.appendEndTag("ui:column"); }
[ "@", "Override", "public", "void", "doRender", "(", "final", "WComponent", "component", ",", "final", "WebXmlRenderContext", "renderContext", ")", "{", "WColumn", "col", "=", "(", "WColumn", ")", "component", ";", "XmlStringBuilder", "xml", "=", "renderContext", ".", "getWriter", "(", ")", ";", "xml", ".", "appendTagOpen", "(", "\"ui:column\"", ")", ";", "xml", ".", "appendAttribute", "(", "\"id\"", ",", "component", ".", "getId", "(", ")", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"class\"", ",", "component", ".", "getHtmlClass", "(", ")", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"track\"", ",", "component", ".", "isTracking", "(", ")", ",", "\"true\"", ")", ";", "int", "width", "=", "col", ".", "getWidth", "(", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"width\"", ",", "width", ">", "0", ",", "width", ")", ";", "switch", "(", "col", ".", "getAlignment", "(", ")", ")", "{", "case", "LEFT", ":", "// left is assumed if omitted", "break", ";", "case", "RIGHT", ":", "xml", ".", "appendAttribute", "(", "\"align\"", ",", "\"right\"", ")", ";", "break", ";", "case", "CENTER", ":", "xml", ".", "appendAttribute", "(", "\"align\"", ",", "\"center\"", ")", ";", "break", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Invalid alignment: \"", "+", "col", ".", "getAlignment", "(", ")", ")", ";", "}", "xml", ".", "appendClose", "(", ")", ";", "// Paint column contents", "paintChildren", "(", "col", ",", "renderContext", ")", ";", "xml", ".", "appendEndTag", "(", "\"ui:column\"", ")", ";", "}" ]
Paints the given WButton. @param component the WColumn to paint. @param renderContext the RenderContext to paint to.
[ "Paints", "the", "given", "WButton", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WColumnRenderer.java#L23-L58
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/preprocessor/serializer/NormalizerSerializer.java
NormalizerSerializer.writeHeader
private void writeHeader(OutputStream stream, Header header) throws IOException { """ Write the data header @param stream the output stream @param header the header to write @throws IOException """ DataOutputStream dos = new DataOutputStream(stream); dos.writeUTF(HEADER); // Write the current version dos.writeInt(1); // Write the normalizer opType dos.writeUTF(header.normalizerType.toString()); // If the header contains a custom class opName, write that too if (header.customStrategyClass != null) { dos.writeUTF(header.customStrategyClass.getName()); } }
java
private void writeHeader(OutputStream stream, Header header) throws IOException { DataOutputStream dos = new DataOutputStream(stream); dos.writeUTF(HEADER); // Write the current version dos.writeInt(1); // Write the normalizer opType dos.writeUTF(header.normalizerType.toString()); // If the header contains a custom class opName, write that too if (header.customStrategyClass != null) { dos.writeUTF(header.customStrategyClass.getName()); } }
[ "private", "void", "writeHeader", "(", "OutputStream", "stream", ",", "Header", "header", ")", "throws", "IOException", "{", "DataOutputStream", "dos", "=", "new", "DataOutputStream", "(", "stream", ")", ";", "dos", ".", "writeUTF", "(", "HEADER", ")", ";", "// Write the current version", "dos", ".", "writeInt", "(", "1", ")", ";", "// Write the normalizer opType", "dos", ".", "writeUTF", "(", "header", ".", "normalizerType", ".", "toString", "(", ")", ")", ";", "// If the header contains a custom class opName, write that too", "if", "(", "header", ".", "customStrategyClass", "!=", "null", ")", "{", "dos", ".", "writeUTF", "(", "header", ".", "customStrategyClass", ".", "getName", "(", ")", ")", ";", "}", "}" ]
Write the data header @param stream the output stream @param header the header to write @throws IOException
[ "Write", "the", "data", "header" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/preprocessor/serializer/NormalizerSerializer.java#L254-L268
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/api/MCAAuthorizationManager.java
MCAAuthorizationManager.logout
public void logout(Context context, ResponseListener listener) { """ logs out user @param context Android Activity that will handle the authorization (like facebook or google) @param listener Response listener """ clearAuthorizationData(); authorizationProcessManager.logout(context, listener); }
java
public void logout(Context context, ResponseListener listener){ clearAuthorizationData(); authorizationProcessManager.logout(context, listener); }
[ "public", "void", "logout", "(", "Context", "context", ",", "ResponseListener", "listener", ")", "{", "clearAuthorizationData", "(", ")", ";", "authorizationProcessManager", ".", "logout", "(", "context", ",", "listener", ")", ";", "}" ]
logs out user @param context Android Activity that will handle the authorization (like facebook or google) @param listener Response listener
[ "logs", "out", "user" ]
train
https://github.com/ibm-bluemix-mobile-services/bms-clientsdk-android-core/blob/8db4f00d0d564792397bfc0e5bd57d52a238b858/lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/api/MCAAuthorizationManager.java#L332-L335
Azure/azure-sdk-for-java
sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/DatabaseVulnerabilityAssessmentScansInner.java
DatabaseVulnerabilityAssessmentScansInner.beginInitiateScan
public void beginInitiateScan(String resourceGroupName, String serverName, String databaseName, String scanId) { """ Executes a Vulnerability Assessment database scan. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database. @param scanId The vulnerability assessment scan Id of the scan to retrieve. @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 """ beginInitiateScanWithServiceResponseAsync(resourceGroupName, serverName, databaseName, scanId).toBlocking().single().body(); }
java
public void beginInitiateScan(String resourceGroupName, String serverName, String databaseName, String scanId) { beginInitiateScanWithServiceResponseAsync(resourceGroupName, serverName, databaseName, scanId).toBlocking().single().body(); }
[ "public", "void", "beginInitiateScan", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "databaseName", ",", "String", "scanId", ")", "{", "beginInitiateScanWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "databaseName", ",", "scanId", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Executes a Vulnerability Assessment database scan. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database. @param scanId The vulnerability assessment scan Id of the scan to retrieve. @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
[ "Executes", "a", "Vulnerability", "Assessment", "database", "scan", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/DatabaseVulnerabilityAssessmentScansInner.java#L414-L416
VoltDB/voltdb
third_party/java/src/com/google_voltpatches/common/collect/ForwardingSortedMap.java
ForwardingSortedMap.standardContainsKey
@Override @Beta protected boolean standardContainsKey(@Nullable Object key) { """ A sensible definition of {@link #containsKey} in terms of the {@code firstKey()} method of {@link #tailMap}. If you override {@link #tailMap}, you may wish to override {@link #containsKey} to forward to this implementation. @since 7.0 """ try { // any CCE will be caught @SuppressWarnings("unchecked") SortedMap<Object, V> self = (SortedMap<Object, V>) this; Object ceilingKey = self.tailMap(key).firstKey(); return unsafeCompare(ceilingKey, key) == 0; } catch (ClassCastException e) { return false; } catch (NoSuchElementException e) { return false; } catch (NullPointerException e) { return false; } }
java
@Override @Beta protected boolean standardContainsKey(@Nullable Object key) { try { // any CCE will be caught @SuppressWarnings("unchecked") SortedMap<Object, V> self = (SortedMap<Object, V>) this; Object ceilingKey = self.tailMap(key).firstKey(); return unsafeCompare(ceilingKey, key) == 0; } catch (ClassCastException e) { return false; } catch (NoSuchElementException e) { return false; } catch (NullPointerException e) { return false; } }
[ "@", "Override", "@", "Beta", "protected", "boolean", "standardContainsKey", "(", "@", "Nullable", "Object", "key", ")", "{", "try", "{", "// any CCE will be caught", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "SortedMap", "<", "Object", ",", "V", ">", "self", "=", "(", "SortedMap", "<", "Object", ",", "V", ">", ")", "this", ";", "Object", "ceilingKey", "=", "self", ".", "tailMap", "(", "key", ")", ".", "firstKey", "(", ")", ";", "return", "unsafeCompare", "(", "ceilingKey", ",", "key", ")", "==", "0", ";", "}", "catch", "(", "ClassCastException", "e", ")", "{", "return", "false", ";", "}", "catch", "(", "NoSuchElementException", "e", ")", "{", "return", "false", ";", "}", "catch", "(", "NullPointerException", "e", ")", "{", "return", "false", ";", "}", "}" ]
A sensible definition of {@link #containsKey} in terms of the {@code firstKey()} method of {@link #tailMap}. If you override {@link #tailMap}, you may wish to override {@link #containsKey} to forward to this implementation. @since 7.0
[ "A", "sensible", "definition", "of", "{", "@link", "#containsKey", "}", "in", "terms", "of", "the", "{", "@code", "firstKey", "()", "}", "method", "of", "{", "@link", "#tailMap", "}", ".", "If", "you", "override", "{", "@link", "#tailMap", "}", "you", "may", "wish", "to", "override", "{", "@link", "#containsKey", "}", "to", "forward", "to", "this", "implementation", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/com/google_voltpatches/common/collect/ForwardingSortedMap.java#L132-L148
wcm-io/wcm-io-handler
link/src/main/java/io/wcm/handler/link/type/InternalCrossContextLinkType.java
InternalCrossContextLinkType.getSyntheticLinkResource
public static @NotNull Resource getSyntheticLinkResource(@NotNull ResourceResolver resourceResolver, @NotNull String pageRef) { """ Get synthetic link resource for this link type. @param resourceResolver Resource resolver @param pageRef Path to target page @return Synthetic link resource """ Map<String, Object> map = new HashMap<>(); map.put(LinkNameConstants.PN_LINK_TYPE, ID); map.put(LinkNameConstants.PN_LINK_CROSSCONTEXT_CONTENT_REF, pageRef); return new SyntheticLinkResource(resourceResolver, map); }
java
public static @NotNull Resource getSyntheticLinkResource(@NotNull ResourceResolver resourceResolver, @NotNull String pageRef) { Map<String, Object> map = new HashMap<>(); map.put(LinkNameConstants.PN_LINK_TYPE, ID); map.put(LinkNameConstants.PN_LINK_CROSSCONTEXT_CONTENT_REF, pageRef); return new SyntheticLinkResource(resourceResolver, map); }
[ "public", "static", "@", "NotNull", "Resource", "getSyntheticLinkResource", "(", "@", "NotNull", "ResourceResolver", "resourceResolver", ",", "@", "NotNull", "String", "pageRef", ")", "{", "Map", "<", "String", ",", "Object", ">", "map", "=", "new", "HashMap", "<>", "(", ")", ";", "map", ".", "put", "(", "LinkNameConstants", ".", "PN_LINK_TYPE", ",", "ID", ")", ";", "map", ".", "put", "(", "LinkNameConstants", ".", "PN_LINK_CROSSCONTEXT_CONTENT_REF", ",", "pageRef", ")", ";", "return", "new", "SyntheticLinkResource", "(", "resourceResolver", ",", "map", ")", ";", "}" ]
Get synthetic link resource for this link type. @param resourceResolver Resource resolver @param pageRef Path to target page @return Synthetic link resource
[ "Get", "synthetic", "link", "resource", "for", "this", "link", "type", "." ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/link/src/main/java/io/wcm/handler/link/type/InternalCrossContextLinkType.java#L116-L121
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java
ArrayUtil.insert
@SuppressWarnings("unchecked") public static <T> Object insert(Object array, int index, T... newElements) { """ 将新元素插入到到已有数组中的某个位置<br> 添加新元素会生成一个新的数组,不影响原数组<br> 如果插入位置为为负数,从原数组从后向前计数,若大于原数组长度,则空白处用null填充 @param <T> 数组元素类型 @param array 已有数组 @param index 插入位置,此位置为对应此位置元素之前的空档 @param newElements 新元素 @return 新数组 @since 4.0.8 """ if (isEmpty(newElements)) { return array; } if(isEmpty(array)) { return newElements; } final int len = length(array); if (index < 0) { index = (index % len) + len; } final T[] result = newArray(array.getClass().getComponentType(), Math.max(len, index) + newElements.length); System.arraycopy(array, 0, result, 0, Math.min(len, index)); System.arraycopy(newElements, 0, result, index, newElements.length); if (index < len) { System.arraycopy(array, index, result, index + newElements.length, len - index); } return result; }
java
@SuppressWarnings("unchecked") public static <T> Object insert(Object array, int index, T... newElements) { if (isEmpty(newElements)) { return array; } if(isEmpty(array)) { return newElements; } final int len = length(array); if (index < 0) { index = (index % len) + len; } final T[] result = newArray(array.getClass().getComponentType(), Math.max(len, index) + newElements.length); System.arraycopy(array, 0, result, 0, Math.min(len, index)); System.arraycopy(newElements, 0, result, index, newElements.length); if (index < len) { System.arraycopy(array, index, result, index + newElements.length, len - index); } return result; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "Object", "insert", "(", "Object", "array", ",", "int", "index", ",", "T", "...", "newElements", ")", "{", "if", "(", "isEmpty", "(", "newElements", ")", ")", "{", "return", "array", ";", "}", "if", "(", "isEmpty", "(", "array", ")", ")", "{", "return", "newElements", ";", "}", "final", "int", "len", "=", "length", "(", "array", ")", ";", "if", "(", "index", "<", "0", ")", "{", "index", "=", "(", "index", "%", "len", ")", "+", "len", ";", "}", "final", "T", "[", "]", "result", "=", "newArray", "(", "array", ".", "getClass", "(", ")", ".", "getComponentType", "(", ")", ",", "Math", ".", "max", "(", "len", ",", "index", ")", "+", "newElements", ".", "length", ")", ";", "System", ".", "arraycopy", "(", "array", ",", "0", ",", "result", ",", "0", ",", "Math", ".", "min", "(", "len", ",", "index", ")", ")", ";", "System", ".", "arraycopy", "(", "newElements", ",", "0", ",", "result", ",", "index", ",", "newElements", ".", "length", ")", ";", "if", "(", "index", "<", "len", ")", "{", "System", ".", "arraycopy", "(", "array", ",", "index", ",", "result", ",", "index", "+", "newElements", ".", "length", ",", "len", "-", "index", ")", ";", "}", "return", "result", ";", "}" ]
将新元素插入到到已有数组中的某个位置<br> 添加新元素会生成一个新的数组,不影响原数组<br> 如果插入位置为为负数,从原数组从后向前计数,若大于原数组长度,则空白处用null填充 @param <T> 数组元素类型 @param array 已有数组 @param index 插入位置,此位置为对应此位置元素之前的空档 @param newElements 新元素 @return 新数组 @since 4.0.8
[ "将新元素插入到到已有数组中的某个位置<br", ">", "添加新元素会生成一个新的数组,不影响原数组<br", ">", "如果插入位置为为负数,从原数组从后向前计数,若大于原数组长度,则空白处用null填充" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java#L473-L494
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/raw/KeyEncoder.java
KeyEncoder.encodeDesc
public static int encodeDesc(Character value, byte[] dst, int dstOffset) { """ Encodes the given Character object into exactly 1 or 3 bytes for descending order. If the Character object is never expected to be null, consider encoding as a char primitive. @param value optional Character value to encode @param dst destination for encoded bytes @param dstOffset offset into destination array @return amount of bytes written """ if (value == null) { dst[dstOffset] = NULL_BYTE_LOW; return 1; } else { dst[dstOffset] = NOT_NULL_BYTE_LOW; DataEncoder.encode((char) ~value.charValue(), dst, dstOffset + 1); return 3; } }
java
public static int encodeDesc(Character value, byte[] dst, int dstOffset) { if (value == null) { dst[dstOffset] = NULL_BYTE_LOW; return 1; } else { dst[dstOffset] = NOT_NULL_BYTE_LOW; DataEncoder.encode((char) ~value.charValue(), dst, dstOffset + 1); return 3; } }
[ "public", "static", "int", "encodeDesc", "(", "Character", "value", ",", "byte", "[", "]", "dst", ",", "int", "dstOffset", ")", "{", "if", "(", "value", "==", "null", ")", "{", "dst", "[", "dstOffset", "]", "=", "NULL_BYTE_LOW", ";", "return", "1", ";", "}", "else", "{", "dst", "[", "dstOffset", "]", "=", "NOT_NULL_BYTE_LOW", ";", "DataEncoder", ".", "encode", "(", "(", "char", ")", "~", "value", ".", "charValue", "(", ")", ",", "dst", ",", "dstOffset", "+", "1", ")", ";", "return", "3", ";", "}", "}" ]
Encodes the given Character object into exactly 1 or 3 bytes for descending order. If the Character object is never expected to be null, consider encoding as a char primitive. @param value optional Character value to encode @param dst destination for encoded bytes @param dstOffset offset into destination array @return amount of bytes written
[ "Encodes", "the", "given", "Character", "object", "into", "exactly", "1", "or", "3", "bytes", "for", "descending", "order", ".", "If", "the", "Character", "object", "is", "never", "expected", "to", "be", "null", "consider", "encoding", "as", "a", "char", "primitive", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/KeyEncoder.java#L191-L200
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringHelper.java
StringHelper.getExplodedToOrderedSet
@Nonnull @ReturnsMutableCopy public static CommonsLinkedHashSet <String> getExplodedToOrderedSet (@Nonnull final String sSep, @Nullable final String sElements) { """ Take a concatenated String and return an ordered {@link CommonsLinkedHashSet} of all elements in the passed string, using specified separator string. @param sSep The separator to use. May not be <code>null</code>. @param sElements The concatenated String to convert. May be <code>null</code> or empty. @return The ordered {@link Set} represented by the passed string. Never <code>null</code>. If the passed input string is <code>null</code> or "" an empty list is returned. """ return getExploded (sSep, sElements, -1, new CommonsLinkedHashSet <> ()); }
java
@Nonnull @ReturnsMutableCopy public static CommonsLinkedHashSet <String> getExplodedToOrderedSet (@Nonnull final String sSep, @Nullable final String sElements) { return getExploded (sSep, sElements, -1, new CommonsLinkedHashSet <> ()); }
[ "@", "Nonnull", "@", "ReturnsMutableCopy", "public", "static", "CommonsLinkedHashSet", "<", "String", ">", "getExplodedToOrderedSet", "(", "@", "Nonnull", "final", "String", "sSep", ",", "@", "Nullable", "final", "String", "sElements", ")", "{", "return", "getExploded", "(", "sSep", ",", "sElements", ",", "-", "1", ",", "new", "CommonsLinkedHashSet", "<>", "(", ")", ")", ";", "}" ]
Take a concatenated String and return an ordered {@link CommonsLinkedHashSet} of all elements in the passed string, using specified separator string. @param sSep The separator to use. May not be <code>null</code>. @param sElements The concatenated String to convert. May be <code>null</code> or empty. @return The ordered {@link Set} represented by the passed string. Never <code>null</code>. If the passed input string is <code>null</code> or "" an empty list is returned.
[ "Take", "a", "concatenated", "String", "and", "return", "an", "ordered", "{", "@link", "CommonsLinkedHashSet", "}", "of", "all", "elements", "in", "the", "passed", "string", "using", "specified", "separator", "string", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L2314-L2320
citrusframework/citrus
modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/ReceiveMessageBuilder.java
ReceiveMessageBuilder.payloadModel
public T payloadModel(Object payload) { """ Expect this message payload as model object which is marshalled to a character sequence using the default object to xml mapper that is available in Spring bean application context. @param payload @return """ Assert.notNull(applicationContext, "Citrus application context is not initialized!"); if (!CollectionUtils.isEmpty(applicationContext.getBeansOfType(Marshaller.class))) { return payload(payload, applicationContext.getBean(Marshaller.class)); } else if (!CollectionUtils.isEmpty(applicationContext.getBeansOfType(ObjectMapper.class))) { return payload(payload, applicationContext.getBean(ObjectMapper.class)); } throw new CitrusRuntimeException("Unable to find default object mapper or marshaller in application context"); }
java
public T payloadModel(Object payload) { Assert.notNull(applicationContext, "Citrus application context is not initialized!"); if (!CollectionUtils.isEmpty(applicationContext.getBeansOfType(Marshaller.class))) { return payload(payload, applicationContext.getBean(Marshaller.class)); } else if (!CollectionUtils.isEmpty(applicationContext.getBeansOfType(ObjectMapper.class))) { return payload(payload, applicationContext.getBean(ObjectMapper.class)); } throw new CitrusRuntimeException("Unable to find default object mapper or marshaller in application context"); }
[ "public", "T", "payloadModel", "(", "Object", "payload", ")", "{", "Assert", ".", "notNull", "(", "applicationContext", ",", "\"Citrus application context is not initialized!\"", ")", ";", "if", "(", "!", "CollectionUtils", ".", "isEmpty", "(", "applicationContext", ".", "getBeansOfType", "(", "Marshaller", ".", "class", ")", ")", ")", "{", "return", "payload", "(", "payload", ",", "applicationContext", ".", "getBean", "(", "Marshaller", ".", "class", ")", ")", ";", "}", "else", "if", "(", "!", "CollectionUtils", ".", "isEmpty", "(", "applicationContext", ".", "getBeansOfType", "(", "ObjectMapper", ".", "class", ")", ")", ")", "{", "return", "payload", "(", "payload", ",", "applicationContext", ".", "getBean", "(", "ObjectMapper", ".", "class", ")", ")", ";", "}", "throw", "new", "CitrusRuntimeException", "(", "\"Unable to find default object mapper or marshaller in application context\"", ")", ";", "}" ]
Expect this message payload as model object which is marshalled to a character sequence using the default object to xml mapper that is available in Spring bean application context. @param payload @return
[ "Expect", "this", "message", "payload", "as", "model", "object", "which", "is", "marshalled", "to", "a", "character", "sequence", "using", "the", "default", "object", "to", "xml", "mapper", "that", "is", "available", "in", "Spring", "bean", "application", "context", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/ReceiveMessageBuilder.java#L263-L273
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.findLastIndexOf
public static int findLastIndexOf(Object self, int startIndex, Closure condition) { """ Iterates over the elements of an aggregate of items, starting from a specified startIndex, and returns the index of the last item that matches the condition specified in the closure. @param self the iteration object over which to iterate @param startIndex start matching from this index @param condition the matching condition @return an integer that is the index of the last matched object or -1 if no match was found @since 1.5.2 """ return findLastIndexOf(InvokerHelper.asIterator(self), startIndex, condition); }
java
public static int findLastIndexOf(Object self, int startIndex, Closure condition) { return findLastIndexOf(InvokerHelper.asIterator(self), startIndex, condition); }
[ "public", "static", "int", "findLastIndexOf", "(", "Object", "self", ",", "int", "startIndex", ",", "Closure", "condition", ")", "{", "return", "findLastIndexOf", "(", "InvokerHelper", ".", "asIterator", "(", "self", ")", ",", "startIndex", ",", "condition", ")", ";", "}" ]
Iterates over the elements of an aggregate of items, starting from a specified startIndex, and returns the index of the last item that matches the condition specified in the closure. @param self the iteration object over which to iterate @param startIndex start matching from this index @param condition the matching condition @return an integer that is the index of the last matched object or -1 if no match was found @since 1.5.2
[ "Iterates", "over", "the", "elements", "of", "an", "aggregate", "of", "items", "starting", "from", "a", "specified", "startIndex", "and", "returns", "the", "index", "of", "the", "last", "item", "that", "matches", "the", "condition", "specified", "in", "the", "closure", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L16834-L16836
monitorjbl/json-view
json-view/src/main/java/com/monitorjbl/json/JsonViewSerializer.java
JsonViewSerializer.registerCustomSerializer
@SuppressWarnings("unchecked") public <T> void registerCustomSerializer(Class<T> cls, JsonSerializer<T> forType) { """ Registering custom serializer allows to the JSonView to deal with custom serializations for certains field types.<br> This way you could register for instance a JODA serialization as a DateTimeSerializer. <br> Thus, when JSonView find a field of that type (DateTime), it will delegate the serialization to the serializer specified.<br> Example:<br> <code> JsonViewSupportFactoryBean bean = new JsonViewSupportFactoryBean( mapper ); bean.registerCustomSerializer( DateTime.class, new DateTimeSerializer() ); </code> @param <T> Type class of the serializer @param cls {@link Class} The class type you want to add a custom serializer @param forType {@link JsonSerializer} The serializer you want to apply for that type """ if(customSerializersMap == null) { customSerializersMap = new HashMap<>(); } if(cls == null) { throw new IllegalArgumentException("Class must not be null"); } else if(cls.equals(JsonView.class)) { throw new IllegalArgumentException("Class cannot be " + JsonView.class); } else if(customSerializersMap.containsKey(cls)) { throw new IllegalArgumentException("Class " + cls + " already has a serializer registered (" + customSerializersMap.get(cls) + ")"); } customSerializersMap.put(cls, (JsonSerializer<Object>) forType); }
java
@SuppressWarnings("unchecked") public <T> void registerCustomSerializer(Class<T> cls, JsonSerializer<T> forType) { if(customSerializersMap == null) { customSerializersMap = new HashMap<>(); } if(cls == null) { throw new IllegalArgumentException("Class must not be null"); } else if(cls.equals(JsonView.class)) { throw new IllegalArgumentException("Class cannot be " + JsonView.class); } else if(customSerializersMap.containsKey(cls)) { throw new IllegalArgumentException("Class " + cls + " already has a serializer registered (" + customSerializersMap.get(cls) + ")"); } customSerializersMap.put(cls, (JsonSerializer<Object>) forType); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", ">", "void", "registerCustomSerializer", "(", "Class", "<", "T", ">", "cls", ",", "JsonSerializer", "<", "T", ">", "forType", ")", "{", "if", "(", "customSerializersMap", "==", "null", ")", "{", "customSerializersMap", "=", "new", "HashMap", "<>", "(", ")", ";", "}", "if", "(", "cls", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Class must not be null\"", ")", ";", "}", "else", "if", "(", "cls", ".", "equals", "(", "JsonView", ".", "class", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Class cannot be \"", "+", "JsonView", ".", "class", ")", ";", "}", "else", "if", "(", "customSerializersMap", ".", "containsKey", "(", "cls", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Class \"", "+", "cls", "+", "\" already has a serializer registered (\"", "+", "customSerializersMap", ".", "get", "(", "cls", ")", "+", "\")\"", ")", ";", "}", "customSerializersMap", ".", "put", "(", "cls", ",", "(", "JsonSerializer", "<", "Object", ">", ")", "forType", ")", ";", "}" ]
Registering custom serializer allows to the JSonView to deal with custom serializations for certains field types.<br> This way you could register for instance a JODA serialization as a DateTimeSerializer. <br> Thus, when JSonView find a field of that type (DateTime), it will delegate the serialization to the serializer specified.<br> Example:<br> <code> JsonViewSupportFactoryBean bean = new JsonViewSupportFactoryBean( mapper ); bean.registerCustomSerializer( DateTime.class, new DateTimeSerializer() ); </code> @param <T> Type class of the serializer @param cls {@link Class} The class type you want to add a custom serializer @param forType {@link JsonSerializer} The serializer you want to apply for that type
[ "Registering", "custom", "serializer", "allows", "to", "the", "JSonView", "to", "deal", "with", "custom", "serializations", "for", "certains", "field", "types", ".", "<br", ">", "This", "way", "you", "could", "register", "for", "instance", "a", "JODA", "serialization", "as", "a", "DateTimeSerializer", ".", "<br", ">", "Thus", "when", "JSonView", "find", "a", "field", "of", "that", "type", "(", "DateTime", ")", "it", "will", "delegate", "the", "serialization", "to", "the", "serializer", "specified", ".", "<br", ">", "Example", ":", "<br", ">", "<code", ">", "JsonViewSupportFactoryBean", "bean", "=", "new", "JsonViewSupportFactoryBean", "(", "mapper", ")", ";", "bean", ".", "registerCustomSerializer", "(", "DateTime", ".", "class", "new", "DateTimeSerializer", "()", ")", ";", "<", "/", "code", ">" ]
train
https://github.com/monitorjbl/json-view/blob/c01505ac76e5416abe8af85c5816f60bd5d483ea/json-view/src/main/java/com/monitorjbl/json/JsonViewSerializer.java#L86-L101
Waxolunist/bittwiddling
src/main/java/com/vcollaborate/bitwise/BinaryStringUtils.java
BinaryStringUtils.prettyPrint
public static final String prettyPrint(final String binaryString, final char separator) { """ Returns {@code binaryString} zero-padded separated by {@code seaparator} in groups of 4. """ String paddedBinaryString = zeroPadString(binaryString); List<String> splitted = Splitter.fixedLength(4).splitToList(paddedBinaryString); return Joiner.on(separator).join(splitted); }
java
public static final String prettyPrint(final String binaryString, final char separator) { String paddedBinaryString = zeroPadString(binaryString); List<String> splitted = Splitter.fixedLength(4).splitToList(paddedBinaryString); return Joiner.on(separator).join(splitted); }
[ "public", "static", "final", "String", "prettyPrint", "(", "final", "String", "binaryString", ",", "final", "char", "separator", ")", "{", "String", "paddedBinaryString", "=", "zeroPadString", "(", "binaryString", ")", ";", "List", "<", "String", ">", "splitted", "=", "Splitter", ".", "fixedLength", "(", "4", ")", ".", "splitToList", "(", "paddedBinaryString", ")", ";", "return", "Joiner", ".", "on", "(", "separator", ")", ".", "join", "(", "splitted", ")", ";", "}" ]
Returns {@code binaryString} zero-padded separated by {@code seaparator} in groups of 4.
[ "Returns", "{" ]
train
https://github.com/Waxolunist/bittwiddling/blob/2c36342add73aab1223292d12fcff453aa3c07cd/src/main/java/com/vcollaborate/bitwise/BinaryStringUtils.java#L44-L48
NextFaze/power-adapters
power-adapters-data/src/main/java/com/nextfaze/poweradapters/data/Data.java
Data.fromList
@NonNull public static <T> Data<T> fromList(@NonNull Callable<List<? extends T>> loader) { """ Creates a {@link Data} whose elements will be populated by invoking the specified loader function in a worker thread. @param loader The function to be invoked to load the list of elements. @param <T> The type of element presented by the returned data. @return A {@linkplain Data} instance that will present the elements retrieved via the loader function. """ return fromList(loader, DataExecutors.defaultExecutor()); }
java
@NonNull public static <T> Data<T> fromList(@NonNull Callable<List<? extends T>> loader) { return fromList(loader, DataExecutors.defaultExecutor()); }
[ "@", "NonNull", "public", "static", "<", "T", ">", "Data", "<", "T", ">", "fromList", "(", "@", "NonNull", "Callable", "<", "List", "<", "?", "extends", "T", ">", ">", "loader", ")", "{", "return", "fromList", "(", "loader", ",", "DataExecutors", ".", "defaultExecutor", "(", ")", ")", ";", "}" ]
Creates a {@link Data} whose elements will be populated by invoking the specified loader function in a worker thread. @param loader The function to be invoked to load the list of elements. @param <T> The type of element presented by the returned data. @return A {@linkplain Data} instance that will present the elements retrieved via the loader function.
[ "Creates", "a", "{" ]
train
https://github.com/NextFaze/power-adapters/blob/cdf00b1b723ed9d6bcd549ae9741a19dd59651e1/power-adapters-data/src/main/java/com/nextfaze/poweradapters/data/Data.java#L516-L519
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/db/Record.java
Record.doRemoteCommand
public Object doRemoteCommand(String strCommand, Map<String, Object> properties) { """ Do a remote command (Override this with your code). @param strCommand The command to execute @param properties The properties @return Boolean.FALSE if the command was not handled, anything else if it was. """ return Boolean.FALSE; // Override this to handle this command }
java
public Object doRemoteCommand(String strCommand, Map<String, Object> properties) { return Boolean.FALSE; // Override this to handle this command }
[ "public", "Object", "doRemoteCommand", "(", "String", "strCommand", ",", "Map", "<", "String", ",", "Object", ">", "properties", ")", "{", "return", "Boolean", ".", "FALSE", ";", "// Override this to handle this command", "}" ]
Do a remote command (Override this with your code). @param strCommand The command to execute @param properties The properties @return Boolean.FALSE if the command was not handled, anything else if it was.
[ "Do", "a", "remote", "command", "(", "Override", "this", "with", "your", "code", ")", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/Record.java#L3429-L3432
strator-dev/greenpepper
greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/domain/Execution.java
Execution.newInstance
public static Execution newInstance(Specification specification, SystemUnderTest systemUnderTest, XmlReport xmlReport) { """ <p>newInstance.</p> @param specification a {@link com.greenpepper.server.domain.Specification} object. @param systemUnderTest a {@link com.greenpepper.server.domain.SystemUnderTest} object. @param xmlReport a {@link com.greenpepper.report.XmlReport} object. @return a {@link com.greenpepper.server.domain.Execution} object. """ if(xmlReport.getGlobalException() != null) { return error(specification, systemUnderTest, null, xmlReport.getGlobalException()); } Execution execution = new Execution(); execution.setExecutionDate(new Timestamp(System.currentTimeMillis())); execution.setSpecification(specification); execution.setSystemUnderTest(systemUnderTest); execution.setFailures( xmlReport.getFailure(0) ); execution.setErrors( xmlReport.getError(0) ); execution.setSuccess( xmlReport.getSuccess(0) ); execution.setIgnored( xmlReport.getIgnored(0) ); String results = xmlReport.getResults(0); if(results != null) { execution.setResults(results); } if (xmlReport.getSections(0) != null) { StringBuilder sections = new StringBuilder(); int index = 0; while (xmlReport.getSections(index) != null) { if (index > 0) sections.append(','); sections.append(xmlReport.getSections(index)); index++; } execution.setSections(sections.toString()); } return execution; }
java
public static Execution newInstance(Specification specification, SystemUnderTest systemUnderTest, XmlReport xmlReport) { if(xmlReport.getGlobalException() != null) { return error(specification, systemUnderTest, null, xmlReport.getGlobalException()); } Execution execution = new Execution(); execution.setExecutionDate(new Timestamp(System.currentTimeMillis())); execution.setSpecification(specification); execution.setSystemUnderTest(systemUnderTest); execution.setFailures( xmlReport.getFailure(0) ); execution.setErrors( xmlReport.getError(0) ); execution.setSuccess( xmlReport.getSuccess(0) ); execution.setIgnored( xmlReport.getIgnored(0) ); String results = xmlReport.getResults(0); if(results != null) { execution.setResults(results); } if (xmlReport.getSections(0) != null) { StringBuilder sections = new StringBuilder(); int index = 0; while (xmlReport.getSections(index) != null) { if (index > 0) sections.append(','); sections.append(xmlReport.getSections(index)); index++; } execution.setSections(sections.toString()); } return execution; }
[ "public", "static", "Execution", "newInstance", "(", "Specification", "specification", ",", "SystemUnderTest", "systemUnderTest", ",", "XmlReport", "xmlReport", ")", "{", "if", "(", "xmlReport", ".", "getGlobalException", "(", ")", "!=", "null", ")", "{", "return", "error", "(", "specification", ",", "systemUnderTest", ",", "null", ",", "xmlReport", ".", "getGlobalException", "(", ")", ")", ";", "}", "Execution", "execution", "=", "new", "Execution", "(", ")", ";", "execution", ".", "setExecutionDate", "(", "new", "Timestamp", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ")", ";", "execution", ".", "setSpecification", "(", "specification", ")", ";", "execution", ".", "setSystemUnderTest", "(", "systemUnderTest", ")", ";", "execution", ".", "setFailures", "(", "xmlReport", ".", "getFailure", "(", "0", ")", ")", ";", "execution", ".", "setErrors", "(", "xmlReport", ".", "getError", "(", "0", ")", ")", ";", "execution", ".", "setSuccess", "(", "xmlReport", ".", "getSuccess", "(", "0", ")", ")", ";", "execution", ".", "setIgnored", "(", "xmlReport", ".", "getIgnored", "(", "0", ")", ")", ";", "String", "results", "=", "xmlReport", ".", "getResults", "(", "0", ")", ";", "if", "(", "results", "!=", "null", ")", "{", "execution", ".", "setResults", "(", "results", ")", ";", "}", "if", "(", "xmlReport", ".", "getSections", "(", "0", ")", "!=", "null", ")", "{", "StringBuilder", "sections", "=", "new", "StringBuilder", "(", ")", ";", "int", "index", "=", "0", ";", "while", "(", "xmlReport", ".", "getSections", "(", "index", ")", "!=", "null", ")", "{", "if", "(", "index", ">", "0", ")", "sections", ".", "append", "(", "'", "'", ")", ";", "sections", ".", "append", "(", "xmlReport", ".", "getSections", "(", "index", ")", ")", ";", "index", "++", ";", "}", "execution", ".", "setSections", "(", "sections", ".", "toString", "(", ")", ")", ";", "}", "return", "execution", ";", "}" ]
<p>newInstance.</p> @param specification a {@link com.greenpepper.server.domain.Specification} object. @param systemUnderTest a {@link com.greenpepper.server.domain.SystemUnderTest} object. @param xmlReport a {@link com.greenpepper.report.XmlReport} object. @return a {@link com.greenpepper.server.domain.Execution} object.
[ "<p", ">", "newInstance", ".", "<", "/", "p", ">" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/domain/Execution.java#L89-L127
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/INode.java
INode.enforceRegularStorageINode
public static void enforceRegularStorageINode(INodeFile inode, String msg) throws IOException { """ Verify if file is regular storage, otherwise throw an exception """ if (inode.getStorageType() != StorageType.REGULAR_STORAGE) { LOG.error(msg); throw new IOException(msg); } }
java
public static void enforceRegularStorageINode(INodeFile inode, String msg) throws IOException { if (inode.getStorageType() != StorageType.REGULAR_STORAGE) { LOG.error(msg); throw new IOException(msg); } }
[ "public", "static", "void", "enforceRegularStorageINode", "(", "INodeFile", "inode", ",", "String", "msg", ")", "throws", "IOException", "{", "if", "(", "inode", ".", "getStorageType", "(", ")", "!=", "StorageType", ".", "REGULAR_STORAGE", ")", "{", "LOG", ".", "error", "(", "msg", ")", ";", "throw", "new", "IOException", "(", "msg", ")", ";", "}", "}" ]
Verify if file is regular storage, otherwise throw an exception
[ "Verify", "if", "file", "is", "regular", "storage", "otherwise", "throw", "an", "exception" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/INode.java#L251-L257
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/AlertsInner.java
AlertsInner.getAsync
public Observable<AlertInner> getAsync(String deviceName, String name, String resourceGroupName) { """ Gets an alert by name. @param deviceName The device name. @param name The alert name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the AlertInner object """ return getWithServiceResponseAsync(deviceName, name, resourceGroupName).map(new Func1<ServiceResponse<AlertInner>, AlertInner>() { @Override public AlertInner call(ServiceResponse<AlertInner> response) { return response.body(); } }); }
java
public Observable<AlertInner> getAsync(String deviceName, String name, String resourceGroupName) { return getWithServiceResponseAsync(deviceName, name, resourceGroupName).map(new Func1<ServiceResponse<AlertInner>, AlertInner>() { @Override public AlertInner call(ServiceResponse<AlertInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "AlertInner", ">", "getAsync", "(", "String", "deviceName", ",", "String", "name", ",", "String", "resourceGroupName", ")", "{", "return", "getWithServiceResponseAsync", "(", "deviceName", ",", "name", ",", "resourceGroupName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "AlertInner", ">", ",", "AlertInner", ">", "(", ")", "{", "@", "Override", "public", "AlertInner", "call", "(", "ServiceResponse", "<", "AlertInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets an alert by name. @param deviceName The device name. @param name The alert name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the AlertInner object
[ "Gets", "an", "alert", "by", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/AlertsInner.java#L235-L242
aws/aws-sdk-java
aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/GetClusterCredentialsRequest.java
GetClusterCredentialsRequest.getDbGroups
public java.util.List<String> getDbGroups() { """ <p> A list of the names of existing database groups that the user named in <code>DbUser</code> will join for the current session, in addition to any group memberships for an existing user. If not specified, a new user is added only to PUBLIC. </p> <p> Database group name constraints </p> <ul> <li> <p> Must be 1 to 64 alphanumeric characters or hyphens </p> </li> <li> <p> Must contain only lowercase letters, numbers, underscore, plus sign, period (dot), at symbol (@), or hyphen. </p> </li> <li> <p> First character must be a letter. </p> </li> <li> <p> Must not contain a colon ( : ) or slash ( / ). </p> </li> <li> <p> Cannot be a reserved word. A list of reserved words can be found in <a href="http://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html">Reserved Words</a> in the Amazon Redshift Database Developer Guide. </p> </li> </ul> @return A list of the names of existing database groups that the user named in <code>DbUser</code> will join for the current session, in addition to any group memberships for an existing user. If not specified, a new user is added only to PUBLIC.</p> <p> Database group name constraints </p> <ul> <li> <p> Must be 1 to 64 alphanumeric characters or hyphens </p> </li> <li> <p> Must contain only lowercase letters, numbers, underscore, plus sign, period (dot), at symbol (@), or hyphen. </p> </li> <li> <p> First character must be a letter. </p> </li> <li> <p> Must not contain a colon ( : ) or slash ( / ). </p> </li> <li> <p> Cannot be a reserved word. A list of reserved words can be found in <a href="http://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html">Reserved Words</a> in the Amazon Redshift Database Developer Guide. </p> </li> """ if (dbGroups == null) { dbGroups = new com.amazonaws.internal.SdkInternalList<String>(); } return dbGroups; }
java
public java.util.List<String> getDbGroups() { if (dbGroups == null) { dbGroups = new com.amazonaws.internal.SdkInternalList<String>(); } return dbGroups; }
[ "public", "java", ".", "util", ".", "List", "<", "String", ">", "getDbGroups", "(", ")", "{", "if", "(", "dbGroups", "==", "null", ")", "{", "dbGroups", "=", "new", "com", ".", "amazonaws", ".", "internal", ".", "SdkInternalList", "<", "String", ">", "(", ")", ";", "}", "return", "dbGroups", ";", "}" ]
<p> A list of the names of existing database groups that the user named in <code>DbUser</code> will join for the current session, in addition to any group memberships for an existing user. If not specified, a new user is added only to PUBLIC. </p> <p> Database group name constraints </p> <ul> <li> <p> Must be 1 to 64 alphanumeric characters or hyphens </p> </li> <li> <p> Must contain only lowercase letters, numbers, underscore, plus sign, period (dot), at symbol (@), or hyphen. </p> </li> <li> <p> First character must be a letter. </p> </li> <li> <p> Must not contain a colon ( : ) or slash ( / ). </p> </li> <li> <p> Cannot be a reserved word. A list of reserved words can be found in <a href="http://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html">Reserved Words</a> in the Amazon Redshift Database Developer Guide. </p> </li> </ul> @return A list of the names of existing database groups that the user named in <code>DbUser</code> will join for the current session, in addition to any group memberships for an existing user. If not specified, a new user is added only to PUBLIC.</p> <p> Database group name constraints </p> <ul> <li> <p> Must be 1 to 64 alphanumeric characters or hyphens </p> </li> <li> <p> Must contain only lowercase letters, numbers, underscore, plus sign, period (dot), at symbol (@), or hyphen. </p> </li> <li> <p> First character must be a letter. </p> </li> <li> <p> Must not contain a colon ( : ) or slash ( / ). </p> </li> <li> <p> Cannot be a reserved word. A list of reserved words can be found in <a href="http://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html">Reserved Words</a> in the Amazon Redshift Database Developer Guide. </p> </li>
[ "<p", ">", "A", "list", "of", "the", "names", "of", "existing", "database", "groups", "that", "the", "user", "named", "in", "<code", ">", "DbUser<", "/", "code", ">", "will", "join", "for", "the", "current", "session", "in", "addition", "to", "any", "group", "memberships", "for", "an", "existing", "user", ".", "If", "not", "specified", "a", "new", "user", "is", "added", "only", "to", "PUBLIC", ".", "<", "/", "p", ">", "<p", ">", "Database", "group", "name", "constraints", "<", "/", "p", ">", "<ul", ">", "<li", ">", "<p", ">", "Must", "be", "1", "to", "64", "alphanumeric", "characters", "or", "hyphens", "<", "/", "p", ">", "<", "/", "li", ">", "<li", ">", "<p", ">", "Must", "contain", "only", "lowercase", "letters", "numbers", "underscore", "plus", "sign", "period", "(", "dot", ")", "at", "symbol", "(", "@", ")", "or", "hyphen", ".", "<", "/", "p", ">", "<", "/", "li", ">", "<li", ">", "<p", ">", "First", "character", "must", "be", "a", "letter", ".", "<", "/", "p", ">", "<", "/", "li", ">", "<li", ">", "<p", ">", "Must", "not", "contain", "a", "colon", "(", ":", ")", "or", "slash", "(", "/", ")", ".", "<", "/", "p", ">", "<", "/", "li", ">", "<li", ">", "<p", ">", "Cannot", "be", "a", "reserved", "word", ".", "A", "list", "of", "reserved", "words", "can", "be", "found", "in", "<a", "href", "=", "http", ":", "//", "docs", ".", "aws", ".", "amazon", ".", "com", "/", "redshift", "/", "latest", "/", "dg", "/", "r_pg_keywords", ".", "html", ">", "Reserved", "Words<", "/", "a", ">", "in", "the", "Amazon", "Redshift", "Database", "Developer", "Guide", ".", "<", "/", "p", ">", "<", "/", "li", ">", "<", "/", "ul", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/GetClusterCredentialsRequest.java#L961-L966
matiwinnetou/spring-soy-view
spring-soy-view-ajax-compiler/src/main/java/pl/matisoft/soy/ajax/utils/I18nUtils.java
I18nUtils.getLocaleFromString
public static Locale getLocaleFromString(String localeString) { """ Convert a string based locale into a Locale Object. Assumes the string has form "{language}_{country}_{variant}". Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr_MAC" @param localeString The String @return the Locale """ if (localeString == null) { return null; } localeString = localeString.trim(); if (localeString.toLowerCase().equals("default")) { return Locale.getDefault(); } // Extract language int languageIndex = localeString.indexOf('_'); String language = null; if (languageIndex == -1) { // No further "_" so is "{language}" only return new Locale(localeString, ""); } else { language = localeString.substring(0, languageIndex); } // Extract country int countryIndex = localeString.indexOf('_', languageIndex + 1); String country = null; if (countryIndex == -1) { // No further "_" so is "{language}_{country}" country = localeString.substring(languageIndex + 1); return new Locale(language, country); } else { // Assume all remaining is the variant so is "{language}_{country}_{variant}" country = localeString.substring(languageIndex + 1, countryIndex); String variant = localeString.substring(countryIndex + 1); return new Locale(language, country, variant); } }
java
public static Locale getLocaleFromString(String localeString) { if (localeString == null) { return null; } localeString = localeString.trim(); if (localeString.toLowerCase().equals("default")) { return Locale.getDefault(); } // Extract language int languageIndex = localeString.indexOf('_'); String language = null; if (languageIndex == -1) { // No further "_" so is "{language}" only return new Locale(localeString, ""); } else { language = localeString.substring(0, languageIndex); } // Extract country int countryIndex = localeString.indexOf('_', languageIndex + 1); String country = null; if (countryIndex == -1) { // No further "_" so is "{language}_{country}" country = localeString.substring(languageIndex + 1); return new Locale(language, country); } else { // Assume all remaining is the variant so is "{language}_{country}_{variant}" country = localeString.substring(languageIndex + 1, countryIndex); String variant = localeString.substring(countryIndex + 1); return new Locale(language, country, variant); } }
[ "public", "static", "Locale", "getLocaleFromString", "(", "String", "localeString", ")", "{", "if", "(", "localeString", "==", "null", ")", "{", "return", "null", ";", "}", "localeString", "=", "localeString", ".", "trim", "(", ")", ";", "if", "(", "localeString", ".", "toLowerCase", "(", ")", ".", "equals", "(", "\"default\"", ")", ")", "{", "return", "Locale", ".", "getDefault", "(", ")", ";", "}", "// Extract language", "int", "languageIndex", "=", "localeString", ".", "indexOf", "(", "'", "'", ")", ";", "String", "language", "=", "null", ";", "if", "(", "languageIndex", "==", "-", "1", ")", "{", "// No further \"_\" so is \"{language}\" only", "return", "new", "Locale", "(", "localeString", ",", "\"\"", ")", ";", "}", "else", "{", "language", "=", "localeString", ".", "substring", "(", "0", ",", "languageIndex", ")", ";", "}", "// Extract country", "int", "countryIndex", "=", "localeString", ".", "indexOf", "(", "'", "'", ",", "languageIndex", "+", "1", ")", ";", "String", "country", "=", "null", ";", "if", "(", "countryIndex", "==", "-", "1", ")", "{", "// No further \"_\" so is \"{language}_{country}\"", "country", "=", "localeString", ".", "substring", "(", "languageIndex", "+", "1", ")", ";", "return", "new", "Locale", "(", "language", ",", "country", ")", ";", "}", "else", "{", "// Assume all remaining is the variant so is \"{language}_{country}_{variant}\"", "country", "=", "localeString", ".", "substring", "(", "languageIndex", "+", "1", ",", "countryIndex", ")", ";", "String", "variant", "=", "localeString", ".", "substring", "(", "countryIndex", "+", "1", ")", ";", "return", "new", "Locale", "(", "language", ",", "country", ",", "variant", ")", ";", "}", "}" ]
Convert a string based locale into a Locale Object. Assumes the string has form "{language}_{country}_{variant}". Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr_MAC" @param localeString The String @return the Locale
[ "Convert", "a", "string", "based", "locale", "into", "a", "Locale", "Object", ".", "Assumes", "the", "string", "has", "form", "{", "language", "}", "_", "{", "country", "}", "_", "{", "variant", "}", ".", "Examples", ":", "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr_MAC" ]
train
https://github.com/matiwinnetou/spring-soy-view/blob/a27c1b2bc76b074a2753ddd7b0c7f685c883d1d1/spring-soy-view-ajax-compiler/src/main/java/pl/matisoft/soy/ajax/utils/I18nUtils.java#L44-L76
jlinn/quartz-redis-jobstore
src/main/java/net/joelinn/quartz/jobstore/RedisJobStore.java
RedisJobStore.storeJobAndTrigger
@Override public void storeJobAndTrigger(final JobDetail newJob, final OperableTrigger newTrigger) throws ObjectAlreadyExistsException, JobPersistenceException { """ Store the given <code>{@link org.quartz.JobDetail}</code> and <code>{@link org.quartz.Trigger}</code>. @param newJob The <code>JobDetail</code> to be stored. @param newTrigger The <code>Trigger</code> to be stored. @throws org.quartz.ObjectAlreadyExistsException if a <code>Job</code> with the same name/group already exists. """ try { doWithLock(new LockCallbackWithoutResult() { @Override public Void doWithLock(JedisCommands jedis) throws JobPersistenceException { storage.storeJob(newJob, false, jedis); storage.storeTrigger(newTrigger, false, jedis); return null; } }); } catch (ObjectAlreadyExistsException e) { logger.info("Job and / or trigger already exist in storage.", e); throw e; } catch (Exception e) { logger.error("Could not store job.", e); throw new JobPersistenceException(e.getMessage(), e); } }
java
@Override public void storeJobAndTrigger(final JobDetail newJob, final OperableTrigger newTrigger) throws ObjectAlreadyExistsException, JobPersistenceException { try { doWithLock(new LockCallbackWithoutResult() { @Override public Void doWithLock(JedisCommands jedis) throws JobPersistenceException { storage.storeJob(newJob, false, jedis); storage.storeTrigger(newTrigger, false, jedis); return null; } }); } catch (ObjectAlreadyExistsException e) { logger.info("Job and / or trigger already exist in storage.", e); throw e; } catch (Exception e) { logger.error("Could not store job.", e); throw new JobPersistenceException(e.getMessage(), e); } }
[ "@", "Override", "public", "void", "storeJobAndTrigger", "(", "final", "JobDetail", "newJob", ",", "final", "OperableTrigger", "newTrigger", ")", "throws", "ObjectAlreadyExistsException", ",", "JobPersistenceException", "{", "try", "{", "doWithLock", "(", "new", "LockCallbackWithoutResult", "(", ")", "{", "@", "Override", "public", "Void", "doWithLock", "(", "JedisCommands", "jedis", ")", "throws", "JobPersistenceException", "{", "storage", ".", "storeJob", "(", "newJob", ",", "false", ",", "jedis", ")", ";", "storage", ".", "storeTrigger", "(", "newTrigger", ",", "false", ",", "jedis", ")", ";", "return", "null", ";", "}", "}", ")", ";", "}", "catch", "(", "ObjectAlreadyExistsException", "e", ")", "{", "logger", ".", "info", "(", "\"Job and / or trigger already exist in storage.\"", ",", "e", ")", ";", "throw", "e", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Could not store job.\"", ",", "e", ")", ";", "throw", "new", "JobPersistenceException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}" ]
Store the given <code>{@link org.quartz.JobDetail}</code> and <code>{@link org.quartz.Trigger}</code>. @param newJob The <code>JobDetail</code> to be stored. @param newTrigger The <code>Trigger</code> to be stored. @throws org.quartz.ObjectAlreadyExistsException if a <code>Job</code> with the same name/group already exists.
[ "Store", "the", "given", "<code", ">", "{", "@link", "org", ".", "quartz", ".", "JobDetail", "}", "<", "/", "code", ">", "and", "<code", ">", "{", "@link", "org", ".", "quartz", ".", "Trigger", "}", "<", "/", "code", ">", "." ]
train
https://github.com/jlinn/quartz-redis-jobstore/blob/be9a52ee776d8a09866fe99fd9718bc13a0cb992/src/main/java/net/joelinn/quartz/jobstore/RedisJobStore.java#L257-L275
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java
AppServiceEnvironmentsInner.createOrUpdateMultiRolePool
public WorkerPoolResourceInner createOrUpdateMultiRolePool(String resourceGroupName, String name, WorkerPoolResourceInner multiRolePoolEnvelope) { """ Create or update a multi-role pool. Create or update a multi-role pool. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @param multiRolePoolEnvelope Properties of the multi-role pool. @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 WorkerPoolResourceInner object if successful. """ return createOrUpdateMultiRolePoolWithServiceResponseAsync(resourceGroupName, name, multiRolePoolEnvelope).toBlocking().last().body(); }
java
public WorkerPoolResourceInner createOrUpdateMultiRolePool(String resourceGroupName, String name, WorkerPoolResourceInner multiRolePoolEnvelope) { return createOrUpdateMultiRolePoolWithServiceResponseAsync(resourceGroupName, name, multiRolePoolEnvelope).toBlocking().last().body(); }
[ "public", "WorkerPoolResourceInner", "createOrUpdateMultiRolePool", "(", "String", "resourceGroupName", ",", "String", "name", ",", "WorkerPoolResourceInner", "multiRolePoolEnvelope", ")", "{", "return", "createOrUpdateMultiRolePoolWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ",", "multiRolePoolEnvelope", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Create or update a multi-role pool. Create or update a multi-role pool. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @param multiRolePoolEnvelope Properties of the multi-role pool. @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 WorkerPoolResourceInner object if successful.
[ "Create", "or", "update", "a", "multi", "-", "role", "pool", ".", "Create", "or", "update", "a", "multi", "-", "role", "pool", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L2273-L2275
teatrove/teatrove
trove/src/main/java/org/teatrove/trove/classfile/Modifiers.java
Modifiers.setPrivate
public static int setPrivate(int modifier, boolean b) { """ When set private, the modifier is cleared from being public or protected. """ if (b) { return (modifier | PRIVATE) & (~PUBLIC & ~PROTECTED); } else { return modifier & ~PRIVATE; } }
java
public static int setPrivate(int modifier, boolean b) { if (b) { return (modifier | PRIVATE) & (~PUBLIC & ~PROTECTED); } else { return modifier & ~PRIVATE; } }
[ "public", "static", "int", "setPrivate", "(", "int", "modifier", ",", "boolean", "b", ")", "{", "if", "(", "b", ")", "{", "return", "(", "modifier", "|", "PRIVATE", ")", "&", "(", "~", "PUBLIC", "&", "~", "PROTECTED", ")", ";", "}", "else", "{", "return", "modifier", "&", "~", "PRIVATE", ";", "}", "}" ]
When set private, the modifier is cleared from being public or protected.
[ "When", "set", "private", "the", "modifier", "is", "cleared", "from", "being", "public", "or", "protected", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/Modifiers.java#L47-L54
arakelian/docker-junit-rule
src/main/java/com/arakelian/docker/junit/Container.java
Container.waitForPort
public final void waitForPort(final String host, final int port, final int timeout, final TimeUnit unit) throws IllegalArgumentException { """ Wait for the specified port to accept socket connection within a given time frame. @param host target host name @param port target port number @param timeout timeout value @param unit timeout units @throws IllegalArgumentException if invalid arguments are passed to method """ Preconditions.checkArgument(host != null, "host must be non-null"); Preconditions.checkArgument(port > 0, "port must be positive integer"); Preconditions.checkArgument(unit != null, "unit must be non-null"); final long startTime = System.currentTimeMillis(); final long timeoutTime = startTime + TimeUnit.MILLISECONDS.convert(timeout, unit); LOGGER.info("Waiting for docker container at {}:{} for {} {}", host, port, timeout, unit); final SocketAddress address = new InetSocketAddress(host, port); for (;;) { if (isSocketAlive(address, 2000)) { LOGGER.info( "Successfully connected to container at {}:{} after {}ms", host, port, System.currentTimeMillis() - startTime); return; } try { Thread.sleep(1000); LOGGER.info("Waiting for container at {}:{}", host, port); if (System.currentTimeMillis() > timeoutTime) { LOGGER.error("Failed to connect with container at {}:{}", host, port); throw new IllegalStateException( "Timeout waiting for socket connection to " + host + ":" + port); } } catch (final InterruptedException ie) { throw new IllegalStateException(ie); } } }
java
public final void waitForPort(final String host, final int port, final int timeout, final TimeUnit unit) throws IllegalArgumentException { Preconditions.checkArgument(host != null, "host must be non-null"); Preconditions.checkArgument(port > 0, "port must be positive integer"); Preconditions.checkArgument(unit != null, "unit must be non-null"); final long startTime = System.currentTimeMillis(); final long timeoutTime = startTime + TimeUnit.MILLISECONDS.convert(timeout, unit); LOGGER.info("Waiting for docker container at {}:{} for {} {}", host, port, timeout, unit); final SocketAddress address = new InetSocketAddress(host, port); for (;;) { if (isSocketAlive(address, 2000)) { LOGGER.info( "Successfully connected to container at {}:{} after {}ms", host, port, System.currentTimeMillis() - startTime); return; } try { Thread.sleep(1000); LOGGER.info("Waiting for container at {}:{}", host, port); if (System.currentTimeMillis() > timeoutTime) { LOGGER.error("Failed to connect with container at {}:{}", host, port); throw new IllegalStateException( "Timeout waiting for socket connection to " + host + ":" + port); } } catch (final InterruptedException ie) { throw new IllegalStateException(ie); } } }
[ "public", "final", "void", "waitForPort", "(", "final", "String", "host", ",", "final", "int", "port", ",", "final", "int", "timeout", ",", "final", "TimeUnit", "unit", ")", "throws", "IllegalArgumentException", "{", "Preconditions", ".", "checkArgument", "(", "host", "!=", "null", ",", "\"host must be non-null\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "port", ">", "0", ",", "\"port must be positive integer\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "unit", "!=", "null", ",", "\"unit must be non-null\"", ")", ";", "final", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "final", "long", "timeoutTime", "=", "startTime", "+", "TimeUnit", ".", "MILLISECONDS", ".", "convert", "(", "timeout", ",", "unit", ")", ";", "LOGGER", ".", "info", "(", "\"Waiting for docker container at {}:{} for {} {}\"", ",", "host", ",", "port", ",", "timeout", ",", "unit", ")", ";", "final", "SocketAddress", "address", "=", "new", "InetSocketAddress", "(", "host", ",", "port", ")", ";", "for", "(", ";", ";", ")", "{", "if", "(", "isSocketAlive", "(", "address", ",", "2000", ")", ")", "{", "LOGGER", ".", "info", "(", "\"Successfully connected to container at {}:{} after {}ms\"", ",", "host", ",", "port", ",", "System", ".", "currentTimeMillis", "(", ")", "-", "startTime", ")", ";", "return", ";", "}", "try", "{", "Thread", ".", "sleep", "(", "1000", ")", ";", "LOGGER", ".", "info", "(", "\"Waiting for container at {}:{}\"", ",", "host", ",", "port", ")", ";", "if", "(", "System", ".", "currentTimeMillis", "(", ")", ">", "timeoutTime", ")", "{", "LOGGER", ".", "error", "(", "\"Failed to connect with container at {}:{}\"", ",", "host", ",", "port", ")", ";", "throw", "new", "IllegalStateException", "(", "\"Timeout waiting for socket connection to \"", "+", "host", "+", "\":\"", "+", "port", ")", ";", "}", "}", "catch", "(", "final", "InterruptedException", "ie", ")", "{", "throw", "new", "IllegalStateException", "(", "ie", ")", ";", "}", "}", "}" ]
Wait for the specified port to accept socket connection within a given time frame. @param host target host name @param port target port number @param timeout timeout value @param unit timeout units @throws IllegalArgumentException if invalid arguments are passed to method
[ "Wait", "for", "the", "specified", "port", "to", "accept", "socket", "connection", "within", "a", "given", "time", "frame", "." ]
train
https://github.com/arakelian/docker-junit-rule/blob/cc99d63896a07df398b53fd5f0f6e4777e3b23cf/src/main/java/com/arakelian/docker/junit/Container.java#L416-L448
Azure/azure-sdk-for-java
appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DiagnosticsInner.java
DiagnosticsInner.executeSiteDetectorSlotAsync
public Observable<DiagnosticDetectorResponseInner> executeSiteDetectorSlotAsync(String resourceGroupName, String siteName, String detectorName, String diagnosticCategory, String slot) { """ Execute Detector. Execute Detector. @param resourceGroupName Name of the resource group to which the resource belongs. @param siteName Site Name @param detectorName Detector Resource Name @param diagnosticCategory Category Name @param slot Slot Name @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DiagnosticDetectorResponseInner object """ return executeSiteDetectorSlotWithServiceResponseAsync(resourceGroupName, siteName, detectorName, diagnosticCategory, slot).map(new Func1<ServiceResponse<DiagnosticDetectorResponseInner>, DiagnosticDetectorResponseInner>() { @Override public DiagnosticDetectorResponseInner call(ServiceResponse<DiagnosticDetectorResponseInner> response) { return response.body(); } }); }
java
public Observable<DiagnosticDetectorResponseInner> executeSiteDetectorSlotAsync(String resourceGroupName, String siteName, String detectorName, String diagnosticCategory, String slot) { return executeSiteDetectorSlotWithServiceResponseAsync(resourceGroupName, siteName, detectorName, diagnosticCategory, slot).map(new Func1<ServiceResponse<DiagnosticDetectorResponseInner>, DiagnosticDetectorResponseInner>() { @Override public DiagnosticDetectorResponseInner call(ServiceResponse<DiagnosticDetectorResponseInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DiagnosticDetectorResponseInner", ">", "executeSiteDetectorSlotAsync", "(", "String", "resourceGroupName", ",", "String", "siteName", ",", "String", "detectorName", ",", "String", "diagnosticCategory", ",", "String", "slot", ")", "{", "return", "executeSiteDetectorSlotWithServiceResponseAsync", "(", "resourceGroupName", ",", "siteName", ",", "detectorName", ",", "diagnosticCategory", ",", "slot", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "DiagnosticDetectorResponseInner", ">", ",", "DiagnosticDetectorResponseInner", ">", "(", ")", "{", "@", "Override", "public", "DiagnosticDetectorResponseInner", "call", "(", "ServiceResponse", "<", "DiagnosticDetectorResponseInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Execute Detector. Execute Detector. @param resourceGroupName Name of the resource group to which the resource belongs. @param siteName Site Name @param detectorName Detector Resource Name @param diagnosticCategory Category Name @param slot Slot Name @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DiagnosticDetectorResponseInner object
[ "Execute", "Detector", ".", "Execute", "Detector", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DiagnosticsInner.java#L2405-L2412
sarl/sarl
main/coreplugins/io.sarl.lang/src/io/sarl/lang/formatting2/SARLFormatter.java
SARLFormatter._format
protected void _format(SarlAgent agent, IFormattableDocument document) { """ Format the given SARL agent. @param agent the SARL component. @param document the document. """ formatAnnotations(agent, document, XbaseFormatterPreferenceKeys.newLineAfterClassAnnotations); formatModifiers(agent, document); final ISemanticRegionsFinder regionFor = this.textRegionExtensions.regionFor(agent); document.append(regionFor.keyword(this.keywords.getAgentKeyword()), ONE_SPACE); document.surround(regionFor.keyword(this.keywords.getExtendsKeyword()), ONE_SPACE); document.format(agent.getExtends()); formatBody(agent, document); }
java
protected void _format(SarlAgent agent, IFormattableDocument document) { formatAnnotations(agent, document, XbaseFormatterPreferenceKeys.newLineAfterClassAnnotations); formatModifiers(agent, document); final ISemanticRegionsFinder regionFor = this.textRegionExtensions.regionFor(agent); document.append(regionFor.keyword(this.keywords.getAgentKeyword()), ONE_SPACE); document.surround(regionFor.keyword(this.keywords.getExtendsKeyword()), ONE_SPACE); document.format(agent.getExtends()); formatBody(agent, document); }
[ "protected", "void", "_format", "(", "SarlAgent", "agent", ",", "IFormattableDocument", "document", ")", "{", "formatAnnotations", "(", "agent", ",", "document", ",", "XbaseFormatterPreferenceKeys", ".", "newLineAfterClassAnnotations", ")", ";", "formatModifiers", "(", "agent", ",", "document", ")", ";", "final", "ISemanticRegionsFinder", "regionFor", "=", "this", ".", "textRegionExtensions", ".", "regionFor", "(", "agent", ")", ";", "document", ".", "append", "(", "regionFor", ".", "keyword", "(", "this", ".", "keywords", ".", "getAgentKeyword", "(", ")", ")", ",", "ONE_SPACE", ")", ";", "document", ".", "surround", "(", "regionFor", ".", "keyword", "(", "this", ".", "keywords", ".", "getExtendsKeyword", "(", ")", ")", ",", "ONE_SPACE", ")", ";", "document", ".", "format", "(", "agent", ".", "getExtends", "(", ")", ")", ";", "formatBody", "(", "agent", ",", "document", ")", ";", "}" ]
Format the given SARL agent. @param agent the SARL component. @param document the document.
[ "Format", "the", "given", "SARL", "agent", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/formatting2/SARLFormatter.java#L232-L243
SonarSource/sonarqube
server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/StringFieldBuilder.java
StringFieldBuilder.addSubField
private T addSubField(String fieldName, SortedMap<String, String> fieldDefinition) { """ Add a sub-field. A {@code SortedMap} is required for consistency of the index settings hash. """ subFields.put(fieldName, fieldDefinition); return castThis(); }
java
private T addSubField(String fieldName, SortedMap<String, String> fieldDefinition) { subFields.put(fieldName, fieldDefinition); return castThis(); }
[ "private", "T", "addSubField", "(", "String", "fieldName", ",", "SortedMap", "<", "String", ",", "String", ">", "fieldDefinition", ")", "{", "subFields", ".", "put", "(", "fieldName", ",", "fieldDefinition", ")", ";", "return", "castThis", "(", ")", ";", "}" ]
Add a sub-field. A {@code SortedMap} is required for consistency of the index settings hash.
[ "Add", "a", "sub", "-", "field", ".", "A", "{" ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/StringFieldBuilder.java#L60-L63
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/decomposition/eig/EigenvalueSmall_F64.java
EigenvalueSmall_F64.value2x2_fast
public void value2x2_fast( double a11 , double a12, double a21 , double a22 ) { """ Computes the eigenvalues of a 2 by 2 matrix using a faster but more prone to errors method. This is the typical method. """ double left = (a11+a22)/2.0; double inside = 4.0*a12*a21 + (a11-a22)*(a11-a22); if( inside < 0 ) { value0.real = value1.real = left; value0.imaginary = Math.sqrt(-inside)/2.0; value1.imaginary = -value0.imaginary; } else { double right = Math.sqrt(inside)/2.0; value0.real = (left+right); value1.real = (left-right); value0.imaginary = value1.imaginary = 0.0; } }
java
public void value2x2_fast( double a11 , double a12, double a21 , double a22 ) { double left = (a11+a22)/2.0; double inside = 4.0*a12*a21 + (a11-a22)*(a11-a22); if( inside < 0 ) { value0.real = value1.real = left; value0.imaginary = Math.sqrt(-inside)/2.0; value1.imaginary = -value0.imaginary; } else { double right = Math.sqrt(inside)/2.0; value0.real = (left+right); value1.real = (left-right); value0.imaginary = value1.imaginary = 0.0; } }
[ "public", "void", "value2x2_fast", "(", "double", "a11", ",", "double", "a12", ",", "double", "a21", ",", "double", "a22", ")", "{", "double", "left", "=", "(", "a11", "+", "a22", ")", "/", "2.0", ";", "double", "inside", "=", "4.0", "*", "a12", "*", "a21", "+", "(", "a11", "-", "a22", ")", "*", "(", "a11", "-", "a22", ")", ";", "if", "(", "inside", "<", "0", ")", "{", "value0", ".", "real", "=", "value1", ".", "real", "=", "left", ";", "value0", ".", "imaginary", "=", "Math", ".", "sqrt", "(", "-", "inside", ")", "/", "2.0", ";", "value1", ".", "imaginary", "=", "-", "value0", ".", "imaginary", ";", "}", "else", "{", "double", "right", "=", "Math", ".", "sqrt", "(", "inside", ")", "/", "2.0", ";", "value0", ".", "real", "=", "(", "left", "+", "right", ")", ";", "value1", ".", "real", "=", "(", "left", "-", "right", ")", ";", "value0", ".", "imaginary", "=", "value1", ".", "imaginary", "=", "0.0", ";", "}", "}" ]
Computes the eigenvalues of a 2 by 2 matrix using a faster but more prone to errors method. This is the typical method.
[ "Computes", "the", "eigenvalues", "of", "a", "2", "by", "2", "matrix", "using", "a", "faster", "but", "more", "prone", "to", "errors", "method", ".", "This", "is", "the", "typical", "method", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/decomposition/eig/EigenvalueSmall_F64.java#L95-L110
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/LocalNameRangeQuery.java
LocalNameRangeQuery.getLowerTerm
private static Term getLowerTerm(String lowerName) { """ Creates a {@link Term} for the lower bound local name. @param lowerName the lower bound local name. @return a {@link Term} for the lower bound local name. """ String text; if (lowerName == null) { text = ""; } else { text = lowerName; } return new Term(FieldNames.LOCAL_NAME, text); }
java
private static Term getLowerTerm(String lowerName) { String text; if (lowerName == null) { text = ""; } else { text = lowerName; } return new Term(FieldNames.LOCAL_NAME, text); }
[ "private", "static", "Term", "getLowerTerm", "(", "String", "lowerName", ")", "{", "String", "text", ";", "if", "(", "lowerName", "==", "null", ")", "{", "text", "=", "\"\"", ";", "}", "else", "{", "text", "=", "lowerName", ";", "}", "return", "new", "Term", "(", "FieldNames", ".", "LOCAL_NAME", ",", "text", ")", ";", "}" ]
Creates a {@link Term} for the lower bound local name. @param lowerName the lower bound local name. @return a {@link Term} for the lower bound local name.
[ "Creates", "a", "{", "@link", "Term", "}", "for", "the", "lower", "bound", "local", "name", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/LocalNameRangeQuery.java#L52-L60
padrig64/ValidationFramework
validationframework-swing/src/main/java/com/google/code/validationframework/swing/decoration/AbstractComponentDecoration.java
AbstractComponentDecoration.updateDecorationPainterUnclippedBounds
private void updateDecorationPainterUnclippedBounds(JLayeredPane layeredPane, Point relativeLocationToOwner) { """ Calculates and updates the unclipped bounds of the decoration painter in layered pane coordinates. @param layeredPane Layered pane containing the decoration painter. @param relativeLocationToOwner Location of the decoration painter relatively to the decorated component. """ Rectangle decorationBoundsInLayeredPane; if (layeredPane == null) { decorationBoundsInLayeredPane = new Rectangle(); } else { // Calculate location of the decorated component in the layered pane containing the decoration painter Point decoratedComponentLocationInLayeredPane = SwingUtilities.convertPoint(decoratedComponent.getParent (), decoratedComponent.getLocation(), layeredPane); // Deduces the location of the decoration painter in the layered pane decorationBoundsInLayeredPane = new Rectangle(decoratedComponentLocationInLayeredPane.x + relativeLocationToOwner.x, decoratedComponentLocationInLayeredPane.y + relativeLocationToOwner.y, getWidth(), getHeight()); } // Update decoration painter decorationPainter.setBounds(decorationBoundsInLayeredPane); }
java
private void updateDecorationPainterUnclippedBounds(JLayeredPane layeredPane, Point relativeLocationToOwner) { Rectangle decorationBoundsInLayeredPane; if (layeredPane == null) { decorationBoundsInLayeredPane = new Rectangle(); } else { // Calculate location of the decorated component in the layered pane containing the decoration painter Point decoratedComponentLocationInLayeredPane = SwingUtilities.convertPoint(decoratedComponent.getParent (), decoratedComponent.getLocation(), layeredPane); // Deduces the location of the decoration painter in the layered pane decorationBoundsInLayeredPane = new Rectangle(decoratedComponentLocationInLayeredPane.x + relativeLocationToOwner.x, decoratedComponentLocationInLayeredPane.y + relativeLocationToOwner.y, getWidth(), getHeight()); } // Update decoration painter decorationPainter.setBounds(decorationBoundsInLayeredPane); }
[ "private", "void", "updateDecorationPainterUnclippedBounds", "(", "JLayeredPane", "layeredPane", ",", "Point", "relativeLocationToOwner", ")", "{", "Rectangle", "decorationBoundsInLayeredPane", ";", "if", "(", "layeredPane", "==", "null", ")", "{", "decorationBoundsInLayeredPane", "=", "new", "Rectangle", "(", ")", ";", "}", "else", "{", "// Calculate location of the decorated component in the layered pane containing the decoration painter", "Point", "decoratedComponentLocationInLayeredPane", "=", "SwingUtilities", ".", "convertPoint", "(", "decoratedComponent", ".", "getParent", "(", ")", ",", "decoratedComponent", ".", "getLocation", "(", ")", ",", "layeredPane", ")", ";", "// Deduces the location of the decoration painter in the layered pane", "decorationBoundsInLayeredPane", "=", "new", "Rectangle", "(", "decoratedComponentLocationInLayeredPane", ".", "x", "+", "relativeLocationToOwner", ".", "x", ",", "decoratedComponentLocationInLayeredPane", ".", "y", "+", "relativeLocationToOwner", ".", "y", ",", "getWidth", "(", ")", ",", "getHeight", "(", ")", ")", ";", "}", "// Update decoration painter", "decorationPainter", ".", "setBounds", "(", "decorationBoundsInLayeredPane", ")", ";", "}" ]
Calculates and updates the unclipped bounds of the decoration painter in layered pane coordinates. @param layeredPane Layered pane containing the decoration painter. @param relativeLocationToOwner Location of the decoration painter relatively to the decorated component.
[ "Calculates", "and", "updates", "the", "unclipped", "bounds", "of", "the", "decoration", "painter", "in", "layered", "pane", "coordinates", "." ]
train
https://github.com/padrig64/ValidationFramework/blob/2dd3c7b3403993db366d24a927645f467ccd1dda/validationframework-swing/src/main/java/com/google/code/validationframework/swing/decoration/AbstractComponentDecoration.java#L665-L683
ysc/HtmlExtractor
html-extractor/src/main/java/org/apdplat/extractor/html/impl/ExtractRegular.java
ExtractRegular.getInstance
public static ExtractRegular getInstance(String serverUrl, String redisHost, int redisPort) { """ 获取抽取规则实例 @param serverUrl 配置管理WEB服务器的抽取规则下载地址 @param redisHost Redis服务器主机 @param redisPort Redis服务器端口 @return 抽取规则实例 """ if (extractRegular != null) { return extractRegular; } synchronized (ExtractRegular.class) { if (extractRegular == null) { extractRegular = new ExtractRegular(); //订阅Redis服务器Channel:pr,当规则改变的时候会收到通知消息CHANGE并重新初始化规则集合 extractRegular.subscribeRedis(redisHost, redisPort, serverUrl); //初始化抽取规则 extractRegular.init(serverUrl); } } return extractRegular; }
java
public static ExtractRegular getInstance(String serverUrl, String redisHost, int redisPort) { if (extractRegular != null) { return extractRegular; } synchronized (ExtractRegular.class) { if (extractRegular == null) { extractRegular = new ExtractRegular(); //订阅Redis服务器Channel:pr,当规则改变的时候会收到通知消息CHANGE并重新初始化规则集合 extractRegular.subscribeRedis(redisHost, redisPort, serverUrl); //初始化抽取规则 extractRegular.init(serverUrl); } } return extractRegular; }
[ "public", "static", "ExtractRegular", "getInstance", "(", "String", "serverUrl", ",", "String", "redisHost", ",", "int", "redisPort", ")", "{", "if", "(", "extractRegular", "!=", "null", ")", "{", "return", "extractRegular", ";", "}", "synchronized", "(", "ExtractRegular", ".", "class", ")", "{", "if", "(", "extractRegular", "==", "null", ")", "{", "extractRegular", "=", "new", "ExtractRegular", "(", ")", ";", "//订阅Redis服务器Channel:pr,当规则改变的时候会收到通知消息CHANGE并重新初始化规则集合", "extractRegular", ".", "subscribeRedis", "(", "redisHost", ",", "redisPort", ",", "serverUrl", ")", ";", "//初始化抽取规则", "extractRegular", ".", "init", "(", "serverUrl", ")", ";", "}", "}", "return", "extractRegular", ";", "}" ]
获取抽取规则实例 @param serverUrl 配置管理WEB服务器的抽取规则下载地址 @param redisHost Redis服务器主机 @param redisPort Redis服务器端口 @return 抽取规则实例
[ "获取抽取规则实例" ]
train
https://github.com/ysc/HtmlExtractor/blob/5378bc5f94138562c55506cf81de1ffe72ab701e/html-extractor/src/main/java/org/apdplat/extractor/html/impl/ExtractRegular.java#L96-L110
threerings/narya
core/src/main/java/com/threerings/presents/peer/server/PeerManager.java
PeerManager.acquireLock
public void acquireLock (final NodeObject.Lock lock, final ResultListener<String> listener) { """ Acquires a lock on a resource shared amongst this node's peers. If the lock is successfully acquired, the supplied listener will receive this node's name. If another node acquires the lock first, then the listener will receive the name of that node. """ // wait until any pending resolution is complete queryLock(lock, new ChainedResultListener<String, String>(listener) { public void requestCompleted (String result) { if (result == null) { if (_suboids.isEmpty()) { lockAcquired(lock, 0L, listener); } else { _locks.put(lock, new LockHandler(lock, true, listener)); } } else { listener.requestCompleted(result); } } }); }
java
public void acquireLock (final NodeObject.Lock lock, final ResultListener<String> listener) { // wait until any pending resolution is complete queryLock(lock, new ChainedResultListener<String, String>(listener) { public void requestCompleted (String result) { if (result == null) { if (_suboids.isEmpty()) { lockAcquired(lock, 0L, listener); } else { _locks.put(lock, new LockHandler(lock, true, listener)); } } else { listener.requestCompleted(result); } } }); }
[ "public", "void", "acquireLock", "(", "final", "NodeObject", ".", "Lock", "lock", ",", "final", "ResultListener", "<", "String", ">", "listener", ")", "{", "// wait until any pending resolution is complete", "queryLock", "(", "lock", ",", "new", "ChainedResultListener", "<", "String", ",", "String", ">", "(", "listener", ")", "{", "public", "void", "requestCompleted", "(", "String", "result", ")", "{", "if", "(", "result", "==", "null", ")", "{", "if", "(", "_suboids", ".", "isEmpty", "(", ")", ")", "{", "lockAcquired", "(", "lock", ",", "0L", ",", "listener", ")", ";", "}", "else", "{", "_locks", ".", "put", "(", "lock", ",", "new", "LockHandler", "(", "lock", ",", "true", ",", "listener", ")", ")", ";", "}", "}", "else", "{", "listener", ".", "requestCompleted", "(", "result", ")", ";", "}", "}", "}", ")", ";", "}" ]
Acquires a lock on a resource shared amongst this node's peers. If the lock is successfully acquired, the supplied listener will receive this node's name. If another node acquires the lock first, then the listener will receive the name of that node.
[ "Acquires", "a", "lock", "on", "a", "resource", "shared", "amongst", "this", "node", "s", "peers", ".", "If", "the", "lock", "is", "successfully", "acquired", "the", "supplied", "listener", "will", "receive", "this", "node", "s", "name", ".", "If", "another", "node", "acquires", "the", "lock", "first", "then", "the", "listener", "will", "receive", "the", "name", "of", "that", "node", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/peer/server/PeerManager.java#L799-L815
osglworks/java-tool
src/main/java/org/osgl/Lang.java
F1.compose
public <X1, X2> F2<X1, X2, R> compose(final Func2<? super X1, ? super X2, ? extends P1> before) { """ Returns an {@code F2&lt;X1, X2, R&gt;>} function by composing the specified {@code Func2&ltX1, X2, P1&gt;} function with this function applied last @param <X1> the type of first param the new function applied to @param <X2> the type of second param the new function applied to @param before the function to be applied first when applying the return function @return an new function such that f(x1, x2) == apply(f1(x1, x2)) """ final F1<P1, R> me = this; return new F2<X1, X2, R>() { @Override public R apply(X1 x1, X2 x2) { return me.apply(before.apply(x1, x2)); } }; }
java
public <X1, X2> F2<X1, X2, R> compose(final Func2<? super X1, ? super X2, ? extends P1> before) { final F1<P1, R> me = this; return new F2<X1, X2, R>() { @Override public R apply(X1 x1, X2 x2) { return me.apply(before.apply(x1, x2)); } }; }
[ "public", "<", "X1", ",", "X2", ">", "F2", "<", "X1", ",", "X2", ",", "R", ">", "compose", "(", "final", "Func2", "<", "?", "super", "X1", ",", "?", "super", "X2", ",", "?", "extends", "P1", ">", "before", ")", "{", "final", "F1", "<", "P1", ",", "R", ">", "me", "=", "this", ";", "return", "new", "F2", "<", "X1", ",", "X2", ",", "R", ">", "(", ")", "{", "@", "Override", "public", "R", "apply", "(", "X1", "x1", ",", "X2", "x2", ")", "{", "return", "me", ".", "apply", "(", "before", ".", "apply", "(", "x1", ",", "x2", ")", ")", ";", "}", "}", ";", "}" ]
Returns an {@code F2&lt;X1, X2, R&gt;>} function by composing the specified {@code Func2&ltX1, X2, P1&gt;} function with this function applied last @param <X1> the type of first param the new function applied to @param <X2> the type of second param the new function applied to @param before the function to be applied first when applying the return function @return an new function such that f(x1, x2) == apply(f1(x1, x2))
[ "Returns", "an", "{", "@code", "F2&lt", ";", "X1", "X2", "R&gt", ";", ">", "}", "function", "by", "composing", "the", "specified", "{", "@code", "Func2&ltX1", "X2", "P1&gt", ";", "}", "function", "with", "this", "function", "applied", "last" ]
train
https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/Lang.java#L675-L685
protostuff/protostuff
protostuff-json/src/main/java/io/protostuff/JsonIOUtil.java
JsonIOUtil.parseListFrom
public static <T> List<T> parseListFrom(JsonParser parser, Schema<T> schema, boolean numeric) throws IOException { """ Parses the {@code messages} from the parser using the given {@code schema}. """ if (parser.nextToken() != JsonToken.START_ARRAY) { throw new JsonInputException("Expected token: [ but was " + parser.getCurrentToken() + " on message: " + schema.messageFullName()); } final JsonInput input = new JsonInput(parser, numeric); final List<T> list = new ArrayList<T>(); for (JsonToken t = parser.nextToken(); t != JsonToken.END_ARRAY; t = parser.nextToken()) { if (t != JsonToken.START_OBJECT) { throw new JsonInputException("Expected token: { but was " + parser.getCurrentToken() + " on message " + schema.messageFullName()); } final T message = schema.newMessage(); schema.mergeFrom(input, message); if (parser.getCurrentToken() != JsonToken.END_OBJECT) { throw new JsonInputException("Expected token: } but was " + parser.getCurrentToken() + " on message " + schema.messageFullName()); } list.add(message); input.reset(); } return list; }
java
public static <T> List<T> parseListFrom(JsonParser parser, Schema<T> schema, boolean numeric) throws IOException { if (parser.nextToken() != JsonToken.START_ARRAY) { throw new JsonInputException("Expected token: [ but was " + parser.getCurrentToken() + " on message: " + schema.messageFullName()); } final JsonInput input = new JsonInput(parser, numeric); final List<T> list = new ArrayList<T>(); for (JsonToken t = parser.nextToken(); t != JsonToken.END_ARRAY; t = parser.nextToken()) { if (t != JsonToken.START_OBJECT) { throw new JsonInputException("Expected token: { but was " + parser.getCurrentToken() + " on message " + schema.messageFullName()); } final T message = schema.newMessage(); schema.mergeFrom(input, message); if (parser.getCurrentToken() != JsonToken.END_OBJECT) { throw new JsonInputException("Expected token: } but was " + parser.getCurrentToken() + " on message " + schema.messageFullName()); } list.add(message); input.reset(); } return list; }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "parseListFrom", "(", "JsonParser", "parser", ",", "Schema", "<", "T", ">", "schema", ",", "boolean", "numeric", ")", "throws", "IOException", "{", "if", "(", "parser", ".", "nextToken", "(", ")", "!=", "JsonToken", ".", "START_ARRAY", ")", "{", "throw", "new", "JsonInputException", "(", "\"Expected token: [ but was \"", "+", "parser", ".", "getCurrentToken", "(", ")", "+", "\" on message: \"", "+", "schema", ".", "messageFullName", "(", ")", ")", ";", "}", "final", "JsonInput", "input", "=", "new", "JsonInput", "(", "parser", ",", "numeric", ")", ";", "final", "List", "<", "T", ">", "list", "=", "new", "ArrayList", "<", "T", ">", "(", ")", ";", "for", "(", "JsonToken", "t", "=", "parser", ".", "nextToken", "(", ")", ";", "t", "!=", "JsonToken", ".", "END_ARRAY", ";", "t", "=", "parser", ".", "nextToken", "(", ")", ")", "{", "if", "(", "t", "!=", "JsonToken", ".", "START_OBJECT", ")", "{", "throw", "new", "JsonInputException", "(", "\"Expected token: { but was \"", "+", "parser", ".", "getCurrentToken", "(", ")", "+", "\" on message \"", "+", "schema", ".", "messageFullName", "(", ")", ")", ";", "}", "final", "T", "message", "=", "schema", ".", "newMessage", "(", ")", ";", "schema", ".", "mergeFrom", "(", "input", ",", "message", ")", ";", "if", "(", "parser", ".", "getCurrentToken", "(", ")", "!=", "JsonToken", ".", "END_OBJECT", ")", "{", "throw", "new", "JsonInputException", "(", "\"Expected token: } but was \"", "+", "parser", ".", "getCurrentToken", "(", ")", "+", "\" on message \"", "+", "schema", ".", "messageFullName", "(", ")", ")", ";", "}", "list", ".", "add", "(", "message", ")", ";", "input", ".", "reset", "(", ")", ";", "}", "return", "list", ";", "}" ]
Parses the {@code messages} from the parser using the given {@code schema}.
[ "Parses", "the", "{" ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-json/src/main/java/io/protostuff/JsonIOUtil.java#L623-L658
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/ENU.java
ENU.ecefToEnu
public Coordinate ecefToEnu( Coordinate cEcef ) { """ Converts an Earth-Centered Earth-Fixed (ECEF) coordinate to ENU. @param cEcef the ECEF coordinate. @return the ENU coordinate. @throws MatrixException """ double deltaX = cEcef.x - _ecefROriginX; double deltaY = cEcef.y - _ecefROriginY; double deltaZ = cEcef.z - _ecefROriginZ; double[][] deltas = new double[][]{{deltaX}, {deltaY}, {deltaZ}}; RealMatrix deltaMatrix = MatrixUtils.createRealMatrix(deltas); RealMatrix enuMatrix = _rotationMatrix.multiply(deltaMatrix); double[] column = enuMatrix.getColumn(0); return new Coordinate(column[0], column[1], column[2]); }
java
public Coordinate ecefToEnu( Coordinate cEcef ) { double deltaX = cEcef.x - _ecefROriginX; double deltaY = cEcef.y - _ecefROriginY; double deltaZ = cEcef.z - _ecefROriginZ; double[][] deltas = new double[][]{{deltaX}, {deltaY}, {deltaZ}}; RealMatrix deltaMatrix = MatrixUtils.createRealMatrix(deltas); RealMatrix enuMatrix = _rotationMatrix.multiply(deltaMatrix); double[] column = enuMatrix.getColumn(0); return new Coordinate(column[0], column[1], column[2]); }
[ "public", "Coordinate", "ecefToEnu", "(", "Coordinate", "cEcef", ")", "{", "double", "deltaX", "=", "cEcef", ".", "x", "-", "_ecefROriginX", ";", "double", "deltaY", "=", "cEcef", ".", "y", "-", "_ecefROriginY", ";", "double", "deltaZ", "=", "cEcef", ".", "z", "-", "_ecefROriginZ", ";", "double", "[", "]", "[", "]", "deltas", "=", "new", "double", "[", "]", "[", "]", "{", "{", "deltaX", "}", ",", "{", "deltaY", "}", ",", "{", "deltaZ", "}", "}", ";", "RealMatrix", "deltaMatrix", "=", "MatrixUtils", ".", "createRealMatrix", "(", "deltas", ")", ";", "RealMatrix", "enuMatrix", "=", "_rotationMatrix", ".", "multiply", "(", "deltaMatrix", ")", ";", "double", "[", "]", "column", "=", "enuMatrix", ".", "getColumn", "(", "0", ")", ";", "return", "new", "Coordinate", "(", "column", "[", "0", "]", ",", "column", "[", "1", "]", ",", "column", "[", "2", "]", ")", ";", "}" ]
Converts an Earth-Centered Earth-Fixed (ECEF) coordinate to ENU. @param cEcef the ECEF coordinate. @return the ENU coordinate. @throws MatrixException
[ "Converts", "an", "Earth", "-", "Centered", "Earth", "-", "Fixed", "(", "ECEF", ")", "coordinate", "to", "ENU", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/ENU.java#L165-L177